text:
Q: What triggers the Avenger music change? What triggers the change of music on the Avenger?
In XCOM 2 (and XCOM 1 as well), the story follows a Three Act formula denoted by a different music track playing during each act while on The Avenger.  The tracks in XCOM 2 are titled Stage One, Lazarus (for the second stage), and Stage Three.  However, as the differences between the tracks are relatively subtle, it can be difficult to notice exactly when they change.
What events trigger the switch between acts, and consequently, between music tracks?

A: From the modding code, this seems to be the relevant code. This will contain spoilers!

 Chapter 1 will play until you build the Shadow Chamber
 Chapter 2 will play from building the Shadow Chamber until killing (I presume) the incomplete avatar during one of your missions
 Chapter 3 will play from that point forward.

function PlayBaseViewMusic()
{
    SetSwitch('StrategyScreen', 'Avenger');

    if( class'XComGameState_HeadquartersXCom'.static.IsObjectiveCompleted('T1_M6_KillAvatar') )
    {
        SetSwitch('HQChapter', 'Chapter03');
    }
    else if( class'XComGameState_HeadquartersXCom'.static.IsObjectiveCompleted('T3_M2_BuildShadowChamber') )
    {
        SetSwitch('HQChapter', 'Chapter02');
    }
    else
    {
        SetSwitch('HQChapter', 'Chapter01');
    }
}


text:
Q: How can I get the name of a calling function within a module in Mathematica? If I write a function or module that calls another module, how can I get the name of the calling function/module? This would be helpful for debugging purposes.

A: The Stack function will do almost exactly what you want, giving a list of the "tags" (for your purposes, read "functions") that are in the call stack. It's not bullet-proof, because of the existence of other functions like StackBegin and StackInhibit, but those are very exotic to begin with.
In most instances, Stack will return the symbols that name the functions being evaluated. To figure out what context those symbols are from, you can use the Context function, which is aboput as close as you can come to figuring out what package they're a part of. This requires some care, though, as symbols can be added to packages dynamically (via Get, Import, ToExpression or Symbol) and they can be redefined or modified (with new evaluation rules, for instance) in other packages as well.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does this website create the buttons on the homepage? http://wufoo.com/
How does the website create the cool buttons on the homepage? With CSS, JavaScript? The hover effect is the best i've seen.
The buttons i'm on about are 'Custom Branding' etc!

A: The effect is created using CSS3 transitions and a hover effect.
When the link is hovered, the background position is changed, and a transition causes it to animate smoothly.
Additionally, each link contains an icon in the upper-right. The icons are then transformed to rotate and scale, again with transitions which cause them to animate smoothly.


text:
Q: Understanding the role of the species known as "PM" As a professional programmer I work daily with a species known as the "PM". While they usually go by that common acronym, it seems there are actually several discrete varieties: product managers, project managers, and program managers. There may be other species yet undiscovered. Through years of close observation and study, the subtleties of their differentiation elude me. I have only been able to determine their common responsibly: to communicate to me, the programmer, in the vaguest possible terms, what it is they think they want built. I then tell them, in the vaguest possible terms, when I think it will be delivered, and they go away.
So my question for the stackoverflow crowdsourcing juggernaut is this: please explain the differences between the product managers, project managers, and program managers. Please do so with out waving your hands, as I can not see them, and it doesn't help anyway.

A: Project Manager a person responsible for managing project, specifically its scope, quality of deliverables, deadlines, time spent, and budget. PM bears responsibility for all project deliverables. See my other answer for a drill down on PM responsibilities. On small projects PM wears multiple hats, but during bigger ventures may have others to help her (or him), such auxiliary jobs might carry the titles of:

*

*Project Co-ordinator is someone who co-ordinates project work between various parties involved and individual stakeholders.

*Project Administrator keeps reporting up to date, including project status, does all kinds of other administrative tasks.

*Project Expeditor does exactly what the title says: chases everyone up, removes obstacles from the project team's path and makes sure there is always steady progress.
Product Manager takes responsibility for a product and full product lifecycle. The products are normally created and evolved through a series of projects. The relationship between products and projects is many-to-many. A single project may contribute to many products' evolution and a single product requires several projects to keep carrying it from one lifecycle stage to another. It's also important that product lifecycle constitutes a series of states (such as "shipping the product" or "supporting the product") that are usually carried on as processes and state changes done as projects. Read on the difference between a project and a process.
Program Manager manages a series of interdependent projects aimed towards a common end. Some of the projects are executed in parallel, some sequentially. Program Management is fairly similar to project management, where individual tasks are replaced by entire projects. Think in terms of the space exploration program.
Obviously these titles are not set in stone and companies would often attribute a somewhat different meaning or completely redefine them. The definitions I've given are generally accepted within the management community.

A: I'll attempt to explain them as I've worked with them. Please do understand that the definitions can be murky and change from organization to organization.
Project Manager: Responsible for coordinating the schedule of the project within the engineering. This should be the one single person that management can go to in order to know the current status of the committed work for a given release. This person is typically hip deep in spreadsheets, Gantt charts and status meetings.
Product Manager: Responsible for the deciding which user-visible features will be on the plate for consideration in a given release. This person should be well versed in what the customer is attempting to use the software for and be able to act as a developer's resource for understanding what to build from a functionality point of view.
Program Manager: Essentially a project manager responsible for coordinating the release across the different disciplines in a company. This is the person who makes sure that marketing has the press release ready at the same time as engineering is ready to ship and that sales have been trained on the product.
These are how the last couple of companies I have worked for have defined the roles, but you will certainly see many variations.

A: Rather than focussing on subjective definitions of each of these roles (yes, they are subjective and you'll get 10 different answers from 10 different people), I would focus more on the task responsibilities of the individuals. A tool to help you with this is a RACI matrix (aka responsbility assignment matrix) which makes it clear who is responsible and accountable for activities.
This industry will go on creating new "manager" titles forever and a day. As far as I'm concerned, just tell me what they actually do upfront in the project then we'll refer back to that whenever there is ambiguity.

A: I read in the book (the title eludes me, but it has "Management Anti-Patterns" somewhere in it) that PM are usually developers elevated to a manager role, but who has no idea how to manage. And still developers want that role because that is one step up the hierarchy (and a higher pay bracket).
A good developer does not necessary means a good manager, and once you become manager, you got pressures coming from your peers and from the top, and some cannot cope with it. Some companies are 'enlightened' enough to develop a separate career track for developers and have their pay match those of the managers.
I'm sure you come across one of the more introvert species of PM. The last time I was in a mock PM situation (it's a software engineering module which we have to do paperwork, like SCRUM) I was chasing my team-members for updates every week and doing code reviews. So that's one perspective for you.


text:
Q: How to get the count of joined table (HABTM) Is there a way to get the count of items connected using HABTM?
For example I have tables Users and Tags. (and another one tags_users)
user model has the following:
public $hasAndBelongsToMany = array("Tags");

I can do simply $this->User->find("all") and I get the users and connected tags from the Tags table.
But instead of getting the tags I want to get the amount of the tags (count) for every user.
How to do this in cake?

A: I found a simple solution:
In the User Model I just specify a virtualfield:
public  $virtualFields = array(
  'tag_count' => 'SELECT count(*) FROM tags_users WHERE user_id = User.id'
  );


text:
Q: SQL Server 2014 Install Failed with The computer must be trusted for delegation and the current user error I'm attempting to install SQL Sever 2014 newly installed Windows Sever 2012 R2 Standard edition OS.  During the GUI portion of the installation it fails with the following error:

There was an error generating the XML document.

Looking at the detail.txt files I see the following error:

(01) 2015-09-14 19:32:31 Slp:             Message:  (01) 2015-09-14
  19:32:31 Slp:                         The requested operation cannot
  be completed. The computer must be trusted for delegation and the
  current user account must be configured to allow delegation. (01)
  2015-09-14 19:32:31 Slp:                          (01) 2015-09-14
  19:32:31 Slp:             HResult : 0x80090345 (01) 2015-09-14
  19:32:31 Slp:             Stack:  (01) 2015-09-14 19:32:31 Slp:
  at System.Security.Cryptography.ProtectedData.Protect(Byte[] userData,
  Byte[] optionalEntropy, DataProtectionScope scope) (01) 2015-09-14
  19:32:31 Slp:                         at
  Microsoft.SqlServer.Common.SqlSecureString.WriteXml(XmlWriter writer)
  (01) 2015-09-14 19:32:31 Slp:                         at
  System.Xml.Serialization.XmlSerializationWriter.WriteSerializable(IXmlSerializable
  serializable, String name, String ns, Boolean isNullable, Boolean
  wrapped) (01) 2015-09-14 19:32:31 Slp:                         at
  Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAgentConfigurationPublic.Write6_AgentConfigurationPublic(String
  n, String ns, AgentConfigurationPublic o, Boolean isNullable, Boolean
  needType) (01) 2015-09-14 19:32:31 Slp:                         at
  Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAgentConfigurationPublic.Write7_AgentConfigurationPublic(Object
  o)

I've attempted to do the install as administrator same issue either way.

A: I was able to resolve the issue by creating a local account adding that account to the administrators account.  I think this might have been a domain issue as this server is in a different domain than my own.  A local account worked to get the installation to complete.
Used this link for the answer:


text:
Q: .htaccess, proper rewriting of directory and file with same name As of now my website has a few static pages, one of which is /portfolio. Among other things, my htaccess hides the .html extension.  I'd like to add a portfolio directory, but I do not want to move my existing portfolio page into the portfolio directory as the default index file.  My /portfolio page is one of my Google sitelinks and I am afraid if it is moved or if the url changes in someway, Google will consider it to be a brand new page.
My problem is once I add the /portfolio/ directory, whenever I try to visit the original /portfolio page, a trailing slash is automatically added and it links to the directory itself.
I've tried countless options, one being a rewrite of /portfolio/ to /portfolio, however this creates an infinite loop.  I also tried "DirectorySlash Off" but that only removed the trailing slash while being inside the directory, it didn't revert access to the original /portfolio page.
Ultimately, I would like to keep my /portfolio page as-is, linking to pages inside the directory like so /portfolio/example and if either /portfolio or /portfolio/ is accessed it will result in showing the same page which is outside of the directory without Google thinking it is duplicate content.
A similar question exists here:
.htaccess rewriting url to page or directory though this still resulted in an infinite loop for me for some reason, I'm guess it has something to do with the hidden extensions.
Here's my htaccess-

RewriteEngine On

# HTML to PHP
RemoveHandler .html .htm
AddType application/x-httpd-php .htm .html

# Hide extension
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

# Force WWW
RewriteCond %{HTTP_HOST} ^mydomain\.net
RewriteRule ^(.*)$ http://www.mydomain.net/$1 [R=301,L]

# Blog Subdomain
RewriteCond %{HTTP_HOST} ^blog.mydomain.net$
RewriteRule ^(.*)$ http://www.mydomain.net/blog/$1 [R=301,L]

I know it's not a great idea having a directory with the same name as a static page, but I really would rather not alter the existing page and lose the Google sitelink, so a clean and proper way to handle this would be a help.

A: There are two things going "wrong" here, and two ways to fix it.
The first is that apache "figures out" that there is a directory by the name of "portfolio" before the rewrite conditions are applied. That means that the rewrite conditions are receiving "portfolio/" instead of "portfolio".
Second, the "!-d" rule is specifically avoiding the rewrite that you want to make if there is in fact a directory by that name
Solution 1: Manually re-route requests for the portfolio directory to remove the slash.
# Manually re-route portfolio/ requests to portfolio
RewriteCond %{REQUEST_FILENAME} portfolio/$
RewriteRule ^(.*)/$ $1

# Hide extension
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

Note the removal of the "!-d" condition.
The downside to this is that you are having to hard-code the "portfolio" edge case directly into the rewrite rules, and will still result in the browser being first redirected to portfolio/
Solution 2: Set DirectorySlash Off and remove directory exists test
# Disable Automatic Directory detection
DirectorySlash Off

# Hide extension
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

Setting DirectorySlash Off would fix this issue the best, but may break other parts of your site where you actually want the auto DirectorySlash. Best of Luck, and I hope this helps.
Note when testing solution 2, your browser may remember the redirect of "portfolio" to "portfolio/" and perform the redirect before it even sends the request to the server. Be sure to test in a cache-clear, clean environment for best results.


text:
Q: How can get total amount users without duplicate? I have the table payments, I need get total amount users with a limit 3
SELECT SUM(money),username FROM `payments` ORDER BY money DESC LIMIT 3

Table:
+----------+--------+
| username | money  |
+----------+--------+
| Alex     | 200    |
+----------+--------+
| Alex     | 100    |
+----------+--------+
| John     | 50     |
+----------+--------+
| Emily    | 400    |
+----------+--------+
| etc ...

How i can get this result? :
+----------+--------+
| username | amount |
+----------+--------+
| Emily    | 400    |
+----------+--------+
| Alex     | 300    |
+----------+--------+
| John     | 50     |
+----------+--------+

A: as you need user wise total so, you've to add group by clause
You can try below - you need to add group by clause
SELECT username, SUM(money) AS amount
FROM payments
GROUP BY username
ORDER BY amount DESC
LIMIT 3;


text:
Q: datatables pagination with serverside get api I am facing an issue in javascript datatables. I want to add pagination in table
My Code
// i want to pass get api in datatable .. how should i do

 $('#example').dataTable( {
  "pagingType": "simple",
  "searching": false,
  "bFilter": false,
  "ajax": 'https://gencomp.com/api/v2/emails',   //not working
   "order": [[ 0, "desc" ]]
 } );

API:
`https://gencomp.com/api/v2/emails?per_page=100&page=${page}`;

i want to display my page1 and page2 and so on.. previous and next can't move on page2
how can i do? anyone please help me?
Screenshot


text:
Q: Pyschools Topic 13 Q 9 csv.writer I've come up with two different functions for this exercise.  One using the csv class writer and one with the DictWriter class.  Both pass the expected results listed but, they fail the private test cases?
import csv
def csvWriter(filename, records):
    header = []
    for i in records:
        if len(i) < 1:
          records.remove(i)
    for i in records:
        for v in i:
          if v not in header:
            header.append(v)
    for i in records:
        if len(i) == 0:
            return '0 records processed.'
    test=open(filename,'w')
    wr = csv.writer(test,header,lineterminator='\n')
    wr.writerow(header)
    for i in records:
        wr.writerow(i.values())
    test.close()
    return '%d records processed.' % len(records)

csvWriter('filename',[{'a':1,'b':2},{'a':3,'b':4}]
repr(open('filename').read()) --->  'a,b\n1,2,\na,b\n3,4' check
'2 records passed.' ---> '2 records passed.' check
Private Test Cases ---> Failed ?

A: The reason this function was failing on the Private Test Cases was, that a second argument could be passed and the values would be written without being sorted.
import csv
def csvWriter(filename, records):
  header = []
  for i in records:
    if len(i) < 1:
      records.remove(i)
  for i in records:
    for v in i:
      if v not in header:
        header.append(v)
  for i in records:
    if len(i) == 0:
      return '0 records processed.'
  test=open(filename,'w')
  dict_wr = csv.DictWriter(test,header,lineterminator='\n')
  dict_wr.writerow(dict(zip(header,header)))
  for i in records:
  # Adding in the **sorted** built-in fixed it
    dict_wr.writerow(dict(zip(header,sorted(i.values()))))
  test.close()
  return '%d records processed.' % len(records)

Still pretty rough, we weren't suppose to use the csv module either.  I'm going go back to improve upon this and give it a try without the module.
Any suggestions?

A: import csv
def csvWriter(filename, records):
header = []

f = []
with open(filename, 'w')as new_file:

    csv_writer = csv.writer(new_file,header,lineterminator='\n')

    for line in records:
        if line not in header:
            header.append(sorted(line))
            header.append(sorted(line.values()))
            for x in header:
                if x not in f:
                    f.append(x)
                    csv_writer.writerow(x)
return '%s records processed.' % len(records)


text:
Q: Android PullToRefresh library clipping view issue in PullToRefreshScrollView Video of the issue here
Link to the library
The video might be a little hard to see, but what is happening is the content in the ScrollView is clipping strangely when I add a new fragment to the Activity. Instead of smoothly animating down, creates an extra margin of about 55 px (on a 720 x 1280 phone), then corrects itself once the animation completes.
I dug around the source code and found that if I comment these two methods out of the onSizeChanged() method of the PullToRefreshBase class, the animations will work correctly:
@Override
protected final void onSizeChanged(int w, int h, int oldw, int oldh) {
    if (DEBUG) {
        Log.d(LOG_TAG, String.format("onSizeChanged. W: %d, H: %d", w, h));
    }

    super.onSizeChanged(w, h, oldw, oldh);

    //TODO both of these methods below combined cause the glitchy issue

    // We need to update the header/footer when our size changes
    refreshLoadingViewsSize();

    // Update the Refreshable View layout
    refreshRefreshableViewSize(w, h);

    //TODO both of these methods above combined cause the glitchy issue

    /**
     * As we're currently in a Layout Pass, we need to schedule another one
     * to layout any changes we've made here
     */
    post(new Runnable() {
        @Override
        public void run() {
            requestLayout();
        }
    });
}

The refreshLoadingViewsSize() and refreshRefreshableViewSize() methods are what cause the problem, together. But, when I comment them out, the PullToRefresh functionality doesn't work anymore. This is because the first method, which sets the header size, isn't being called. This means the header height is always 0, which breaks the pulldown functionality, which relies on the height of the header to work. Furthermore the header itself won't even show up, and that doesn't work.
Commenting just one out will make the clipping problem even worse, unfortunately.
I also tried a hacky fix, where I run those two methods only on the first call of onSizeChanged, and ignore them afterwards. Like this:
if(mFirstGo) {
    // We need to update the header/footer when our size changes
    refreshLoadingViewsSize();

    // Update the Refreshable View layout
    refreshRefreshableViewSize(w, h);

    mFirstGo = false;
}

This works great except for one problem. When the fragment is added, the padding is incorrectly set so that the content of the ScrollView is higher than it should be. This is because the padding is set the first time, but then is never reset again. It's like if the padding is 0 the entire time that isn't a problem, but if it is set at first, it needs to continue to be reset each time the view size changes.
I think the cause of this issue is the padding change happening independently of the view change, but I'm not exactly sure. If anyone has some insight here I'd really appreciate it. Thanks!


text:
Q: split string using to words using the empty spaces and storing them in a list using python for example i have this string :
ch = "promotion bac 2019"
and an empty list :
t=[]
i want to make the list get each word separately using the empty spaces
result will be :
t=["promotion","bac","2019"]
i tried deleting each word from the string after storing it in the list but i didn't work properly . dont mind looking at my code its really bad
def splitword (ch,t):
    i=0
    while len(ch)!=-1:
            if ch[i]== " " :
                t.append(ch[0:i])
                ch=ch.replace(ch[0:i],"")
            else :
                i=i+1

t=[]
ch = "promotion bac 2019"
splitword (ch,t)
print(t)

A: To split a string into words delimited by space you can use s.split(' ').
However, if want to implement the code to perform the splitting then can iterate over the string for each character and check if that character is a space or not then assemble the words.
def splitword(s):
  w = ''
  words = []
  for ch in s:
      if ch == ' ':
          if len(w) != 0:
              # have a new word to add to list
              words.append(w)
              # clear w for next word
              w = ''
      else:
          # append character to next word
          w += ch
  # check last word
  if len(w) != 0:
      words.append(w)
  return words

s = "promotion bac 2019"
t = splitword(s)
print(t)

Output:
['promotion', 'bac', '2019']

A: here the fixes for your code

def splitword (ch,t):
     i=0
     while i != len(ch):
         if ch[i]== " " :
             t.append(ch[0:i])
             ch=ch.replace(ch[0:i+1],"") # need to add 1 for the end position
             i = 0  # reset position
         else :
             i=i+1
     if ch:
        t.append(ch)  # add the last word
t=[]
ch = "promotion bac 2019"
splitword (ch,t)
print(t)

But from my side of view the @Sayse has gave you good advice about the split function.


text:
Q: How to merge two tables where one is parent of the other? I am trying to merge two tables together and maintain the fact that one is the child of the other table. i want to show that it has a parent while still maintaining the parent with its unique values.
here's what i have in relations:
subdomain.domain_id is related to (you guessed it) domain.id
my table examples
domain:
id | name | description | validator | need | need_amount
---|------|-------------|-----------|------|-------------
5  | prog | this iss..  | 6         | low  | 5

subdomain
id | name | description | validator | domain_id | need | need_amount
---|------|-------------|-----------|-----------|------|------------
5  | java | java is...  | 10        | 5         | high | 10
6  | c++  | c++...      | 9         | 5         | high | 10

i want to be able to see
id | domain_name | subdomain_name | description | validator | need | need_amount
---|-------------|----------------|-------------|-----------|------|-------------
5  | prog        | null           | this iss..  | 6         | low  | 5
5  | prog        | java           | this is...  | 10        | high | 10
6  | prog        | c++            | this is..   | 9         | high | 10

OR like this, (ideally the one above)
id | name         | description | validator | need | need_amount
---|--------------|-------------|-----------|------|------------
5  | prog         | this iss..  | 6         | low  | 5
5  | prog - java  | java is...  | 10        | high | 10
6  | prog - c++   | c++...      | 9         | high | 10

Any ideas??? is it possible? Thanks!
Thanks to @Pradeep
SELECT id,
       name AS domain_name,
       NULL AS subdomain_name,
       description,
       validator,
       need,
       need_amount
FROM   domain
UNION ALL
SELECT a.id,
       b.name AS domain_name,
       a.name            AS subdomain_name,
       a.description,
       a.validator,
       a.need,
       a.need_amount
FROM   subdomain a join domain b on a.domain_id=b.id

A: try this.
SELECT id,
       name AS domain_name,
       NULL AS subdomain_name,
       description,
       validator,
       need,
       need_amount
FROM   parent
UNION ALL
SELECT a.id,
       b.domain_name AS domain_name,
       a.name            AS subdomain_name,
       a.description,
       a.validator,
       a.need,
       a.need_amount
FROM   child a join parent b on a.domain_id=b.domain_id


text:
Q: Haskell, returning String while using IO Integer to compute that string Today I ran into the following problem:
I can read the current screen resolution in Haskell using Xlib-bindings using a function called getScreenWidth (--> I get an IO Integer). This is working so far.
Now I want to use that value as a label for a plugin of my desktop environment (xmonad). The plugin infrastructure only allows a function mapping a "WorkspaceId" (which basically is an integer) to a String.
...
-- Constructor for PrettyPrint:
ppCurrent :: WorkspaceId -> String
...

Currently I am using my own function to map an ID to a String, which is working:
myPPCurrent :: WorkspaceId -> String
myPPCurrent x = "Desktop: " ++ show x

The output is as expected "Desktop: 1" (or whatever ID i am on).
Now I want it to be "Desktop: 1 (1680px)" where 1680 equals the return value of getScreenWidth.
My Problem: getScreenWidth returns IO Integer, so I can not simply use,
myPPCurrent x = do
    y <- getScreenWidth
    return "Desktop: " ++ show x ++ show y

since i the return type isn't String. Google told me, that I can not convert "IO Integer" to "Integer" in Haskell, so I really have no clue, how I can keep the prototype/constructor (however Haskell calls it) "WorkspaceId -> String" while using an "IO Integer" to generate that String.
Is that even possible at all? If so, how?

A: I've never used XMonad: I'm basing this answer on general Haskell knowledge and what I've found on the internet in 2½minutes.
Anyway, I'm assuming somewhere you have a main that calls xmonad.
main = xmonad myConfig

Or maybe
main = xmonad XConfig {
          normalBorderColor = "#8080ff",
          -- etc

Or whatever. Let's look at the types.
main :: IO ()
xmonad :: (LayoutClass l Window, Read (l Window)) => XConfig l -> IO ()
myConfig :: XConfig l -- whatever type `l` is

Now suppose instead of myConfig, we have
makeMyConfig :: IO (XConfig l) -- I still don't know what `l` is

makeMyConfig isn't a configuration --- it's something that will make a configuration at runtime, potentially depending on files from disk, or the time, or the screen resolution.... You use it like so:
main = do
    config <- makeMyConfig
    xmonad config

And the point is that because the XConfig l we're using now is derived from an IO (XConfig l), it can incorporate Strings derived from IO Strings and Integers derived from IO Integers, etc. So that's your in for using getScreenWidth in your configuration.

A: You can't leave the IO monad once you're in it, so you'll need to return an IO String instead of a String e.g.
myPPCurrent :: WorkspaceId -> Integer -> String
myPPCurrent x = "Desktop: " ++ show x ++ show y

getWorkspaceName :: WorkspaceId -> IO String
getWorkspaceName id = do
    w <- getScreenWidth
    return $ myPPCurrent id w


text:
Q: MERGE doesn't work in SQL 2008 R2 when SQL 2005 is installed To install our application we use a setup created ad hoc, which (together with many other operations) runs some scripts, including a script that contains the MERGE clause. The minimum requirement is to use MS SQL Server 2008 R2.
A customer get an error when trying to execute the script described above, which says:
Error: Incorrect syntax near the keyword 'MERGE'.

I'm trying to figure out why, since he is using a SQL 2008 R2 database. I've discovered that in the same machine there's a SQL 2005 installation. Could this cause a conflict? Can this has something to do with compatibility level? If I try to run the same script via the SQL 2008 R2 SSMS it works.


text:
Q: Проблема с кросс-доменным запросом node.js сервер:
var express = require('express');

var app = express();

app.get('/', function(req, res) {

     res.sendFile('index.html');

});

app.listen(8080);

index.html:
<html>
 <script>
  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://yandex.com', true);
  xhr.onload = function() {
     document.write( this.responseText );
  }

  xhr.send();
</script></html>

Oшибка:

В чем проблема?

*

*Браузер - yandex

*ОС - Windows

A: Кроссдоменные запросы запрещает браузер в целях безопасности.
Используй jsonp для этих целей


text:
Q: unlocking screen returns to login (lightdm) Unlocking the screen for an openbox session returns to the lightdm login screen. I want to not return to lightdm or allow to switch away from the current logged in user. Had this working in 16.04 but running into issues with 20.04.
Using xautolock, light-locker or gnome-screensaver returns to lightdm after unlocking.
edit: Login back via lgihtdm does resume the session at least.


text:
Q: I need a no-arg constructor in my subclass, but superclass has defined constructor I'm dealing with the Square super class. It has a defined constructor where it takes a double value for side. I have to make a subclass that has a no-arg constructor that sets side to 10. If the super class does not have a no-arg constructor, is it even possible to do this?
Thanks in advance.
public class Square
{
private double side;

public Square (double s)
{
     side = s;
}
}

public class MySquare extends Square
{
private double area;

 public MySquare(double s){
  super(s);

}
}

A: You need to just add a no-arg constructor to the subclass and invoke the superclass constructor with the correct value using the "super" method
public class Square {

    private double side;

    public Square(double s) {
        side = s;
    }
}

public class MySquare extends Square {

    private double area;

    public MySquare(double s) {
        super(s);
    }

    public MySquare() {
        super(10);
    }
}


text:
Q: Can I answer old/dead questions with posts from my blog? I've never asked a question on Stack Overflow before.  But I've been to SO quite often after Googling for answers to my questions.  And every now and then, I end up at these great questions which I would love an answer to, but I find the answers unsatisfying (or just nonexistant).
I also write blog posts about my "hard to crack" questions once I've found my answer (usually through hard work; there's no point writing a post about someone else's work unless I add something).  Now I would like to "contribute" this post back to old SO questions which failed me, so anyone else Googling for the same question and ending up on the old thread will see my blog post.
But it feels like spamming, especially if it bumps the question to the top and notifies everyone unnecessarily.  Chances are, the OP doesn't need an answer anymore.  The people I want seeing my answer are those who, like me, happen to get there through Google.
Is it okay for me to answer with blog post links on old/dead questions here on Stack Overflow?
--
P.S. I already read this: How to refer to your blog when answering?
I want to know about posting answers on inactive questions.

A: I think the consensus reached on those older questions you link to is just as valid for an old/dead question as it is for a newly posted one. Besides, an old question that is bumped by adding an answer will only transiently float to the top of the active list, and it probably won't appear on the hot list due to its age, so I doubt anyone will be all that bothered by the necroposting.
There's even a badge for answering old questions, so have at it!

A: There is no specific point in time at which a topic is declared dead and no one can revive it. No one's against it, either. Part of the concept of this site is that people in the future will be able to have their questions answered as best as possible; any knowledge that contributes to that is welcomed.

A:
Is it ok for me to answer with blog post links on old/dead questions here on StackOverflow?

For sure!
But, you should follow a few guidelines:

*

*Don't just post a link to the blog.

*Add some context.  Like: "I was also struggling with the same problem and here is how I solved it.

*Post quotes and small code samples from the blog.  Make your answer contain some value besides just a link to the blog.


text:
Q: Solve a system of diophantine equations I have a problem with elemental number theory. I started with the expression
$$
(a - \frac{1}{b})(b - \frac{1}{c})(c - \frac{1}{a})
$$
and task to find all natural $a,b,c$ so that the result of the expression is an integer.
I managed to show that-
$$ a | bc - 1$$
$$b | ac - 1$$
$$c | ab - 1 $$
But I don't know how to solve this 3 equations. Is there even enough data?

A: Expand to get $abc|ab+ac+bc+1$.
Then $\frac{1}{a}+\frac{1}b+\frac{1}c+\frac{1}{abc}$ must be an integer. If $3 \le a \le b \le  c$,
then $\frac{1}{a}+\frac{1}b+\frac{1}c+\frac{1}{abc} \le \frac{28}{27}$. Now easy casework. ;)


text:
Q: Shared memory issue while debugging I am trying to use Nsight to debug the following code:
__device__ void change(int shared[])
{
    if(threadIdx.x<10)
        shared[threadIdx.x]=threadIdx.x;
}
__global__ void MyK()
{
    int shared[10];
    change(shared);
    __syncthreads();
}

I am calling my kernel in the main method like this :
cudaSetDevice(1);
MyK<<<1,20>>>();

When I put a breakpoint before change(shared), I can see that the shared array is created and its values are set to 0. However, if I put the breakpoint after __syncthreads(), the debugger shows the following error:

cannot resolve name shared

Can't I pass my shared array to another device function?

A: The reason why you see the "Cannot resolve name shared" in the memory watch window is because shared array is being optimised out by the compiler since it is not being used at all by any part of your kernel after change(shared). Like user586831 mentioned earlier, try outputing the value as your return value for your device function.
Also on another note, not sure if you really meant "_ shared _" array or referring to the array by its name 'shared'. Anyway you're not using shared memory in your code above. "int shared" is just a normal integer array type. You need to specify the _ shared _ qualifier in order to declare shared memory. For e.g. extern _ shared _ int shared[10]

A: Is that the actual code or you omitted _ _ shared _ _ from the buffer declaration ?
Keep also in mind that the _ _device _ _ functions get inlined by the compiler and that
the debugger can stop only at some point in the whole process.
Try to use a kernel of a multiple of at least 16 or 32 threads or otherwise you are not running
a full SP and that might trick the debugger.

A: Calling __syncthreads() for some and not all threads can cause a deadlock. threadIdx.x < 10 calls _syncthreads()
As previously mentioned you are not using shared memory here.
The compiler is clever if you are not using the value afterwards the memory location can become invalid.
Try outputing the value as your return value for your device function. Should work fine especially if you move/remove __syncthreads().


text:
Q: apache 2.4 don't find the SSL Certificate File I try to configure SSL on my apache 2.4.12 Webserver. But apache2 can't find the Certificate and Key File in the corespondening ssl directory. I already checked file permissions but without success. The Certificates are not empty and the same Certificates worked in a apache 2.0.64  ssl installation.
here the error message:
/usr/sbin/apache2 -f /etc/apache2/httpd.conf
AH00526: Syntax error on line 7 of /etc/apache2/mod_ssl.conf:
SSLCertificateFile: file '/etc/apache2/ssl/cert/server.crt' does not exist or is empty

here my mod_ssl.conf
cat mod_ssl.conf
    <VirtualHost _default_:443>
    #  General setup for the virtual host
    DocumentRoot "/var/www/"
    ServerName 192.168.2.1:443
    ServerAdmin you@your.address
    SSLEngine on
    SSLCertificateFile "/etc/apache2/ssl/cert/server.crt"
    SSLCertificateKeyFile "/etc/apache2/ssl/key/server.key"
</VirtualHost>

/etc/apache2/ssl/cert$ ll
drwxrwxrwx    2 www      www            232 Jan  1 01:57 .
drwxrwxrwx    4 www      www            288 Jan  1 01:54 ..
-rwxrwxrwx    1 www      www            863 Feb 10  2015 server.crt

/etc/apache2/ssl/key$ ll
drwxrwxrwx    2 www      www            232 Jan  1 01:56 .
drwxrwxrwx    4 www      www            288 Jan  1 01:54 ..
-rwxrwxrwx    1 www      www            916 Feb 10  2015 server.key

Has anyone come across something like this before?


text:
Q: Is it standard compliant to write font-size: 62.5%/1.2em in CSS? I noticed that some stylesheets have something like this:
body { font-size: 62.5%/1.2em; }

I got a warning "unexpected token /" when I wrote this in NetBeans. And if I changed the EM value, say,
body { font-size: 62.5%/1em; }

the computed font-size remained 16px.
My question is, Is it standard compliant to write something like that? And how to computed the actual font-size?

A: In CSS2, the font-size property does not allow a value of the form x/y.
What you're using is the font short hand property, which allows x/y as a short-hand of font-size: x; line-height: y;. So either use
body { font: 62.5%/1.2em sans-serif; }
/*                       ^^^^^^^^^^ the font-family is needed. */

or
body {
  font-size: 62.5%;
  line-height: 1.2em;
}


text:
Q: Solve $y''-xy'+y = 1 , y(0)=1, y'(0) = 2 $ with Laplace transform What's making me get stuck is the Laplace transform of $xy'$. I'm aware of different methods of solving this, but it's asking specifically for Laplace transform.

A: Note that if $y(x)$ has Laplace transform $\bar y (s)$, then

*

*$y'$ has Laplace transform $s\bar y - y(0)$

*$y''$ has Laplace transform $s^2\bar y - sy(0)-y'(0)$

*$xy'$ has Laplace transform $-\frac{d}{ds}\bar y$

So, $y''-xy + y = 1, y(0)=1, y'(0)=2$ becomes:
$$(s^2\bar y-s-2)+\frac{d}{ds}(s\bar y-1)+\bar y=\frac{1}{s}$$
Rearranging gives
$$s\bar y'+(s^2+2)\bar y=\frac{1}{s}+s+2$$
From which we see:
$$s^2\bar y'+(s^3+2s)\bar y=s^2+2s+1$$
Letting $u=s^2\bar y$, this becomes:
$$u'+sy=(s+1)^2$$
Using the integrating factor of $e^{s^2/2}$, we see:
$$\frac{d}{ds}(ue^{s^2/2})=(s+1)^2e^{s^2/2}$$
A bit of careful integration by parts gets us that $ue^{s^2/2}=(s+2)e^{s^2/2}+C$. We now have $u(s)=s+2+Ce^{-s^2/2}$, whence $\bar y=\frac{1}{s}+\frac{2}{s^2}+CL^{-1}(e^{-s^2/2})$, where $L^{-1}$ represents the Laplace transform.
Noting that $2x+1$ has Laplace transform $\frac{1}{s}+\frac{2}{s^2}$, we find this to be the solution for $C=0$.
I'm not entirely sure how to reconcile/deal with the case for $C\neq 0$. We've found a solution, in any case.


text:
Q: Simulink: Control Variant Subsystems Using Mask I would like to find a simple process for switching the model innards under a mask using the mask parameters.
This question has expanded enough such that it has been reimplemented here.
Variant subsystems are an excellent method and can be controlled via workspace parameters;
however, I have found mask parameters to not interface with the variant subsystem selection.
This link is the first of a series of posts on how to use mask parameters to make changes to blocks inside of the system;
however, the method is not as intuitive as using variant subsystems and a switch.
The link is also from 2008 and I believe that it may have been superceded at some point.
MWE
I have made a model containing a system labeled Source.
It is connected to a Display block which displays its output.
Source is a variant subsystem.
It contains 3 variants:

*

*Source\One

*Source\Two

*Source\Three.

Each variant contains one Constant block.
The value of the Constant block is eponymous with the block label.
For example, Source\Two contains a constant block with value 2.
Source is also a masked subsystem.
Its mask contains a Radio Button parameter with a value labeled variantValue.
The Radio Button options for the variantValue parameter are:

*

*Choice 1

*Choice 2

*Choice 3

The mask Initialization code is as follows:
switch variantValue

case 'Choice 1'
set_param('Source','OverrideUsingVariant','One')
disp('One')

case 'Choice 2'
set_param('Source','OverrideUsingVariant','Two')

case 'Choice 3'
set_param('Source','OverrideUsingVariant','Three')

end

I have set the variant to Override.
I cannot set the mask to allow library blocks to modify contents, as this is greyed out.
I will drop the variant subsystem deeper into the hierarchy from the masked subsystem when a masked subsystem which is a variant subsystem works.

A: To do anything which does not go via your base workspace, you first need to set the "Overwrite variant conditions...", now you can choose the active variant with code:
set_param('untitled/Variant Subsystem','OverrideUsingVariant','Variant1')

What remains is creating a mask which, whenever the parameter is changed in your mask, runs the above line. This can be done via the initialisation commands.


text:
Q: How to put array on loop multiple circle? I have try to draw multple circle with for. it works , but now i want to put array in a "for" part.
function draw_circle (circleX, circleY, radius, fill) {
      context.fillStyle = "black";
      context.fillRect(0, 0, 800, 300);

      context.strokeStyle = "red";
      context.strokeRect(5, 5, 790, 290);

      context.fillStyle = fill;
      context.arc(circleX, circleY, radius, 0, Math.PI*2);
      context.fill();
 }

 function draw_multiple() {
      var i;
      var circles = []; // How to put array so this code will work with array?
      for(i = 0; i < 10 ; i++) {
      draw_circle ((i*70)+100,100, 30 , "cyan");
      }
 }

 draw_multiple();

A: I think you want to call draw_circle for multiple circles and circles information would be in array. If that is the case then check the code snippet below:
Here, we have created a circle class which will hold all the properties like origin, radius, fill color etc. We can create instances of this class and add them in array to have a circles collection. We also have a draw method in circle class so that circle can draw itself. Now, in our drawCircles method we have added circles in collection and passed parameters in circles constructor. Now, we can call draw method on all objects in collection. You can also separate the object creation and drawing logic based upon when you want to perform these actions e.g. say on page load or in some ajax call you have got the circle information. Then you can add them to collection may be singelton or global collection based upon how you want to manage things. I would not suggest global variable though. You can then associate drawCircle method with some control event like button click etc.

<canvas id="centerdCircles" width="600" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<input type="button" value="Draw Centerd Circles" onclick="drawCenterdCircles();"/>

<canvas id="separateCircles" width="600" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<input type="button" value="Draw Separated Circles" onclick="drawSeparatedCircles();"/>


text:
Q: Is there a list for iOS app exit codes? There is global method exit which takes exit code and exits the app. I thought that using it was discouraged but then I saw WWDC video where they normally used it.
Question 1: I have good reason to actually call exit in my app. If I do call it could it cause problems with app review?
Question 2: If I call it I would like to pass proper exit code. Where can I find list of exit codes with their meaning?
Edit: The UI of the app is not visible at the time when I would like to call exit. The user will have no way to notice it was called. So recommendation from Apple's Human Interface Guidelines (not to call it because users would perceive it as crash) does not apply.


text:
Q: You don't have the permission to access the requested resource error is geven when a post request is sent I am tring to send a 'POST' request and catch it from python backend. I use flask python framework. Actually, I am doing changes to already developed application.
in the templates I found the code that generate the relavent html.

                        Upload files for the customer {{customer.CustomerName}}.

                    <form method="POST"  action="/admin/customers/{{ customer.ID }}/file_uploading/">

                            <button type="submit" class="btn btn-transparent">Upload</button>
                    </form>

Here, I try to catch the POST request.
@app.route('/admin/customers/<cust_id>/<action>/', methods=[ 'GET', 'POST' ])
@login_required
def main_admin_customers(cust_id=None, action=None, subaction=None):
 if cust_id == None:
        c = customers.customer_details()
        return render_template('admin_customers_list.html',
            customers=c.list_customers())
    else:
        if cust_id.isdigit():
            cust_id = int(cust_id)
            c = customers.customer_details(customerid=cust_id)
            cust_data = c.retrieve_customer()
            if cust_data == None:
                return error_message(message='No such customer.')
            else:
                user = request.cookies['username']

                if action == None:
                    s = scheduling.schedule(customer_id=cust_id)
                    return render_template('admin_customers_view.html')

                # file uploading
                # if the action is file_upload and required file is there
                # upload it to the file server.
                # file url and relevent information should be store in the database
                # files will be categorise for each customer from their ID.

                elif action == 'file_uploading':
                    return redirect(url_for('main_admin_customers',
                        cust_id=cust_id))

                 # Simple asset creation
                elif action == 'create_asset':
                    pass

However, I get the following error
Forbidden

You don't have the permission to access the requested resource. It is either read-protected or not readable by the server.

However, when I debug the code, as soon as I submit the form, I get the above error message. It didn't even hit the break points at main_admin_customers.
What is the mistake I've done here?

A: Following page explain the reason. Basically, I need to include csrf token.
https://flask-wtf.readthedocs.org/en/latest/csrf.html
If the template has a form, you don't need to do any thing. It is the same as before:

<form method="post" action="/">
    {{ form.csrf_token }}
</form>

But if the template has no forms, you still need a csrf token:

<form method="post" action="/">
    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />
</form>


text:
Q: Tmux regex or wildcard search I can do ctrl+b [ ctrl+r to search upwards through my tmux window.
But is it possible to find a line containing, say, foo and bar but not contiguously?
I'm imagining doing something like:
:foo.*bar

I'm searching through logs outputted to stdout, so the results have to be on one line to be relevant.

A: C-b C-r doesn't do anything by default, it would be helpful if you show what you have bound it to, although I assume it is some variant of copy-mode \; send -X search-backward ....
Anyway, searching with regular expressions is supported since tmux 3.1.


text:
Q: Neo4j: Relationships I am currently working on a project which aims to use graph databases, in particular Neo4j. My question concerns how to create the "Relationship" relations between the different nodes, for information, the data to be used is in CSV format, in this case, I will import data that is in .csv format, first we create the nodes based on this data, then we move on to creating the relationships between the different nodes.
I tried a lot of code but we didn't get the desired result regarding the creation of relationships between nodes.
I used the following code:
Load csv with headers from "file:///airports.csv" as airports create (a1: Airport {label: airports.label, city: airports.city, state: airports.state})
match (n) return (n)

Load csv with headers from "file:///flights.csv" as flights create (n: Flights {flight: flights.flight, airline: flights.airline, capacity: flights.capacity})
match(n) return(n)

while the nodes are created.
but neither do relationships. in addition I had the following message: (no changes, no records) this after the execution of the following code:
Load csv with headers from "file:///flights.csv" as flights match (a: Flights {flight: flights.flight}), (b: Airport {label: flights.arrive}) create (a) –[r : Arrivals] -> (b)
match (n) return (n)

Load csv with headers from "file:///flights.csv" as flights match (a: Flight { flight: flights. flight}), (b: Airport {label: flights. depart}) create (a) –[r : Departures] -> (b)

match (n) return (n)

To inform you, I have two tables of data whose extension .csv one for airports and the other for flights.
How should we create the relationship that exists between airports and flights? I don't know where is the error.

A: I agree with jose_bacoy to check that all of these fields actually match each other.
Also. you don't need to process flights.csv three times. You can use a MERGE statement that will either create the node or match it if it already exists. Then with one pass through the file, you can:

*

*Create the flight (or match it)

*Create the relationship to the departure airport

*Create the relationship to the arrival airport

LOAD CSV WITH HEADERS FROM "file" as flights
MERGE (n: Flights {flight: flights.flight, airline: flights.airline, capacity: flights.capacity})

MERGE (n)–[:Departures]->(b: Airport {label: flights.depart})

MERGE (n)-[:Arrivals]->(c: Airport {label: flights.arrive})

This will also create the Airport nodes if they do not exist.


text:
Q: join with prefix string Have two MYSQL tables need them to join. Orders table has conso column as primary key
CONSO TABLE
CONSO(p_key)     | sku      |Tally_Name
-------------------------
f|HP3001         | HP3001   |Computer_Accessory
f|XP3001         | XP3001   |XPRO
f|YP3001         | YP3001   |YPRO
a|HP3001         | HP3001   |Computer_Accessory
a|XP3001         | XP3001   |XPRO
a|YP3001         | YP3001   |Computer_Accessory

ORDER TABLE
f|sku
-----
HP3001
YP3001
XP3001
XP3001
Hp3001

Result expected is to concat with prefixstring 'f|` and join
concat ('f|',order.f|sku)= conso.conso
f|sku   | Tally_Name
--------------------
HP3001  |Computer_Accessory
YP3001  |YPRO
XP3001  |XPRO
XP3001  |XPRO
Hp3001  |Computer_Accessory


text:
Q: Позиции фигур sfml и box2d Всем привет. У меня возникла такая проблема - тела box2d не совпадают с координатами sfml. Я знаю, что box2d работает с метрами и рисует фигуры относительно центра, в то время как sfml рисует фигуры в пикселях и относительно левого верхнего угла. Но результат разочаровывает.
BodyDef.position.Set((object.getAABB().left + (object.getAABB().width/2.f))/30.f,
                     (object.getAABB().top + (object.getAABB().height/2.f))/30.f);
Shape.SetAsBox((object.getAABB().height/2.f)/30.f, (object.getAABB().width/2.f)/30.f);

Object - это прямоугольник, который имеет координаты sfml. Первой строкой я получаю его координаты по X и к ним прибавляю его длину делённую на 2. Аналогично с координатой по Y. Таким образом я получаю координаты центра фигуры и делю их на 30, чтоб перевести координаты в пикселях - в метры, чего требует box2d. Далее, в последней строке, я задаю фигуру, которая должна стоять на месте этих координат. Box2d рисует фигуру от её центра, поэтому я высоту и ширину делю на два и перевожу их в метры. В box2d используется система международная система Си (кг, метры, секунды).

A: Я решил проблему! Всё дело в том, что я неправильно понимал AABB. Вот правильный фрагмент кода:
BodyDef.position.Set((object.getAABB().left + (object.getAABB().width/2.f) )/30.f,
                     ((object.getAABB().top + (object.getAABB().height/2.f)))/30.f);

Shape.SetAsBox((object.getAABB().width/2.f)/30.f, (object.getAABB().height/2.f)/30.f);


text:
Q: Illegal state exception caused by NoClassDefFoundError I'm trying to make a simple Android project that takes a json code, reads it and displays the output when i click on a button. I imported 2 external libraries, com.fasterxml.jackson.core.jar and com.fasterxml.jackson.databind.jar
here is the code,
package com.example.tejas.comon;

import android.support.v7.app.AppCompatActivity;

import java.io.File;
import java.io.IOException;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "myMessage";  long id;
    String firstname = "";
    String lastname = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void onClick(View view){
        try{

            ObjectMapper mapper = new ObjectMapper();

            JsonNode root = mapper.readTree(new File("E:\\a.json"));

            TextView textViewID =(TextView) findViewById(R.id.text_Id);
            TextView textViewFname =(TextView) findViewById(R.id.text_Fname);
            TextView textViewLname =(TextView) findViewById(R.id.text_Lname);
            //Get ID
            id = root.path("id").asLong();
            textViewID.setText((int)id);

            //Get Name
            JsonNode nameNode = root.path("name");
            if( nameNode.isMissingNode()){
                //do nothing now
            } else {
                firstname = nameNode.path("first").asText();
                lastname = nameNode.path("last").asText();

                textViewFname.setText(firstname);
                textViewLname.setText(lastname);
            }

            Log.i(TAG,Long.toString(id));
            Log.i(TAG,firstname);
            Log.i(TAG,lastname);
        }catch (JsonGenerationException e){
            e.printStackTrace();
        }catch (JsonMappingException e ){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}

and here is the error
 11-01 11:51:54.573 3561-3561/com.example.tejas.comon E/AndroidRuntime: FATAL EXCEPTION: main
   Process: com.example.tejas.comon, PID: 3561
   java.lang.IllegalStateException: Could not execute method for android:onClick
       at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
       at android.view.View.performClick(View.java:4780)
       at android.view.View$PerformClick.run(View.java:19866)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:135)
       at android.app.ActivityThread.main(ActivityThread.java:5254)
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    Caused by: java.lang.reflect.InvocationTargetException
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
       at android.view.View.performClick(View.java:4780)
       at android.view.View$PerformClick.run(View.java:19866)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:135)
       at android.app.ActivityThread.main(ActivityThread.java:5254)
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/fasterxml/jackson/annotation/JsonAutoDetect;
       at com.fasterxml.jackson.databind.introspect.VisibilityChecker$Std.<clinit>(VisibilityChecker.java:172)
       at com.fasterxml.jackson.databind.introspect.VisibilityChecker$Std.defaultInstance(VisibilityChecker.java:180)
       at com.fasterxml.jackson.databind.ObjectMapper.<clinit>(ObjectMapper.java:195)
       at com.example.tejas.comon.MainActivity.onClick(MainActivity.java:38)
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
       at android.view.View.performClick(View.java:4780)
       at android.view.View$PerformClick.run(View.java:19866)
       at android.os.Handler.handleCallback(Handler.java:739)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:135)
       at android.app.ActivityThread.main(ActivityThread.java:5254)
       at java.lang.reflect.Method.invoke(Native Method)
       at java.lang.reflect.Method.invoke(Method.java:372)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
    Caused by: java.lang.ClassNotFoundException: Didn't find class "com.fasterxml.jackson.annotation.JsonAutoDetect" on path: DexPathList[[dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-support-annotations-24.2.1_b6343c6d7c5e90b35a6cd0b4b81057315b662eb5-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-slice_9-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-slice_8-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-slice_7-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-slice_6-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-slice_5-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-slice_4-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-slice_3-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-slice_2-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-slice_1-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-slice_0-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-internal_impl-24.2.1_b359b2374d8440f9d50bbae0e692ec6e2c581da6-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-internal_impl-24.2.1_ab66133e1fbd3f516301dedaf0cec658eee394b0-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-internal_impl-24.2.1_a6744094956b1304b74e46941d88d9ac7aa74c2a-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-internal_impl-24.2.1_5e587ec0010893c0647a59d4eedb4d6a8a6d0204-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-internal_impl-24.2.1_14cece6c6722e9e44464e611791fca05f5804d5f-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-com.fasterxml.jackson.databind_d8adf718561770d2b8c122c749c1791ccbb850d4-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-com.fasterxml.jackson.core_21a86c83e902b6b59aaee614f85bafbfffc4ad8f-classes.dex", dex file "/data/data/com.example.tejas.comon/files/instant-run/dex/slice-com.android.support-support-vector-drawable-24.2.1_84bbb9c551b4ae409ae8

I imported both those external libraries properly and made sure that they were gradle sync.
IllegalStateException for onClick is a problem that is bugging me in my other projects to. Please can someone solve this problem?
Edit 1 : The XML file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.tejas.comon.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me !"
        android:id="@+id/myButton"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:onClick="onClick" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="ID:"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/text_Id"
        android:layout_alignParentTop="true"
        android:layout_alignStart="@+id/myButton" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="First Name:"
        android:id="@+id/textView3"
        android:layout_below="@+id/textView"
        android:layout_alignParentStart="true"
        android:layout_marginTop="45dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/text_Fname"
        android:layout_alignTop="@+id/textView3"
        android:layout_alignStart="@+id/text_Id" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Last Name:"
        android:id="@+id/textView5"
        android:layout_below="@+id/textView3"
        android:layout_alignParentStart="true"
        android:layout_marginTop="57dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/text_Lname"
        android:layout_alignTop="@+id/textView5"
        android:layout_alignStart="@+id/text_Fname" />
</RelativeLayout>

A: use these dependencies with latest version
1.jackson-databind
2.jackson-annotations
3.jackson-core


text:
Q: why after Hibernate4 save() the database will change? why after execute such code without flush(),database will change?
public static void main(String args[]){

ApplicationContext ac = new FileSystemXmlApplicationContext("src/main/resources/config/spring/spring-common.xml");

SessionFactory sessionFactory = (SessionFactory)ac.getBean("sessionFactory");

Session session = sessionFactory.openSession();

Student student = new Student();

student.setName("zyc");

session.save(student);
}

I use this class to create sessionFactory.
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

A: The "database will change" here if Student is defined to use IDENTITY for id generation.  Meaning that the insert for Student will happen immediately on the call to save for IDENTITY based generators.


text:
Q: Spring MVC session scoped bean used in different thread (parallelStream) In a spring MVC controller method I am currently trying to run a parallel stream where in a thread a session scoped (User) bean is used.  This results in a threading error since session scoped beans are ThreadLocal.
Is there a way to use a session scoped beans utilizing @Autowired in threads rather than manually setting up beans that will be used in threads (through setters)


text:
Q: Python backed PostgreSQL PSQL user INPUT name confused with invalid integer Intro:
I have been working on building a Python backed PostgreSQL database of a Swiss style tournament using Vagrant running a Ubuntu VM for my Relational Database course in Udacity.
Question:
Why is the user input name causing an integer error?
Vagrant:
vagrant@vagrant:/vagrant/tournament$ python tournament_test.py
1. countPlayers() returns 0 after initial deletePlayers() execution.
Traceback (most recent call last):
  File "tournament_test.py", line 151, in <module>
    testCount()
  File "tournament_test.py", line 26, in testCount
    registerPlayer("Chandra Nalaar")
  File "/vagrant/tournament/tournament.py", line 50, in registerPlayer
    cursor.execute("INSERT INTO players VALUES (%s)", (name,))
 psycopg2.DataError: invalid input syntax for integer: "Chandra Nalaar"
LINE 1: INSERT INTO players VALUES ('Chandra Nalaar')
                                    ^

SQL:
CREATE TABLE players (player_id SERIAL UNIQUE PRIMARY KEY, player_name
VARCHAR(40));

Python:
def registerPlayer(player_name):
    db = connect()
    cursor = db.cursor()
    cursor.execute("INSERT INTO players VALUES (%s)", (player_name,))
    player_id = cursor.fetchone()[0]
    db.commit()
    cursor.close()
    db.close()

Python (user input test):
registerPlayer("Chandra Nalaar")

Update 1:
So I altered the execute statement syntax to include the row specification as recommended by PRMoureu and I returned a new error.
Vagrant:
vagrant@vagrant:/vagrant/tournament$ python tournament_test.py
1. countPlayers() returns 0 after initial deletePlayers() execution.
Traceback (most recent call last):
  File "tournament_test.py", line 151, in <module>
    testCount()
  File "tournament_test.py", line 26, in testCount
    registerPlayer("Chandra Nalaar")
  File "/vagrant/tournament/tournament.py", line 50, in registerPlayer
    cursor.execute("INSERT INTO players (player_name) VALUES (%s)",
(player_name,))
psycopg2.ProgrammingError: column "player_name" of relation "players" does
not exist
LINE 1: INSERT INTO players (player_name) VALUES ('Chandra Nalaar')
                         ^

Which lead me to the conclusion that I am not using my current tournament database. So I went back to Vagrant and imported my file with \i which gave me a new error.
Vagrant:
    psql:tournament.sql:11: ERROR:  relation "players" already exists
So I updated my SQL file with DROP IF EXIST commands learned Here from another thread and was able to get through the Register_Player errors.
Thanks PRMoureu

A: In the INSERT statement you are using, it expects a value for all fields, with the player_id first (player_id is an integer).
You need to specify an ID :
cursor.execute("INSERT INTO players VALUES (%s, %s)", (a_new_ID, player_name,))

or change the syntax to this :
cursor.execute("INSERT INTO players (player_name) VALUES (%s)", (player_name,))


text:
Q: Error occurred while accessing Java Security Manager Privilege Block when change user password When i try to change passwords for users in carbon on API-M i get "Error occurred while accessing Java Security Manager Privilege Block", but passwords are changed despite on error. Passwords are not change for existing users, for new users passwords are change. Recently i changed certificates on API-M.
What is the problem? Do certificates affect on this error?

A: Your debug logs contains only client side exception
org.wso2.carbon.user.mgt.stub.UserAdminStub.changePassword(UserAdminStub.java:3678)
        at org.wso2.carbon.user.mgt.ui.UserAdminClient.changePassword(UserAdminClient.java:102)
In order to get an idea about actual backend exception have a look below places. You may probably remote debug the code based on APIM version you are using.
[1] https://github.com/wso2/carbon-kernel/blob/v4.4.26/core/org.wso2.carbon.user.core/src/main/java/org/wso2/carbon/user/core/ldap/ReadWriteLDAPUserStoreManager.java#L682
[2] https://github.com/wso2/carbon-kernel/blob/v4.4.26/core/org.wso2.carbon.user.core/src/main/java/org/wso2/carbon/user/core/common/AbstractUserStoreManager.java#L1108
[3] https://github.com/wso2/carbon-kernel/blob/v4.4.26/core/org.wso2.carbon.user.core/src/main/java/org/wso2/carbon/user/core/common/AbstractUserStoreManager.java#L176

A: "Error occurred while accessing Java Security Manager Privilege Block" is a generic error message comes from user core component. Please provide complete stack trace to investigate the issue.
You can put below entry
log4j.logger.org.wso2.carbon.user.core=DEBUG
to log4j.properties to get more information.
There is no direct relationship with certificates.

A: i enabled log4j.logger.org.wso2.carbon.user.core=DEBUG. When i try to change a password for user i get this:
DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Authorization cache miss for username : admin resource /permission/admin/manage/identity/usermgt/update action : ui.execute {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Allowed roles for the ResourceID: /permission/admin/manage/identity/usermgt/update Action: ui.execute {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: INTERNAL/admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Roles which have permission for resource : /permission/admin/manage/identity/usermgt/update action : ui.execute {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  INTERNAL/admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  admin user is in role :  INTERNAL/admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Authorization cache miss for username : alibek resource /permission action : ui.execute {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Allowed roles for the ResourceID: /permission Action: ui.execute {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: INTERNAL/admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Roles which have permission for resource : /permission action : ui.execute {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  INTERNAL/admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.common.AbstractUserStoreManager} -  Retrieving internal roles for user name :  alibek and search filter * {org.wso2.carbon.user.core.common.AbstractUserStoreManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  alibek user is in role :  INTERNAL/admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Searching for user alibek {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
 DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Using default configurations for the user DN cache, having search base : ou=Users,dc=wso2,dc=org {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
 DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Using default configurations for the user DN cache, having search base : ou=Users,dc=wso2,dc=org {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
 DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Searching for user with SearchFilter: (&(objectClass=person)(uid=alibek)) in SearchBase:  {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
 DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Using default configurations for the user DN cache, having search base : ou=Users,dc=wso2,dc=org {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
 DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  Name in space for alibek is uid=alibek,ou=Users,dc=wso2,dc=org {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
 DEBUG {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager} -  User: alibek exist: true {org.wso2.carbon.user.core.ldap.ReadOnlyLDAPUserStoreManager}
 ERROR {org.wso2.carbon.user.core.common.AbstractUserStoreManager} -  Error occurred while accessing Java Security Manager Privilege Block {org.wso2.carbon.user.core.common.AbstractUserStoreManager}
 ERROR {org.wso2.carbon.user.mgt.ui.UserAdminClient} -  Error occurred while accessing Java Security Manager Privilege Block {org.wso2.carbon.user.mgt.ui.UserAdminClient}
org.wso2.carbon.user.mgt.stub.UserAdminUserAdminException: UserAdminUserAdminException
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
        at java.lang.Class.newInstance(Class.java:442)
        at org.wso2.carbon.user.mgt.stub.UserAdminStub.changePassword(UserAdminStub.java:3678)
        at org.wso2.carbon.user.mgt.ui.UserAdminClient.changePassword(UserAdminClient.java:102)
        at org.apache.jsp.user.change_002dpasswd_002dfinish_002dajaxprocessor_jsp._jspService(change_002dpasswd_002dfinish_002dajaxprocessor_jsp.java:148)
        at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
        at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:439)
        at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:395)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:339)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
        at org.wso2.carbon.ui.JspServlet.service(JspServlet.java:155)
        at org.wso2.carbon.ui.TilesJspServlet.service(TilesJspServlet.java:80)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
        at org.eclipse.equinox.http.helper.ContextPathServletAdaptor.service(ContextPathServletAdaptor.java:37)
        at org.eclipse.equinox.http.servlet.internal.ServletRegistration.service(ServletRegistration.java:61)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.processAlias(ProxyServlet.java:128)
        at org.eclipse.equinox.http.servlet.internal.ProxyServlet.service(ProxyServlet.java:68)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
        at org.wso2.carbon.tomcat.ext.servlet.DelegationServlet.service(DelegationServlet.java:68)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.ui.filters.cache.URLBasedCachePreventionFilter.doFilter(URLBasedCachePreventionFilter.java:57)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.owasp.csrfguard.CsrfGuardFilter.doFilter(CsrfGuardFilter.java:88)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.wso2.carbon.tomcat.ext.filter.CharacterSetFilter.doFilter(CharacterSetFilter.java:65)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.filters.HttpHeaderSecurityFilter.doFilter(HttpHeaderSecurityFilter.java:124)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
        at org.apache.catalina.valves.RequestFilterValve.process(RequestFilterValve.java:364)
        at org.apache.catalina.valves.RemoteAddrValve.invoke(RemoteAddrValve.java:76)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
        at org.wso2.carbon.identity.context.rewrite.valve.TenantContextRewriteValve.invoke(TenantContextRewriteValve.java:80)
        at org.wso2.carbon.identity.authz.valve.AuthorizationValve.invoke(AuthorizationValve.java:91)
        at org.wso2.carbon.identity.auth.valve.AuthenticationValve.invoke(AuthenticationValve.java:60)
        at org.wso2.carbon.ui.valve.XSSValve.invoke(XSSValve.java:94)
        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:99)
        at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
        at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:57)
        at org.wso2.carbon.event.receiver.core.internal.tenantmgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:48)
        at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
        at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:62)
        at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:159)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
        at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:57)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1775)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1734)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:748)
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Authorization cache miss for username : admin resource /permission/admin/login action : ui.execute {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Allowed roles for the ResourceID: /permission/admin/login Action: ui.execute {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: INTERNAL/admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: TEST_SSL {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: INTERNAL/creator {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: MessageRole {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: SMROLE {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: identity {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: INTERNAL/subscriber {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: TestRole {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: INTERNAL/identity {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: INTERNAL/publisher {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  role: APPLICATION/TST01_TST01 {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Roles which have permission for resource : /permission/admin/login action : ui.execute {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  INTERNAL/admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  TEST_SSL {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  INTERNAL/creator {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  MessageRole {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  SMROLE {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  identity {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  INTERNAL/subscriber {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  TestRole {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  INTERNAL/identity {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  INTERNAL/publisher {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  Role :  APPLICATION/TST01_TST01 {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}
 DEBUG {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager} -  admin user is in role :  INTERNAL/admin {org.wso2.carbon.user.core.authorization.JDBCAuthorizationManager}


text:
Q: Network only works after login? I'm on linux academy RHCSA course and at the last test I have a VM that has to has its eth0 connection plugged off. So I turned it on with "nmcli con up eth0" and I went into "etc/sysconfig/network-scripts/ifcfg-eth0" and set "ONBOOT" to "yes". But it only connects when I log in to the VM. I can't just turn on a VM with virt-manager and ssh from the host terminal.

A: Run below command.
nmcli connection modify "System eth0" connection.autoconnect yes
Then
nmcli connection down ; nmcli connection up


text:
Q: How to decrypt encrypted string? I almost lost my mind trying to reverse this function, a friend of mine suggested to ask "the pros" so I am here.
<?php
$data = "Data to be encrypted";
$ceva = $data;
$textHos = 'MCRYPT_RIJNDAEL_128';
function encrypt($plaintext,$textHos) {
    $textLen=str_pad(dechex(strlen($plaintext)),8, '0', STR_PAD_LEFT);
    $salt='WSj2g7jTvc8ISmL60Akn';
    $textHosHash=hash('sha256',$salt.$textHos);
    $textHos= md5($textHos,true);
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $textHos,
                                 $plaintext, MCRYPT_MODE_CBC,$iv);

    $ciphertext = $iv . $textHosHash . $textLen . $ciphertext;
    $ciphertext_base64 = base64_encode($ciphertext);
    return  $ciphertext_base64;
}
$data = encrypt($ceva,$textHos);
echo $data;
?>

The output is:
P8avDeviXdd7bKfNMP0gwmZmZjg1OWMzOWFlNzRiMzU2Y2JiMTQ5OTY4MTI3MWNiYjQzYjBkMTAyNDUzM2ZhNGJjZmZhNzQ4M2QxN2M0ZGYwMDAwMDAxNN2xStdw/bhxIxSOevRp37HiXJeVXz7Ge31KEvq9dZjT

any help with resolving the encrypted text into a readable one again?
Thanks.

A: Your encrypt function makes a lot of nonsense and I hope it doesn't run in any production environment.
function encrypt($plaintext,$textHos) {
    // not needed..
    //$textLen=str_pad(dechex(strlen($plaintext)),8, '0', STR_PAD_LEFT);
    //$salt='WSj2g7jTvc8ISmL60Akn';
    //$textHosHash=hash('sha256',$salt.$textHos);

    $textHos = md5($textHos,true);
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
    $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $textHos,
                                 $plaintext, MCRYPT_MODE_CBC,$iv);

    // i commented out the unneccessary parts..
    $ciphertext = $iv /* . $textHosHash . $textLen . */ $ciphertext;
    $ciphertext_base64 = base64_encode($ciphertext);
    return $ciphertext_base64;
}

So whats left in the encrypted data is the iv vector (and 72 chars of some unneccessary data) and the encrypted data itself - encoded in base64
Reversing this is quite easy
function decrypt($ciphertext, $textHos) {
    $text = base64_decode($ciphertext);
    $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
    $iv = substr($text, 0, $iv_size);
    $textHos = md5($textHos, true);
    // the +72 is neccessary for your original code - the code above doesn't need this part
    $ciphertext = substr($text, $iv_size + 72);
    $encrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $textHos, $ciphertext, MCRYPT_MODE_CBC, $iv);
    return rtrim($encrypted, chr(0));
}

Note: DON'T USE THIS CODE IN PRODUCTION! Nowdays AES128 isn't safe


text:
Q: Draw faster circles with Python turtle I have an exercise wherein I have to draw a lot of circles with Python turtle. I have set speed(0) and I am using:
from turtle import*
speed(0)
i=0
while i < 360:
    forward(1)
    left(1)
    i+=1

to draw circles. It takes so long. Is there any faster way?

A: Have you tried turtle.delay() or turtle.tracer() ? See documentation here and here.  These set options for screen refreshing which is responsible for most of the delays.

A: Turtle has a function for drawing circles and the speed of that is much faster than going in a circle one step at a time.
 import turtle
 tina=turtle.Turtle()

 tina.circle(70)

It will look like this

If you want to draw your circle even faster, you can try adding a delay block as well.
import turtle
tina=turtle.Turtle()

tina.delay(1)
tina.speed(0)

A: You could draw fewer segments, so rather than 360 you go for 120:
while i < 360:
    forward(3)
    left(3)
    i+=3

That will make your circle less smooth, but three times faster to draw.

A: The circle() method might not be faster, but may be easier to manage:
turtle.circle()

A: Use Multithread to draw two semi circles simultaneously.
Initially the turtle will be at (0,0) so just clone the turtle and make them both face in opposite direction by 180° then draw semicircles. The code is below:
from threading import Thread
import turtle
t = turtle.Turtle()
t.speed(0)
def semi1(r):
   r.circle(50,180)
def semi2(t):
   t.circle(50,180)

r = t.clone()
r.rt(180)

a = Thread(target=semi1).start()
b = Thread(target=semi2).start()

This may draw the circle fast.


text:
Q: .append() produces different results for different argument types I am using JQuery and Jquery UI to create a dialog box which contains a custom form.  I have a basic dialog frame, which has a tool appended to its body.  So the basic structure of my dialog is Jquery UI Frame > Dialog Frame > ToolBody > Tool Content.
Code:

ToolManager.prototype.showTool = function(tool){
    var $container = $("#" + this.id);
    var $tool = $("#" + tool.id);
    var $toolBody = $("#" + this.toolBodyId);

    $container.dialog({
        resizable: false,
        modal: true,
        width: tool.width,
        stack: true,
        height: 'auto',
        draggable: true,
        close: this.tearDown,
        open: this.setup
    });

    $tool.removeClass("hidden");
    $toolBody.append($tool.html());
    //$toolBody.append($tool);
    $container.show();
};

This works despite its need for refactoring, however before using this method I was attempting to use the commented out line:
 $toolBody.append($tool);

This method wreaked havoc on my layout and caused the appended content to be blocked from receiving focus.  Can anyone explain the difference between appending a Jquery Object and appending an html string?  Or why it behaved this way?

A: AFAIK, an object is a reference to a DOM element, and not a copy of that element.
So can you can use html() to show all it's html content, or text() to show all it's text content, with tags removed.
You might be better off using clone() which makes an exact copy, and can be used in conjunction with appendTo()
Something like: $(tool).clone().appendTo().toolBody

A: This line of code:
$toolBody.append($tool);

Will take the nodes in $tool, and move them to the first (hopefully, the only) node of $toolBody.
This line of code:
$toolBody.append($tool.html());

Turns all of the HTML code inside of $tool and turns it into a string.  The jQuery Append method has sugar around it and is smart enough to realize that when you're attempting to append() a string, it should first turn that string into a set of nodes.
Effectively, you're moving the nodes in the former and case and doing a (poor) clone of the nodes inside of $tool in the latter case.


text:
Q: PhantomJS "SSL handshake failed" on HTTPS site, even when using all the flags PhantomJS will fail to load many HTTPS urls by default, but you can get many of them to work by adding some command line flags like --ignore-ssl-errors=true and --ssl-protocol=any. However I'm finding some sites that fail even when these flags are enabled; for example try the following code snippet:
var page = require('webpage').create();

page.onResourceError = function(e){
  console.log("Page resource failed to load. Reason: "+e.errorString);
}

page.open("https://www.bluehaven.com/pool-remodeling/", function(status){
  console.log("Load status: "+status);
});

When I run this script with those two flags enabled, I get the following output:
$ phantomjs --ignore-ssl-errors=true --ssl-protocol=any lib/test_phantom.js
Page resource failed to load. Reason: SSL handshake failed
Load status: fail

I've googled quite a bit and the discussions around PhantomJS and SSL failures all recommend using the above two command flags, or suggest that this is due to a bug in PhantomJS that isn't likely to get fixed anytime soon.
Does anyone here on SO have different ideas on how I can get PhantomJS to load the above URL (and any other sites where the same HTTPS errors occur)? My plan B is to try out SlimerJS as I understand it doesn't share this SSL error, but that will involve some risk and I'd rather not do it unless absolutely needed.

A: The program works fine on Ubuntu 14.04 with phantomjs 1.9.0.
Since the server only supports ECDHE ciphers I would assume that you are using an old version of OpenSSL with no support for these ciphers on your system.


text:
Q: Was it a mistake to flag these answers? My not an answer flags for the below answers were declined "a moderator reviewed your flag, but found no evidence to support it".

*

*I am sorry I am kind of sleepy .. but you can read here to get an idea of your problem :) [dead URL]

*This thread has a good discussion of this issue, near the bottom: [dead URL]

*Here's a post on Suns' site on how to do this... [dead URL]

*There's a good explanation of how you can do this here: [dead URL] that can be extended to buttons of any shape.

*The code here works great for my project. Check it out. [dead URL]

*Two years ago I faced something similar, which made me remember of this discussion at Sun's Forum: [dead URL] Maybe this could be a starting point for you.
Was it a mistake to flag the above answers? Description for the flag I used says:

This was posted as an answer, but it does not answer the question. It should possibly be an edit, a comment, another question, or deleted altogether.

A: Many of these should have been removed regardless of the link being broken or not. But yes, flagging as 'other' and indicating a broken link would have helped quite a bit, if only to alert us that the 'answers' should not be converted to comments (or we'd just be turning a broken answer into a broken comment).
Edit
Wait, Jeff, I swear, we test every single one before converting it. Really, we do.

A: It is not a mistake of flag all these answers, but you need to flag them in correct category. Some of the answers already selected as Answer for the question. All these may be related to the question but the link is broken now. As Yi Jinng's comment if you flagged as broken link all these may accepted by the moderators.