Q:

trying to open fragment from fragment java.lang.ClassCastException: android.app.Application cannot be cast to androidx.appcompat.app.AppCompatActivity

I use this code in recyclerViewAdapter. I need to open new fragment from fragment.
    @Override
    public void onClick(View view) {

        AppCompatActivity activity = (AppCompatActivity) view.getContext();

        CarDetailFragment carDetailFragment = new CarDetailFragment();
        FragmentManager  fragmentManager = activity.getSupportFragmentManager();
        FragmentTransaction fragmentTransaction=fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragmentCar, carDetailFragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }

A:

Declare a public static context variable in your Fragment and assign getActivity to it and then use this variable in Adapter to your getSupportFragmentManager.
public static Context context; //declare the variable in your Fragment

context=getActivity;// assign it in your Fragment before calling Adapter

Then in Adapter use it like this
FragmentManager fragmentManager= ((AppCompatActivity) YourFragmentName.context).getSupportFragmentManager();

EDIT
As static context variable could cause memory leak so you can use this
    // while calling the adapter pass getActivity as context
    MyAdapter myAdapter = new MyAdapter(getActivity, /* other variables */);

Then in Adapter use it like this
    private Context context;
    public MyAdapter(Context context, /* Other part */ ) {
        this.context = context;
        //other part
      }

   FragmentManager fragmentManager= ((AppCompatActivity) context).getSupportFragmentManager();


Q:

Is there any OpenStack server validator tool?

I'm building a webserver for OpenStack as part of my thesis at a data storage company for their data storage service. I need a tool that validates the server responses according to the OpenStack specifications and I also need a tool that can stress-test my webserver according to OpenStack specification. I've searched in google, but couldn't really find any such tools. Do you know about any such tools which would help me in my purpose. The specification that I'm following is found in this link http://docs.rackspace.com/files/api/v1/cf-devguide-20120601.pdf. Thank you.

A:

The validator as you describe doesn't exist as a tool or separate utility. You can, however, run all of OpenStack in a relatively small virtual machine (1GB VM) using the devstack script (see http://devstack.org).
Its not fast, but it is definitively, the APIs you are wanting to work against. Snapshot that VM, and you can recreate it at need to test your web service at your liesure. Its not something i would recommend for performance testing, but then Im not sure what your writing or wanting to test to be able to make any reasonable recommendations there.


Q:

While loop for 300seconds in python

I am new in python
I want to run my while loop for 300seconds or upto 300s
After 300seconds it must terminate
How I can write program in python
Plz help.

A:

Try something like this, which will loop 300 seconds
import time

start_time = time.time()

while (time.time() - start_time) < 300:
    print("/", end='')

print("End.")


Q:

Are slugs still required?

I always used to transform major information of an entity (e.g. title, name) with a slugifizer to a slug which doesn't contain spaces, special chars etc.
Now I accidentally forgot the slugifizer and it worked too even with spaces.
Is a slug still required in this time?
Except for IE users of course...
Regards
PS:
I don't want to start a discussion about this topic. I just want to know if all modern browsers (and backends of course) can handle all problems a not-slugged value could cause.

A:

Slugs were primarily for SEO value.
URLs cannot contain spaces or other reserved characters.  If you put spaces in your URL and it works, it's because the browser is being nice to you, not because it is correct.


Q:

Google map coordinates in react

I'm trying to get the current position on google map. The code is working fine when I get the coordinates, but these coordinates I want to get and google map toom because right now, coordinates are static for google map.
 import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
import { withGoogleMap, GoogleMap, Marker } from "google-map-react"
import { InfoWindow } from 'google-map-react';
import Geolocation from 'react-geolocation'

const AnyReactComponent = ({ text }) =>
{ text }
;

export default class Map extends Component {

  static defaultProps = {
    center: { lat: 40.7446790, lng: -73.9485420 },
    zoom: 11
  }
render() {
    return (
      <Geolocation
  render={({
    fetchingPosition,
    position: { coords: { latitude, longitude } = {} } = {},
    error,
    getCurrentPosition
  }) =>

      <button onClick={getCurrentPosition}>Get Position</button>
      {error &&

          {error.message}

}

        latitude: {latitude}
        longitude: {longitude}

        <GoogleMapReact

          defaultCenter={ this.props.center }
          defaultZoom={ this.props.zoom }>
          <AnyReactComponent
            lat={ latitude }
            lng={ longitude }
            text={ 'Wheres Waldo?' }
          />
        </GoogleMapReact>

}
/>
    )
  }
}

With Geolocation I get very well coordinates, but these coordinates want to set in:
static defaultProps = {
    center: { lat: 40.7446790, lng: -73.9485420 },
    zoom: 11
  }

A:

You must define a state for your <Map> component, which will store your current coordinates.
Then, you should pass the state to your GoogleMapReact component.
In order to set the state with the coordinates found by the Geolocation services, you can use onSuccess callback (https://www.npmjs.com/package/react-geolocation#onsuccess-function):
<Geolocation
    onSuccess={this.geoSuccess}
    ...
/>

The geoSuccess function is:
geoSuccess = position => {
   let coords = {
     lat: position.coords.latitude,
     lng: position.coords.longitude
   }

   this.setState({
     center: coords
   })
};

Demo here:
https://43qv620770.codesandbox.io/
The full code can be found here (the file Map.js):
https://codesandbox.io/s/43qv620770


Q:

how to limit number of entity. google app engine

I want to make just 1 DailyPost entity. But when I make two requests at the same time, there are two DailyPost entities.
How can I limit this?
Environment:
Google App Engine
runtime : Python27
datastore : ndb
def get_today():
  return datetime.datetime.combine(datetime.date.today(), datetime.time())

class DailyPost(ndb.Model):
  user = ndb.KeyProperty(kind=User)
  content = ndb.StringProperty()
  created = ndb.DateTimeProperty(auto_now_add=True)

class GetOrCreateHandler(webapp2.RequestHandler):
  def get(self):
    user = session.get_user() # user from session (pseudo code)
    post = DailyPost.query(DailyPost.created >= get_today(),
                           DailyPost.user==user.key).get()
    if not post:
      # Delay to test. (or time.sleep)
      for i in range(30000):
        print 1
      post = DailyPost(content='some text..', user=user.key)
      post.put()

    self.response.write(post.content)

A:

Just use unique value of each day as a key with get_or_insert method:
import datetime

class DailyPost(ndb.Model):
  user = ndb.KeyProperty(kind=User)
  content = ndb.StringProperty()
  #created = ndb.DateTimeProperty(auto_now_add=True)

class GetOrCreateHandler(webapp2.RequestHandler):
  def get(self):
    user = self.session.get_user() # user from session (pseudo code)
    _id = '%s.%s' % (user.id, datetime.date.today().strftime('%s'))
    DailyPost.get_or_insert(_id, user=user, content='bla')
    self.response.write(post.content)


Q:

Is it true that if $f$ is surjective from $A$ to $B$ then there is an injective function $g$ from $B$ to $A$?

I think the answer is yes because otherwise $f$ wouldn't be a function.
Is this correct? And how would the formal proof go?

A:

Yes. To prove it we use the axiom of choice. Since $f$ is surjective then for every element of $b \in B$ there exists an $a \in A$ such that $f(a)=b$. To construct the function $g$ we choose one such $a$ for every $b$ and map the $b$ into that $a$ which we know exists. This map is injective by construction.

A:

Yes, this is correct but is equivalent to the Axiom of Choice (because we have to pick a unique element from each (non-empty!) $f^{-1}[\{b\}]$, essentially). But AC is widely believed and used, so don't worry.
The proof I sketched above (using AC).


Q:

Identify why a user can drop a database

I have a sql server user that has the ability to drop any database. I've been running the code below to check the rights that the user has in SQL Server but have not been able to identify how the user has the ability to drop databases.  Is there a sql script that can help me identify how this user can drop dbs?  Is there a command to deny them dropping any databases?  (SSMS is not showing the user as part of the dbcreator role)
select USER_NAME(p.grantee_principal_id) AS principal_name,
    dp.type_desc AS principal_type_desc,
    p.class_desc,
    OBJECT_NAME(p.major_id) AS object_name,
    p.permission_name,
    p.state_desc AS permission_state_desc
from    sys.database_permissions p
inner   JOIN sys.database_principals dp
on     p.grantee_principal_id = dp.principal_id
order by principal_name

The output of the query above provides the following three records for the user if it is helpful

class_desc    object_name permission_name permission_state_desc
  OBJECT_OR_COLUMN  xp_cmdshell EXECUTE          GRANT
  DATABASE          NULL           CONNECT             GRANT
  DATABASE             NULL           CREATE DATABASE GRANT

A:

I would suggest running this query on the master
SELECT
    [UserName] = CASE princ.[type]
                    WHEN 'S' THEN princ.[name]
                    WHEN 'U' THEN ulogin.[name] COLLATE Latin1_General_CI_AI
                 END,
    [UserType] = CASE princ.[type]
                    WHEN 'S' THEN 'SQL User'
                    WHEN 'U' THEN 'Windows User'
                 END,
    [DatabaseUserName] = princ.[name],
    [Role] = null,
    [PermissionType] = perm.[permission_name],
    [PermissionState] = perm.[state_desc],
    [ObjectType] = obj.type_desc,--perm.[class_desc],
    [ObjectName] = OBJECT_NAME(perm.major_id),
    [ColumnName] = col.[name]
FROM
    --database user
    sys.database_principals princ
LEFT JOIN
    --Login accounts
    sys.login_token ulogin on princ.[sid] = ulogin.[sid]
LEFT JOIN
    --Permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = princ.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col ON col.[object_id] = perm.major_id
                    AND col.[column_id] = perm.[minor_id]
LEFT JOIN
    sys.objects obj ON perm.[major_id] = obj.[object_id]
WHERE
    princ.[type] in ('S','U')
UNION
--List all access provisioned to a sql user or windows user/group through a database or application role
SELECT
    [UserName] = CASE memberprinc.[type]
                    WHEN 'S' THEN memberprinc.[name]
                    WHEN 'U' THEN ulogin.[name] COLLATE Latin1_General_CI_AI
                 END,
    [UserType] = CASE memberprinc.[type]
                    WHEN 'S' THEN 'SQL User'
                    WHEN 'U' THEN 'Windows User'
                 END,
    [DatabaseUserName] = memberprinc.[name],
    [Role] = roleprinc.[name],
    [PermissionType] = perm.[permission_name],
    [PermissionState] = perm.[state_desc],
    [ObjectType] = obj.type_desc,--perm.[class_desc],
    [ObjectName] = OBJECT_NAME(perm.major_id),
    [ColumnName] = col.[name]
FROM
    --Role/member associations
    sys.database_role_members members
JOIN
    --Roles
    sys.database_principals roleprinc ON roleprinc.[principal_id] = members.[role_principal_id]
JOIN
    --Role members (database users)
    sys.database_principals memberprinc ON memberprinc.[principal_id] = members.[member_principal_id]
LEFT JOIN
    --Login accounts
    sys.login_token ulogin on memberprinc.[sid] = ulogin.[sid]
LEFT JOIN
    --Permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col on col.[object_id] = perm.major_id
                    AND col.[column_id] = perm.[minor_id]
LEFT JOIN
    sys.objects obj ON perm.[major_id] = obj.[object_id]
UNION
--List all access provisioned to the public role, which everyone gets by default
SELECT
    [UserName] = '{All Users}',
    [UserType] = '{All Users}',
    [DatabaseUserName] = '{All Users}',
    [Role] = roleprinc.[name],
    [PermissionType] = perm.[permission_name],
    [PermissionState] = perm.[state_desc],
    [ObjectType] = obj.type_desc,--perm.[class_desc],
    [ObjectName] = OBJECT_NAME(perm.major_id),
    [ColumnName] = col.[name]
FROM
    --Roles
    sys.database_principals roleprinc
LEFT JOIN
    --Role permissions
    sys.database_permissions perm ON perm.[grantee_principal_id] = roleprinc.[principal_id]
LEFT JOIN
    --Table columns
    sys.columns col on col.[object_id] = perm.major_id
                    AND col.[column_id] = perm.[minor_id]
JOIN
    --All objects
    sys.objects obj ON obj.[object_id] = perm.[major_id]
WHERE
    --Only roles
    roleprinc.[type] = 'R' AND
    --Only public role
    roleprinc.[name] = 'public' AND
    --Only objects of ours, not the MS objects
    obj.is_ms_shipped = 0
ORDER BY
    princ.[Name],
    OBJECT_NAME(perm.major_id),
    col.[name],
    perm.[permission_name],
    perm.[state_desc],
    obj.type_desc--perm.[class_desc]

This should give you a pretty good idea of the roles that have access to your master database and see weather or not the user has any of those roles. You can also run this against any of your other databases to check the user's permissions on a database by database level. This should be an important tool to help track this down.

A:

Is there a sql script that can help me identify how this user can drop dbs?

I have used this a few times with some good results, source of the code below can be found here:

SELECT SP1.[name] AS 'Login', 'Role: ' + SP2.[name] COLLATE DATABASE_DEFAULT AS 'ServerPermission'
FROM sys.server_principals SP1
  JOIN sys.server_role_members SRM
    ON SP1.principal_id = SRM.member_principal_id
  JOIN sys.server_principals SP2
    ON SRM.role_principal_id = SP2.principal_id
UNION ALL
SELECT SP.[name] AS 'Login' , SPerm.state_desc + ' ' + SPerm.permission_name COLLATE DATABASE_DEFAULT AS 'ServerPermission'  FROM sys.server_principals SP
  JOIN sys.server_permissions SPerm
    ON SP.principal_id = SPerm.grantee_principal_id
ORDER BY [Login], [ServerPermission];

Is there a command to deny them dropping any databases?

Going on documentation here, the security requirements for a user to drop a database are stated as:

Requires the CONTROL permission on the database, or ALTER ANY DATABASE permission, or membership in the db_owner fixed database role

You can explictily deny the permission to one mentioned above but understand that the level you deny it at may not take affect like you think. I recall reading a white paper that walked through how SQL Server goes about validating permissions of a user upon connection but cannot locate it right now. If I recall I may deny them connection to a database but the fact the user is part of the sysadmin role takes precedence.
I would look at auditing specifically for the DROP DATABASE command to be safe.

A:

The query you've got there will list only permissions for the database against which you run it.  One way to get permission to drop a database is ALTER ANY DATABASE, which is a server-level permission.  To check those, try this query:
SELECT
  [srvprin].[name] [server_principal],
  [srvprin].[type_desc] [principal_type],
  [srvperm].[permission_name],
  [srvperm].[state_desc]
FROM [sys].[server_permissions] srvperm
  INNER JOIN [sys].[server_principals] srvprin
    ON [srvperm].[grantee_principal_id] = [srvprin].[principal_id]
WHERE [srvprin].[type] IN ('S', 'U', 'G')
ORDER BY [server_principal], [permission_name];

In other words, the user might be getting the permission to drop databases at the server login level rather than the database user level.


Q:

What genre of video game does Diablo belong to?

I've recently played Diablo 1 and 2 and I'm totally hooked. Now I've been wondering what genre this game belongs to, so it would help me find similar games.

A:

The genre has a few popular names, including:

Hack and slash
Action RPG
Dungeon crawl
Diablo-like or Diablo-esque

And sometimes even the term "roguelike" is used - there is a vast difference between the roguelike genre and games like Diablo, but the latter are obviously influenced by the former.
The most common term I've encountered is "hack and slash". There are many, many games that belong to this genre, especially since the success of Diablo.
The excellent Moby Games site has a page about the genre, which briefly outlines what defines it as well as providing a list of all the games it considers to be "Diablo variants".


Q:

Compute $1^2 + 3^2+ 5^2 + \cdots + (2n-1)^2$ by mathematical induction

I am doing mathematical induction. I am stuck with the question below. The left hand side is not getting equal to the right hand side.
Please guide me how to do it further.

$1^2 + 3^2+ 5^2 + \cdots + (2n-1)^2 = \frac{1}{3}n(2n-1)(2n+1)$.

Sol:
$P(n):\ 1^2 + 3^2 + 5^2 + \cdots + (2n-1)^2 = \frac{1}{3}n(2n-1)(2n+1)$.
For $n=n_1 = 1$
$$P(1) = \frac{1}{3}{3} = (1)^2.$$
Hence it is true for $n=n_0 = 1$.
Let it be true for $n=k$
$$P(k): 1^2 + 3^2 + 5^2 + \cdots + (2k-1)^2 = \frac{1}{3}k(2k-1)(2k+1).$$
We have to prove that it is true for $P(k+1)$.
$$P(k+1) = 1^1+3^2+5^2+\cdots+(2k+1)^2 = \frac{1}{3}(k+1)(2k+1)(2k+3)\tag{A}.$$
Taking LHS:
$$\begin{align*}
1^2 + 3^2 + 5^2 + \cdots + (2k+1)^2 &= 1^2+3^2+5^2+\cdots + (2k+1)^2\\
&= 1^2 + 3^2 + 5^2 + \cdots + (2k-1)^2 + (2k+1)^2\\
&= \frac{1}{3}k(2k-1)(2k+1) + (2k+1)^2\\
&=\frac{k(2k-1)(2k+1)+3(2k+1)^2}{3}\\
&=\frac{(2k+1)}{3}\left[k(2k-1) + 3(2k+1)\right]\\
&=\frac{(2k+1)}{3}\left[2k^2 - k + 6k + 3\right]\\
&=\frac{1}{3}(2k+1)(2k^2 +5k + 3)\\
&=\frac{1}{3}(2k+1)(k+1)\left(k+\frac{3}{2}\right) \tag{B}
\end{align*}$$
EDIT:
Solving EQ (A):
$=(1/3)(2k^2+5K+3) (2K+1) \tag{C}$
Comparing EQ(B) and EQ(C)
Hence proved that it is true for $n = k+1.$
Thus the proposition is true for all $n >= 1$.
Thanks.

A:

NOTE:  I am not saying anything different, before someone start commenting that my answer is not any different.
$$
\begin{align*}
1^2 + 3^2 + 5^2 + \cdots + (2k+1)^2 &= 1^2+3^2+5^2+\cdots + (2k+1)^2\\
&= 1^2 + 3^2 + 5^2 + \cdots + (2k-1)^2 + (2k+1)^2\\
&= \frac{1}{3}k(2k-1)(2k+1) + (2k+1)^2\\
&=\frac{k(2k-1)(2k+1)+3(2k+1)^2}{3}\\
&=\frac{(2k+1)}{3}\left[k(2k-1) + 3(2k+1)\right]\\
&=\frac{(2k+1)}{3}\left[2k^2 - k + 6k + 3\right]\\
&=\frac{1}{3}(2k+1)(2k^2 +5k + 3)\\
&=\frac{1}{3}(2k+1) \hspace{3pt}\left[(k+1)(2k+3)\right] \\
&= \frac{1}{3} (k+1)(2(k+1)-1)(2(k+1)+1)
\end{align*}
$$
The last line shows that the result is true for $n=k+1$

A:

Everything is OK except for the very last line. You somehow lost a factor of two. The penultimate line is already the result you want, since $2k^2+5k+3=(k+1)(2k+3)$.


Q:

Java Regex-matches anything except three specific string

Given such Java Regex codes:
Pattern pattern = Pattern.compile("[^(bob)(alice)(kitty)]");
String s = "a";
Matcher matcher = pattern.matcher(s);

boolean bl = matcher.find();
System.out.println(bl);

The output is false. Why? The regex [^(bob)(alice)(kitty)] matches any things except bob, alice or kitty. Then the result should be true, right?

A:

Because your regex is not doing what you think it should be doing.
Use this regex with Negative lookahead:
Pattern pattern = Pattern.compile("^(?!bob|alice|kitty).*$");

Your regex: [^(bob)(alice)(kitty)] is using a character class and inside a character class there are no groups.

(?!bob|alice|kitty) is negative lookahead that means fail the match if any of these 3 words appear at start of input.
Important to use anchors ^ and $ to make sure we're not matching from middle of the string.
If you want to avoid matching these 3 words anywhere in input then use this regex:
^(?!.*?(?:bob|alice|kitty)).*$

RegEx Demo


Q:

How to set value of multiple input fields with same button

I want to set input field value only when it is clicked and want to set value in two different input fields from same button, when one input field is selected only set value in this field when other selected/clicked value set their.
Try with different ways but not successful.
I hope i will be helped in this problem.
thanks

var phoneScreen = $("#phone"); var phoneNumber = phoneScreen.val();
var delBtn = $("#del"); var clrBtn = $("#clr");
var numBtn = $(".number");

numBtn.click(function() {
    var number = $(this).val();
  updatePhoneNumber(number);
  printPhoneNumber();
});
delBtn.click(function() {
    deleteNumber();
  printPhoneNumber();
});
clrBtn.click(function() {
    clearNumber();
  printPhoneNumber();
});

function updatePhoneNumber(newNumber) {
    phoneNumber = phoneNumber + newNumber;
}
function deleteNumber() {
    phoneNumber = phoneNumber.slice(0,-1);
}
function clearNumber() {
    phoneNumber = "";
}
function printPhoneNumber() {
    phoneScreen.val(phoneNumber);
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

<input type="number" id="phone" placeholder="(123) 45-7" min="0" step="1"/>

<input type="number" id="phone2" placeholder="(123) 45-7" min="0" step="1"/>

<form action="#" method="post" id="form">
<button type="button" class="rightside__pad-btn number" value="1">1</button>
<button type="button" type="button" class="rightside__pad-btn number" value="2">2</button>
<button type="button" type="button" class="rightside__pad-btn number" value="3">3</button>

<button type="button" type="button" class="rightside__pad-btn number" value="4">4</button>
<button type="button" type="button" class="rightside__pad-btn number" value="5">5</button>
<button type="button" type="button" class="rightside__pad-btn number" value="6">6</button>

<button type="button" type="button" class="rightside__pad-btn number" value="7">7</button>
<button type="button" type="button" class="rightside__pad-btn number" value="8">8</button>
<button type="button" type="button" class="rightside__pad-btn number" value="9">9</button>

<button type="button" id="del" class="rightside__pad-btn del">
</button>
<button type="button" class="rightside__pad-btn number" value="0">0</button>
<button type="button" id="dial" class="rightside__pad-btn" value="">
</button>

    </form>

A:

I just added few changes

var hasFocus = $('#phone'); Set #phone as default focused element.
Update the hasFocus to selected input element.

   $('input[type=number]').on('click', function(){
      hasFocus = $(this);
    });

Now added function to set value to focused element hasFocus.val(hasFocus.val() +number);
Please update

var phoneScreen = $("#phone");
var phoneNumber = phoneScreen.val();
var delBtn = $("#del"); var clrBtn = $("#clr");
var numBtn = $(".number");
var hasFocus = $('#phone');
$('input[type=number]').on('click', function(){
  hasFocus = $(this);
})
numBtn.click(function() {
    var number = $(this).val();
    hasFocus.val(hasFocus.val() +number);
  //updatePhoneNumber(number);
  //printPhoneNumber(number);
});
delBtn.click(function() {
    deleteNumber();
  printPhoneNumber();
});
clrBtn.click(function() {
    clearNumber();
  printPhoneNumber();
});

function updatePhoneNumber(newNumber) {
    phoneNumber = phoneNumber + newNumber;
}
function deleteNumber() {
    phoneNumber = phoneNumber.slice(0,-1);
}
function clearNumber() {
    phoneNumber = "";
}
function printPhoneNumber() {
    phoneScreen.val(phoneNumber);
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

<input type="number" id="phone" placeholder="(123) 45-7" min="0" step="1"/>

<input type="number" id="phone2" placeholder="(123) 45-7" min="0" step="1"/>

<form action="#" method="post" id="form">
<button type="button" class="rightside__pad-btn number" value="1">1</button>
<button type="button" type="button" class="rightside__pad-btn number" value="2">2</button>
<button type="button" type="button" class="rightside__pad-btn number" value="3">3</button>

<button type="button" type="button" class="rightside__pad-btn number" value="4">4</button>
<button type="button" type="button" class="rightside__pad-btn number" value="5">5</button>
<button type="button" type="button" class="rightside__pad-btn number" value="6">6</button>

<button type="button" type="button" class="rightside__pad-btn number" value="7">7</button>
<button type="button" type="button" class="rightside__pad-btn number" value="8">8</button>
<button type="button" type="button" class="rightside__pad-btn number" value="9">9</button>

<button type="button" id="del" class="rightside__pad-btn del">
</button>
<button type="button" class="rightside__pad-btn number" value="0">0</button>
<button type="button" id="dial" class="rightside__pad-btn" value="">
</button>

    </form>


Q:

A simple web application-user with log on information

I have a simple web page in which the user will enter some information before submitting the form. I would like to retrieve his IPaddress after the post is done.

A:

Here is function from another relevant post that should help:
function getUserIpAddr()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) //if from shared
    {
        return $_SERVER['HTTP_CLIENT_IP'];
    }
    else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))   //if from a proxy
    {
        return $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else
    {
        return $_SERVER['REMOTE_ADDR'];
    }
}

This will cover the occasional proxy user and shared networks.


Q:

Regex to match linebreaks not preceded by non-escaped quotes in text file

I have a textfile where strings are enclosed by quotes " " and any containing quotes are escaped by \. I wan't to remove any linebrakes (\n) at in the text, as long as they are not preceded by an un-escaped quote sign ("), since thats the end of a line.
Here's an example:
"tre miljarder på att modernisera snabbtågen.\"
Dagens mest ironiska nyhet.,Väntar på att alla Summerburst-uppdateringar snart ska dö ut   så min ångest kan släppa och jag kan återgå till ett normalt liv.,RT @mapeone: En till hashtag     på Facebook och jag badar naken i grisblod.,Dagens biologiska lektion och psykologiska  reflektion.
Så förlorade fåglarna sina penisar - DN.SE http://t.co/PFaseQMt8B,Hahaha \"@Aliceyouknow:  Hah ironiskt att jag för exakt ett år sen ville gräva ner mig lika mycket som jag vill nu   med.\" #livet,Det är bara kvinnor som på riktigt förstår paniken i om Zlatans hår skulle    försvinna. #ikon,@nellie_lind ah han har ju rakat sidorna, snart ryker väl hela skiten,Alltså    Zlatan ge fan i att mecka med håret.,Jag har ett jobb. Hur tungt är inte det. #tungt"

The regex pattern I've come up with so far looks like this:
[^"]\n+

But it also matches the character before the \n, e.g. the quote at the end of "snabbtågen.\" on line 1 and dot (.) after "reflektion" on line 2.
I want it to match a \n preceded by anything else than a non escaped ", but not include what's preceding it. How can that be done?

A:

You should use negative lookbehind assertion
>>> print s
'first line'
'hello world
again'
>>> s2 = re.sub(r"(?<!')\s+", " ", s)
>>> print s2
'first line'
'hello world again'


Q:

Android How to add TableRows at 0 without scrolling the ScrollLayout up

I have the following structure in my UI
    <ScrollView
        android:id="@+id/vscroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TableLayout
            android:id="@+id/table"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >
        </TableLayout>

    </ScrollView>

I fill the TableLayout with TableRows programmatically.
Sometimes I need to add rows at the top of the table (insert before child(0)). And the problem is the ScrollView jumps up.
I can tell you that I Logged the ScrollY() position of the ScrollView before and after the row insertion. And it remains the same (!!)
This is what is causing the jump, because now I have some more rows and scroll position Y= 234 (for example) before was on row A and now the same position Y means row Q.
Row A was the (lt's say) fifth row, and now after insertion row Q is the fifth row
So you see, from the ScrollView point of view nothing changed, but the View shows now a different Row.
If at this point you are not totally confused with my explanation, then maybe you can advise how can I insert rows at the top without changing what I see on screen.
In other words I want the insertion to go stealth without any influence on what the user sees.
If some code will help clear the picture, here is how I insert 5 rows at the top
table = (TableLayout) findViewById(R.id.table);
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
for(int i=0; i<5 ; i++) {
    TableRow mr = new TableRow(getContext());
    // some stuff to set the row texts
    table.addView(mr, 0, params);
}

Before Insertion    After Insertion
Row 0               New Row 0
Row 1               New Row 1
Row 2               New Row 2
Row 3               New Row 3        <--- vscroll Y position stays the same
Row 4               New Row 4
Row 5               Old Row 0
Row 6               Old Row 1
Row 7               Old Row 2
Row 8               Old Row 3        (vscroll jumps up from here to new Row 3)
Row 9               Old Row 4
Row 10              Old Row 5
Row 11              Old Row 6

A:

I haven't tested it but you could try to post() a Runnable where you would get the newly inserted row's height and then scroll the ScrollView by that amount so it stays at the same position:
final TableRow newRow = new TableRow(this);
        // add stuff to the row
        tl.addView(newRow, 0, params);
        // sv is your ScrollView vscroll
        sv.post(new Runnable() {

            @Override
            public void run() {
                int size = newRow.getHeight();
                sv.scrollBy(0, size);
            }

        });


Q:

How can I remove a question ban quickly?

I was recently put on a ban(again) because I asked some poorly received questions, which I deleted because they weren't fit for the site, or were duplicates. I visited Why are questions no longer being accepted from my account? and I understand that I can edit my questions to make them more clear(which I did), and post well-received answers (which I have since my first ban), and I am wondering if there is anything else I can do.
I have edited my questions as best as I could, by fixing grammar, content, etc., but the ban is persistent. I understand that the ban should not be lifted easily, because that would defeat the purpose.
I am not asking why I am in a question ban, I am seeking advice for how to remove it quickly. Should I just keep answering questions? Am I in good shape?
Advice on how I can edit my questions is greatly appreciated (or you can edit them yourself if you want).

A:

I've upvoted one of your questions, and it lifted the restriction. Note that you're still very close to being restricted again if you get downvoted some more, so do try to post good questions that would be upvoted from now on, to teach the system that you're asking good questions now.


Q:

RTFMP - Remote stream not showing

I'm trying to create a 2-way videochat. Your own webcam shows perfectly fine, but the other doesn't. I used this page as an example: http://www.adobe.com/devnet/flashmediaserver/articles/p2p_apps_cirrus_lccs.html
Following the steps on the page doesn't seem to work for me. I exchange the peer IDs via PHP. I make my Flash visit a page, which stores the peer ID in the database using a POST request. To fetch the peer ID of the partner, I use PHP sessions, which store both your ID, and that of your partner. I can then use these variables to visit another PHP page, which echoes the partner's peer ID. Both are the same as in the database, so there's nothing wrong with that.
The NetConnection:
Connection = new NetConnection();
Connection.addEventListener(NetStatusEvent.NET_STATUS, CheckConnect);
Connection.connect(RTFMP + DevKey);

This is how I set up your own webcam plus its NetStream:
StreamOut = new NetStream(Connection, NetStream.DIRECT_CONNECTIONS);
var SelfCam:DynamicStreamingVideoSource = new DynamicStreamingVideoSource();
var VideoItems:Vector.<DynamicStreamingVideoItem>;
VideoItems = new Vector.<DynamicStreamingVideoItem>();
VideoItems[0] = new DynamicStreamingVideoItem();

SelfCam.host = "";
SelfCam.streamType = StreamType.LIVE;
SelfCam.streamItems = VideoItems;

Self.source = SelfCam;

var Cam:Camera = Camera.getCamera();
var Mic:Microphone = Microphone.getMicrophone();
Cam.setMode(380, 255, 15);
Cam.setQuality(0, 80);
Self.videoObject.attachCamera(Cam);

StreamOut.attachAudio(Mic);
StreamOut.attachCamera(Cam);
StreamOut.publish("vids");

And this is how I receive the published stream "vids":
StreamIn = new NetStream(Connection, OtherID);
StreamIn.play("vids");
StreamIn.client = this;
Other.videoObject.attachNetStream(StreamIn);

The Other and Self objects are of type <s:VideoDisplay>.
I'm sure it must be something pretty damn simple, but I can't seem to lay my finger on it.

A:

Never mind, I had to use mx:VideoDisplay rather than s:VideoDisplay.


Q:

How can I find which compatibility mode an H2 database is in?

I know I can set a compatibility mode via SQL in H2, eg.
SET MODE ORACLE
Is there corresponding SQL to query which mode the database is currently in?

A:

You can do:
SELECT VALUE FROM INFORMATION_SCHEMA.SETTINGS WHERE NAME = 'MODE';

Then make a case insensitive comparison to the different modes.


Q:

For any matrix in $A\in\mathcal{C}^{n\times n}$ , does $\lambda_{i}(A)\leq\sigma_{i}(A)$?

Specifically, Does following hold $ \sum_{i}\lambda_{i}^{2}(A)\leq\sum_{i}\sigma_{i}^{2}(A)$
I know $|\lambda_{1}|\leq\sigma_{1}$, and Its my guess that by min max theorem it is true for other $i$ as well?

A:

The "point-wise" inequality does not generally hold. However, some inequalities involving summations and multiplications can be shown but they are not so trivial to establish.
Suppose $A\in\mathbb{C}^{n\times n}$, $\lambda_1(A)\geq\cdots\geq\lambda_n(A)$ and $\sigma_1(A)\geq\cdots\geq\sigma_n(A)$ are, respectively, its eigenvalues and singular values. You can quite easily show that
$$
\left|\prod_{i=1}^k\lambda_i(A)\right|
\leq
\prod_{i=1}^k\sigma_i(A).
$$
Let $A=URU^*$ be the Schur decomposition of $A$ ($R$ is upper triangular) such that the diagonal of $R$ is $\lambda_1(A),\ldots,\lambda_n(A)$. Take $R_k$ to be the $k\times k$ leading principal submatrix of $R$ so that $\det(R_k)=\lambda_1(A)\cdots\lambda_k(A)$. Interlacing inequalities for singular values together with their invariance w.r.t. unitary transformations imply that $\sigma_i(R_k)\leq\sigma_i(R)=\sigma_i(A)$ ($i=1,\ldots,k$) and hence $|\lambda_1(A)\cdots\lambda_k(A)|=|\det(R_k)|=\sigma_1(R_k)\cdots\sigma_k(R_k)\leq \sigma_1(R)\cdots\sigma_k(R)=\sigma_1(A)\cdots\sigma_k(A)$.
Next, you can use the following: let $\alpha_1\geq\cdots\geq\alpha_n\geq 0$ and $\beta_1\geq\cdots\geq\beta_n\geq 0$, $\alpha_1\cdots\alpha_k\leq\beta_1\cdots\beta_k$ for $k=1,\ldots,n$ and $f:\mathbb{R}\rightarrow\mathbb{R}$ such that $f(e^x)$ is convex and increasing on $[\min\{\alpha_n,\beta_n\},\beta_1]$. Then $f(\alpha_1)+\cdots+f(\alpha_k)\leq f(\beta_1)+\cdots +f(\beta_k)$ for $k=1,\ldots,n$.
In particular, using $f(x)=x^2$ ($e^{2x}$ is convex on $\mathbb{R}$), you get
$$
\sum_{i=1}^k\lambda_i^2(A)\leq\sum_{i=1}^k\sigma_i^2(A), \qquad k=1,\ldots,n.
$$
In fact, you can use $f(x)=x^l$ for any $l>0$ to get
$$
\sum_{i=1}^k\lambda_i^l(A)\leq\sum_{i=1}^k\sigma_i^l(A).
$$


Q:

App crashes on launch with < 256 RAM iOS Devices

The Info
I recently launched an app on the AppStore. After testing on the simulator thousands of times, and actual devices hundreds of times we finally released our app.
The Problem
Reviews started popping up about app crashes when the user launches the app. We figured that the app crashes on launch on iOS devices with less than (or equal to) 256 Mb of RAM. The following devices are devices our app supports with less than 256:

iPod Touch 4G
iPhone 3GS
iPad 1

The app doesn't always crash. Sometimes it launches fine and runs smoothly. Other times it crashes. The time from launch (when the user taps the icon) to crash is usually two seconds, which would mean that the system isn't shutting it down.
Findings
When using Instruments to test on certain devices, I find the following:

There are no memory leaks (I'm using ARC), but there are memory warnings
Items are being allocated like crazy. There are so many allocated items, and even though I'm using ARC it's as if ARC isn't doing what it's supposed to be doing
Because of what I see as "over-allocation", the result is:
This app takes (on average) 60 MB of Real Memory and 166 MB of Virtual. When the app launches the memory being used quickly increases until it reaches about 60 MB at which point the view has been loaded.
Here is a snapshot of the Activity Monitor in Instruments:

I know that those figures are WAYY to high (although the CPU % never really gets up there). I am worried that ARC is not working properly, or the more likely case: I'm not allocating objects correctly. What could possibly be happening?
The Code and Warnings
In Xcode, there are only a few warnings, none of which pertain to the app launch or any files associated with the launching of the app. I placed breakpoints in both the App Delegate and my viewDidLoad method to check and see if the crash occurred there - it didn't.
More Background Info
Also, Xcode never generates any errors or messages in the debugger. There are also no crash reports in iTunes Connect, it just says, "Too few reports have been submitted for a report to be shown." I've added crash reporting to my app, but I haven't released that version.
A Few Questions
I started using Obj-C just as ARC arrived, so I'm new to dealing with memory, allocation, etc. (that is probably obvious) but I'd like to know a few things:
How can I use @autoreleasepool to reduce my memory impact? What do I do with memory warnings, what do I write in the didRecieveMemoryWarning since I'm using ARC?
Would removing NSLog statements help speed things up?
And the most important question:
Why does my app take up so much memory and how can I reduce my whopping 60 MB footprint?
I'd really appreciate any help! Thanks in advance!
EDIT: After testing on the iPhone 4 (A4), we noticed that the app doesn't crash when run whereas on devices with less than 256 MB of RAM it does.

A:

I finally solved the issue. I spent a few hours pondering why my application could possibly take up more RAM than Angry Birds or Doodle Jump. That just didn't make sense, because my app does no CALayer Drawing, or complex Open GL Graphics Rendering, or heavy web connection.
I found this slideshow while searching for answers and slide 17 listed the ways to reduce memory footprint. One thing that stuck out was PNGCrush (Graphics Compression).
My app contains a lot of custom graphics (PNG files), but I hadn't thought of them affecting my app in any way, apparently images (when not optimized properly) severely increase an applications memory footprint.
After installing PNGCrush and using it on a particularly large image (3.2 MB) and then deleting a few unused images I ended up reducing my apps memory footprint from 60+ MB and severe lag to 35 MB and no lag. That took a whopping five minutes.
I haven't finished "crushing" all my images, but when I do I'll update everyone on the final memory footprint.
For all those interested, here is a link to a blog that explains how to install PNGCrush (it's rather complicated).
UPDATE: Instead of using the PNGCrush process (which is very helpful, although time consuming with lots of images) I now use a program called ImageOptim that provides a GUI for multiple scripts like PNGCrush. Heres a short description:

ImageOptim seamlessly integrates various optimisation tools: PNGOUT, AdvPNG, PNGCrush, extended OptiPNG, JpegOptim, jpegrescan, jpegtran, and Gifsicle.

Here's a link to the website with a free download for OS X 10.6 - 10.8. Note, I am not a developer, publisher or advertiser of this software.


Q:

What does EAFFFFFE mean in ARM architecture

I often see instruction EAFFFFFE(which means Branch to current PC address) when studying ARM architecture assembly.
What does it mean and why is it needed to branch to current PC address?

A:

A branch to the current address will be generated by, for example,
while(1);

or
for(;;);

in C.  Both of these loops run forever, doing nothing.
Why would you want this?  Well, in production code, you probably wouldn't.  But in example or test code, it's quite common to reach the 'end' of a running program.  What should the CPU do then?  It is possible to halt most CPUs to save power, but this is hardly necessary when running simple test code, and anyway it often interacts poorly with debuggers.  Entering an infinite loop is the simplest way to get the CPU to do 'nothing'.
(I've taken your word for it that EAFFFFFE is what you say it is - you don't specify an ARM architecture or instruction set.)


Q:

calculate $\lim_{x \rightarrow 0}\left ( x^{-6}\cdot (1-\cos(x)^{\sin(x)})^2 \right )$

as in topic, my task is to calculate $$\lim_{x \rightarrow 0}\left ( x^{-6}\cdot (1-\cos x^{\sin x})^2 \right )$$
I do the following: (assuming that de'Hospital is pointless here, as it seems to be) I write Taylor series for $\sin x, \cos x$ $$\sin x=x-\frac{x^3}{3!}+\frac{x^5}{5!}-\frac{x^7}{7!}+o(x^7)$$ $$\cos x=1-\frac{x^2}{2!}+\frac{x^4}{4!}-\frac{x^6}{6!}+o(x^6)$$ I notice that denominator tells me to use sixth degree something and i get $$\frac{\cos x^{2 \cdot \sin x}- 2 \cdot (\cos x)^{\sin x} + 1}{x^6}$$ and my idea here was to use Bernuolli to $\cos x^{\sin x}$ so that $(1+x)^n\geq1+nx$ but it is going to be nasty and the expression $(...)\geq(...)$ does not tell anything about that limit. Any hints? Thank you in advance.

A:

first find the first terms of the series expansion of $1-\cos(x)^{\sin(x)}$ without using the ones of sin and cos, you will find that$$1-\cos(x)^{\sin(x)}=\frac{x^3}{2}+\text{higer trems}$$ which implies $$\lim_{x\to 0}\frac{(1-\cos(x)^{\sin(x)})^2}{x^6}=\lim_{x\to 0}\frac{\frac{x^6}{4}+x^3(\text{higer terms})+\text{(higer terms)}^2}{x^6}=\frac{1}{4}$$ since the degree of higer terms is larger than 3.

A:

$$\lim_{x \rightarrow 0}\left ( x^{-6}\cdot (1-\cos x^{\sin x})^2 \right )$$
$$=\lim_{x\to 0}\left(\frac{\sin x}x\right)^6\cdot \lim_{x\to 0}\left(\frac{1-\cos x^{\sin x}}{\sin^3x}\right)^2$$
Now, Putting $y=\sin x$ in the last limit, as $x\to 0,y=\sin x\to 0$ and $\cos x^{\sin x}=(\cos^2x)^{\frac {\sin x}2}=(1-y^2)^\frac y2$
$$\lim_{x\to 0}\frac{1-\cos x^{\sin x}}{\sin^3x}$$
$$=\lim_{y\to 0}\frac{1-(1-y^2)^{\frac y2}}{y^3}$$
$$=\lim_{y\to 0}\frac{1-\left(1+(-y^2)\cdot \frac y2+(-y^2)^2\cdot\frac{\frac y2\left(\frac y2-1\right)}{2!}+\cdots\right)}{y^3}$$
$$=\lim_{y\to 0}\{\frac12+O(y^2)\}\text { as }y\ne0 \text { as } y\to 0$$
$$=\frac12$$


Q:

Show all services on right click

Whenever you have more than 4 services, they are put in a dropdown option "Services" on right click instead of just being added to the right click menu itself.
Is this an option somewhere that can be changed?
Thanks.

A:

Services Manager seems to just modify .GlobalPreferences.plist:
defaults write -g NSServicesMinimumItemCountForContextSubmenu -int 999

You have to reopen applications to apply the changes.

A:

The little known Apple Services Manager, released via Mac OS X Automation, offers such a setting (bottom right of the main window), besides other service amenities like fine grained control over which service actually turns up in the menu.


Q:

how to get number of documents term appear in, in elasticsearch rails

if I have many documents and want to know " how many documents the term 'rails'  appear in "
is there a way to get this information from elasticsearch " tire gem " from the index ?

A:

You can use Facets to make something like SQL 'group-by' aggregate function, as described here in elasticsearch documentation.
A sample code would look like:
index_name = "documents" # name of your index
search_word = 'rails' # word searching for
field_name = 'document_text' # field to search in
search = Tire.search index_name do
  query do
    string "#{field_name}:#{search_word}"
  end
  facet 'ids-facets', :global => false do
    terms :id
  end
end
document_ids = search.results.facets['ids-facets']['terms']

Hope this helps.


Q:

Retrofit Get method with parsed url

I am working on the project that includes a call to API.
The API has implemented pagination in response.
I am getting next page's URL inside the response header.
It is some sort of parsed URL like %3A for ':' and %2F for '/'.
so is there any way in the retrofit that I can call get method using that URL.
thank you in advanced

A:

You can try with this
@GET(Endpoint.URL")
Call<ListResponse> getList();


Q:

Prove the inequality $ax+by+cz+\sqrt{\left(a^2+b^2+c^2\right)\left(x^2+y^2+z^2\right)}\ge\frac23(a+b+c)(x+y+z)$

Prove the inequality
$$ax+by+cz+\sqrt{\left(a^2+b^2+c^2\right)\left(x^2+y^2+z^2\right)}\ge\frac23(a+b+c)(x+y+z)$$
$a,b,c,x,y,z \in \mathbb R$

My attempts:
$$ax+by+cz+\sqrt{\left(a^2+b^2+c^2\right)\left(x^2+y^2+z^2\right)}\ge\frac23(a+b+c)(x+y+z)$$
$$(a+x-b-y)^2+(c+z-a-x)^2+(b+y-c-z)^2+(a+b+c-x-y-z)^2 \ge \\ \ge 3 \left( \sqrt{a^2+b^2+c^2}-\sqrt{x^2+y^2+z^2} \right)^2$$ Let $a-x=A, \:b-y=B, \:c-z=C,\:a+x=X, \:b+y=Y, \:c+z=Z$. Then
$$(X-Y)^2+(X-Z)^2+(Y-Z)^2+(A+B+C)^2 \ge \\ \ge \frac{3}{4} \left( \sqrt{(A+X)^2+(B+Y)^2+(C+Z)^2}-\sqrt{(A-X)^2+(B-Y)^2+(C-Z)^2} \right)^2$$

A:

Suppose you had two vectors on the unit sphere $\hat u=\langle0,0,1\rangle$ and $\hat v\langle\sin\psi,0,\cos\psi\rangle$. $0\le\psi\le\pi$ and you wanted to find the vector $\hat w=\langle\sin\theta\cos\phi,\sin\theta\sin\phi,\cos\theta\rangle$ such that $(\hat w\cdot\hat u)(\hat w\cdot\hat v)$ is maximized.
Then we want to maximize
$$(\sin\theta\cos\phi\sin\psi+\cos\theta\cos\psi)\cos\theta=\frac12\cos\phi\sin\psi\sin2\theta+\frac12\cos\psi(1+\cos2\theta)$$
If $\sin2\theta<0$ we want $\cos\phi=-1$ whereas if $\sin2\theta>0$, $\cos\phi=1$. In either case $(\hat w\cdot\hat u)(\hat w\cdot\hat v)=\frac12\cos\psi+\frac12\cos(2\theta\pm\psi)$ which has a maximum of
$$\frac12(1+\cos\psi)=\cos^2\frac{\psi}2$$
By rotations we could have started out with any $2$ unit vectors $\hat u$ and $\hat v$ and found that
$$(\hat w\cdot\hat u)(\hat w\cdot\hat v)\le\frac12(1+\hat u\cdot\hat v)$$
Here our
$$\begin{align}\hat u&=\frac{\langle a,b,c\rangle}{\sqrt{a^2+b^2+c^2}}\\
\hat v&=\frac{\langle x,y,z\rangle}{\sqrt{x^2+y^2+z^2}}\\
\hat w&=\frac{\langle1,1,1\rangle}{\sqrt{3}}\end{align}$$
So we have
$$\frac{(a+b+c)(x+y+z)}{3\sqrt{a^2+b^2+c^2}\sqrt{x^2+y^2+z^2}}\le\frac12\left(1+\frac{ax+by+cz}{\sqrt{a^2+b^2+c^2}\sqrt{x^2+y^2+z^2}}\right)$$
Which works out to
$$\frac23(a+b+c)(x+y+z)\le\sqrt{a^2+b^2+c^2}\sqrt{x^2+y^2+z^2}+ax+by+cz$$
I feel kinda bad about the first part of my proof, though: shouldn't there be a more elegant way to show that the unit vector $\hat w$ has to lie halfway between $\hat u$ and $\hat v$?
EDIT: I felt so bad about the first part of my proof that I wanted to show how it could be done cleaner. Again, given $2$ unit vectors $\hat u$ and $\hat v$ we are trying to find the unit vector $\hat w$ that maximizes $\left(\hat w\cdot\hat u\right)\cdot\left(\hat w\cdot\hat v\right)$. We decompose $\hat w$ into its components parallel and perpendicular to the plane containing $\hat u$ and $\hat v$:
$$\hat w=\vec w_{\parallel}+\vec w_{\bot}$$
Then
$$1=\|\hat w\|^2=\|\vec w_{\parallel}\|^2+2\vec w_{\parallel}\cdot\vec w_{\bot}+\|\vec w_{\bot}\|^2=\|\vec w_{\parallel}\|^2+\|\vec w_{\bot}\|^2$$
So $\|\vec w_{\parallel}\|^2\le1$. Then assuming we can attain a positive value of our objective function
$$\left(\hat w\cdot\hat u\right)\cdot\left(\hat w\cdot\hat v\right)=\left(\vec w_{\parallel}\cdot\hat u\right)\cdot\left(\vec w_{\parallel}\cdot\hat v\right)\le\frac{\left(\vec w_{\parallel}\cdot\hat u\right)\cdot\left(\vec w_{\parallel}\cdot\hat v\right)}{\|\vec w_{\parallel}\|^2}$$
So the maximum is attained only for a unit vector $\hat w$ lying in the plane containing $\hat u$ and $\hat v$. This reduces to a $2$-dimensional problem. Let $\hat w\cdot\hat u=\cos\alpha$, $\hat w\cdot\hat v=\cos\xi$, and $\hat u\cdot\hat v=\cos\psi$. Then
$$\begin{align}\left(\hat w\cdot\hat u\right)\cdot\left(\hat w\cdot\hat v\right)&=\cos\alpha\cos\xi=\frac12\left(\cos(\alpha+\xi)+\cos(\alpha-\xi)\right)\\
&=\frac12\left(\cos\psi+\cos(\alpha-\xi)\right)\le\frac12\left(\cos\psi+1\right)\end{align}$$
This is familiar from optics where if you have light passing through $2$ plane polarizing filters at angle $\psi$ between them you get maximum transmission when a third such filter at angle $\frac{\psi}2$ is placed between them so the transmission coefficient through the last $2$ filters becomes $\cos^4\frac{\psi}2=\frac14(1+\cos\psi)^2$.
Well, that might have seemed more long-winded than my previous proof and it was, but the cool thing about it is that no reference was made to spherical coordinates so now we can let
$$\begin{align}\hat u=\frac{\sum\limits_{i=1}^na_i\hat e_i}{\sqrt{\sum\limits_{i=1}^na_i^2}},&&
\hat v=\frac{\sum\limits_{i=1}^nx_i\hat e_i}{\sqrt{\sum\limits_{i=1}^nx_i^2}},&&
\hat w=\frac{\sum\limits_{i=1}^n\hat e_i}{\sqrt n}\end{align}$$
And this will work out to
$$\sum_{i=1}^na_ix_i+\sqrt{\sum\limits_{i=1}^na_i^2}\sqrt{\sum\limits_{i=1}^nx_i^2}\ge\frac2n\left(\sum_{i=1}^na_i\right)\left(\sum_{i=1}^nx_i\right)$$
Valid for $n\ge1$.


Q:

Can I turn a Piezo Buzzer into an ultrasonic Mist Maker?

You may have been reading my questions for a project I am doing.  This one is a bit off the wall - I purchased a small 'bottle-top-humidifier' off of amazon and opened it up just to take out the ultrasonic mist maker.
I've been scouring the web for a couple of hours to try to find JUST the piezo ceramic disc that generates the mist.  I've come across a few articles explaining piezoelectronics and it seems that a piezo buzzer and a piezo mist maker are made up of the same materials.
Is this correct?  Can I go purchase some piezo buzzers and use them to create fog? Does anyone have any literature on this?

A:

Piezo transducers for creating audible sound operate in a bending mode and resonate, typically, at 2kHz to 4kHz.
Piezo tranducers used in nebulizers operate in a thickness mode and resonate, typically, at 1MHz to 2.5MHz (1.6MHz is a popular choice).
They're quite different (1000:1 in resonant frequency)- just go and buy the right thing for the job.


Q:

chmod unable to change group permission on cygwin

I am trying to copy files to an AWS instance using SCP but am running into permission denied error as below,i tried to change the group name to "Users" as well which didnt work either?can anyone provide guidance on how to fix this?
 drwx------+ 1 username      NA+Group(513)    0 May 10 23:33 .ssh
-rwxr-xr-x  1 Administrators NA+Group(513) 1692 May  5 17:00 ngc.pem
-rwxr-xr-x  1 Administrators NA+Group(513) 1692 May  8 12:47 test.pem
-rwxr-xr-x  1 Administrators NA+Group(513) 1464 May  8 13:45 test.ppk

username@machine ~
$ scp -i test.pem index.html ec2-publicip.us-west-2.compute.amazonaws.com:~
Permission denied (publickey).
lost connection

username@machine ~
$ chown usernam1 test.pem
chown: changing ownership of 'test.pem': Permission denied

username@machine ~
$ chown :Users test.pem
chown: changing group of 'test.pem': Permission denied

A:

Permission denied does not relate to the permissions of the .pem file in your computer, but to the permissions of the .pem file to the server it is trying to access. First - you need to specify the specific user you are trying to scp into. For example, if this is an Ubuntu server, the correct syntax for the command would be - scp -i test.pem index.html ubuntu@ec2-publicip.us-west-2.compute.amazonaws.com:., that will copy the file to the home folder of the ubuntu user.


Q:

Need to extract following texts which doesn't have a clear xpath with rvest in R

I have a few webpages which I wanted to scrape (html example below). In my example I wanted to get the company name, location, salary, posted date so my approach to get the company name is like this:
library(xml2)
library(rvest)
library(tidyverse)

url <- "https://joblist.ala.org/job/library-director/53812381/"
page <- xml2::read_html(url)

company_name <- page %>%
  rvest::html_nodes("li") %>%
  rvest::html_nodes(xpath = '//*[@class="clearfix"]') %>%
  #rvest::html_nodes("div")%>%
  rvest::html_nodes("span") %>%
  #rvest::html_name()%>%
  rvest::html_text()%>%
  stringr::str_replace_all("[\r\n\t]" , "")%>%
  stringr::str_trim()

However this yields:
# [1] "Description"
# [2] "We are looking for a Skilled, Dynamic, and Collaborative Leader"
# [3] "Mobile Public Library"
# [4] ""
# [5] "Mobile, Alabama, United States"
# [6] "53812381"
# [7] "April 21, 2020"
# [8] "Library Director"
# [9] "Mobile Public Library"
# [10] "Public Library"
# [11] "Administration/Management"
# [12] "No"
# [13] "Full-Time"
# [14] "Indefinite"
# [15] "Master's Degree"
# [16] "5-7 Years"
# [17] "0-10%"
# [18] "Jobs You May Like"

I thought I can get what I want through indexing, but then when I move to next site, the position for some elements change. Like here:
url <- "https://joblist.ala.org/job/ceo-library-director-orange-county-library-system/53673222/"
page <- xml2::read_html(url)

company_name <- page %>%
  rvest::html_nodes("li") %>%
  rvest::html_nodes(xpath = '//*[@class="clearfix"]') %>%
  #rvest::html_nodes("div")%>%
  rvest::html_nodes("span") %>%
  #rvest::html_name()%>%
  rvest::html_text()%>%
  stringr::str_replace_all("[\r\n\t]" , "")%>%
  stringr::str_trim()

Yields:
# [1] "Description"
# [2] "Requirements"
# [3] "Orange County Library System"
# [4] ""
# [5] "Orlando, Florida, 32801, United States"
# [6] "53673222"
# [7] "April 1, 2020"
# [8] "CEO / Library Director -  Orange County Library System"
# [9] "Orange County Library System"
# [10] "Public Library"
# [11] "Administration/Management"
# [12] "No"
# [13] "Full-time"
# [14] "Indefinite"
# [15] "Master's Degree"
# [16] "Over 10 Years"
# [17] "10-25%"
# [18] "$151,882.00 - $160,000.00 (Yearly Salary)"
# [19] "Jobs You May Like"

Console Inspector looks like this:

Location:

  Orlando, Florida, 32801, United States

Job ID:

  53673222

Posted:

  April 1, 2020

Position Title:

  CEO / Library Director -  Orange County Library System

Company Name:

  Orange County Library System

Library or Company Type:

  Public Library

Job Category:

  Administration/Management

Entry Level:

  No

Job Type:

  Full-time

Job Duration:

  Indefinite

Min Education:

  Master's Degree

Min Experience:

   Over 10 Years

Required Travel:

   10-25%

Salary:

   $151,882.00 - $160,000.00 (Yearly Salary)

I was wondering if someone can help me out by showing how to get the company name, I can replicate it for others. Not good with HTML. Thank you!

A:

Since there are no specific classes for each category, we may use regex to extract the information.
library(rvest)

url <- "https://joblist.ala.org/job/library-director/53812381/"
page <- xml2::read_html(URL)

page %>%
  html_nodes("li") %>%
  html_nodes(xpath = '//*[@class="clearfix"]') %>%
  html_text() %>%
  gsub('[\r\n\t]', '', .) %>%
  grep('Company Name:', ., value = TRUE) %>%
  sub('Company Name:', '', .) %>% .[2]

#[1] " Mobile Public Library"

You can extract the information from other categories in the same way. For example, with 'Position Title:' :
page %>%
  html_nodes("li") %>%
  html_nodes(xpath = '//*[@class="clearfix"]') %>%
  html_text() %>%
  gsub('[\r\n\t]', '', .) %>%
  grep('Position Title:', ., value = TRUE) %>%
  sub('Position Title:', '', .) %>% .[2]

#[1] " Library Director"

Probably, you could just write a function and pass strings like "Company Name:" and "Position Title:" to it.


Q:

Self-join in Oracle SQL - selecting rows based on 1 same column and 1 different column

It may not be a self-join I need, but I'm having difficulty with this problem and I hope someone can help me.
Sample Data:
Row   Code   ReservationID   ClientID EmployeeID
1     T            123          7777     John
2     T            456          2020     John
3     P            456          2020     John
4     P            999          3100     Steve
5     P            876          3100     Steve
6     T            333          2424     John
7     P            333          2424     Lynda

Desired output:
Row   Code   ReservationID   ClientID EmployeeID
2     T            456          2020     John
3     P            456          2020     John
6     T            333          2424     John
7     P            333          2424     Lynda

I'm looking for a query that will only return Rows 2, 3, 6, and 7.
The selection criteria is when there is a row with Code = T and another row with Code = P but for the same Reservation ID and CLientID.  The EmployeeID may be the same or different (I want to return the EmployeeID in the results but not use it in the select criteria).
Reading forums I think I need a self-join (which I don't know how to do).  Any help you can offer would really be appreciated!  Thanks!

A:

One method uses exists:
select t.*
from t
where (t.code = 'T' and exists (select 1 from t t2 where t2.reservationId = t.reservationId and t2.clientId = t.clientId and t2.code = 'P'
                               )
      ) or
      (t.code = 'P' and exists (select 1 from t t2 where t2.reservationId = t.reservationId and t2.clientId = t.clientId and t2.code = 'T'
                               )
      );

For performance, you want an index on (reservationId, clientId, code).

A:

I think the simplest solution is:
select distinct t1.*
  from my_table t1
  join my_table t2 on t1.reservationid = t2.reservationid
  where t1.code = 'T' and t2.code = 'P'
     or t1.code = 'P' and t2.code = 'T';


Q:

Prove $2^n$ is smaller than binomial coefficent of $2n$ over $n$

I need to show that $\binom{2n}{n} \geq 2^n$.
I'm required to do this by using induction.
For $n=1$ this is rather easy.
I just don't get very far when going to the next step for $n+1$. Is there a way to write this as a sum, or is there another easy way to do that?

A:

Hint:
$$\binom{2n+2}{n+1}=\frac{(2n+2)(2n+1)}{(n+1)^2}\binom{2n}{n}$$
So it's sufficient to show that
$$\frac{(2n+2)(2n+1)}{(n+1)^2}=\frac{2(2n+1)}{n+1}\ge 2$$
for sufficiently large $n$.


Q:

Google cloud endpoints and guice

I'm having trouble getting google cloud endpoints working with google guice. It appears from the classes available in the endpoints library that this should be possible, but it isn't clear to me how to wire it up, and I see no documentation.
There apparently was a solution, but the API seems to have changed since then.
I tried extending com.google.api.server.spi.guice.SystemServiceModule overriding both configure() and getServiceClasses(), and implementing a GuiceServletContextListener.
The getInjector() method on the GuiceServletContextListeneris invoked, and thus the configure() method on the SystemServiceModule, but the "getServiceClasses() method is never invoked. When services are called, the service class has not had any dependencies injected.
Does anybody know how to wire this up correctly?

A:

Key to use endpoints with guice is to get the servlet mapping right. Try
public class YourGuiceListener extends GuiceServletContextListener {
    static class ServletModule extends GuiceSystemServiceServletModule {
        @Override
        protected void configureServlets() {
            super.configureServlets();
            Set<Class<?>> serviceClasses = new HashSet<Class<?>>();
            serviceClasses.add(YourEndpointsService1.class);
            serviceClasses.add(YourEndpointsService2.class);
            this.serveGuiceSystemServiceServlet("/_ah/spi/*", serviceClasses);//endpoints servlet mapping
            ...
        }
    }

    public static class InjectionModule extends AbstractModule {
        @Override
        protected void configure() {
            bind... //optional bindings
        }
    }
}

add Guice listener and filter to web.xml
<listener><listener-class>package.YourGuiceListener</listener-class></listener>
<filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
</filter-mapping>


Q:

issues with the iphone app runs on ipad

I had a problem with my iPhone app runs on iPad .I am using camera overlay view in first screen (launches when app starts) but when i navigate to other screen there is  a blank white space on top of it.This appears in iPad only , on iPhone all works great.
Here is attached image showing blank white screen

code for camera overlay view
    controlView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
controlViewLandscape  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 480, 320)];

controlView1= [[UIView alloc]initWithFrame:CGRectMake(0,170, 420, 480)];
controlViewLandscape1=  [[UIView alloc]initWithFrame:CGRectMake(0, 0, 480, 320)];

anImagePickerController = [UIImagePickerController new];
anImagePickerController.view.frame=CGRectMake(0, 0, 320, 480);
anImagePickerController.delegate = self;
anImagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
anImagePickerController.cameraDevice=UIImagePickerControllerCameraDeviceFront;
anImagePickerController.showsCameraControls=NO;
anImagePickerController.wantsFullScreenLayout=YES;
anImagePickerController.cameraViewTransform=CGAffineTransformScale(anImagePickerController.cameraViewTransform, 1.16676, 1.34299);

UIButton *startbutton = [UIButton buttonWithType:UIButtonTypeCustom];
[startbutton setImage:[UIImage imageNamed:@"play2.png"] forState:UIControlStateNormal];
startbutton.frame=CGRectMake(130, 390, 55, 55);
[startbutton setTitle:@"Start" forState:UIControlStateNormal];
[startbutton addTarget:self action:@selector(startChat) forControlEvents:UIControlEventTouchUpInside];
anImagePickerController.cameraOverlayView = startbutton;

UIButton *startbutton1 = [UIButton buttonWithType:UIButtonTypeCustom];
startbutton1.frame=CGRectMake(-50, 10, 150, 30);
[startbutton1 setTitle:@"Status:" forState:UIControlStateNormal];
startbutton1.titleLabel.font=[UIFont boldSystemFontOfSize:12];

UIButton *startbutton2 = [UIButton buttonWithType:UIButtonTypeCustom];
startbutton2.frame=CGRectMake(13, 10, 150, 30);
[startbutton2 setTitle:@"Disconnected" forState:UIControlStateNormal];
startbutton2.titleLabel.font=[UIFont boldSystemFontOfSize:12];

//setting button

UIButton *settingBtn = [UIButton buttonWithType:UIButtonTypeCustom];
settingBtn.frame=CGRectMake(272, 10, 43, 43);
//[settingBtn setTitle:@"Setting" forState:UIControlStateNormal];
[settingBtn setImage:[UIImage imageNamed:@"settings.png"] forState:UIControlStateNormal];
[settingBtn addTarget:self action:@selector(settingNavigate) forControlEvents:UIControlEventTouchUpInside];
[controlView addSubview:settingBtn];
[controlView addSubview:startbutton2];
[controlView addSubview:startbutton];
[controlView addSubview:startbutton1];
controlView.tag=10;
//for landscape

UIButton *startbuttonl = [UIButton buttonWithType:UIButtonTypeCustom];
[startbuttonl setImage:[UIImage imageNamed:@"play2.png"] forState:UIControlStateNormal];
startbuttonl.frame=CGRectMake(210, 245, 55, 55);
[startbuttonl setTitle:@"Start" forState:UIControlStateNormal];
[startbuttonl addTarget:self action:@selector(startChat) forControlEvents:UIControlEventTouchUpInside];

UIButton *startbutton1l = [UIButton buttonWithType:UIButtonTypeCustom];
startbutton1l.frame=CGRectMake(-60,-8, 150, 30);
[startbutton1l setTitle:@"Status:" forState:UIControlStateNormal];
startbutton1l.titleLabel.font=[UIFont boldSystemFontOfSize:12];
UIButton *startbutton2l = [UIButton buttonWithType:UIButtonTypeCustom];
startbutton2l.frame=CGRectMake(3, -8, 150, 30);
[startbutton2l setTitle:@"Disconnected" forState:UIControlStateNormal];
startbutton2l.titleLabel.font=[UIFont boldSystemFontOfSize:12];
//setting button

UIButton *settingBtnl = [UIButton buttonWithType:UIButtonTypeCustom];
settingBtnl.frame=CGRectMake(420,0, 43, 43);
//[settingBtn setTitle:@"Setting" forState:UIControlStateNormal];
[settingBtnl setImage:[UIImage imageNamed:@"settings.png"] forState:UIControlStateNormal];
[settingBtnl addTarget:self action:@selector(settingNavigate) forControlEvents:UIControlEventTouchUpInside];

[controlViewLandscape addSubview:settingBtnl];
[controlViewLandscape addSubview:startbutton2l];
[controlViewLandscape addSubview:startbuttonl];
[controlViewLandscape addSubview:startbutton1l];

//for landscape left

UIButton *startbuttonlr = [UIButton buttonWithType:UIButtonTypeCustom];
[startbuttonlr setImage:[UIImage imageNamed:@"play2.png"] forState:UIControlStateNormal];
startbuttonlr.frame=CGRectMake(220, 263, 55, 55);
[startbuttonlr setTitle:@"Start" forState:UIControlStateNormal];
[startbuttonlr addTarget:self action:@selector(startChat) forControlEvents:UIControlEventTouchUpInside];

UIButton *startbutton1lr = [UIButton buttonWithType:UIButtonTypeCustom];
startbutton1lr.frame=CGRectMake(-40, 20, 150, 30);
[startbutton1lr setTitle:@"Status:" forState:UIControlStateNormal];
startbutton1lr.titleLabel.font=[UIFont boldSystemFontOfSize:12];

UIButton *startbutton2lr = [UIButton buttonWithType:UIButtonTypeCustom];
startbutton2lr.frame=CGRectMake(23, 20, 150, 30);
[startbutton2lr setTitle:@"Disconnected" forState:UIControlStateNormal];
startbutton2lr.titleLabel.font=[UIFont boldSystemFontOfSize:12];

//setting button

UIButton *settingBtnlr = [UIButton buttonWithType:UIButtonTypeCustom];
settingBtnlr.frame=CGRectMake(440, 20, 43, 43);
//[settingBtn setTitle:@"Setting" forState:UIControlStateNormal];
[settingBtnlr setImage:[UIImage imageNamed:@"settings.png"] forState:UIControlStateNormal];
[settingBtnlr addTarget:self action:@selector(settingNavigate) forControlEvents:UIControlEventTouchUpInside];

[controlViewLandscape1 addSubview:settingBtnlr];
[controlViewLandscape1 addSubview:startbutton2lr];
[controlViewLandscape1 addSubview:startbuttonlr];
[controlViewLandscape1 addSubview:startbutton1lr];

//for portrait down

UIButton *startbuttonlp = [UIButton buttonWithType:UIButtonTypeCustom];
[startbuttonlp setImage:[UIImage imageNamed:@"play2.png"] forState:UIControlStateNormal];
//startbuttonlp.frame=CGRectMake(-50, 210, 55, 55);
startbuttonlp.frame=CGRectMake(50, 385, 55, 55);
[startbuttonlp setTitle:@"Start" forState:UIControlStateNormal];
[startbuttonlp addTarget:self action:@selector(startChat) forControlEvents:UIControlEventTouchUpInside];

UIButton *startbutton1lp = [UIButton buttonWithType:UIButtonTypeCustom];
startbutton1lp.frame=CGRectMake(-130, 0, 150, 30);
[startbutton1lp setTitle:@"Status:" forState:UIControlStateNormal];
startbutton1lp.titleLabel.font=[UIFont boldSystemFontOfSize:12];

UIButton *startbutton2lp = [UIButton buttonWithType:UIButtonTypeCustom];
startbutton2lp.frame=CGRectMake(-66, 0, 150, 30);
[startbutton2lp setTitle:@"Disconnected" forState:UIControlStateNormal];
startbutton2lp.titleLabel.font=[UIFont boldSystemFontOfSize:12];
//setting button

UIButton *settingBtnlp = [UIButton buttonWithType:UIButtonTypeCustom];
settingBtnlp.frame=CGRectMake(192,0, 43, 43);
//  settingBtnlp.frame=CGRectMake(92, 70, 43, 43);
[settingBtnlp setImage:[UIImage imageNamed:@"settings.png"] forState:UIControlStateNormal];
[settingBtnlp addTarget:self action:@selector(settingNavigate) forControlEvents:UIControlEventTouchUpInside];

[controlView1 addSubview:settingBtnlp];
[controlView1 addSubview:startbutton2lp];
[controlView1 addSubview:startbuttonlp];
[controlView1 addSubview:startbutton1lp];
//to rotate it to landscape
CGAffineTransform landscapeTransform = CGAffineTransformMakeRotation(degreesToRadian(90) );
landscapeTransform = CGAffineTransformTranslate( landscapeTransform, +90.0, +90.0 );
[controlViewLandscape setTransform:landscapeTransform];

//to rotate it to landscape right
CGAffineTransform landscapeTransformr = CGAffineTransformMakeRotation(degreesToRadian(-90) );
landscapeTransformr = CGAffineTransformTranslate( landscapeTransformr, -90, -90);
[controlViewLandscape1 setTransform:landscapeTransformr];
//to rotate it to portrait right
CGAffineTransform landscapeTransformrp = CGAffineTransformMakeRotation(degreesToRadian(180) );
landscapeTransformrp = CGAffineTransformTranslate( landscapeTransformrp, +180.0, +180.0 );
[controlView1 setTransform:landscapeTransformrp];

controlViewLandscape.tag=20;
controlViewLandscape1.tag=40;
controlView1.tag=30;
//controlView1.hidden=YES;

//  controlViewLandscape.hidden=YES;
//  controlViewLandscape1.hidden=YES;
//  controlView.hidden=YES;
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

if ( ([self  interfaceOrientation] == UIInterfaceOrientationPortrait))
{

    controlView.hidden = NO;
    controlViewLandscape.hidden = YES;
    controlView1.hidden = YES;
    controlViewLandscape1.hidden = YES;

}

if ( ([self  interfaceOrientation] == UIInterfaceOrientationLandscapeLeft))
{

    controlView.hidden = YES;
    controlViewLandscape.hidden = YES ;
    controlView1.hidden = YES;
    controlViewLandscape1.hidden = NO;

}

if ( ([self  interfaceOrientation] == UIInterfaceOrientationPortraitUpsideDown ))
{

    controlView.hidden = YES;
    controlViewLandscape.hidden = YES;
    controlView1.hidden = NO;
    controlViewLandscape1.hidden =YES;

}

if ( ([self  interfaceOrientation] == UIInterfaceOrientationLandscapeRight))
{

    controlView.hidden = YES;
    controlViewLandscape.hidden = NO;
    controlView1.hidden = YES;
    controlViewLandscape1.hidden = YES;
}
overlayView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 500, 500)];
[overlayView addSubview:controlView];
[overlayView addSubview:controlViewLandscape];
[overlayView addSubview:controlViewLandscape1];
[overlayView addSubview:controlView1];

//anImagePickerController.cameraOverlayView = controlView;
anImagePickerController.cameraOverlayView = overlayView;

[self.navigationController presentModalViewController:anImagePickerController animated:NO];

[anImagePickerController release];

A:

solved,
use the following line to show the status bar
[[UIApplication sharedApplication]setStatusBarHidden:NO];

And it display a black bar instead of a white space.
Thanks everyone for the cooperation


Q:

Is there anyway to make this into a for loop or improve it?

I have this code that I want to basically: Change the button image for a certain amount of time and then reset it, then change another button etc...
 buttonList[total[0]].setImage(imagePlay, forState: .Normal);
        let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(speed * Double(NSEC_PER_SEC)))
        dispatch_after(time, dispatch_get_main_queue()) {
            self.buttonList[total[0]].setImage(self.og, forState: .Normal);
            self.buttonList[total[1]].setImage(self.imagePlay, forState: .Normal);
            let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(speed * Double(NSEC_PER_SEC)))
            dispatch_after(time, dispatch_get_main_queue()) {
                self.buttonList[total[1]].setImage(self.og, forState: .Normal);
                self.buttonList[total[2]].setImage(self.imagePlay, forState: .Normal);
                let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(speed * Double(NSEC_PER_SEC)))
                dispatch_after(time, dispatch_get_main_queue()) {
                    self.buttonList[total[2]].setImage(self.og, forState: .Normal);
                    self.buttonList[total[3]].setImage(self.imagePlay, forState: .Normal);
                    let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(speed * Double(NSEC_PER_SEC)))
                    dispatch_after(time, dispatch_get_main_queue()) {
                        self.buttonList[total[3]].setImage(self.og, forState: .Normal);
                        self.buttonList[total[4]].setImage(self.imagePlay, forState: .Normal);
                        let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(speed * Double(NSEC_PER_SEC)))
                        dispatch_after(time, dispatch_get_main_queue()) {
                            self.buttonList[total[4]].setImage(self.og, forState: .Normal);
                            self.buttonList[total[5]].setImage(self.imagePlay, forState: .Normal);
                            let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(speed * Double(NSEC_PER_SEC)))
                            dispatch_after(time, dispatch_get_main_queue()) {
                                self.buttonList[total[5]].setImage(self.og, forState: .Normal);
                                self.buttonList[total[6]].setImage(self.imagePlay, forState: .Normal);
                                let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(speed * Double(NSEC_PER_SEC)))
                                dispatch_after(time, dispatch_get_main_queue()) {
                                    self.buttonList[total[6]].setImage(self.og, forState: .Normal);
                                    self.buttonList[total[7]].setImage(self.imagePlay, forState: .Normal);
                                    let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(speed * Double(NSEC_PER_SEC)))
                                    dispatch_after(time, dispatch_get_main_queue()) {
                                            self.buttonList[total[7]].setImage(self.og, forState: .Normal);
                                            self.buttonList[total[8]].setImage(self.imagePlay, forState: .Normal);
                                            let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(speed * Double(NSEC_PER_SEC)))
                                            dispatch_after(time, dispatch_get_main_queue()) {
                                                self.buttonList[total[8]].setImage(self.og, forState: .Normal);
                                                self.replayButton.enabled = true;
                                                for(var i = 0; i < self.buttonList.count; i++){
                                                    self.buttonList[i].enabled = true;

As you can see this is a long process as eventually I will have arrays with sizes of 30+, can someone suggest a better way please? Thank You.

A:

You could use a function that just schedules everything in advance, like this:
func updateButtonImages() {
    let buttons = total.map { buttonList[$0] }
    buttons[0].setImage(imagePlay, forState: .Normal)

    var time = dispatch_time(DISPATCH_TIME_NOW, 0)
    for (priorButton, currentButton) in zip(buttons[0..<buttons.count - 1], buttons[1..<buttons.count]) {
        time = dispatch_time(time, Int64(speed * Double(NSEC_PER_SEC)))
        dispatch_after(time, dispatch_get_main_queue()) {
            priorButton.setImage(og, forState: .Normal)
            currentButton.setImage(imagePlay, forState: .Normal)
        }
    }

    time = dispatch_time(time, Int64(speed * Double(NSEC_PER_SEC)))
    dispatch_after(time, dispatch_get_main_queue()) {
        buttons.last?.setImage(og, forState: .Normal)
        replayButton.enabled = true
        buttonList.forEach { $0.enabled = true }
    }
}

Or you could use a function that reschedules itself, like this:
func updateButtonImages(currentIndex currentIndex: Int = 0, priorIndex: Int? = nil) {
    if let priorIndex = priorIndex {
        buttonList[total[priorIndex]].setImage(og, forState: .Normal)
    }

    if currentIndex == total.count {
        replayButton.enabled = true
        buttonList.forEach {
            $0.enabled = true
        }
        return
    }

    buttonList[total[currentIndex]].setImage(imagePlay, forState: .Normal)

    let nextUpdateTime = dispatch_time(DISPATCH_TIME_NOW, Int64(speed * Double(NSEC_PER_SEC)))
    dispatch_after(nextUpdateTime, dispatch_get_main_queue()) {
        updateButtonImages(currentIndex: currentIndex + 1, priorIndex: currentIndex)
    }
}

Either way, just call updateButtonImages() to start the process.


Q:

How to set the local Hazelcast member as a preferred?

For example, we have 3 machines and each machine has 1 member and 1 client. To improve performance, I want that each client would send put/get requests to the local member first and only if there is no local member, it would communicate with other members in the cluster.
Does this make sense? And if yes, can we put "localhost" as a first member in the "hazelcast.xml" to achieve this?

A:

If you are using Hazelcast Map, it is partitioned data structure so your primary data is partitioned across hazelcast members. Hazelcast Client is smart enough to figure out where this primary data is located and executes operation(READ,WRITE) on that hazelcast member. Therefore, connecting to local member does not add a big value in your use case.
What you can use is Near Cache Feature to optimize your read operations.


Q:

Adding list item when user does not have permissions question

I am trying to programmatically add a list item to a SharePoint list. The code works fine when executed by a user with contribute permissions, but does not work when a user has view only. Funny thing is, i can debug through the same code with both users and it does not seem to fail on the user with read only.
I only want users to be able to add items to the list (which has a workflow to approve before they are visible) so giving the users contribute permissions will not work.
I tried running with elevated privileges but that did not work.
Is there a permissions setting to only allow add item ot list, or is there a way to programmatically bypass this issue?
This is the code i am working on right now:
                var siteId = SPContext.Current.Site.ID;
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(siteId))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            web.AllowUnsafeUpdates = true;

                        // Fetch the List
                        SPList list = web.Lists["List Name"];

                        //Add a new item in the List
                        SPListItem itemToAdd = list.Items.Add();
                        itemToAdd["Title"] = titlename;
                        itemToAdd.Update();
                        web.AllowUnsafeUpdates = false;
                        }
                    }
                });

Solved, run with elevated privileges grants you system account access, but you still cannot add an item with it. The full answer can be found on the second reply here:
https://stackoverflow.com/questions/5164626/impersonate-as-different-user-inside-the-webpart-code

A:

You can create a custom permission level that allows adding but not editing.
See this MSDN article about how to do that. You will want to copy the contribute permission but remove the edit permissions.


Q:

Thunk + Redux (in React Native) : Can't get action to work

I'm brand new to this stack.  I've seen quite a few other questions about this and have read the Thunk documentation but I can't stitch this together.
When I run the code below I get the error "Actions must be plain objects, use custom middleware for async actions" which is exactly the problem I'm trying to solve with Thunk.
My action looks like this:
src/actions/recipes.js
// this calls the API
function fetchApiGetRecipes() {
  return fetch('https://mywebsite.com/endpoint/', {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + idToken
    }
  }).then((json) => {
    dispatch({
      type: 'RECIPES_REPLACE',
      data: json
    })

  });
}

// this is passed into my container to use to refresh the recipe list
export function getRecipes() {
  if (Firebase === null) return () => new Promise(resolve => resolve());

  if (Firebase.auth().currentUser !== null) {
          Firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
            // console.log(idToken);
            return dispatch => new Promise(resolve => fetchApiGetRecipes(idToken) )
          }).catch(function(error) {
            // Handle error
          });

  } else {
    console.log("Null user");
  }

}

What is the correct syntax to use Thunk here and fix the error I'm getting when the app starts up?
EDIT:  I create the store like this:
import { createStore, applyMiddleware, compose } from 'redux';
import { persistStore, persistCombineReducers } from 'redux-persist';
import storage from 'redux-persist/es/storage'; // default: localStorage if web, AsyncStorage if react-native
import thunk from 'redux-thunk';
import reducers from '../reducers';

// Redux Persist config
const config = {
  key: 'root',
  storage,
  blacklist: ['status'],
};

const reducer = persistCombineReducers(config, reducers);

const middleware = [thunk];

const configureStore = () => {
  const store = createStore(
    reducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
    compose(applyMiddleware(...middleware)),
  );

  const persistor = persistStore(
    store,
    null,
    () => { store.getState(); },
  );

  return { persistor, store };
};

export default configureStore;

A:

Your getRecipes function doesn't return a function in the if (Firebase.auth().currentUser !== null) clause.
You need to return a function where you are just doing
Firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {
            // console.log(idToken);
            return dispatch => new Promise(resolve => fetchApiGetRecipes(idToken) )
          }).catch(function(error) {
            // Handle error
          });

The dispatch function (I assume is the intended one to return) is being returned in the then clause of the promise. That doesn't return the dispatch function to the outer method getRecipies. Hence the error


Q:

Maximize area of a rectangle between parabola and a line

I was given a task to maximize the area of a rectangle that can be inscribed between parabola $y=1-x^2$ and a line $y=0$ such that one side of the rectangle lies on the $x$ axis. My idea is to somehow parametrize rectangle area and then use derivatives to maximize that area but I am not sure if that's correct nor how to do it..
Thanks ;)

A:

$\cdot$ You that Area = base $\times$ height = $x \cdot f(x) = x(1-x^2)$. Now you wish to maximize this Area. So find it's critical point.


Q:

drag an svg rect

When I try to drag an svg rect like below it first selects any text on my page and then become draggable. How I can make it draggable initially?
<g
      onDragStart={this.onDragStart}
      onDrag={this.onDrag}
      onDragEnd={this.onDragEnd}>
   <rect></rect>
   <text>{text}</text>
</g>

I'm using React and here are a functions of my component:
  onDragStart = (event) => {
    this.setState({
      dx: event.clientX - this.state.x,
      dy: event.clientY - this.state.y
    });
  };

  onDrag = (event) => {
    this.setState({
      x: event.clientX - this.state.dx,
      y: event.clientY - this.state.dy
    });
  };

  onDragEnd = (event) => {
    this.setState({
      x: event.clientX - this.state.dx,
      y: event.clientY - this.state.dy
    });
  };

A:

It turned out, I should use onMouseDown, onMouseMove, onMouseOut and onMouseUp events adding a bool property 'active' in the component state. Now it works.
<g
  onMouseDown={this.onDragStart}
  onMouseMove={this.onDrag}
  onMouseOut={this.onDrag}
  onMouseUp={this.onDragEnd}>
   <rect></rect>
   <text>{text}</text>
</g>

  onDragStart = (event) => {
    this.setState({
      active: true,
      dx: event.clientX - this.state.x,
      dy: event.clientY - this.state.y
    });
  };

  onDrag = (event) => {
    if(this.state.active)
      this.setState({
        x: event.clientX - this.state.dx,
        y: event.clientY - this.state.dy
      });
  };

  onDragEnd = (event) => {
    this.setState({
      active: false,
      x: event.clientX - this.state.dx,
      y: event.clientY - this.state.dy
    });
  };


Q:

Get the status of the current task

When I mention task below, I am referring to a specific Android concept here:
http://developer.android.com/guide/components/tasks-and-back-stack.html#TaskLaunchModes
Hi there,
Let's say there is a button in a base activity. When this button is pressed, a third party file viewer activity is launched from base activity through intent, which displays a file to the user. We do not set any flag in this intent, so I assume the viewer activity is in the same task as the base activity.
So when this viewer activity is in the foreground, is there anyway to detect Home button press, since this triggers the status of the current task to change (probably from having one activity in the foreground to having all of them in the background?)?
Any thought/idea/comment is highly welcomed!
Thanks!

A:

This code at least get the name of the current top activity:
ActivityManager am = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
  if (!tasks.isEmpty()) {
    topActivityName = tasks.get(0).topActivity.getPackageName();
  }


Q:

SQL computed column evaluating numbers should return string

A similar question is here: Computed column should result to string
However in my case, I cannot cast the numeric values to strings. I need to evaluate the numbers and based on them return a text description. Is that possible?
ALTER TABLE dbo.test ADD classTest AS CASE
    WHEN speed > 10 THEN 'fast'
    ELSE 'error' END

Otherwise I suppose I can return numbers that correspond to text values in a look-up table and create a view...

Unfortunately I edited out my syntax error yesterday, I think I was missing the 'END' and an apostrophe somewhere. The fix didn't seem to work yesterday but I just tried it again and things are moving smoothly.

A:

You were close. Just a couple of syntax errors.  Single quotes and END
ALTER TABLE dbo.test ADD classTest AS CASE
    WHEN speed > 10 THEN 'fast'
    ELSE 'error' END

Select * from test

speed   classTest
11      fast
5       error


Q:

There's no place like home

I recently watched The Wizard Of Oz and thought that when Dorothy taps her shoes together three times, it would be easier if she used a program to do it. So let's help her.
Task
Output slippers being tapped together 3 times.
Output
Slippers being tapped together. A pair of slippers not being tapped looks like this:
  __.....__                   __.....__
 / ,------.\                 /.------, \
(  \        \               /        /  )
\  \      ___\             /___      /  /
 \  \   ,'  __`.         .´__  ',   /  /
  \  `.'  ='  `=\       /=´  '=  '.´  /
   `.  `.        \     /        .´  .´
     `.  `.       \   /       .´  .´
       `.  `-.___.'\ /'.___.-´  .´
         `-._      / \      _.-´
             `----'   '----´

And a pair being tapped together looks like this:
         __.....__     __.....__
        /.------, \   / ,------.\
       /        /  ) (  \        \
      /___      /  / \  \      ___\
    .´__  ',   /  /   \  \   ,'  __`.
   /=´  '=  '.´  /     \  `.'  ='  `=\
  /        .´  .´       `.  `.        \
 /       .´  .´           `.  `.       \
/'.___.-´  .´               `.  `-.___.'\
\      _.-´                   `-._      /
 '----´                           `----'

Basically, output
  __.....__                   __.....__
 / ,------.\                 /.------, \
(  \        \               /        /  )
\  \      ___\             /___      /  /
 \  \   ,'  __`.         .´__  ',   /  /
  \  `.'  ='  `=\       /=´  '=  '.´  /
   `.  `.        \     /        .´  .´
     `.  `.       \   /       .´  .´
       `.  `-.___.'\ /'.___.-´  .´
         `-._      / \      _.-´
             `----'   '----´

         __.....__     __.....__
        /.------, \   / ,------.\
       /        /  ) (  \        \
      /___      /  / \  \      ___\
    .´__  ',   /  /   \  \   ,'  __`.
   /=´  '=  '.´  /     \  `.'  ='  `=\
  /        .´  .´       `.  `.        \
 /       .´  .´           `.  `.       \
/'.___.-´  .´               `.  `-.___.'\
\      _.-´                   `-._      /
 '----´                           `----'

  __.....__                   __.....__
 / ,------.\                 /.------, \
(  \        \               /        /  )
\  \      ___\             /___      /  /
 \  \   ,'  __`.         .´__  ',   /  /
  \  `.'  ='  `=\       /=´  '=  '.´  /
   `.  `.        \     /        .´  .´
     `.  `.       \   /       .´  .´
       `.  `-.___.'\ /'.___.-´  .´
         `-._      / \      _.-´
             `----'   '----´

         __.....__     __.....__
        /.------, \   / ,------.\
       /        /  ) (  \        \
      /___      /  / \  \      ___\
    .´__  ',   /  /   \  \   ,'  __`.
   /=´  '=  '.´  /     \  `.'  ='  `=\
  /        .´  .´       `.  `.        \
 /       .´  .´           `.  `.       \
/'.___.-´  .´               `.  `-.___.'\
\      _.-´                   `-._      /
 '----´                           `----'

  __.....__                   __.....__
 / ,------.\                 /.------, \
(  \        \               /        /  )
\  \      ___\             /___      /  /
 \  \   ,'  __`.         .´__  ',   /  /
  \  `.'  ='  `=\       /=´  '=  '.´  /
   `.  `.        \     /        .´  .´
     `.  `.       \   /       .´  .´
       `.  `-.___.'\ /'.___.-´  .´
         `-._      / \      _.-´
             `----'   '----´

         __.....__     __.....__
        /.------, \   / ,------.\
       /        /  ) (  \        \
      /___      /  / \  \      ___\
    .´__  ',   /  /   \  \   ,'  __`.
   /=´  '=  '.´  /     \  `.'  ='  `=\
  /        .´  .´       `.  `.        \
 /       .´  .´           `.  `.       \
/'.___.-´  .´               `.  `-.___.'\
\      _.-´                   `-._      /
 '----´                           `----'

For reference, the characters used are _-.,/\()='`´
Rules

The output can have an optional leading/trailing whitespace
While not explicitly banned, builtins detract from the competition, so please don't post an answer which is simply a single builtin*
This is a code-golf so shortest code in characters wins. Characters is chosen due to the use of a multibyte character.

* For all you killjoys out there, this rule is intended for comedic effect and shouldn't be taken literally

A:

SOGL V0.12, 113 110 108 characters
░╗╬)λ]cw╚╥Æ⁄║RL↓κΟiRDΨ℮≠3*s4sφ¡┐rκ⁾žχ&ν3.ΦƧ⁴ty¬`OΗΒ%Τz׀PΥω╤8⅟∆KΣ⅜4⅔⅝⁰?Z+pķcE□L6⁵/4γ⁽Κ¹‘▓:±↔Ζ`´ŗ⁴@┼⁴┼≥@┼;┼+3∙

Try it Here!
Explanation:
...‘                       push a compressed string of one slipper (one as the top left one) with a leading newline
    ▓                      convert from a multiline string to an array of lines
     :                     dulplicate a copy for reversing horizontally
      ±↔                   reverse horizontally
        Ζ`´ŗ               replace ` with ´
            ⁴              create a copy of the original slipper for the untapped part
             @┼            append a line of spaces after it horizontally
               ⁴┼          append horizontally a copy of the reversed slipper
                 ≥         move this - the untapped version - to the botton of the stack
                  @┼       append a space after the reversed slipper
                    ;┼     append the original slipper after it
                      +    join the two vertically together
                       3∙  multiply vertically three times

A:

Charcoal, 165 127 bytes
Ｆ´´`«‖ＴＰ⪫⪪”}∧≕Ｉ3⁼wＸ¿↔？⁺⊖？◧χêIr﹪≦⎈X⊞c_⁹jＥτＴＣεh⌊Y﹪ＹＹ}φ⬤»[↷¢|nＸ;ＩζCHE⁷ＲrCsd～¢_⊖⦄⎚§⌈▷φＳ¤Iv}›ＲPx!∧⁵Ｆ]üC”`ι»Ｃ⁴²¦⁰Ｃ²¹¦¹²Ｔ⁴²¦²⁴Ｆ²Ｃ⁰¦²⁴

Try it online! Verbose approximation (I don't know how to write ´ in Verbose mode). Explanation:
Ｆ´´`«

Loop twice, once with ´, once with `.
‖Ｔ

Reflect the canvas, transforming the characters, except for the above two, which is why they are special-cased. Note that this causes the right slipper to end up on the left, which is actually correct for the second row.
⪫⪪””`ι»

Print the compressed slipper string, but with `s replaced with the loop character. (Note that the compressed string includes left padding; this means that the reflected string from the first iteration doesn't touch the second string.)
Ｃ⁴²¦⁰

The right slipper is in the wrong place on the canvas, so copy it to the correct place. (This also makes an extra copy of the left slipper.)
Ｃ²¹¦¹²

The second row also needs a copy of the pair of slippers, but this is the same way around as they were originally created. (Actually both pairs get copied, so we now have eight slippers.)
Ｔ⁴²¦²⁴

Delete all unnecessary extra slippers, leaving two rows of two slippers.
Ｆ²Ｃ⁰¦²⁴

Make two additional vertical duplicates of the whole thing.

A:

Bash + Common Utilities (268 265 258 Bytes)
Saved a few bytes thanks to Justin Mariner
Bash (31 21 Bytes)
gzip -d w;cat w w w

Additional File named w (237 Bytes) (Base64 Encoded so I can paste it here)
H4sICIT6rlkAA3cAbZFbDsQgCEX/WQV/ziQWV+BOTOgiu4JZ2YAWhVYSGxpOfNyDyExazPiuOQMsmIe1F5YoTHK2OCDOIEnWVzzhTYBZo5oYbuOkAXwRnNS9qTJ0e9SMOVJKneScFXWWW3bUn+XcFUWaack6krsxav2DH5QP8LaHNcxG7wkMSYUsOSenc8oIHYAy0ExRYxKCl5ByZtZLrG0ZrzZA9eSvohU54RwQUGa7CTgFEX7OIf2XhTsMveQvSeYBO9j3Rpglf2PrHgCR75Y6zgCrwGfJczBuZjgy1c1QH8Af0NuE5gAwAA

This might be seen as cheating, and I kind of agree :P.


Q:

Showing $\langle 2x+1,5\rangle$ is a maximal ideal

Consider the integral domain $\mathbb{Z}[x]$. Show that the ideal $\langle 2x+1,5\rangle$ is a maximal ideal of $\mathbb{Z}[x]$.
I need help with this problem I don't even know where to start since its not 1 generated its throwing me off as to how I should proceed in solving it any hints or help is greatly appreciated thank you.

A:

Notice that, for the Chinese Remainder Theorem, we have:$$\mathbb{Z[x]}/(2x+1,5)\cong\mathbb{Z_5[x]}/(2x+1)$$
Now we know that if R is an integral domain and I is a maximal ideal, R/I is a field.
$(2x+1)$ is a maximal ideal $\iff$ $2x+1$ is irreducible over $\mathbb{Z_5[x]}$, which it is. So you have your thesis.


Q:

Solenoid not embeddable in plane

I'm trying to find an reference (in English) that gives a proof that any $P$-adic solenoid (where $P$ is a sequence of prime numbers) cannot be embedded in the plane, $\mathbb{R}^2$.  So far, all the references seem to only say so, but they never give a proof.  I know Van Dantzig was the originator of the concept, but his paper is in German.  Can anyone help me find a paper or book that gives a proof and is written in English?

A:

Van Dantzig did introduce solenoids in

van Dantzig, D.. "Ueber topologisch homogene Kontinua." Fundamenta Mathematicae 15.1 (1930): 102-125.

but at the time he did not comment on the question of their planarity.
Much later Bing published a result implying that they are not planar and this appears to be the first proof of that fact.

Bing, R. H. "A simple closed curve is the only homogeneous bounded plane continuum that contains an arc." Canad. J. Math 12 (1960): 209-230.


Q:

Bash error while compiling boost with cmake

I'm trying to compile boost(as part of another library installation) but it reports to me that my gcc is broken.
when I run cmake I get
-- The C compiler identification is unknown
-- The CXX compiler identification is GNU 4.7.2
-- Check for working C compiler: /usr/bin/gcc
-- Check for working C compiler: /usr/bin/gcc -- broken
CMake Error at /usr/share/cmake-2.8/Modules/CMakeTestCCompiler.cmake:52 (MESSAGE):
  The C compiler "/usr/bin/gcc" is not able to compile a simple test program.

  It fails with the following output:

   Change Dir: /home/lecopivo/code/bempp-inst/bempp/build/contrib/boost/build/CMakeFiles/CMakeTmp

  Run Build Command:/usr/bin/make "cmTryCompileExec3895803733/fast"

  /usr/bin/make -f CMakeFiles/cmTryCompileExec3895803733.dir/build.make
  CMakeFiles/cmTryCompileExec3895803733.dir/build

  make[1]: Entering directory
  `/home/lecopivo/code/bempp-inst/bempp/build/contrib/boost/build/CMakeFiles/CMakeTmp'

  /usr/bin/cmake -E cmake_progress_report
  /home/lecopivo/code/bempp-inst/bempp/build/contrib/boost/build/CMakeFiles/CMakeTmp/CMakeFiles
  1

  Building C object
  CMakeFiles/cmTryCompileExec3895803733.dir/testCCompiler.c.o

  /usr/bin/gcc -m64 -O3 -march=native (Default on Linux) -o
  CMakeFiles/cmTryCompileExec3895803733.dir/testCCompiler.c.o -c
  /home/lecopivo/code/bempp-inst/bempp/build/contrib/boost/build/CMakeFiles/CMakeTmp/testCCompiler.c

  /bin/sh: 1: Syntax error: "(" unexpected

  make[1]: *** [CMakeFiles/cmTryCompileExec3895803733.dir/testCCompiler.c.o]
  Error 2

  make[1]: Leaving directory
  `/home/lecopivo/code/bempp-inst/bempp/build/contrib/boost/build/CMakeFiles/CMakeTmp'

  make: *** [cmTryCompileExec3895803733/fast] Error 2

  CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
  CMakeLists.txt:28 (project)

-- Configuring incomplete, errors occurred!

I really do not know what might be wrong. When I make my own cmake project in C I have no problems compiling it.

A:

The error you are getting is not from gcc but from /bin/sh, there is no sign that the problem is actually with gcc itself.
/usr/bin/gcc -m64 -O3 -march=native (Default on Linux) -o
CMakeFiles/cmTryCompileExec3895803733.dir/testCCompiler.c.o -c
/home/lecopivo/code/bempp-inst/bempp/build/contrib/boost/build/CMakeFiles/CMakeTmp/testCCompiler.c

/bin/sh: 1: Syntax error: "(" unexpected

Is this value (Default on Linux) something that you have entered somewhere?