POST JSON to Razor Page returning 400

Question: I know (well, strongly suspect) that this is because the AntiRequestForgery token is invalid.
I'm making two requests using Fiddler.  The first returns a page with a form:
GET http://localhost:5000/ HTTP/1.1
Accept: text/html, application/xhtml+xml, image/jxr, */*
Accept-Language: en-GB,en;q=0.5
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393
Accept-Encoding: gzip, deflate
Host: localhost:5000
Connection: Keep-Alive
Cookie: Webstorm-c18bf75a=81231d9f-edfd-4dbe-bb5a-f6a38d7df3c8; Webstorm-e6130ebb=b043c250-7e3b-44e1-ae53-2a1fd1e938ad; ai_user=a5B0s|2018-04-18T10:45:08.497Z; Webstorm-4df43b9a=25c25d80-7f4a-4ecf-8b74-a84698ccdfbe; .AspNetCore.Antiforgery.eVFzQSsi0_I=CfDJ8ERJiHn9THRElV--1wHd1Ro9Jv2DKwgMTQr1VCL4I-TphhEyTEiHsVS0z8K-Jyz_6VMNQETIEk3Yi5czv3rgMAwzmG76UrsB078j5oPJ8m6esxBQ8zLH9OEpeXqMDu570wRLkCSEQPyTIakVibTOmEM

HTTP/1.1 200 OK
Date: Sun, 25 Nov 2018 14:44:15 GMT
Content-Type: text/html; charset=utf-8
Server: Kestrel
Cache-Control: no-cache, no-store
Pragma: no-cache
Content-Length: 697

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width" />
    <title>Index</title>

Index

<form method="post" action="/Echo">

Enter message:  <input type="text" name="message" id="message"/>

<input type="submit" value="Submit"/>

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8ERJiHn9THRElV--1wHd1Rp9WyK4QCn6-wcGhXPDZHOFgkcjhJEBGrYgrsoDN3ETiqDId6aMvaHxmtunVp8ioxWYWAMqVqp3HU4ErpY7_lUzw1monlv7AMPY_Q2mzcP1YijG-86DgSeJXaXnpCWNl4c" /></form>

I can see the embedded token, I'm wanting to send the post as JSON instead of url encoded.  The second request I'm sending is this:
POST http://localhost:5000/Echo HTTP/1.1
Accept: text/html, application/xhtml+xml, image/jxr, */*
Referer: http://localhost:5000/
Accept-Language: en-GB,en;q=0.5
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393
Content-Type: application/json
Accept-Encoding: gzip, deflate
Content-Length: 229
Host: localhost:5000
Connection: Keep-Alive
Pragma: no-cache
Cookie: Webstorm-c18bf75a=81231d9f-edfd-4dbe-bb5a-f6a38d7df3c8; Webstorm-e6130ebb=b043c250-7e3b-44e1-ae53-2a1fd1e938ad; ai_user=a5B0s|2018-04-18T10:45:08.497Z; Webstorm-4df43b9a=25c25d80-7f4a-4ecf-8b74-a84698ccdfbe; .AspNetCore.Antiforgery.eVFzQSsi0_I=CfDJ8ERJiHn9THRElV--1wHd1Ro9Jv2DKwgMTQr1VCL4I-TphhEyTEiHsVS0z8K-Jyz_6VMNQETIEk3Yi5czv3rgMAwzmG76UrsB078j5oPJ8m6esxBQ8zLH9OEpeXqMDu570wRLkCSEQPyTIakVibTOmEM

{
    "message":  "Hello+World",
    "__RequestVerificationToken": "CfDJ8ERJiHn9THRElV--1wHd1Rp9WyK4QCn6-wcGhXPDZHOFgkcjhJEBGrYgrsoDN3ETiqDId6aMvaHxmtunVp8ioxWYWAMqVqp3HU4ErpY7_lUzw1monlv7AMPY_Q2mzcP1YijG-86DgSeJXaXnpCWNl4c"
}

This returns a 400:
HTTP/1.1 400 Bad Request
Date: Sun, 25 Nov 2018 14:45:12 GMT
Server: Kestrel
Content-Length: 0

How should I pass the token when I'm POSTing JSON?
Answer: Literally just saw the answer.  The tokan should be passed as a header:
__RequestVerificationToken: CfDJ8ERJiHn9THRElV--1wHd1RqrINvuOTauZLAAg86eE91T6PHlKf21JOJVGA1TdMoksEVSlE-UWkOon2A0x1RSOqy0gQ_uSZxwQiBy8YArAowajUR1uJo3B4XAWl3abaToa8Gp8K4SPJ1hmSKjXAwzZvk

POST JSON to Razor Page returning 400


I am not sure which download I require for VSCodium

Question: I've been using Ubuntu for about a week so total noob here.
I want to install VSCodium on my laptop running Ubuntu 20.04.
At the following, I do not know which download is most suitable:
https://github.com/VSCodium/vscodium/releases
Please could someone advise me?
If I had to guess, I would say - VSCodium-linux-x64-1.46.1.tar.gz
Thanks.
Answer: I found the following guide which worked seamlessly for me on Ubuntu 20.04:
https://www.addictivetips.com/ubuntu-linux-tips/install-vscodium-ide-on-linux/
Answer: You can download the package ending with amd64.deb and run sudo dpkg -i codium*amd64.deb
You can also install vscodium as a snap package, this way you will get automatic updates
sudo apt-get install snap
sudo snap install codium


React Native + Expo trying to import custom fonts but error

Question: I'm trying to import custom fonts to React Native using the Expo framework but I get an error:
Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s%s, undefined,  You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `Layout`.,
    in Layout
    in Unknown (created by Route())
    in Route (created by Route())
    in LocationProvider (created by Route())
    in Route() (created by RootRoute)
    in RootRoute (created by ContextNavigator)
...

Here's my code. It tells me to check the export, but it looks like it's exporting alright (I'm using _layout.js):
import { Stack, NavigationContainer } from 'expo-router';
import { useCallback } from 'react';
import { useFonts } from 'expo-font';
import * as SplashScreen from 'expo-splash-screen';
import { Provider } from '../hook/context/auth';
import { LoginPage } from './(auth)/login';

SplashScreen.preventAutoHideAsync();

export default function Layout(){
    const [fontsLoaded] = useFonts({
        'DMBold': require('../assets/fonts/DMSans-Bold.ttf'),
        'DMMedium': require('../assets/fonts/DMSans-Medium.ttf'),
        'DMRegular': require('../assets/fonts/DMSans-Regular.ttf'),
    })

    const onLayoutRootView = useCallback(async() => {
        if(fontsLoaded){
            await SplashScreen.hideAsync()
        }
    }, [fontsLoaded])

    if(!fontsLoaded){
        return null; // load splash screen
    }

    return (
    <Provider>
        <NavigationContainer>
            <Stack.Navigator onLayout={onLayoutRootView}>
                <Stack.Screen name="Login" component={LoginPage} />
            </Stack.Navigator>
        </NavigationContainer>
    </Provider>
    )
}

I'm pretty sure I have the relative path right:
Comment: Can you console log the `fontsLoaded` right after importing the fonts? Also make sure the font files arent corrupted.
Comment: @MoinulHaq this is my output:
`false`
`true`

Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s%s, undefined,  You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `Layout`.,
    in Layout
    in Unknown (created by Route())
    in Route (created by Route())
    in LocationProvider (created by Route())
Comment: Also, I open up the fonts in OpenType and they appear to be fine.
Comment: Can you share the `LoginPage`, seems like the issue is from there. The issue might be with the export of LoginPage.
Answer: This error message might be related to your imports, not the fonts.
Either a component might not be properly exported or you might have mixed up default and named imports.
export default function LoginPage() {}

import LoginPage from './(auth)/login';

// OR

export function LoginPage() {}

import { LoginPage } from './(auth)/login';

Depending on the above


magento full text search not working on Live

Question: Magento full text search not working
I do following steps
full text search option enable from system->configuration->catalogsearch
and
 app/code/core/Mage/CatalogSearch/Model/resources/Fulltext.php

change
 $likeCond = '(' . join(' OR ', $like) . ')';

to
 $likeCond = '(' . join(' AND', $like) . ')';

but still i not  able to search fulltext word exactly match.
Answer: You also need to change
$where .= ($where ? ' OR ' : '') . $likeCond;

to
$where .= ($where ? ' AND ' : '') . $likeCond;


Compare contents of variable against contents of another variable - jQuery

Question: I'm creating a page search function and I need to compare the contents of one variable to see if it exists in another variable in an if statement.
To make it simple here's an expample:
var name = 'james';
var place = 'james lives in europe';

if (place:contains(james)) {
   ....... do something
}

Anyone know how to do this with jquery. cheers
Answer: if (place.indexOf(name ) >=0) {
  // …
}

Answer: Yes you can use a regexp :
var str="james lives in europe";
var reg1=new RegExp("[james]","g");
if (str.match(reg1)) {
  document.write("'[james]' is in str");
}

Answer: You can use simple javascript -
if (place.indexOf(name) != -1) {
   alert('do something');
}


toggle array of image when button is clicked

Question: I have this html, I want to know if it is possible to toggle this images when the button is clicked, but only displaying one at a time, using jquery

Cambiar

Comment: yes is possible... try it out and let us know how it goes
Answer: Good evening! Yes, this is possible using jQuery; although if you are actually thinking about a carousel effect I suggest you, to use a plugin such as owlCarousel.
When you program using jQuery, you must think on how it is possible to manipulate the html through jQuery APIs. First, let us approach our problem through thinking.
First) We have four images that we wish to display one at a time within an interval time (the size in this case I recommend it to be always fixed eg. 400px by 400px or any other size, it does not matter).
Second) With jQuery we can grab each img element tag with a simple $('img'). We can do two things.
Solution I: We create an img element tag and style it depending on our wish with simple css for now (debugging purposes) and then, if this is our only img tag in our page, we actually can just grab that img () and save it to a var in JS as: var myImg = $('img'); Then using jQuery's awesome API, we can use a function called setInterval(function(){ alert("Hello"); }, 3000); where inside the brackets is the code of the anonymous function we wish to execute, which is our first argument; the second argument is just the interval that the function will run over and over again until you stop it (in this case we do not).
But what kind of code will make it change? Well, this is called DOM manipulation. We actually can also change attribute values using another jQuery function provided in the API called .attr('attrName: desiredValue');
Here is the thinking logic behind the code, you must code it:
Save the img element tag in a variable using the jQuery selector.
Inside an interval function, do a for loop from zero to n-number-of-pictures.
Inside the for loop, change the img src attribute value to whatever is the source of your image (you can have the sources of images defined inside of an array, it will be better, as imgSources = ['source1',...'sourceN'];) and loop equally with an i counter every n milliseconds. Or better yet, no for loop is needed, just assign the current counter i of the array value to the src attribute and increase it thereafter, and also add a sentinel, so that when it reaches a maximum, let us say array.length - 1 maximum, we reset to 0, good?
And try it. With this, we have an img tag that has a src attribute that will change every n milliseconds.
Answer: it's possible use absolute positioning and  the display attribute
here is a simple demo

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

Cambiar

Answer: try this...

jQuery("#clickme").click(
(function(){
    var i=0;
    function toogle(){
        jQuery(".changeimg").hide();
        jQuery(jQuery(".changeimg").get(i)).show();
        i+=1;
        if (i>jQuery(".changeimg").length)i=0;
    }
    return toogle;
})()
);
img{
  width:80px;
  height:80px;
  display:none;
}

<button id="clickme">
            toogle the Rabbit yay!!
            </button>


variable scope in julia tasks

Question: I have adapted the pmap() implementation to my program to do some scheduling and I have a question about the scope of the variables within the tasks. This is the Julia implementation
function pmap(f, lst)
    np = nprocs()  # determine the number of processes available
    n = length(lst)
    results = cell(n)
    i = 1
    # function to produce the next work item from the queue.
    # in this case it's just an index.
    nextidx() = (idx=i; i+=1; idx)
    @sync begin
        for p=1:np
            if p != myid() || np == 1
                @async begin
                    while true
                        idx = nextidx()
                        if idx > n
                            break
                        end
                        results[idx] = remotecall_fetch(p, f, lst[idx])
                    end
                end
            end
        end
    end
    results
end

If i substitute the line idx = nextidx() by idx=x; i=i+1; , each task updates its local copy of the variable i. However the variable i within the function nextidx() is shared by all the tasks. Why is this?
Answer: Let me first simplifies the above code:
function test()
  i=10
  nexti() = (inx=i;i+=1;inx)
  @sync begin
    @async begin
      i=i+10
      nexti()
      println("value of i in another thread => $i")
    end
  end
  println("value of i in test() => $i")
end

test()

# value of i in another thread => 20
# value of i in test() => 11

We declare nexti() in the same process as i was declared, and i in nexti() refers to the same location, so any changes to i inside nexti() alerts i value in outer scope.
On the other hand @async macro forces the block inside, to run on different process so this block use a copy of i value and any changes inside this block do not alert i value in outer scope.

variable scope in julia tasks


What methods to use for PHP Field Validation

Question: What are the best practices other methods; outside of
!empty();
isset();
!is_null();

and assigning a value to a variable e.g.
$variable = $_POST['value']`

Do I use to make sure form data is validated to be clean enough to use?
Do I go to the lengths of trying to use field length and regex validations?
If the endpoint is an API using MySQL and PHP, does using htmlspecialchars() cause potential issues with loss of data using these methods?
Comment: It depends on what you need to validate... For example to check if an email is valid don't use `!empty();`
Comment: You're mixing a few things, validation / sanitation, SQL injections / XSS., and so on. Overall, this question is way too broad for SO imho, and there're plenty of resources out there for each topic.
Comment: `htmlspecialchars` shouldn't be used when saving data, only on output, so you shouldn't have any loss of data.
Comment: But would I use it just to make sure that the $_POST['email'] actually has something in it, and then check it's an email using regex or something, or just skip straight to the regex?
Comment: Try this
http://www.w3schools.com/php/func_string_htmlspecialchars.asp
Comment: Make sure you bind all variables, this prevents things like injection. validating at the form and using !empty are perfectly fine validation techniques
Comment: Can I ask why `regex` is an included tag? What does this have to do with RegEx
Answer: You can use the filter_input method and use a filter like FILTER_SANITIZE_SPECIAL_CHARS. Its the better way to filter your post paramters. function.filter-input.php
Answer: For input validation, I would point you to the Open Web Application Security Project (OWASP). The have pages on data validation, PHP filters, cheat sheets, and XSS protection.
Since you specifically referenced MySQL, I would note that the best security practice is to use PDO or MySQLi to parameterize your statements. Parameterized statements are much more effective than relying on sanitized input in preventing MySQL injection as PHP does not rely on syntax to differentiate user input and the SQL query itself. When accessing data from the database, however, htmlspecialchars() can still come in handy to prevent XSS attacks.
Answer: Excellent answers thank you!
For the MySQL side of things parameterized statements was definitely going to be the only method used.
I guess really the most important thing for me is the submit values via the post method.
If I'm expecting JSON and only JSON then something like this should work on the server side.
function isJSON(MyTestStr){
    try {
        var MyJSON = JSON.stringify(MyTestStr);
        var json = JSON.parse(MyJSON);
        if(typeof(MyTestStr) == 'string')
            if(MyTestStr.length == 0)
                return false;
    }
   catch(e){
        return false;
    }
    return true;
}

Then I should be able to do anything further by pulling out the values from the JSON directly and use them in the PHP script without much fear.
Answer: Each use of input data needs different filtering / protection.
First, I like to do
$foo = @$_POST['foo'];
if (empty(foo)) ... // take different action if foo is totally missing (not just blank)

For inserting into MySQL, use the escaping mechanism available in the API -- real_escape_string, or "binding".  Do not use the mysql_* API, it has been replaced by mysqli_*.  Do not combine multiple queries into a single call.
For displaying on an HTML page, use htmlentities.  Note:  Do not use that before inserting into a database table; that just clutters the table.  Instead, have the discipline to use it just before displaying.
If you have an old version of PHP, you might be tempted to use Magic Quotes.  Don't!  As a comment puts it "[This] one-size-fits-all approach to escaping/quoting is wrongheaded and downright dangerous."
For JSON, I like  json_encode(...) and json_decode(..., TRUE).


Do gems have secondary effects?

Question: Do elemental gems in Torchlight 2 have secondary effects other than direct elemental damage or elemental armor?
I am referring to poison, fire, ice and electric gem and try to understand which of them are better-
Answer: Each element has its own attack side effect, which has a chance to occur on each hit.  Some of them are hinted at in the loading screen tips.

Ice attacks have a chance to Freeze, which slows down movement, attack, and cast speed by 33% for a few seconds.
Poison attacks have a chance to Poison, which reduces damage and all armor by 33%
Electric attacks have a chance to Shock, which causes the afflicted enemy to emit electric bolts that damage more enemies every time it is hit.
Fire attacks have a chance to Burn, which is fire damage over time that ignores armor.

Note that these all have a chance to occur on elemental attacks from any source, including skills.  Elemental gems give you these effects only as a direct consequence of giving your weapon an additional elemental attack type.
Comment: Doesn't freeze also reduce attack speed?
Answer: As far as I know they don't have any further effects. The idea behind finding the right one for you and your character should be the rest of your skilltree/items. This is because the gem's dmg is affected by skills/items. As an example: if you skilled 40% poison dmg, you'll get 40% more dmg from poison gems in contrast to the other elements.
If that does not really answer your question, feel free to give me further details ;)
edit: see comment - I forget about so much because of all these new games :D
Comment: I am asking it because some friends told me "Put poison gems because there are chances that they poisonous enemies", or "Use ice gems because they could slow down them sometimes", etc. but I didnd't find any reference in game, so I am not sure if they are wrong or not.
Comment: Ah well your friends are right: 1) Poison Gems give chance to put poison debuff on target which reduces dmg dealt by target 2) fire gems put fire debuff on target, makes them burn for additional dmg 3) lightn. gems give chance to paralyze target which ccs them for a certain amount of time 4) frost gem add a chance to deepfreeze target to slowdown movement (not sure but i think atckspeed aswell)

Do gems have secondary effects?


Shutdown message while running the program in Cocos2d for MacOS X

Question: Currently i'm developing a Cocos2d application for Mac OS X using xCode 4.2.1.So my problem is,sometimes while running the program the system get's stuck and show me a message like this- You need to restart your computer.Hold down the power button until it turns off.Then press the power button again. After receiving this message i can't proceed further without restarting the computer.  What might be the problem behind this issue. Can anyone help me out.
Answer: What You get is called a kernel panic.
Resolution

Restart your Mac with a Safe Boot and see if the kernel panic happens
  again
In most cases, kernel panics are not caused by an issue with your Mac.
  They are most likely caused by an issue external to your Mac. If the
  kernel panic doesn't happen again within a few weeks, you don't need
  to troubleshoot further.

Depending on the model of Mac you have, restart one of these ways:
  • Press and hold the Power button for several seconds to turn off your Mac. Then, press the Power button to startup your Mac.
  • If you have a Restart button, press it.
As soon as your Mac starts up, hold down the Shift key to start up with a Safe Boot into Safe Mode. Note: If you are using a third-party
  external keyboard and cannot start with a Safe Boot, try using an
  Apple keyboard instead.
If your Mac has a kernel panic starting up, or while in Safe Mode, jump to the "Troubleshooting a recurring kernel panic" section of this
  article.
If your Mac starts up without a kernel panic after a Safe Boot, restart your Mac by choosing Apple Menu > Restart…, then let it start
  up normally. Run Software Update and install all available updates
  until Software Update reports "Your software is up to date". Mac OS X
  updates improve the tolerance for external issues such as malformed
  network packets. For most kernel panics, this is all you have to do.

Note: It is possible, although very unlikely, that something on your network is sending your Mac malformed network packets which could cause recurring kernel panics. If the hardware and software on your Mac checks out as OK, check the devices on your network. Make sure your router's firmware is up-to-date, and that the router is not malfunctioning.  Refer to your router's manufacturer for service and support.

And You also can try to find the problem in kernel.log. Go to the console app in the utilities folder and then type this:
tail -f /var/log/kernel.log

It will print kernel.log file to Your console.

More information:
Kernel Logs from the Command Line in Mac OS X.
How to log a kernel panic.
Kernel Panic.
Comment: Thank you for your reply. But this happens only when i run a particular application that i'm currently developing.
Comment: @Augustine did You try my second suggestion to look at `kernel.log`?


Is anonymous authentication possible with auth_code grant in Spring Security OAuth2?

Question: I'm trying to implement an OAuth2 client with SpringBoot 1.5.13 and spring-security-oauth2 2.0.15.RELEASE.
I want to be able to authorize anonymous users with auth_code grant.
However I'm running into issues when trying to finish the auth flow.
Since I don't want to call any other external service to obtain user identity info, I'm using the DefaultTokenServices. The DefaultTokenServices needs a TokenStore for it's operation, so I'm supplying the simplest one - InMemoryTokenStore.
I have tried two approaches that both failed:
1. Redirect to OAuth2ClientAuthenticationProcessingFilter
If I redirect user after authorization grant to a URL, that OAuth2ClientAuthenticationProcessingFilter filters on, the filter properly requests and obtains an access token. However, the next thing it tries to do is:
OAuth2Authentication result = tokenServices.loadAuthentication(accessToken.getValue());

And that call fails on BadCredentialsException("Could not obtain user details from token"), because the DefaultTokenService tries to call tokenStore#readAccessToken, but the InMemoryTokenStore is entirely empty at this point.
2. Redirect to another URL (simple RestController)
If I redirect user after authorization grant to another URL, that doesn't match the OAuth2ClientAuthenticationProcessingFilter, I cannot even obtain the access token.
When trying to call restTemplate.getAccessToken() in the RestController, the call fails in AccessTokenProviderChain due to this exception:
if (auth instanceof AnonymousAuthenticationToken) {
    if (!resource.isClientOnly()) {
        throw new InsufficientAuthenticationException(
                "Authentication is required to obtain an access token (anonymous not allowed)");
    }
}

EDIT: I've tried to use my own implementation of AccessTokenProviderChain, that simply omits this check, and the parts related to clientTokenServices and at first look it seems to work. But I am not sure if this is a correct approach sufficient for multitenancy (multiple anonymous concurrent users authorizing via multiple OAuth2 providers).
Obviously my auth is an anonymous auth, I need an anonymous auth flow! I know It is perfectly possible in Spring Security 5.2.x, but I don't understand how to do this in spring-security-oauth2?
Is it not possible to do anonymous authorization with auth_code grant?
Answer: So it seems anonymous auth is not possible together with OAuth2 auth_code grant, as explained in this open bug: https://github.com/spring-projects/spring-security-oauth/issues/1842
I've solved the issue by ditching the spring security oauth library and moved to ScribeJava.


Count distinct multiple columns for each another column

Question: Let's have a table "pairs" with 3 columns, like this:
pairs(person, item1, item2)
1, 1, 1
1, 1, 2
1, 1, 2
2, 2, 1
2, 2, 1

How to get a number of unique pairs of item1-item2 for each person? Like this:
Person , pair_num
1, 2
2, 1

All I can think out is :
select person, count(*) from (
select distinct person, item1, item2
from pairs
)
group by person;
But is there any solution without a subquery?
Comment: In RDBMS land, a table without a PRIMARY KEY isn't really  a table.
Answer: SELECT person, (item1 + item2) AS pair FROM pairs GROUP BY person;

Answer: count(distinct) can take multiple arguments:
select person, count(distinct item1, item2) as numpairs
from pairs
group by person;

If you want (1,2) to be the same as (2,1), then use least() and greatest():
select person, count(distinct least(item1, item2), greatest(item1, item2)) as numpairs
from pairs
group by person;


django get model with foreign key

Question: Let's say I have 2 tables in my DB. One of them is called Person which has attributes 'name' and 'id' and the other one is called Role which has attributes 'person'(which is a foreign key to the id in Person table) and 'id'.
Now I'd like to make a query that given a name like David, finds all the persons with that name and also returns the Roles associated with them. We know that every Person is associated to at most 1 role.
I know that I cannot use Person.objects.filter(name=David).select_related('Role') Because Role is not Person's attribute. Is there anyway I can get this with only 1 hit to DB?
Answer: This is in fact a very simple query, contrary to some of the other answers. The thing to remember is that if you want Roles, you should start with the Role model. So just follow the relationships backwards from there:
Role.objects.filter(person__name='David')

Comment: No. I also need the Person object. Basically I'm looking for a way to get both Role and Person with 1 hit to the DB.
Comment: Then add `select_related('person')`.
Answer: To get the persons, it is as you already wrote:
Person.objects.filter(name='David')

To get all the roles related to any person called David:
Role.objects.filter(person__name='David')

To get the roles of a given person:
Role.objects.filter(person=person)

So what I understand from your question is that you want to do something like this:
for person in Person.objects.filter(name='David'):
    person_roles = Role.objects.filter(person=person)
    # ...
    # do something with person_roles (that should contain
    # at most one object according to your constraints).

Comment: No: the result of the query would have to be stored in a very complicated Python object if that were possible...
Comment: So there is no way to get the persons with name David and the associated roles in one query?

django get model with foreign key


PHP: Echoing values of input fields

Question: I am grabbing the values of several input fields with the help of an Ajax/JS function. The issue is that the values of the textbox are not being echoed. I checked with the firebug tool and it shows that the post is performed but there is a blank value. Why is the PHP not echoing the value when the JS function submits it?
EXAMPLE
JS

HTML
<form action="" method="post" enctype="multipart/form-data" id="contact_form" name="form4">

Contact Name *

      <input type="text" id="contact_name" class="detail" name="contact_name" value="<?php echo isset($_POST['contact_name'])? $_POST['contact_name'] : ''; ?>" />

<? echo $_POST['contact_name'];  ?>

Email Address *

    <input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />

<? echo $_POST['email'];  ?>

</form>

Answer: You need to use .serialize() on the form probably
Answer: Friend first understand the Javascript behaviour.
When you post a form, it becomes one request to the server. At the same time when you send an ajax to server it becomes another separate request to the server
So you should either do form post or ajax.
As you are using ajax here you, in the ajax request you have to pass data separately in data parameter

Comment: If you want to use `` then ajax will not fill that for you, for that you will have to use without ajax. Make a simple form post and then it will work. Otherwise store `$('#contact_form').serialize()` data in some variable and after ajax success play with as you want. Hope you are getting
Comment: Thank you friend, I am new to this and now I am starting to understand it thanks to your help. One thing that I am still having difficulty is echoing the value of each input field: ``

PHP: Echoing values of input fields


Cannot reboot after upgrade to Ubuntu 14.04 from 12.04 sometimes

Question: My laptop: Lenovo V460
I upgraded from Ubuntu 12.04 to 14.04.  Sometimes it fails to reboot (from both terminal and desktop) and just hangs. I see only several points blinking one after another.
My laptop worked well when I was under Ubuntu 12.04. Could anyone explain what is causing this problem and how to fix it?
Answer: Sharing my solution for anybody who meets the same problem.
Under 12.04, I installed bumblebee to switch graphic cards.
It seems that bumblebee causes Ubuntu 14.04 to have this issue.
I removed it sudo apt-get remove bumblebee* and my problem is solved.


How can I add content:"NEW" to paragraphs 2 & 3 using only CSS?

Question:
help me put content="NEW" with css, but only in paragraf 2 and 3.
i mustn't change html code.
if possible pls wiht pseudo classes.

Subheading

Paragraph 2

Paragraph 3

Sub subheading

Paragraph 4

Paragraph 5

Paragraph 6

Paragraph 7

Paragraph 8

Paragraph 9

Paragraph 10

Answer: You can accomplish this using the immediate child selector, also referred to as the child combinator (>), which will target only direct p children of #first-div.
From MDN:

The child combinator (>) is placed between two CSS selectors. It
  matches only those elements matched by the second selector that are
  the direct children of elements matched by the first.

#first-div>p::after {
  content: 'NEW';
  color: red;
  padding-left: 10px;
}

Subheading

Paragraph 2

Paragraph 3

Sub subheading

Paragraph 4

Paragraph 5

Paragraph 6

Paragraph 7

Paragraph 8

Paragraph 9

Paragraph 10

jsFiddle
Answer:

#first-div > p::before {
  content : 'NEW ';
  color   : red;
}

Subheading

Paragraph 2

Paragraph 3

Sub subheading

Paragraph 4

Paragraph 5

Paragraph 6

Paragraph 7

Paragraph 8

Paragraph 9

Paragraph 10

Answer: What you want to do is first look at #first-div and drill down on its children using the direct descendant operator (>).
In case you need 2 specific elements, you can use the direct child operator along with the nth-child function.
#first-div > p:nth-child(2):after,
#first-div > p:nth-child(3):after {
  color: red;
  content: "NEW";
}

If you need all p tags under #first-div, just select all of them
#first-div > p:after {
  color: red;
  content: "NEW";
}


Is the number of alternating primes infinite?

Question: I'm not sure if the recreational-mathematics tag is appropriate, but this problem came up during a practice Putnam seminar so maybe?
The problem:

Say that a positive integer is alternating if when expressed in base 2, any two consecutive digits are different. Is the number of alternating primes finite or infinite?

I chose to attempt this problem for the seminar one week, but I didn't get very far. The best I have is:
The alternating numbers are of the form $0, 1, 10, 101, 1010, 10101,... (\text{base}~2)$. Of these, we need only concern ourselves with the odd alternating numbers, which are all alternating numbers ending with $0$. Thus we may write them as a sum:
$$\sum_{k=0}^n 2^{2k} = \sum_{j=0}^n 4^j.$$
Thus the odd alternating numbers are precisely the numbers whose representations in base $4$ consist entirely of $1$'s: $1, 11, 111,... (\text{base}~4)$. The question is now: are there infinitely many primes that are of this form in base $4$?
That's as far as I got. The professor organizing the seminar didn't know what the solution was. Actually he suspected that it was an open problem and he just put it on the weekly problem list for the heck of it.
Do you have any ideas on where we can try to go from here?
Comment: The number with $n$ ones base $4$ is $(4^n-1)/3$. You ought to be able to work out primality conditions for such a number.
Comment: If you are still struggling, another hint: "difference of two squares".
Comment: @proximal, as Old John said, $a^2-b^2 = (a-b)(a+b)$ is all you need - not even modular arithmetic.
Comment: @proximal And now remember that $4=2^2$...
Comment: Update: Still working on it. I get why Gerry's comment is valid (is that what you were referring to John?) and I'm thinking about the primality conditions. Not knowing any number theory other than basic definitions (mod, prime, etc.) is making this tough.
Comment: All I'm getting out of difference of 2 squares is this: if we assume $n$ is even, say $n = 2k$, then $(4^n-1)/3=(4^k+1)(4^k-1)/3 = (4^k+1)a$ for some integer $a$. For $k > 1$, i.e. $n > 2$ even, we get that $(4^n-1)/3$ is composite. So I guess it suffices to consider $n$ odd now?
Comment: Aha. Thank you. I'll post what I have as an answer, could you check that it is correct?
Answer: Following Gerry's remark, we may write any odd alternating number in the following form: $$\frac{4^n-1}{3}.$$
Applying the difference of squares formula, we write $$\frac{4^n-1}{3} = \frac{(2^n+1)(2^n-1)}{3}.$$
For any number $\alpha$ that is not divisible by $3$, either $3 \mid (\alpha-1)$ or $3 \mid (\alpha+1)$. Since $3 \not\mid 2^n$, we conclude that $3 \mid (2^n+1)$ or $3 \mid (2^n-1)$. This shows that for $n > 2$, $\frac{4^n-1}{3}$ is composite. Thus the number of alternating primes is finite.
Comment: Thanks to Gerry, Old John, Sanchez, and Calvin for leading me to this answer.
Comment: The same happens in other bases, $\frac{b^{2n}-1}{b-1}$ is composite for all (not very small) $n$.
Comment: Why do you show that $3$ divides one of the factors? That's already clear from the fact that the quotient is an integer and $3$ is a prime.


A Project has many Sites. Both Projects and Sites can be viewed and edited. What's a good experience for this that doesn't overwhelm the user?

Question: Web app where each Project contains many Sites. Projects and Sites are able to be viewed and edited. I have a feeling that clumping everything on one screen might be a bit overwhelming, especially considering that each Site's "lots of info" is scrolling a couple full browser heights.
So currently I have a table of Project rows like this with nested expandable rows to preview the Sites.
Project1
  - Site1
  - Site2
  - Site3
Project2
  - Site1
  - Site2
  - Site3

Then when you click on one of the projects, it shows that Project's description and info for all of the Sites.
Project1
 - info
Site1
 - lots of info
Site2
 - lots of info
Site3
 - lots of info

I haven't deciding the editing part yet, but my first impression was that editing here might be too much information all at once.
A Site always belongs to a Project. Should they be viewed separately or together? Should they be edited separately or together?
I tend to like using the same screen and modals, but this feels a bit different because it's so much information.
Answer: According to your description, the second view would look more like a book that doesn't seem to result in a good user experience. Very likely there is no need to have two separate views either. A single one can comprize the whole data if it's properly organized.
An approach used for email management can be applied to your case resulting in a non-overwhelming view with a structure as outlined below:
+--------------------------------------------------------------------------------+
| Project1                            | ProjectX - SiteY                         |
|  Project's info beginning           | Lots of info about the selected entry.   |
|   - Site1                           |                                          |
|      Info beginning of the Site1    |                                          |
|   - Site2                           |                                          |
|      Info beginning of the Site2    |                                          |
|   - Site3                           |                                          |
|      Info beginning of the Site3    |                                          |
| Project2                            |                                          |
|   - Site1                           |                                          |
|      Info beginning of the Site1    |                                          |
|   - Site2                           |                                          |
|      Info beginning of the Site2    |                                          |
|   - Site3                           |                                          |
|      Info beginning of the Site3    |                                          |
| ...                                 |                                          |
+--------------------------------------------------------------------------------+
 <Pagination if necessary>

A good example of such view might be the one available in Gmail Labs:  Preview Pane.
Though using such approach an entry's info can be edited with a projects & sites structure displayed next to it, it's not preferred in all situations and some users might want to edit an entry in a separate view, fully dedicated only for editing. Thus, a handy feature to open an edit pane in a separate view would be a good addition.


Azure IoT Hub device registration via POSTMAN results in Unauthorized

Question: I want to create a sas token for registration of device in Azure IoT hub,using postman.The sas token will be created with pre-requested script.
<code>    var resourceUri = "scopeId/registrations/deviceId" // The resource uri
    var deviceId = "deviceId";

    resourceUri = encodeURIComponent(resourceUri.toLowerCase()); // Encode the url

    var expires = Math.ceil((Date.now() / 1000) + 10 * 60); // Expire the token 60 minutes from now

    var toSign = resourceUri + "\n" + expires; // this is the string format to gen signature from

 var crypted = CryptoJS.HmacSHA256(deviceId, CryptoJS.enc.Base64.parse("symmetrickKeyOfEnrollmentGroup"));

var signature = CryptoJS.HmacSHA256(toSign, crypted); // The signature generated from the decodedKey
var encodedUri = encodeURIComponent(CryptoJS.enc.Base64.stringify(signature)); // The url encoded version of the Base64 signature

// Construct authorization string (shared access signature)
var iotHubSasToken = "SharedAccessSignature sr=" + resourceUri + "&sig=" + encodedUri + "&se=" + expires +"&skn=registration";

console.log(iotHubSasToken);
postman.setGlobalVariable("token", iotHubSasToken);
</code>
This is what i created, but i receive Unauthorized.Some ideas where i am wrong, i think i somewhere in the signature, because the "sr" and "se" are okay
Output of the code above which throws Unauthorized:
<code>SharedAccessSignature sr=0ne002ee24e%2Fregistrations%2Fcxdlx3f3zv9xx3f3zq&sig=Ukz%2FPyyLaweLYmFq4gHUP%2BhiO7X%2FyQAE9noAaw4nuLU%3D&se=1659940252&skn=registration
</code>
References:
About SAS: https://learn.microsoft.com/en-us/azure/iot-dps/how-to-control-access
About the REST API: https://learn.microsoft.com/en-us/rest/api/iot-dps/device/runtime-registration/register-device#provisioningserviceerrordetails
About DPS sas token: https://learn.microsoft.com/en-us/azure/iot-dps/how-to-control-access
Error:
Comment: I dont see policy name in the sas token generator code.
Comment: Problem is solved!
Comment: i tried to add it, and also throws unauthorized "&skn=registration" it was something like this
Comment: @livepool If we dont see precise details from the activity logs then it will be difficult to assist... last resort is to check with microsoft support
Comment: How i can check the activity logs, my other suppose is that maybe i wrong construct the signature, only by the summetrick key or else..
Comment: sorry my bad I meant the api logs... also ensure that the url parameters as as per the spec
Comment: Can someone with knowlege assist...
Comment: unless you pose error details we can only shoot in the dark
Comment: This is the only thing i see, pasted in the post
Answer: The issue was in the signature.
<code> var crypted = CryptoJS.HmacSHA256(deviceId, CryptoJS.enc.Base64.parse("symmetrickKeyOfEnrollmentGroup"));

var signature = CryptoJS.HmacSHA256(toSign, crypted); // The signature generated from the decodedKey
var encodedUri = encodeURIComponent(CryptoJS.enc.Base64.stringify(signature)); // The url encoded version of the Base64 signature
</code>
This is the right way of creating it.


What is causing these JavaScript errors when using jQuery's filter() inside a namespace?

Question:
Possible Duplicate:
SyntaxError: Unexpected token ILLEGAL

Can someone tell me why these errors are occurring and what to do to fix them?
<code>/*global $:false */

Blah.BlahBlah = {
  findLinks : function () {
    "use strict";

    $('a').filter(function () {
      return !(/https?:\/\/[^\/]*xyz.*/i.test($(this).attr('href')));
    }).text("***");
  }
};
</code>
Throws these errors in JSHint :

Line 10: } Unexpected ''.
Line 11: }; Expected '}' to match '{' from line 3 and instead saw ';'.
Line 11: }; Missing semicolon.

Chrome console shows this error:

Uncaught SyntaxError: Unexpected token ILLEGAL

However, using this code (JSFiddle) in an encapsulated anonymous function does not throw an error:
<code>/*global $:false */

(function() {

  "use strict";

  $('a').filter(function() {
    return !(/https?:\/\/[^\/]*xyz.*/i.test($(this).attr('href')));
  }).text("***");

}());
</code>
Comment: Jsfiddle copies an illegal character when you do a straight copy-paste from their site... Open your inspector in chrome and you'll see it.
Comment: The first example appears to work fine in the Google Chrome console.
Answer: I pasted your first fragment into jsbin and I saw a strange character before the second-to-last close brace <code>}</code>... possibly a normally non-printable character?
Comment: I see what you mean. The character has been removed.
Comment: @Cofey, it seems that you stated that that wasn't the problem so soon then


Sort Vector with own Struct

Question: i have my vector with my own Struct of type:
struct Absatz_rechts{
    xint yniedrig;
    xint xhoch;
    xint xniedrig;
};

vector<Absatz_rechts> Werte_rechts(Gruppen.size());
Werte_rechts.push_back(Absatz_rechts());

now i want to sort the vector
for (i = 0; i < Gruppen.size(); i++)
{
    cout << Werte_rechts[i].yniedrig << endl;
    cout << Werte_rechts[i].xhoch << endl;
    cout << Werte_rechts[i].xniedrig << endl;
    cout << endl << endl << endl;
}

gives out :
10
75
35

12
35
0

8
75
55

now the sort with:
bool compName(const Absatz_rechts &left, const Absatz_rechts &right)
{
    return (left.yniedrig < right.yniedrig);
};

sort(Werte_rechts.begin(), Werte_rechts.end(), compName);

The Problem ist the new output:
0
0
0

8
75
55

10
75
35

Why are the First three now filled with zero ??
Comment: Well, for one, because you created a vector go `Gruppen.size()` (which means it already has that many elements), **then** you pushed even more elements in. Just create the vector without arguments: `vector Werte_rechts;`, then do your pushes. And stop using `for (i = 0; i < Gruppen.size(); i++)`. just use an iterator on the vector
Answer: Werte_rechts.push_back(Absatz_rechts());

This appends a value-constructed object, its fields all being zero.
After sorting, this will be the first element, so it will appear first when you iterate over the vector to print it. Since you're only printing the first Gruppen.size(), and the total size (including the zero-valued one you appended) is Gruppen.size()+1, you don't see the last element.

Sort Vector with own Struct


FosOauthServerBundle Propel BaseClient not found

Question: I'm using doctrine orm but somehow I get an error that the propel BaseClient is not found (a class usually autogenerated by propel).
Either it's a bug or I'm doing something wrong?
fos_oauth_server:
    db_driver:           orm
    client_class:        Diligentia\OAuthBundle\Entity\Client
    access_token_class:  Diligentia\OAuthBundle\Entity\AccessToken
    refresh_token_class: Diligentia\OAuthBundle\Entity\RefreshToken
    auth_code_class:     Diligentia\OAuthBundle\Entity\AuthCode
    service:
        user_provider: fos_user.user_manager

The error:
PHP Fatal error:  Class 'FOS\OAuthServerBundle\Propel\om\BaseClient' not found in /var/www/redwood/vendor/friendsofsymfony/oauth-server-bundle/Propel/Client.php on line 19

Fatal error: Class 'FOS\OAuthServerBundle\Propel\om\BaseClient' not found in /var/www/redwood/vendor/friendsofsymfony/oauth-server-bundle/Propel/Client.php on line 19
Segmentation fault

Seems to me it shouldn't even attempt to load it.
Answer: predis wasn't installed with composer causing my caching not to work.
Due to that the User Bundle was unable to obtain which db driver I used and putting propel as default causing the unrelated error and my inability to find the issue for a long time.


Modelica Simulation breaks when if condition changes

Question: I try a simple code on modelica using if:
model thermostat1
  parameter Real T0=10;
  Real T(start=T0);
equation
  if T<73 then
    der(T)=-T+80;
  else
     der(T)=-T+50;
  end if;
end thermostat1;

the simulation stops at the moment T reaches 73.
Why can't the simulation continue with the new equation ( der(T)=-T+50 )?
And how can i fix it?
Thank you.
Comment: This text might also help: https://simulationresearch.lbl.gov/modelica/userGuide/bestPractice.html#controls
Comment: more questions on "chattering": https://stackoverflow.com/search?q=%5Bmodelica%5D+chattering
Comment: I would definitely recommend to read this link: https://mbe.modelica.university/behavior/discrete/hysteresis/
Answer: What happens in your model is called chattering. This means, that there are very frequent events happening.
In you case specifically this is caused by the condition T<73 combined with the definitions of the derivatives. Let me try to explain what happens with the model you have provided:

The temperature rises until it reaches 73
Then the temperature starts to fall because the condition in the if-statement turns fall
This causes the if-statement to immediately change to true again, making the temperature rise
This causes the if-statement to change to false again, making the temperature fall
goto 3.

This causes the condition T<73 to change at a very high frequency, in turn creating many events, which have to be handled by the solver. This makes the progress in time very little (what you refer to as "the simulation stops").
There are multiple ways to solve this problem. One is to add a hysteresis to the model. I did that in code below. To describe the hysteresis part I used the code from Modelica.Blocks.Logical.Hysteresis. This will make the boolean variable upperLimit (which replaces your T<73) change only if temperature gets higher than T_highand lower than T_low. I chose this solution as it seems reasonable for a thermostat.
model thermostat1
  parameter Real T0=10;

  parameter Real T_High=74;
  parameter Real T_Low=72;

  Boolean upperLimit "Output of hysteresis block";
  Real T(start=T0);

equation
  upperLimit =not pre(upperLimit) and T > T_High or pre(upperLimit) and T >= T_Low;

  if upperLimit then
    der(T)=-T+50;
  else
    der(T)=-T+80;
  end if;

end thermostat1;

The result of the simulation then looks like:

More general information can be found e.g. at http://book.xogeny.com/behavior/discrete/decay/


How to keep an airplane stable on the runway in Kerbal Space Program?

Question: I've spent the past three hours committing a genocide of historical proportions against my Kerbals, and it's making me quite sad.
Valentina would really appreciate if I could get my airplane off the ground, but it keeps exploding on the runway by the exact same failure mode: The plane veers to one side or another, either I or SAS correct it, which starts a left/right wobble, which builds until one of the wings hits pavement, at which point the craft quickly brings Valentina to her untimely end.
I've covered all my bases, as far as I can tell:

All three wheels (one steerable in front, two fixed in back) are mounted with angle snapping, symmetrically
Wheels are mounted to the fuselage, rather than to the wings (which flex under load)
Wheel base is wide
Center of lift is behind center of mass, and slightly raised
Rear wheels are in front of tail, but not enough to make tail strikes easy
The two engines have been mounted every imaginable way with the same result: Over the wings, on the fuselage, on girder segments, on the wingtips, etc.
Wings have been flown both with and without struts
Wheel friction was even decreased to 0.3 for front wheel and increased to 2.0 for rear wheels, as per a tip found online

It seems if I turn off SAS, I can prevent the oscillation from starting as it's initiated by some control input, whether from me or SAS, but then the plane veers off the runway until it hits something. Intriguingly, there is one thing I've found that does prevent the wobble from starting, and that is to use a single engine mounted directly on the back of the fuselage, which prevents using a tail and is ultimately a fairly significant restriction to build around.
I've spent some time scouring the internet for ways of solving this problem, and found a number of pieces of advice on preventing wobble and improving planes in general, some of which made it into the above list, but Valentina's still dying, and I'm tired of Kerbal funerals.
Comment: Standard KSP airplane-stability request: post a screenshot of your airplane in the SPH, with the center-of-mass, center-of-lift, and center-of thrust markers shown.  Better still, three screenshots showing side, top, and rear views.
Comment: what do you mean by "wheels are mounted with angle snapping"? do you put them vertically or are they at an angle to the ground?
Comment: I used the angle snapping feature (to the right of the symmetry selector in the bottom left hand corner of the screen in the space plane hangar view) to mount the steerable wheel perpendicular to the ground, and the two fixed wheels symmetrically such that zoomed in, the wheels themselves are perpendicular, though the fixed wheel part itself comes with something like a 45 degree angle between the wheel and the shaft that attaches it to the craft, so the shafts naturally sit at something like a 45 degree angle out to either side so the wheels can sit perpendicular. In other words classic tripod
Comment: Have you set your control surfaces to only respond to appropriate controls? E.g. the vertical stabilizer only handles yaw?
Comment: Do you have a picture? Getting a plane of the round isn't that hard. Keeping it from crashing is usually the hard part.
Comment: Decrease the ground roll by adding power,   Then lean the plane back so it doesn't even need wheels.  Ideally get your plane to take off vertically.  Then think of a new name instead of plane, something like "fast goer-upper"       (humour)
Comment: @Mast depends on the size really. Small planes are trivial to get up in the air; large and heavy tend to get issues.
Answer: I've found that all my runway wiggling planes are caused by the wheels. This happens in two instances; initial placement and plane body deformation.
Wheels need to be touching the ground exactly as they were intended to, you cannot angle them in any direction other then their intended direction when placing them. So the ones that go straight up and down can only be straight up and down, no angling left, right, backwards or forwards such as when you place the little wheel on the angled body of the cockpit part. The ones that are at an angle must be placed at that exact angle, you can't angle them to make them wider.
Plane body deformations can cause the wheels to touch the ground at a slightly different angle. Body deformation can be caused by heavy parts, many parts connected together, or forces on the plane.
From your description of your plane I would check the following:

Center of lift is behind center of mass, and slightly raised
When your plane speeds up, it sounds like your lift could be pushing your nose into the runway causing deformation or an oscillation with the same effect.
The two engines have been mounted every imaginable way with the same result: Over the wings, on the fuselage, on girder segments, on the wingtips, etc.
Assuming nothing is blocking the exhaust of the engines, the relation of your thrust to your center of mass could also cause the same problems as above.
Wheel base is wide
If your wheels are far apart there may be deformation caused by heavy parts or many parts between them, I would try attaching struts from each wheel to a single fuselage part. Also ensure that the wheels are placed "correctly".
Comment: Turns out it was wheel positioning! I had my rear wheels mounted on the tail, and it seems the taper of the tail messed up the angle of the wheels creating instability. I moved the wheels from the tail to the fuel fuselage, and now she takes off like a dream! KSP should be handing out engineering degrees :)
Answer: You seem to have done a lot of things right. I'm finding it quite surprising you didn't manage to get the plane to fly yet. I haven't encountered oscillations like that in an airplane but I have encountered them aplenty in case of lightweight probes that have too strong control authority - too good RCS or reaction wheels, so I suspect the source here is the same. Try reducing control authority (or even generally amount) of control surfaces - rudder, ailerons, the front wheel (maybe even make it a fixed one).
Additionally if you have any off-center fuel tanks, double check the fuel is drawn from both at the same rate (same priority). Plane veering off course is not uncommon but uneven fuel draw can exacerbate it a lot.
Also hopefully you're not using any mods that use throttle (Throttle Controlled Avionics etc) as with engines as sluggish to react as jet, this is bound to cause trouble.
If that all fails, you may try building your plane lighter and with mightier (or just more) engines, so it just doesn't have the time to start misbehaving on the runway before you bring it up in the air.
one last thing to verify: look from the side, observe where your center of mass is, then how the control surfaces are located relative to it and if the way they react to your controls makes sense (just try to pull up, down, or roll, on the runway without even starting the engine or disengaging brakes and watch which way the control surfaces move). Control surfaces near center of mass sometimes get "confused" as to their role and do stupid things. You may need to change control authority to a negative value if they bend "the wrong way".
ps. Start with simplest, easiest planes you can and then increase complexity observing and mitigating problems as they arise. Starting from something with MK3 hull without experience in MK1 will be an uphill battle.
ps2. It's unlikely you're doing this but just in case: while on the ground use only yaw controls to change direction, don't touch the roll controls. Roll is the main way to change direction in flight, and best way to crash the plane on the ground.
Comment: +1 for "If that all fails, you may try building your plane lighter and with mightier (or just more) engines, so it just doesn't have the time to start misbehaving on the runway before you bring it up in the air." I've always found that best way to not crash on the take off is to take off.
Comment: @TheEnvironmentalist There is one more method I'm sure would work in your case, although I didn't write about it because I think it's *cheesy* and wouldn't solve the root problem. Drive gently off the runway and use the huge grassy field to take off, without care in the world about the plane veering to a side.
Comment: Hahaha absolutely right, but distinctly less satisfying
Comment: There are some really useful tidbits here which deserve some credit. First, _too strong_ control authority is not the kind of problem I'd think of, and was definitely worth looking into, and fuel tank priority is a really good point. Next, mods can and often do cause these kinds of problems. Finally, while straightforward to those with an engineering background, the idea to start with the simplest, easiest possible planes and build one's way up to a sufficiently complex craft is not obvious to everyone, and is the epitome of the engineering mindset KSP exists to instill and explore. Thanks :)
Answer: I haven't found a sure-fire solution to this, but I think I know what causes it.  If you have more than one engine, you can get asymmetric thrust at low speeds.  Thrust is determined partly by velocity.  If you (or SAS) turns even just a little, the engine opposite your turn will have a higher velocity than the one towards your turn.  At low speeds, this difference can be significant.  This makes one engine generate more thrust than the other, exacerbating the turn.  SAS sees this and turns the other way, which just causes the same problem in the other direction.  Eventually you either crash, or you reach a high enough speed that SAS wiggling can't cause a significant enough difference in engine speeds.
In addition to the tips others have suggested, try locking steering on all your wheels.  This should reduce ground control authority and make oscillations less powerful.  They'll still happen but you'll have more time to get off the ground.
Comment: While I couldn't accept this one because ultimately it was changing wheel positioning that increased stability enough to elegantly take off, I don't think it's unreasonable to imagine that the oscillations originated or were exacerbated through asymmetric thrust. Do you by chance know how much the thrust varies with these small velocity perturbations?
Comment: @TheEnvironmentalist No clue, but it doesn't need to be much because it's a feedback loop.  If you have a perturbation that gives your left engine a tiny bit more thrust, you will turn slightly right.  This gives your left engine more thrust again which makes you turn faster etc...  I think it might be so small it starts with floating-point rounding errors; it's exponential and compounds every frame.
Comment: Interesting, though even being exponential there's a chance it starts out so small it takes longer than a takeoff to reach noticeable levels. Even exponential growth can take a while to get going if it starts out microscopic, and I'd be fascinated to find someone who could figure out a way of measuring the growth rate
Answer: Another possibility to add to the existing answers (it's a bit hard to diagnose without seeing the plane) is that your landing gear might be insufficient for your plane's mass. Can you check what happens if you swap in larger gear?
And one other, more remote possibility to check: Where is your plane's center of drag? It may be too far forward, especially if the tail is too small relative to the plane's wings. Can you check what happens if you increase the tail size to pull the center of drag back?


populating a spinner with unique strings

Question: Im trying to populate a an action bar spinner with unique Strings based on the user input in a dialog box, eg user enters a string and if it's not already in the spinner, it should add itself there. Is such an implementation possible ? I tried using the ArrayList class but of course, duplicates are there, should I use hashset ? thanks
<code>// array of sample strings to popluate dropdown list
ArrayList<String> categories = new ArrayList<String>();

// create an array adapter to popluate dropdown list
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            getBaseContext(),
            android.R.layout.simple_spinner_dropdown_item, categories);

 //thats the alert dialog through which user enters strings
 AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle("New category");
        alert.setMessage("Please enter a new category ");

        // Set an EditText view to get user input
        final EditText input = new EditText(this);
        alert.setView(input);

        alert.setPositiveButton("Ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int whichButton) {
                        Editable value = input.getText();
                        // Do something with value!

                        categories.add(value.toString());

                    }
                });
</code>
Answer: I'd suggest before adding to categories that you check if it's already been added before or not using ArrayList.contains:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#contains(java.lang.Object)
Another thing to think about would be the case sensitivity, perhaps you could convert to lower case before checking if it already exists in the arraylist and only adding if it doesn't.


Item Drop Alert Disappearing and not coming back in TF2?

Question: I got an item drop, but when I clicked on it, it disappeared. I tried going into the backpack to click on the alert but it didn't work either, and now I can't have my item.
I've tried:

Restarting TF2
Reinstalling the game
Answer: It's likely you dismissed the alert with an errant keystroke.

I tried going into the backpack to click on the alert but it didn't work either, and now I can't have my item.

Item alerts are just notifications, the item is already in your backpack when you receive the notification, so even if the alert stuffed up the item should still exist. Assuming you don't have any blank spots in-between items, the last item in your backpack will be the most recent addition.
Note that you need to dismiss the notifications in order to receive more drops, so if item drops have stopped entirely for you, then it might be worth raising a bug using the 'Report' option from the in-game main menu.
To check if you can still earn drops, you'll need to be 'actively playing':

In order for a player to receive an item drop, they must be "actively playing" i.e they meet all of the following criteria:

Is connected to a VAC secured server.
Is responding to in-game drop notifications while not utilizing external programs to do so.
Is running only one instance of the game.
Is not in textmode.

TF2 Wiki - Item Drop System


Is this true $(a*b)^q =(c*d)^q \implies a*b=c*d?$

Question: Is this true $(a*b)^q =(c*d)^q \implies a*b=c*d$?
Here $a,b,c,d \in G$, $(G,*)$ forms a group, and $q$ is an integer
Answer: No, consider the cyclic group $\mathbb{Z} / q\mathbb{Z}$. Then the left-hand side is always satisfied whereas the right-hand side in general is not.
Answer: No, not even for infinite groups.
Let $a=b\neq c=d, q=2$. Consider the group given by the presentation $$\langle a, d\mid a^4, d^4\rangle.$$ This is the free product of two different presentations of $\Bbb Z/4\Bbb Z$.
We have $a^4=d^4$ but $a^2\neq d^2$.
Answer: Choose two units $a,b\in\mathbb Z_p$, then $a\neq b$ but $$a^{p-1}=b^{p-1}=1$$ by Fermat.


How to download a playlist without the videos

Question: Ubuntu 18.04. What I would like to do using youtube-dl is get a list of the video names and the date they were uploaded (the extension doesn't matter) without downloading the videos. Is there a command to do this?
Answer: Open the terminal and type:
sudo apt install jq # command-line JSON processor
cd Desktop/
youtube-dl -j --flat-playlist "https://<yourYoutubePlaylist>" | jq -r '.id' | sed 's_^_https://youtu.be/_' > result.txt

Example command:
youtube-dl -j --flat-playlist "https://www.youtube.com/watch?v=iwhuPxJ0dig&list=PLei96ZX_m9sU3dLM2I5LKcqXeqth-GTe6" | jq -r '.id' | sed 's_^_https://youtu.be/_' > result.txt

The results of example command in result.txt are shown below. Unfortunately the -j (--dump-json) option does not return data about the dates that the videos were uploaded, but it can return the titles of the videos. Another nice feature is that the videos don't need to all be in the same playlist. The same command can also return the URLs of all the videos on the same channel or user webpage.
https://youtu.be/iwhuPxJ0dig
https://youtu.be/ArDT5NsROMk

Explanation:
-j, --dump-json
       Simulate, quiet but print JSON information. See the "OUTPUT
       TEMPLATE" for a description of available keys.

--flat-playlist
       Do not extract the videos of a playlist, only list them.
jq is like sed for JSON data – you can use it to slice and filter and map and transform structured data with the same ease that sed, awk, grep and friends let you play with text.
Comment: Works perfectly thank you very much!


Actively encouraging titled players to use this site

Question: According to this answer, there is not even one grandmaster on Chess Stackexchange.
What a pity, especially when one considers the abundance of top experts and famous professors on e.g. Math Overflow.
My instinct is that there is a real opportunity to incorporate more, if not as much, expertise on this site.
My proposal is that Stackexchange should take the initiative and get in touch with grandmasters and international masters. Invite them to join. Those titled players who have academic backgrounds will be especially valuable.
Thanks.
Comment: On meta, [downvotes may mean disagreement](/help/whats-meta) rather than a question being unclear or not useful.
Comment: Please explain your downvote
Answer: Grandmasters are the closest thing the chess world has to full time professionals. They are not going to waste time on something which doesn't have financial advantage for them and has very little to interest them.
StackExchange is not going to pay them to take part.
There is no real opportunity for them to gain paying students to coach via ChessSE.
Given the low level of the majority of the questions on ChessSE they are not going to be attracted by the content. Before people get over excited and protest, bear in mind that the majority of chess players are not very strong. Low level content is what they understand.


Conformal map that maps $\Bbb C−\{0\}$ onto itself is of the form $az$ for some $a ∈ \Bbb C−\{0\}$, or $zb$ for some $b ∈ \Bbb C − \{0\}$

Question: Hint: Note that $0$ and $∞$ are isolated singularities of $f(z)$, whose corresponding Laurent series admit the same region of convergence, and thereby, must agree with each other by the uniqueness. So what can you tell from these together with the assumption that $f(z)$ is a bijection?
Comment: the title here confuses me greatly.... you know complex numbers commute, right?
Answer: I think you meant $az$ for some $a \neq 0$ or $\frac b z$ for some $b \neq 0$.
Hints: By Picard's Theorem $0$ is not an essential singulairty of $f$.  [In a neighborhood of an essential singularity the function attains 'most' of values  infinitely many times, so it cannot be one-to-one]. If it is a pole than $|f(z)| \to \infty$ as $ z \to 0$ so $\frac  1{f(z)}$ becomes an entire function (after removing the singularity at $0$. It is also well known that the only one-to-one entire functions are of the type $ax+b$. You can finish the proof now.


Sorted Dictionary and List<>() has an error in VS 2010

Question: I have a code , i get it from my question from stack overflow
# Read data
var data = new SortedDictionary<(string id, string idr, string email),
    List<(string reference, decimal amount)>>();

using (var input = File.OpenText("input.txt"))
{
    List<(string reference, decimal amount)> currentInvoice = null;

    for (var line = input.ReadLine(); line != null; line = input.ReadLine())
    {
        var fields = line.Split(new char[] { '@' }, 6);
        switch (fields.Length)
        {
            case 2:
                // Sanitize input
                if (fields[0] != "INV")
                {
                    throw new Exception("Unknown record type.");
                }
                if (currentInvoice == null)
                {
                    throw new Exception("Invoice without context.");
                }

                // Parse
                var invoiceEntry = fields[1].Split(new char[] { ' ' },
                    StringSplitOptions.RemoveEmptyEntries);

                if (invoiceEntry.Length == 2)
                {
                    decimal amount;
                    if (decimal.TryParse(invoiceEntry[1],
                        NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands,
                        CultureInfo.InvariantCulture,
                        out amount))
                    {
                        currentInvoice.Add((invoiceEntry[0], amount));
                    }
                }

                break;

            case 6:
                var currentContext = (id: fields[0], idr: fields[2], email: fields[5]);
                if (!data.TryGetValue(currentContext, out currentInvoice))
                {
                    currentInvoice = new List<(string reference, decimal amount)>();
                    data.Add(currentContext, currentInvoice);
                }
                break;

            default:
                throw new Exception("Unknown record.");
        }
    }
}

SortedDictionary can't be used it says

' using system.collection.generic.sorteddictionary<TKey,TValue> requires 2 agruments '

the List<(string reference, decimal amount)> currentInvoice = null ;  has an error too , it says

'Only assignment,call,increment, decrement, new object expression can be used as a statement'

how to fix this?
Comment: Am i missing something here? there is no error with this code in my environment (though thats not to say there is not other issues)
Comment: @Olivier I think in the past you had to include the `System.ValueTuple` package from NuGet.
Comment: @john Yes, it works. Good to know.
Comment: I think its time to upgrade your visual studio.
Comment: @TheGeneral hmm im sure you're not missing something , i dont know why this code error , the SortedDictionary function cannot be used , and i dont know why ..
Comment: The compiler on VS2017 tells me: *Impossible de définir une classe ou un membre qui utilise des tuples, car le type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' nécessaire au compilateur est introuvable. Une référence est-elle manquante ?* => ?
Comment: Is there anyway to fix this? And i cant understand the language sorry
Comment: I think you are using pre C#7 (maybe)
Comment: @Enrico It says "It's impossible to define a class or member which uses tuples, because the type System.RunTime.CompilerServices.TupleElementNamesAttribute necessary to compile couldn't be found. Are you missing a reference?" - it's not exactly relevant to your situation. You said that you're using Visual Studio 2010, which I thinks limits you to an older version of the .NET Framework (4.0?) which doesn't support value tuples (introduced in 4.7).
Comment: So i cant use this code .. okay thankyou i will find another way to clear my task , thanks for the help
Comment: @TheGeneral hehe i want too , but Office PC only has this IDE and i think i must work with my laptop to fix this task ..
Comment: You could use a custom class with three string properties instead of the tuple, if that's the issue.
Answer: For an older version of Visual Studio you may be able to fix this by installing the following from nuget

Microsoft.Net.Compiler
System.ValueTuple

Note : Take notice of the dependency, you may need to install an older version that supports your targeted framework
It also should be noted, that if you are using VS 2010, it's time to tell your bosses/managers to upgrade, or use the community version.


How to concat integer with wchar_t

Question: I want to concat an integer with wchar_t, tried below method but its crashing
const wchar_t mySalvo[10] = L"Group:";  // THis is global
int salvo = 0;
wchar_t buffer[1] = L"\n";
itoa(salvo, buffer, 1);
wcscat(mySalvo, buffer);  // app crashes here

ITs in C
Comment: `wchar_t buffer[1] = L"\n";` You do not have sufficient memory to hold a string. You need to provide a place for terminating 0.
Comment: The C specific solution seems to be [swprintf() or better snwprintf_s()](https://en.cppreference.com/w/c/io/fwprintf).
Comment: Why do you tag "c++" then? :P
Comment: @L.F. yes VS does support real C, but some parts like VLAs (and maybe others) are missing.
Comment: you've made `mySalvo` a const, so that is telling the compiler you won't ever change the contents of it...
Comment: Possible duplicate of [How to concat an int to a wchar\_t\* in C++?](https://stackoverflow.com/questions/8609842/how-to-concat-an-int-to-a-wchar-t-in-c)
Comment: I am working on vc++ with c file
Comment: @sijith I'm a bit confused. You are using VC++ and you are trying to compile a "C file" in C++ mode? (Since AFAIK VC++ does not support real "C")
Comment: Actually my project is c++ but one file alone in c and in that c file I need to apped integer to wchar_t
Comment: I incresed size to 5 but still crashing on wcscat(mySalvo, buffer);
Comment: @Jabberwocky Thank you! I did not know that :)
Answer: There are numerous issues with this code:
const wchar_t mySalvo[10] = L"Group:";  // THis is global
int salvo = 0;
wchar_t buffer[1] = L"\n";
itoa(salvo, buffer, 1);
wcscat(mySalvo, buffer);  // app crashes here

First of all, using a global is not best practice. There doesn't appear to be any good reason for it to be global, so just make it local to where you need it.
Second, you've specified it is a constant string, and initialised it to a string literal, which means it will probably be stored in a read-only segment of memory. Yet you're writing into it with wcscat (your compiler surely gave you a warning??).
Also the string is limited to 10 wchar_t elements, so even if it weren't read-only, it would only be long enough to store a 3 digit number.
the buffer intended to store your converted string is one wide character long (and the initialisation to newline is pointless) so you will overflow your buffer with any value of salvo above 9.
the third parameter to itoa is the number base, which would normally be 10. It is meaningless to have a number of base 1.
you're using wcscat to write into a constant string, which is verboten, even assuming it were long enough.

So there's a lot of fundamentals here you need to come to terms with. String allocation, memory initialisation, arrays, constant variables and constant literals, and more.
What you are trying to do is simply produce a formatted string. The sprintf family of string formatting functions provide all you could possibly need, plus a secure way of doing it.
The simplest solution would be something like this:
void show_message(unsigned salvo)
{
    wchar_t message[64];
    swprintf_s(message, sizeof(message), L"Group: %u\n", salvo);

    // do something with message!
}

So if you called show_message(123), the resulting value in message would be: "Group: 123\n".
Answer: mySalvo is const - which was spotted by Chris.
And on top of it
wchar_t buffer[1] = L"\n";
itoa(salvo, buffer, 1); -
wcscat(mySalvo, buffer);  // app crashes here

it is undefined behavior asd you do not have enough space to accommodate L"\n". Both calls invoke the UB. itoa will not work with the wchar_t strings. You need to find the appropriate function.
try wchar_t buffer[2] = L"\n"; instead
Comment: Thsi worked but crashed on wcscat(mySalvo, buffer); even after increasing buffer size
Comment: See the rest of UBs in your code (BTW I think you hold the world record  of UBs/line)
Comment: Remove `const` as well :)
Comment: mySalvo is already declared an assigned gloabally so wcscat crashes as its size is exceding while copying
Comment: `const wchar_t mySalvo[10] = L"Group:";  // THis is global` => `wchar_t mySalvo[16] = L"Group:";  // THis is global`
Comment: THanks P__J__
I done some thing like this  int size = wcslen(mySalvo);
 mySalvo[size-1] = (salvo + 1) + '0';  My salvo count is below 10

How to concat integer with wchar_t


Nested ng-repeat to create multiple table with different data

Question: I have Json data
[{"ID": "01000", "Name" : "Name1", "Age" : 25},
 {"ID": "01001", "Name" : "Name2", "Age" : 30},
 {"ID": "01001", "Name" : "Name3", "Age" : 23}]

and  want to show this data in multiple table using ng-repeat. table should look like this

I've created function which locates Distinct ID's into "$scope.ID" variable.
    $scope.ID = [];
    $scope.ID.push("1");
    var s = 0;
    for (var i = 0; i < $scope.Report.length; i++){

        if ($scope.ID[s] != $scope.Report[i].Id){
            $scope.ID.push($scope.Report[i].Id);
            s++;
        }
    }

Then I'm trying to display data into table in this way

        ID

        NAME

        AGE

        {{r.id}}

        {{r.name}}

       {{r.age}}

Script returns two table but, each table has the same three value,

I need that each generated table had own filter value, for this case first table should be filtered by ID: 01000 and second table By ID: 01001.
What should I do for this?
Answer: Try:

    ID

    NAME

    AGE

    {{r.id}}

    {{r.name}}

   {{r.age}}


How to use esc_attr here?

Question: I don't know if it's ok how to use esc_attr in
echo $this->get_field_id( 'title' );

I got this. is it ok or is there an error?
echo esc_attr($this->get_field_id('title'););

Comment: Extra semicolon. use error reporting
Answer: If by esc_attr you mean the integrated wordpress function, you should put a string between the parenthesis. And it's used to escape html attributes.
In your case, you should get rid of the first semicolon:
echo esc_attr($this->get_field_id('title'));

How to use esc_attr here?


Framing Advice - Removing Shower Opening

Question: Finishing up demo on our master bathroom and working towards plans to get it all back together. Located on the top floor of our split level, over the laundry room.
The existing entry to the shower was fully tiled, floated over metal lath. The shower ceiling was built down approx. 12" from the bathroom ceiling and it felt like a tiled bomb shelter.
The ideal plan is to remove the entry completely and have the ceiling and walls flush into the shower area.
My question is - the shower opening looks to be framed out as a load bearing opening. Is the case?
This wall runs parallel to the joists above (attic). The wall is not centered directly under one of the joists, but is running just next to one. There is a drop ceiling below this bathroom, and nothing in the ceiling indicates to me that it's bearing - it is not over another wall or over a joist.
My hope would be to have everything flush in the end and that would require only a couple new studs to finish out corners in the long run.
I'm 99% sure it was framed this way for the tile installation... but better safe than sorry.
Comment: Hello, and welcome to Home Improvement. Looks load-bearing to me, but I'm definitely not a pro. And, thanks for [taking our tour](//diy.stackexchange.com/tour) before posting; few newbies do.
Comment: Thanks for the reply. Yeah - it's definitely framed as bearing it just goes against all the "usual" bearing wall tests... so it's throwing me for a loop.
Comment: Is that a 2x12 or such over the door opening? It looks "massive" for that context.
Comment: It is a 2x10, yes. I thought so too - since it's the same as the bearing headers. But that's what makes me think it's simply a "frame this as an opening", and that's the lumber they had onsite type of situation.
Answer: With your joist direction following the same without support it is probably built for a door. With a door and no header the wall may wobble a bit as many shower doors are glass and heavy. I was taught to always put a header in for a door for that reason. If you are not going to have a door and want it open to the ceiling I would do it. Depending on the depth and spray a shower curtain can span the opening with an expanding rod if needed. Opening up the area (this also held ventilation and may reduce mold growth as your extractor fan can pull the steam out.
Comment: Thanks Ed. That's what I was feeling. We are going to try for no door to help the room feel less closed-in and a rain shower head placed off center to help control the spray out of the opening, since it's fairly shallow. One of the main reasons we wanted to do this renovation was to get the outer walls and ceiling flush - so I'm hoping this works!


exceptions that never occur in java

Question: I writing a class for points and vectors.I want to use them to calculate dot and norm of vectors.
These are point and vector classes
public class Point {
    public float x,y;
}
public class MyVector {
       public Point start,end;
}

I write these code for dot calculation the dot.
public float dot(MyVector v) throws Exception
{
   if( (start.x != v.start.x) || (start.y != v.start.y))
        throw new Exception("Vectors not begin in same Point");
}

I want to use this function to calculate vector's norm.
public float norm()
{
        return dot(this);
}

I know that the exception condition never occur for the norm function. So I won't to throw
exception. I know that i can do this like bellow:
public float norm()
{
    try
    {
        return dot(this);
    }
    catch(Exception e)
    {

    }
}

But I think this is redundant. Is there a way for removing the try and catch in norm function?
Comment: Throw something that extends RuntimeException instead - you aren't required to try/catch unchecked exceptions.  (See http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html )
Answer: This intention cannot be expressed in java. Either function dot throws an exception or not.
You cannot give it a "hint" to specify that there are conditions in which an exception will never been thrown.
You can either live with that situation or switch to use RuntimeException only.
Or you could refactor it to something like this
public float dot(MyVector v) throws Exception
{
   if( (start.x != v.start.x) || (start.y != v.start.y))
        throw new Exception("Vectors not begin in same Point");

   return unchecked_dot(MyVector v)
}

where unchecked_dot performs the actual operation but does not check the arguments and does not declare to throw Exceptions.
public float norm()
{
    return uncheked_dot(this);
}

Answer: There is no way within the java language.
The best way to handle this is with a comment and a rethrow.
For example, if you are using a write method that takes an Appendable but passing a StringBuilder then maybe you want to gloss over the fact that Appendable.append throws an IOException since StringBuilder never actually does this.
  try {
    write(myStringBuilder);
  } catch (IOException ex) {
    // Should never happen since StringBuilders do
    // not throw IOexceptions on append.
    throw new AssertionError(ex);
  }

Note that if you are wrong (now or in the future) about the ability of the delegate function to throw, then by rethrowing in an AssertionError, you give code maintainers more information about what went wrong.
If your project uses a logging system consistently, then logging can be a fine option if logging and dropping the exception would not violate any invariants.
Answer: Do not throw a plain exception.
Make a subclass of RuntimeException and - to make it easier to catch upstream - name it e.g. "DotUndefinedException".
When you do it with a runtime exception you do not have to specify it unless you explicitly want to handle it.
Answer: if you have a reason to believe that dot(...) should throw an exception, may be norm(...) should too. Eating up exceptions is not really a very good idea. But yes, if you do want to, you have to write a try catch. The only other option is that you could throw a RuntimeException from dot(...) in which case you don't need to catch.
Comment: Not really, in this situation, dot() would throw something like illegal argument exception. However, this is not the case at norm() which doesn't take any argument.

exceptions that never occur in java


Is there a finite number of enemies in Lovers in a Dangerous Spacetime?

Question: When exploring the first two levels of Lovers in a Dangerous Spacetime we're finding that we can easily get overwhelmed when the Gumball ship gets surrounded, because of the delay in getting from one side of the ship to the other. It's much safer when we can pick the enemies off a few at a time...
...However, I can't tell if the enemies are infinite or not. If the enemies are finite (that is, they don't respawn) then the strategy of picking them off slowly would allow the players to clear the map and make exploration safe. But if the enemies keep coming, then this strategy doesn't make as much sense.
For context: We haven't made it past level 3 where:

 has multiple waves of enemies where you must keep the warp engine safe from damage, and clearly the number of enemies is finite in this format

So please tag spoilers accordingly :)
Is there a finite number of enemies in Lovers in a Dangerous Spacetime, or do more just keep spawning? Is it possible to "clear" a map so there's no more enemies?
Comment: As a side note, get into the habit of directing the shield preemptively towards the side where you anticipate the most threat (generally the front), and then man turrets that are away from the shield.  Since your bullets can destroy most projectiles, and the shield can block anything, you can ignore anything your shield can block and then mop up those once the threat is eliminated.
Answer: Enemies do respawn on most of the maps. Exceptions are maps like what you described with warp drive (there is usually one map like this per constellation) and

 boss maps. Yes, there are boss battles!

Moreover, you strategy won't work in a long run because there will be events when after interacting with some objects lots of portals are opened around and you suddenly find yourself surrounded. So it's better to get better in running through the ship!


object of type 'closure' is not subsettable with pglm::pglm function in R to estimate panel logit

Question: I'm trying to use the pglm function from pglm package to obtain a random effects panel estimation of an ordered logistic model.
When testing the standalone function pglm it gives me the desired result. Here's my specifications:
pglm::pglm(as.numeric(y)~x1+x2+x3, df,family = pglm::ordinal('logit'),
           model = "random", method = "bfgs", print.level = 3, R = 5, index = 'Year')

where:
 1. all explanatory variable {x1,x2,x3} are numerical doubles
 2. y is an ordered categorical variable ranging from 1 to 22
The table also includes a "Year" variable ranging from 1996 to 2014, that will be used to build the panel data.
When trying to use the pglm function in another function:
pglm_fun <- function(df){

  df <- data.frame(df)
  pglm::pglm(as.numeric(y)~x1+x2+x3, data =  df,family = pglm::ordinal('logit'),
               model = "random", method = "bfgs", print.level = 3, R = 5, index = 'Year')

}

I get an error message occurring when calculating
pdata.frame(data, index)

Error in x[, !na.check] : object of type 'closure' is not subsettable.

When trying to run the code in the console, I do not have such an error and the pdata.frame() function works.
Example of data frame:
df = data.frame(y    = sort(rep(1:4,20)),
       x1   = rnorm(80),
       x2   = rnorm(80),
       x3   = rnorm(80),
       Year = rep(sample(1995:1998, replace = FALSE),20))

Comment: What is `index` in your code? There is also an `index()` function in `plm`, which is probably causing the confusion. Also what is `data` ? How does it relate to `df` ? In short: you should post a reproducible example http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example
Comment: I set the variable `'Year'` as index, and data is simply the data frame I give to the function `pglm_fun`as argument. I'll edit the post with an example of data frame df
Comment: What about `pdata.frame(data, index = "Year")` then?
Comment: Non reproducible for me, running `pglm_fun(df)` works for me.
Comment: Ok, my RStudio compiler is just very unstable. Sometimes it works, sometimes it doesn't, giving me different sorts of errors under this data frame. I'm actually testing a bigger and more complex data frame having about 2k rows, is it possible to share it somehow?
Comment: Maybe you need to declare a variable for the individuals too (and use the `index` argument to declare the variables for individuals as well as times).
Comment: I tried pasting everything into a formula and use R's `as.formula`, but it didn't work either. Moreover, I can append at most one individual and one time index.
Answer: Ok, I figured it out. In this case there are environments problems in R, since the funciton I was using was making copies of variables instead of using global variables directly.
The problem is solved by declaring individual names in the function and leaving the data frame as a global variable:
pglm_fun1 <- function("y","x1","x2","x3","Year"){
  require("pglm")
  pglm(as.numeric(y)~x1+x2+x3, data = df, family = ordinal('logit'),
          model = "random", method = "bfgs", print.level = 3, R = 5, index = 'Year')

}


Is rectangle manifold with boundary

Question: Is a closed rectangle a 2d manifold with boundary? It seems like the corners don't have neighborhoods homeomorphic to the Euclidean half space?
Comment: They are homeomorphic but not diffeomorphic.
Comment: A closed rectangle can be seen as a smooth manifold, depending on the charts you use.  It won't be an embedded submanifold of $\mathbb{R}^2$, however, because the smooth structure would not be the induced one.
Comment: Do you need them to be diffeomorphic for the rectangle to be a manifold with boundary?
Comment: It depends on what is your definition of manifold. Standard notion of manifold is smooth manifold, so every transition map is diffeomorphism. But you can define only continuous manifold, there you require from transition map to be only homeomorphism.
Comment: I can define a homeomorphism from a closed rectangle to a closed circular disc.
Comment: It can be seen as a smooth manifold with corners, @Seth, not one with boundary. Edit; I see what you mean, you mean giving it the smooth structure as if it were a closed disc. Sorry.
Answer: Summary of the comments: it is a topological manifold with boundary. It can be regarded as a smooth manifold with boundary, but then the embedding into $\mathbb{R}^2$ fails to be smooth. It can also be regarded as a smooth manifold with corners.

Is rectangle manifold with boundary