Schema Spy unable to find postgresql driver

Question: I want to use Schema Spy to generate schema diagrams,
I have specifed the following command
java -jar schemaSpy_5.0.0.jar -t pgsql -host 10.100.71.21[:5432] -db mydb -s public -u username -p password -dp postgresql-8.0-312.jdbc3.jar -o output/

I have the postgresql driver jar file in the same directory as schema spy jar file. But it gives the following error
[schemaSpy_5.0.0.jar]/net/sourceforge/schemaspy/dbTypes/pgsql.properties
java.lang.ClassNotFoundException: org.postgresql.Driver

Failed to load driver 'org.postgresql.Driver'from: [file:/home/panx/postgresql-8.0- 312.jdbc3.jar]
This entry doesn't point to a valid file/directory: [/whereever/postgresql-8.0-312.jdbc3.jar]

Use the -dp option to specify the location of the database
 drivers for your database (usually in a .jar or .zip/.Z).

Any help would be appreciated.
Thanks,
Pankaj
Comment: Is there any configuration file which has this line /whereever/postgresql-8.0-312.jdbc3.jar . Maybe it is something you have to edit.
Comment: @mbaydar The -dp configuration is used to specify path to driver file which is what I am doing
Comment: Can you add your configuration file ?
Comment: The configuration file is actually embedded in SchemaSpy.jar. I cant modify it by I can override it by using "-dp" option.
Comment: Please do **not** use that out-dated and obsolete driver. Use a  current driver (9.0 or 9.1). If your driver is actually matching your PostgreSQL version you should immediately update to a supported and current version.
Answer: I think the problem is you didn't add the classpath to the driver. You have to add your classpath like this  java -jar schemaSpy_5.0.0.jar -t pgsql -host 10.100.71.21[:5432] -db mydb -s public -u username -p password -dp /home/panx/postgresql-8.0-312.jdbc3.jar -o output/ If it does not work you can download the source code of this project. In the project there is pgsql.properties file in dbTypes folder. You can change it with your classpath and I think this solves your problem.
Comment: I did not know where to look for the jdbc3 driver path on my computer so I downloaded it from this page: http://jdbc.postgresql.org/download.html and it worked.
Comment: Downloading the source code was the only option left with me. And it worked :)
Answer:
Download the driver from here.

Specify the path to the driver file with -dp.
For example:
java -jar schemaSpy.jar   \
  -t pgsql11              \
  -host <host>:<port>     \
  -db <database_name>     \
  -s <schema_name>        \
  -u <database_user>      \
  -p  <password>          \
  -o <output_directory>   \
  -dp <path_to_downloaded_driver>

One-liner on Windows:
java -jar schemaSpy.jar  -t pgsql -host localhost:5432 -db _dbname_ -s _schena_name_ -u postgres -p  -o D:\RVA\postgreSQL\  -dp "D:\Program Files (x86)\PostgreSQL\pgJDBC\postgresql-42.2.5.jar"

NOTE: There are two possible values for database type's value (-t) when it comes to PostgreSQL:
$ schemaspy --dbhelp
...
INFO  - PostgreSQL Before Version 11 (-t pgsql)
INFO  -    -host        host of database, may contain port
INFO  -    -port        optional port if not default
INFO  -    -db          database name
INFO  - PostgreSQL On Or After Version 11 (-t pgsql11)
INFO  -    -host        host of database, may contain port
INFO  -    -port        optional port if not default
INFO  -    -db          database name
...

Comment: Could you add backticks around the executable statements, it makes the comment more readable and easier to execute the commands.
Answer: I'd like to add a few points.

You would be using Schema Spy with Graphviz. Versions 2.31+ does not add an entry to Window's System path variable.
So after you download and install Graphviz  update the path variable to have path till Graphviz's bin directory.
(C:\Program Files (x86)\Graphviz2.38\bin)
Alternative to downloading entire project source to change the classpath in the property file would be to update the jar using 7-zip.
Open the jar file using 7-zip  navigate to net/sourceforge/schemaspy/dbTypes/
right click pgsql.properties say edit.
Change the following entry for driverPath to make it point to jdbc jar file
driverPath=D:/Work/JavaProjects/tools/postgresql-9.3-1100.jdbc4.jar
Click on save and update. This should do the trick.


Nautlius: add mouse right-click action to compute MD5 sum

Question: Context: 16.04
How does one mouse right-click action to compute the MD5 sum of a file?
Answer: You can work with a nautilus script.

Create the scripts directory if it does not yet exist
mkdir -p ~/.local/share/nautilus/scripts/

Place your script into that directory and make it executable (chmod +x <name_of_script> or via your file manager: right-click file, properties). Any executable script you put there will be available under an entry "Scripts" in your right-click menu.
In your script, you can use the variable NAUTILUS_SCRIPT_SELECTED_FILE_PATHS to retrieve a newline-delimited list of selected files (i. e., one file path in case you selected a single file). You will also need to display the output: this can be done by piping the output of the command to zenity. This simple script will already cut it:
#!/bin/bash
set -eu -o pipefail
md5sum "$NAUTILUS_SCRIPT_SELECTED_FILE_PATHS" | zenity --text-info


Authorize .net CIM with recurring payment

Question: I have a website where users do payment in installments(recurring payments). And since I don't want to store the user's credit card/ account information in my database, I used PCI compliance for which I used AUTHORIZE .NET Cim.
I followed this library, where everything works fine for the first time i.e.

createCustomerProfile
createCustomerPaymentProfile
createCustomerProfileTransaction

For the first time transaction works and I get all the response :
responsecode, transactionid, authid.

But how do I manage recurring payments with customer id or customer payment id.
I have even set : $cim->setParameter('recurringBilling',true);
Here is the complete code :
require('AuthnetCIM.class.php'); // class that has all the functions

$cim = new AuthNetCim('*******', '**********', 'apitest');

// Step 1: create Customer Profile
// Create unique fake email address, description, and customer ID

// $email_address = 'user' . time() . '@domain.com';
$email_address = $row['custemail1'];
$description   = 'Monthly Membership No. ' . md5(uniqid(rand(), true));
$customer_id   = substr(md5(uniqid(rand(), true)), 16, 16);

$cardcvv = $_POST['cardcvv'];
$cardno = $_POST['cardno1'].$_POST['cardno2'].$_POST['cardno3'].$_POST['cardno4'];
$phone = $_POST['billphone_1'] . '-' . $_POST['billphone_2'] . '-' . $_POST['billphone_3'];

$cim->setParameter('email', $email_address);
$cim->setParameter('description', $description);
$cim->setParameter('merchantCustomerId', $customer_id);
$cim->createCustomerProfile();

// Get the profile ID returned from the request
if ($cim->isSuccessful())
{
      $profile_id = $cim->getProfileID();

      $query = "UPDATE orders SET cust_proid='$profile_id' where orderid='$orderid' LIMIT 1";
      $result = mysql_query($query) or die("The following error has occurred:
" . mysql_error());

      $responsenote = $cim->getResponseText();
      $authorization = $cim->getResponse();
 }

 // Step 2: create Payment Profile

 $cim->setParameter('customerProfileId', $profile_id);
 $cim->setParameter('billToFirstName', $_POST['cardname']);
 $cim->setParameter('billToAddress', $_POST['billaddress1']);
 $cim->setParameter('billToCity', $_POST['billcity']);
 $cim->setParameter('billToState', $_POST['billstate']);
 $cim->setParameter('billToZip', $_POST['billzip']);
 $cim->setParameter('billToCountry', 'USA');
 $cim->setParameter('billToPhoneNumber', $phone);
 $cim->setParameter('cardNumber', str_replace('-', '', $cardno));
 $cim->setParameter('expirationDate', $_POST['cardexpyy'].'-'.$_POST['cardexpmm']); // (YYYY-MM)

 $cim->createCustomerPaymentProfile();

 // Get the payment profile ID returned from the request
 if ($cim->isSuccessful())
 {
      $payment_profile_id = $cim->getPaymentProfileId();

      $query2 = "UPDATE orders SET cust_pay_proid='$payment_profile_id' where orderid='$orderid' LIMIT 1";
      $result2 = mysql_query($query2) or die("The following error has occurred:
" . mysql_error());

      $responsenote = $cim->getResponse();
      $authorization = $cim->getResponse();
  }

  elseif($cim->isError())
  {
        $responsenote = $cim->getResponse();
        $authorization = $cim->getResponse();
        $approvalstatus='Declined';
  }
  else
  {
        // echo 'Invalid Card, payment pro id not generated';
        $responsenote = 'Invalid Card';
        $authorization = 'Declined';
        $approvalstatus='Declined';
  }

  // Step 4: Process a transaction
  $purchase_amount = '5';

  if($row['cust_pay_proid'] == '')
  {
      $payment_profile_id = $cim->getPaymentProfileId();
  }
  else {
       $payment_profile_id = $row['cust_pay_proid'];
  }

  // if getPaymentProfileId not created i.e invalid card/ or issue with payment
  if($payment_profile_id != '')
  {
       // Process the transaction
       $cim->setParameter('amount', $purchase_amount);
       $cim->setParameter('customerProfileId', $profile_id);
       $cim->setParameter('customerPaymentProfileId', $payment_profile_id);
       $cim->setParameter('cardCode', $cardcvv);

       $cim->setParameter('recurringBilling',true); // for recurring
       $cim->createCustomerProfileTransaction('profileTransAuthCapture');

       // Get the payment profile ID returned from the request
       if ($cim->isSuccessful())
       {
            $auth_code = $cim->getAuthCode();
            $query3 = "UPDATE orders SET auth_code='$auth_code' where orderid='$orderid' LIMIT 1";
            $result3 = mysql_query($query3) or die("The following error has occurred:
" . mysql_error());

            $responsenote = $cim->getResponse();
            $authorization = $cim->getResponse();
            $transactionid=$cim->getTransactionID();
            $approvalstatus='Approved';
       }
       elseif($cim->isError())
       {
            $responsenote = $cim->getResponse();
            $authorization = $cim->getResponse();
            $approvalstatus='Declined';
       }
       else
       {
            $responsenote = 'Invalid Profile/payment id';
            $authorization = 'Declined';
            $approvalstatus='Declined';
       }
  }
  else
  {
       $responsenote = $cim->getResponse();
       $authorization = $cim->getResponse();
       $approvalstatus='Declined';
  }

Answer: You cannot make or manage subscriptions through CIM as it only is a means for creating and managing payment accounts. The recurring billing flag only is a note that this payment account you created will be used for recurring billing. It doesn't actually setup a subscription.
So if you want to use this as a recurring billing system you need to write your own recurring billing engine to actually schedule and process payments.
Comment: @rhldr They will make a lot of people happy by doing that.
Comment: Authorize.Net will be adding the ability to [create subscriptions using a customer profile](https://community.developer.authorize.net/t5/The-Authorize-Net-Developer-Blog/New-Customer-Profile-and-Recurring-Billing-Enhancements/bc-p/53156#M529) in an upcoming release.
Comment: @JohnConde, how can that be achieved ? Since, I'm not storing the user's card info in my db. Can that not be managed in `createCustomerProfileTransaction()`


Spring REST consumption results in HTTP Status 406 - Not Acceptable

Question: I get this error when i try to consume a REST API:
Exception in thread "main" org.springframework.web.client.HttpClientErrorException: 406 Not Acceptable

Here's the client code that gets executed:
public static void main(String[] args) {
   Car c = getCarById(4);
   System.out.println(c);
}

public static  @ResponseBody Car getCarById(int id){
    return new RestTemplate().getForObject("http://localhost:8080/rest/cars/{id}", Car.class, id);
}

Here's the code of the Controller which maps the request:
@RequestMapping(value="/cars/{id}", method=RequestMethod.GET, headers = {"Accept=text/html,application/xhtml+xml,application/xml"}, produces="application/xml")
public @ResponseBody Car getCarById(@PathVariable("id") int id){
    return carService.getCarById(id);
}

Why is this error (406-Not Acceptable) happening although the mappers should take care of mapping to the correct types?
Comment: have added the **jackson library** now - everything fine.
Answer: You're sending an Accept= header instead of an Accept: header.
Comment: it works now, here a summary:
- ensure you have the **jackson library** added (client & server-side)
- it doesn't matter wheter a "=" or a ":" is written
Comment: you are right thanks! i've changed it but now i get the following error:

"HTTP Status 405 - Request method 'GET' not supported".

Why does this happen?
Comment: it seems like the method of the controller isn't mapping anymore. i don't know why.
Answer: I got this answer when I had a wrong Accept: header in my request. I was trying to request an image/jpeg, but my  request contained "Accept: application/json".
The solution was to use the correct entity class to query for (I was querying for Object just to see what would come), in my case Resource.class.
Answer: add this to spring mvc dispatcher:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</mvc:message-converters>
</mvc:annotation-driven>

<bean id="methodHandlerExceptionResolver"
      class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
        </list>
    </property>
</bean>

Answer: In my case, I fixed this not on the server side but in the client side. I was using Postman and was getting the 406 error. But using a browser was processing the request just fine. So I looked at the request headers in the browser and added the Accept header in Postman, like this: Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Answer: In addition, you can fix add "Accept", "/"
val headers = HttpHeaders()
headers.add("Accept", "*/*")
val httpEntity = HttpEntity("parameters", headers)
restTemplate.exchange(....)
restTemplate.exchange("http://localhost:" + serverPort + "/product/1",
            HttpMethod.GET,
            httpEntity,
            String.javaClass)

Sorry, it's Kotlin
Answer: I got same type of error due to mismatch of the value of ContentType & Accept. Solved the issue by setting the same string value for both of them.
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.valueOf(CONTENT_TYPE));
httpHeaders.setAccept(Arrays.asList(MediaType.valueOf(CONTENT_TYPE)));

Answer: I have had the same problem and finally it was a library problem. If you don't use maven you have to be sure you have include json core library and all its dependencies.
If your method has input parameters loaded in json format and you don't have this libraries you will have a 415 error.
I think the two error has the same origin: incomplete libraries.


MySQL group_concat with join

Question: I have a contact table. Each contact can have multiple phone numbers with different or same table. Similarly each contact can have multiple emails with different or same label. I need to select the all the different phone numbers and email ids belongs to a particular contact.
CREATE TABLE IF NOT EXISTS `contact` (
  `id` int(8) unsigned NOT NULL ,
  `fname` varchar(64)  NOT NULL,
  `lname` varchar(64)  NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1  ;
CREATE TABLE IF NOT EXISTS `phone` (
  `id` int(8) unsigned NOT NULL ,
  `sourceid` int(8) unsigned NOT NULL ,
   `type` varchar(16)  NOT NULL,
  `phone` varchar(16)  NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1  ;
CREATE TABLE IF NOT EXISTS `email` (
  `id` int(8) unsigned NOT NULL ,
  `sourceid` int(8) unsigned NOT NULL ,
  `type` varchar(16)  NOT NULL,
  `email` varchar(128)  NOT NULL
) ENGINE=InnoDB  DEFAULT CHARSET=latin1  ;

INSERT INTO contact values ( 1,'john'      ,'j' ),
(2, 'jose'      ,'f' ),
(3, 'test'      ,'k' ),
(4, 'tester'      ,'j' );

INSERT INTO phone values( 1 ,1, 'Home', '123456' ),
( 2 ,1, 'Home', '123456342' ),
( 3 ,1, 'Office', '12345645' ),
( 4 ,1, 'Mobile', '1234567' ),
( 5 ,2, 'Home', '123456' ),
( 5 ,2, 'Home', '987556' );

INSERT INTO email values
( 1 ,1, 'Home', 'firstname.lastname@example.com' ),
( 2 ,1, 'Home', 'email@example.com' ),
( 3 ,1, 'Office', 'email@example.com' ),
( 4 ,2, 'Home', 'firstname.lastname@example.com' ),
( 5 ,4, 'Home', 'email@example.com' );

I tried GROUP_CONCAT but it is having duplicate entries for the labels.
SELECT C.id, fname, lname
, GROUP_CONCAT(ph.sourceid),
GROUP_CONCAT(em.sourceid),
GROUP_CONCAT(ph.type), GROUP_CONCAT(ph.phone),
GROUP_CONCAT(em.type), GROUP_CONCAT(em.email)
FROM contact AS C
LEFT  JOIN phone AS PH ON PH.sourceid = C.id
LEFT  JOIN email EM ON EM.sourceid = C.id
WHERE C.id='1'
GROUP BY C.id

SQL FIDDLE
Answer: Try this:
SELECT c.id, c.fname, c.lname,
       ph.PhoneType, ph.PhoneNos,
       em.EmailType, em.EmailIds
FROM contact AS c
LEFT JOIN (SELECT ph.sourceid, GROUP_CONCAT(ph.type) AS PhoneType, GROUP_CONCAT(ph.phone) AS PhoneNos
           FROM phone AS ph
           GROUP BY ph.sourceid
          ) AS ph ON ph.sourceid = c.id
LEFT JOIN (SELECT em.sourceid, GROUP_CONCAT(em.type) AS EmailType, GROUP_CONCAT(em.email) AS EmailIds
           FROM email AS em
           GROUP BY em.sourceid
          ) AS em ON em.sourceid = c.id
WHERE c.id = '1'
GROUP BY c.id

Check the SQL FIDDLE DEMO
OUTPUT
| ID | FNAME | LNAME |               PHONETYPE |                          PHONENOS |        EMAILTYPE |                                   EMAILIDS |
|----|-------|-------|-------------------------|-----------------------------------|------------------|--------------------------------------------|
|  1 |  john |     j | Home,Home,Office,Mobile | 123456,123456342,12345645,1234567 | Home,Home,Office | email@example.com,firstname.lastname@example.com,firstname.lastname@example.com |

Comment: Sorry,I forgot to mention that I need the label(type) also. If I add DISTINCT the different labels will not be selected.
Comment: SELECT C.id, fname, lname, GROUP_CONCAT(DISTINCT ph.phone), GROUP_CONCAT(DISTINCT em.email)
,GROUP_CONCAT(DISTINCT em.type)
FROM contact AS C
LEFT JOIN phone AS PH ON PH.sourceid = C.id
LEFT JOIN email AS EM ON EM.sourceid = C.id
WHERE C.id = '1'
GROUP BY C.id

This will return the email types Home and Office, but there are two Home type emails in the table

MySQL group_concat with join


How do I buy cars in GTA online?

Question: When buying cars online, some pictures just have the letter 's'. what does that mean? Also, do you need a garage to buy cars?
Answer: The "S" mean that those cars need to be stolen and brought back to Simeon to be available. And yes you'll need a garage to buy cars online.

How do I buy cars in GTA online?


Cross validation in classifying text documents using scikit-learn

Question: Do you first do cross validation followed by feature extraction or the other way while classifying text documents using scikit-learn?
Here is my pipeline:
union = FeatureUnion(
transformer_list = [
 ('tfidf', TfidfVectorizer()),
 ('featureEx', FeatureExtractor()),
 ('spell_chker', Spellingchecker()),
 ], n_jobs = -1)

I am doing it in the following way, but I wonder if I should extract the features first and do the cross validation. In this example X is list of documents and y is label.
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size= 0.2)

X_train = union.fit_transform(X_train)
X_test = union.transform(X_test)

ch2 = SelectKBest(f_classif, k = 7000)
X_train = ch2.fit_transform(X_train, y_train)
X_test  = ch2.transform(X_test)

clf = SVC(C=1, gamma=0.001, kernel = 'linear', probability=True).fit(
X_train , y_train)

print("classification report:")
y_true, y_pred = y_test, clf.predict(X_test)
print(classification_report(y_true, y_pred))
print()

Answer: Doing the feature selection and then cross validating on those features is sometimes common on text data, but it is less desirable. This can lead to over-fitting and the cross-validation procedure may over-estimate your true accuracy.
When you do the feature selection first, that feauter selection process got to look at all the data. The point of cross validation is to hide 1 fold from the others. By doing the FS first, you leak some of that data knowledge to the other folds.
Comment: The question is feature extraction vs. cross validation, not feature selection vs. cross validation
Comment: The same still applies. The Term Frequency and Inverse Document Frequency (the TF and IDF in Tfidf vectorizer) contain formation from all documents. I just used a different term.


How to prevent strange element misalignments

Question: I'm trying to lay out some elements in a line such that they all have the same top and bottom vertically.
If I create a button and text input with the same specified size, the button actually has a slight margin at the top and bottom which make it appear smaller than the text input.  When I inspect the element in Chrome developer tools, it doesn't show this extra space as part of the actual element!

<button style="height:160px">
    test
    </button>
<input style="height:160px" />

Fiddle
Why is this happening and how do I get rid of the extra space around the button?
Now if I remove the text from the button, suddenly the second element get pushed way down!  I see the same thing if I put a space (e.g.  ) in the input.

<button style="height:160px">
    </button>
<input style="height:160px" />

Fiddle
Again, what's going on here and how do I fix it?
Comment: Tongue firmly in cheek: don't use strange elements. : )
Comment: Use code snippets (Ctrl+M) instead of Fiddle
Answer: The box model and box-sizing property are the reason for the slight size difference on your first example. It's the way browser's calculate the width and height based on margins, padding, etc.
Set the box-sizing property to border-box and they line up just fine

input {
  box-sizing: border-box;
}
<button style="height:160px">
    test
    </button>
<input style="height:160px" />

As for your second example, it's the vertical align property that comes into play. It affects inline elements and the default is baseline. Set it to something like top or middle and they align as you would expect. Throw in the same box-sizing as the previous example and they become the same height:

input {
  vertical-align: top;
  box-sizing: border-box;
}
<button style="height:160px">
    </button>
<input style="height:160px" />
Comment: @Michael Note the default `user agent stylesheet` styles: button uses box-sizing, input does not (chrome).
Answer: First Question:
There isn't any extra space around the button, but there is extra space inside the input tag, in the form of padding, which causes its effective height to exceed 160px.
If you want the total height of the input to be 160px, including padding, set box-sizing: border-box on the input (arguably, this should be the default behavior).
Second Question:
To align the button without any text inside it, set vertical-align: bottom; (or top, or middle) on the button.
For explanation: the default vertical-align value of baseline will try to align the baseline of text inside the element with the text in the parent element, but if there isn't any text inside the element, will instead try to align the bottom margin edge, which means that the bottom of the button ends up around the middle of the input.
Code with Both Fixes:

<button style="height:160px; vertical-align: bottom;">
</button>
<input style="height:160px; box-sizing: border-box;"/>
Answer: The other answers explain box-sizing, and how to align the elements with vertical-align.
Another approach to the alignment is to wrap the elements in a flex container. You can also set the height on the container instead of both the elements.
Example:

div * {
  box-sizing: border-box;
}

div {
  display: flex;
  height: 160px;
}

  <button></button>
  <input>

  <button>Content</button>
  <input>


Trouble trying to find the asymptotic runtime of a recurrence

Question: I'm trying to figure out the runtime of an algorithm. It is a sort which works by dividing the problem up into sets of 2/3's (it's the CLR sort). I'm having some trouble coming up with it, this is what I have:
T(n)=3T([2n]/3)+1 (the 1 is because aside from the recursive calls, there is one exchange           which may or may not be made. Assuming it is done, it is still only a constant cost.)
T(n)=3T([2([2n]/3+1)]/3+1)+1
T(n)=3T([2([2([2n]/3+1)]/3+1)]/3+1)+1
T(n)=3T([2([2([2([2n]/3+1)]/3+1)]/3+1)]/3+1)+1

etc......until we can assume that at some point we finally hit the base case for T(n) and get a constant value of 1 for that runtime. This gives us:
3([2([2([2([2(...........)]/3+1)]/3+1)]/3+1)]/3+1)+1 with logn terms (that's the "......." in the middle). This gives:

3*(2n/3+1)^(logn)+1*logn

3*(2n/3+1)^(logn)+logn

Then I think that since, if the base of the log were 2n/3+1, we could simplify it to simply be 3*logn+logn, we can do so. (I keep hearing that when doing asymptotic notation, the bases of the logs which we chose don't matter....)
This becomes 4logn. The coefficient drops away to become simply logn.
Is this correct? I'm not sure if I expanded this properly, or if my log manipulations were legal...Also, what is this final result--big-O, theta, etc. I'm not sure what I'm looking at...
Thanks.
Answer: You can look at this page to get you a general recurrence relation solution for divide and conquer algorithms.
In this case, b = 3/2, a = 3, and f(n) = O(1). log base 3/2 of 3 is about about 2.709, so we use case 1, which means the run time is O(n^2.709).
Hope that helps!


Find general solution $y''y^3=1$

Question: I'm having this question in my homework assignment in Linear Algebra and diffrential equation class, and trying to find the general solution for this second ODE.
$$y''y^3 = 1$$
Using substitution I said $p = y'$ and $p' = y''  \rightarrow  \frac{dp}{dx}= \frac{dp}{dy} \times \frac{dy}{dx}$
Then we get $y^3 \frac{dp}{dx}$ now what's the next step should I integrate or differentiate the equation? What's the trick on these type of ODEs?
Thanks in advance!
Comment: The end result, following the hints given in some answers below, is $$y(x)=\pm\sqrt{\pm2x+c}.$$
Comment: @Did, I think you miss some $x^2$ term inside the square root.
Comment: @mickep Show me.
Comment: @Did, I'll put it in an answer.
Comment: @Did, it is done...
Comment: @mickep Nice. +1 from me.
Answer: Update This is now a complete solution.
Let $v(x)=y(x)^2$. Then $v'=2yy'$ and so (here we assume that $v\neq 0$)
$$
v''=2(y')^2+2yy''=\frac{1}{2}\frac{(v')^2}{y^2}+\frac{2}{y^2}=\frac{1}{2}\frac{(v')^2}{v}+\frac{2}{v},
$$
or
$$
vv''-\frac{1}{2}(v')^2-2=0
$$
This differential equation can be solved as follows. Differentiating, we find that
$$
v'v''+vv'''-v'v''=0,
$$
so $vv'''=0$. Hence $v'''=0$. But then $v$ must be a polynomial of degree $2$.
Since we differentiated we cannot expect any polynomial of degree $2$ to work. We insert a second degee polynomial $v=a+bx+cx^2$ into the second order differential equation and look for conditions on $a$, $b$ and $c$ that gives us a solution. The condition becomes
$$
2ac-\frac{b^2}{2}-2=0.
$$
Solving for $c$, we find that
$$
v(x)=a+bx+\frac{4+b^2}{4a}x^2.
$$
Then, one could go back to $y$ to get
$$
y(x)=\pm\sqrt{a+bx+\frac{4+b^2}{4a}x^2}.
$$
Comment: Mathematica gives $ y^2(x)= a + \frac{ (x+b)^2}{a} $  Can it be taken to the same form by adjustment of constants?
Comment: @Narasimham Indeed, if you in $d+(x+c)^2/d$ let $c=$2ab/(4+b^2)$ and $d=4a/(4+b^2)$ you end up with the expression I give above.
Comment: @mickup And can be cast in the form $ (a y/b)^2=(x−b)^2 $representing hyperbolas? I ask this (quickly,else we may have to move to chat) for two reasons. One, I did not see DE in this form for a conic before and second, that a variation of the DE could be generalized to represent all conics. –  Narasimham 10 mins ago
Answer: Divide by y^3 then multiply by y' and integrate. That gets you to first order. I think the next integration is possible but a bit messy.
Answer: let $\frac{dy}{dx} = w.$ then you have a system of two differential equations $$\frac{dy}{dx} = w, \frac{dw}{dx} = \frac{1}{y^3}$$  from these two, you can get a differential equation $$\frac{dw}{dy} = \frac{1}{y^3}$$ which can be integrated to give you $$w = \frac{dy}{dx} = \frac{1}{2}(C -\frac{1}{y^2})$$ now you separate the variables to get $$\frac{y^2dy}{Cy^2 - 1} = \frac{dx}{2}$$
you can use partial fractions to find an integral for $y.$

Find general solution $y''y^3=1$


Xcode 8.3 breaks my app

Question: The official release of Xcode 8.3 causes my app to freeze completely after an apparently random amount of time. It also causes network connections to never finish (which may be the reason for the eventual freeze? A deadlock waiting for some resources to be released maybe?).
The exact same code works fine when compiled with Xcode 8.2.1.
Anyone has the same problem?
Comment: I experienced something similar. Not related to building but to archiving. Some functionality in the release version (e.g. using NMSSH to connect via SSH) was failing all the time. After archiving with Xcode 8.2.1 it worked fine.
Answer: Xcode 8.3.1 is now available.
https://developer.apple.com/news/?id=04062017a

Due to the resolved app archives issue listed below, we will soon be
  deprecating Xcode 8.3, at which time app archives built with Xcode 8.3
  will no longer be accepted by the App Store.

Try updating the xcode as there are a number of issues in previous version.
Comment: Thanks, but no joy for me. Same behaviour with Xcode 8.3.1
Comment: Are you able to build the app ?
Comment: Yes, sure, I can build the app, it kinda runs for a while, then freezes.
Answer: So it looks like the problem is related to the use of this kind of construct:
<code>@discardableResult func synchronized<T>(_ lock: Any, closure: () throws -> T) rethrows -> T {
    objc_sync_enter(lock)
    defer {
        objc_sync_exit(lock)
    }
    return try closure()
}
</code>
Replacing this with Matt Gallagher's PThreadMutex (https://github.com/mattgallagher/CwlUtils) fixes the issue.
I hope it isn't a deliberate move by Apple to push people off the Obj-C runtime, because if it is, it's definitely a sneaky way to do it, and pretty inconsiderate on their part given how widespread the use of the above construct probably is. If they don't want people to use those, then they should provide thread synchronization services in Swift instead of completely ignoring the need. Very frustrating.
Answer: I had this trouble yesterday, too.
It was posted on Apple Developer Forms on April 25th that the app archives built with Xcode 8.3 will no longer be accepted by the App Store.
Title:Please update from Xcode 8.3 to Xcode 8.3.1 or later
https://forums.developer.apple.com/message/225571#225571

Xcode 8.3 breaks my app


Is there a way to remotely control gas valve?

Question: We have a short term rental home, and we have a grill that's connected to natural gas. As a prevention of hazard, is there a way to open and close the gas valve remotely? We want to be able to close it if ever a guest mistakenly leaves it on or a cleaner forgets to turn it off for some reason.
Comment: Albeit this is an off-topic shopping question you should Google "Wifi gas valve" and might find https://www.amazon.com/Control-Controler-Compatible-Assistant-Automatic/dp/B07X95X53D. The main issue is that you cannot operate it in the event of a power failure.
Comment: How would you know that you're not turning it off in the middle of the guest cooking something?
Answer: Yes, there are electronically controlled gas valves.
A better idea might be to install a "grill timer". It's like a kitchen timer that you twist to set the time, but instead of ringing a bell it stops the gas from flowing.
Comment: I have used a grill with such a timer in a condo common area. I think this is the solution - more foolproof than a remote shutoff system.
Comment: Good suggestion. I looked for "grill timer" and got meat temperature type timers. The search term "gas timer shut off" was better.


Regarding configuration of Nvidia GeForce GT 740M graphics driver for Toshiba Satellite P50-AX3110 in Ubuntu 13.10

Question: I have a Toshiba Satellite  P50-AX3110 laptop which comes with preinstalled Windows 8 operating system having the following configuration: 4GB RAM, 3rd generation Intel Core i5 processor, 2GB Nvidia GeForce GT 740M with Optimus graphics card.
I have recently installed Ubuntu 13.10 alongside Windows 8 in my laptop. Everything is working fine in Ubuntu 13.10 except the 2GB Nvidia GeForce GT 740M with Optimus graphics card. In the device information in Ubuntu 13.10, when I select
graphics it shows Intel Ivy Bridge, whereas it should show the Nvidia graphics card.
I have tried searching for a solution on many websites on the internet, but nothing worked. Please provide me the steps on how to configure 2GB Nvidia GeForce GT 740M with Optimus graphics card in Ubuntu 13.10 or suggest me any other version of Ubuntu which would support 2GB Nvidia GeForce GT 740M with Optimus graphics card.
One of the solutions I have tried (after searching on the internet) is that I had installed nvidia-331 package along with the bumblebee package from the Synaptic Package Manager, but still the problem persists. Kindly provide me with a solution to the above.
Answer: Intel *bridge is the codename for the Intel embedded Graphic Chips.
So you're using the embedded chip instead of your Nvidia.
You need the Nvidia Linux driver for your Graphics Card. To get it, go to the Nvidia website, select your country, go to the support section, hit "download drivers" and enter your hardware specs.
Assuming you're running a x64 system (4GiB of RAM) this driver might be best for your system: LINUX X64 (AMD64/EM64T) DISPLAY DRIVER


I want to remove Steam completely but I accidentley removed Steam uninstaller

Question: I recently tried to remove Steam so I manually started deleting files, including Steam uninstaller. There are a few files that can not be deleted because they're open in Steam, however I exited Steam already.
Comment: Have you tried re-installing it and then uninstalling it again?
Comment: have you checked the list of running processes? you can see if it still is running, and you can stop it from there.
Comment: Recycle Bin not have the uninstaller in it?
Answer: Assuming you have Steam installed on Windows:
Open the Task Manager:
Press Ctrl+Alt+Del and then click on the "Task Manager" Button.

In the Processes Tab (should look like on the Screenshots) look for processes which have to do with Steam:
These are typically:

Steam Client WebHelper
Steam Client Bootstrapper
Steam Client Service

End those.
Answer: Although you may not see steam running in your task bar, it may still be running in the background which would prevent these files from uninstalling. If you are using Windows press CTRL+SHIFT+ESC to open your task manager. From here select processes and sort by image name. Scroll down until you see "steam.exe" or something similar. Left click it and press End Process in the bottom right corner, then attempt to uninstall steam completely. If this does not work a computer restart should also solve this problem.


manual layout of a custom UITableViewCell for this approach?

Question: Background - I have a custom UITableViewCell layout. Each cell will have a number of UILabels with a variable number of rows of UILabels.  For the sake of argument conside 3 columns of UILabels (different widths), and a variable number of rows depending on the data.
To best allow for content view size changes (e.g. edit mode, change in orientation etc) I was going to manually layout each of the UILabels in the cell in the "layoutSubviews" method, effectively setting up their exact positions.  I thought this way they will be laid out appropriately for events such as EDIT mode, orientation change etc.
Question - I'm wondering whether from a performance point this is the best approach?  Or should I be looking at somehow predefine the UILabel rows, one predefined set for portrait mode and another set for landscape mode?  (not exactly sure of how this would be done, but I'm trying to describe an approach where the layout would not have to be re-calculated when orientation changes etc)
thanks
Answer: suggestion by RickMaddy elsewhere was good:
"Why have a variable number of rows of labels in a single table row? Have one row of labels per table row. Then the problem is easier and performance won't be an issue."


Are ultrasonic ant repellents effective?

Question: I'm considering an ultrasonic ant repellent for the kitchen (where I'd rather not use a chemical pesticide).
Do these things work?
Comment: If you'd prefer to not use chemicals, diatomaceous earth and/or cinnamon supposedly work.
Comment: cinnamon helps only a bit, and for a limited time. is diatomaceous earth better? is it suitable for the kitchen counter?
Comment: diatomaceous earth is extremely sharp shards to an ant, so will kill it if it tries to traverse it. I'd probably not put it on counters, but it'd be fine on the floors and/or outside.
Comment: Side note: I asked my pest exterminater about outside recently, he indicated you would need a WIDE band (10-15 feet at least) of pesticide to really control ants from the outside.
Answer: Not sure about how effective they are specifically on ants -- but I do know one major drawback with these devices: they don't work around corners or behind objects.  In other words, they are line of sight only.  If the ants are behind cabinets, appliances, in the walls, etc, these devices won't work.
My own approach to this issue has been to use pesticide in the yard so they don't get into the house in the first place.  That, and I try to make sure the house is clean (floors vacuumed, counters wiped, food in sealed containers, etc).


Distribution on nodes

Question: I started a CockroachDb in a SIngel cluster with 5 nodes and try to store a table on 3 Specific Nodes. Unfortunately it does not work. Since someone has experience with this
ALTER TABLE belegdaten CONFIGURE ZONE USING
num_replicas = 3,
constraints = '[+ 1, + 2, + 3, - 4, - 5]';
Comment: Looks like there is no such syntax to achieve what you are looking for. It only allows you to specify which region/zone to locate the replicas. See : https://www.cockroachlabs.com/docs/v22.2/configure-replication-zones#types-of-constraints
Answer: CockroachDB doesn't distribute data like what you are trying to do.
To do something like what you want, you can set up your cluster as a multiregion cluster and use regional tables and data domiciling. You'd make the 3 nodes a particular region, then set the locality of the tables you want to the same region. In this scenario, you'd really want a six node cluster with 2 regions each with 3 nodes.
But I'm confused about the use-case here. Why is it important for the tables to be replicated to 3 and only 3 nodes in the cluster? What is the purpose of the other 2 nodes? With CockroachDB you can connect to any node and retrieve the data, even if it's not a replica of the range.

Distribution on nodes


Cross-site duplicate questions

Question: This question was asked recently; it was pointed out that it is fundamentally similar to this question on English Language & Usage SX.  Given this:

Is there a way to vote to close a question as a duplicate of a question on another site?  The software rejects trying to enter the URL from another SX in the "duplicate question" field.  Given the natural overlap of this site and EL&U, I think this is functionality we will need in the future.
(relatedly) Is there an established mechanism of merging answers on two sites?  The Linguistics version of the question has already garnered some useful answers which it would be nice to consolidate with the EL&U version of the question.

(Note, I am not asking about whether it would be appropriate to take these actions; that is another discussion that is taking place in the comments at that question, and someone can raise here if they want.  I am merely asking if it is technically possible to do these things.)
Comment: since this question is not SE-specific perhaps you can ask the meta.SO?
Answer: I don't think that even if it was possible, we should "dupe" this one. It's the same question but under a different point of view.
About your last note, I wanted to say something. Like I've stated in another question's comments, I think we should allow psycholinguistics questions.
Apart from specific questions, I'm talking in general: I'm not saying all of them are actually on topic, because we must consider that there's also psychology in it. But when it treats about linguistics, I think we can not ignore it. This is the only Linguistics site, if we don't allow it, I don't know who would.
I can agree if we want to set some boundary, but cutting it off completely like that just isn't the thing to do, that's what I think. There's really some pretty interesting stuff in that field (although I'm not actually an expert in it), it might be a waste to cut it off.
Comment: psycholinguistics - OK. That question - not psycholinguistics. OK maybe a sliver, but that wasn't a question, just a 'look -at-this-it's-neat-whaddya-think' statement.
Comment: Eheheh you mean the rdeanig question?
Comment: uh...yes...the "rdeanig" question I thought off-topic but not the TOT question (full bias acknowledged!).
Comment: The topic was interesting, honestly, and I've also heard about it before today, but I never went into the matter. Maybe it was just badly/poorly formulated?
Comment: @mitch i watched the TOT question, and IMHO this is clearly cognitive psychology, similar to the deja-vu phenomenon, memorizing. I dont see how you can draw conclusions from this concerning linguistics. My question is a phenomenon directly related to redundancy/structure of language, recognizing of morphems to be able to read a word...I think you should make it clearer in the FAQ. In my question on Capitalization you also say it is off-topic? Despite 5 upvotes. So i think the german philologists have some serious scientific pros & cons to prescribe Capitalization of every noun. Its no dicing.
Comment: @Hauser same I said under [my answer](http://meta.linguistics.stackexchange.com/questions/158/psycholinguistics-or-psychology-of-language-on-or-off-topic/159#159) in the [psycholinguistics on or off topic](http://meta.linguistics.stackexchange.com/questions/158) question.
Answer: Though the questions are the same, the audience including the answerers are not the same.
On English Language & Usage it will attract answers considering only English and not the interesting stuff here about other languages which for me redeemed the whole question.
On English Language & Usage most people are concerned with usage and what is correct, when people there try to cover linguistics topics they are not always well informed. Here we have more linguists and people who know at least some linguistics basics and who are often because of that less interested in correct usage but know more about deeper issues.
When I saw the question I thought "hmm this isn't what the site is about". But when I read the answers I found some surprising and enlightening results, and for me that's what linguistics is about so I discovered that the question, with its answers, did belong here after all.
Answer: I agree with hippietrail, the same question can be asked in different SEs and have different answers because the different points of view. Either they are allowed here (and will generate different answers) or they are closed as off-topic and no merging should be done.
[Edit] Just realised that you specifically do not ask whether it is appropiate. The easiest way I can think of is to migrate the question to the other SE and do the duplicate marking and/or merging there. But our SE doesn't have any migration path now.

Cross-site duplicate questions


Can This Hardwood Floor Be Saved?

Question: I'm considering putting an offer in on a house that is a fixer upper. I'd like to keep the original (1945) hardwood floors but am concerned about their condition.
The floor has a large bare spot in the middle of the room where it looks like the stain and varnish have been worn away leaving the bare wood exposed. Other parts of the room have large black spots (2-3 feet long).

My goal is to sand the floors so they are no longer a darker wood color and then re-stain them a light maple or a natural tone like sand.
Is this possible with these floors?
Comment: How about some pictures?
Comment: you are asking about a worn spot, yet it fills only about 3% of the picture
Comment: With the right people doing the job, it will turn out fabulous, but it will not be cheap...
Comment: it really depends what colour the wood is,
Answer: I sanded a similar wood floor, a bit older though.
I used a drum sander 8 or 10" in diameter and 14 or 16" long roughly.
I sanded diagonal to the grain with coarse then finer grades of paper. It took about 5 passes in total with 2 at the medium paper.
This produced a lot of dust and I sealed all the doors to prevent other rooms getting covered. Also had a big vac to get the dust.
Stain and finish as preferred.
Comment: How did it come out with the drum sander? In my experience they're difficult to get a flat surface. I opted for a slower plate sander.
Comment: The grit cuts more quickly cross-grain, so you can start with that if you need to remove a lot of material. Then you revert to go with the grain for the subsequent grits or you'll end up with visible cross-grain scratches.
Comment: @isherwood started with 6" warped boards, knocked the brads back and ended up with a flat floor. Much improved, but not a billiard table.
Comment: Why diagonally instead of with the grain?
Answer: Solid hardwood floors can be refinished several times. However, we don't know enough about your floor to answer properly. Some factors:

How many times it's been done before. Eventually you start getting through to the tongue of the plank, which leaves thin spots and gaps. You might also start seeing nail heads.
How severe the dark spot damage is. That might be water stains, which can go quite deep. If they're deep and dark enough you won't get them out entirely.
The color you plan on using. The dark stain that's on there now may have seeped all the way down the vertical faces of the planks. That, along with the water stains, may mean you won't get a nice finish with a light stain or just varnish. You may have to stick to a darker color to mask those things.

Can This Hardwood Floor Be Saved?


How to transfer songs from Ubuntu PC into iPod touch 5g

Question: I'm having a hard time trying to find a good solution to this problem.
I want to transfer songs to my iPod touch 5g just like I can through iTunes in Windows. Is there any method/workaround for this ?
I'm asking this question again because all other guides/questions are old and are not very practical at this point of time.
Any help including links to similar questions or any software/methods are very welcome.
Current setup: Ubuntu 15.04 (with Unity) and an iPod touch 5g (iOS 8.4 not jailbroken)
Answer: I advise you to follow this tutorial:
Youtube-Video
Comment: Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Comment: Will do so, but didn't have the time and thought a fast answer - answered instantly - would be nice.


Cross platform hardware-native OpenGL library, possibly with multimedia?

Question: I am looking for the ability to open OpenGL contexts and draw native OpenGL in windows, macOS, linux distros with X, android and iOS
I don't want to rely on the "native" device framework for the actual UI, I don't need to use native components, all I want is an OpenGL context to natively draw in OpenGL. Many of the cross platform SDKs like Marmalade and MoSync focus on making use of the native UI components and stuff like that, all I need is an OpenGl context to draw as I intend to, absolutely no native UI functionality is required, however, access to native hardware features like microphone, camera and other sensors is desired if possible, as well as access to audio/video/network.
I don't want to use QT, I want to do something that is closer to the hardware to work on the low level. The general idea is to make a lightweight cross platform hardware accelerated GUI, written on a level low enough to be truly hardware native, without relying on any native software framework. I know for android I may have to use a java wrapper to launch the native code, but the idea is to have this wrapper minimized, with very little modifications needed to deploy the low level and thus hopefully TRULY cross-platform code, that is only dependent on OpenGL hardware and OpenGL context for it to work wit.h
So I need a bare minimum solution to avoid using non-cross platform features as much as possible.
At the time the only library that comes to my mind is SDL, but I am not sure it supports android and iOS property, so besides library recommendations, more information on how SDL handles android and iOS devices and their hardware is welcomed too.
Comment: I don't know about you, but in my book "portable" and "native" are oxymorons...
Comment: Well, you might be missing the subtle difference adding "hardware" and "software" kind of crews the meaning of native - what I ask is native hardware OpenGL access which IS CROSS-PLATFORM, so I don't have to use the native software framework, which is NOT CROSS-PLATFORM.

Native to hardware api equals cross platform, or at least that is what I hope it does.
Answer: How about:

GLFW
SDL
GLUT (FreeGLUT or OpenGLUT)
Blender's GHOST framework?

Essentially they open a window, create a OpenGL context on it, deliver you the input events and leave the rest up to you.
Answer: What you want is nothing more than a platform-specific OpenGL context setup (which is quite simple and well documented: the NeHe OpenGL tutorial provides code for many environments that does just this here (the explanation is Windows specific, scroll down for the code on different OSes).
Once you have the OpenGL context, nothing prevents you from creating a full GUI with all OpenGL elements.
If you want, you could use Qt to only set up an OpenGL context (ie don't use any QWidgets or anything, other than the window showing you your OpenGL scene). It takes care of the whole setup process, but for only that, Qt becomes a huge dependency, as it only really replaces at most 100 lines of code per platform.
With regards to SDL+Android, have you checked the README?
And for iOS check the same file here.


Where are the OpenCV development libraries installed?

Question: I need to install facedetect in matlab but it needs opencv library files and it has to be included during the compilation. So where is it? (In UbuntuStudio)!
Answer: Please install libopencv-dev first.
The library/header files are the in /usr/include/opencv2.


Python Plotly CDF with Frequency DIstribution Data

Question: How do you make a CDF plot with frequency distribution data in a Pandas DataFrame using Plotly? Suppose the following toy data
value   freq
1       3
2       2
3       1

All of the examples show how to do it with raw data that looks like:
value
1
1
1
2
2
3

I am able to do it with Pandas .plot like so (but I would prefer to do the same with Plotly):
stats_df = df
stats_df['pdf'] = stats_df['count'] / sum(stats_df['count'])

# calculate CDF
stats_df['cdf'] = stats_df['pdf'].cumsum()
stats_df = stats_df.reset_index()

# plot
stats_df.plot(x = 'n_calls',
              y = ['pdf', 'cdf'],
              logx = True,
              kind = 'line',
              grid = True)

If you would like to demonstrate with a toy dataset, here's one: https://raw.githubusercontent.com/plotly/datasets/master/2010_alcohol_consumption_by_country.csv
References:
https://plotly.com/python/v3/discrete-frequency/
https://plotly.com/python/distplot/
Answer: It is not possible to build a CDF in the Plotly.
On Plotly, only PDF and a histogram can be plotted (see below for alcohol sample).

The code for the graph above looks like this:
import plotly.figure_factory as ff
import pandas as pd

data = pd.read_csv(
    'https://raw.githubusercontent.com/plotly/datasets/master/2010_alcohol_consumption_by_country.csv')

x = data['alcohol'].values.tolist()

group_labels = ['']
fig = ff.create_distplot([x], group_labels,
                         bin_size=.25, show_rug=False)
fig.show()

If you need exactly the CDF, then use third-party libraries for data preparation.
In the example below, I am using Numpy.

The code for the graph above looks like this:
import plotly.graph_objs as go
import numpy as np
import pandas as pd

data = pd.read_csv(
    'https://raw.githubusercontent.com/plotly/datasets/master/2010_alcohol_consumption_by_country.csv')

x = data['alcohol'].values.tolist()

hist, bin_edges = np.histogram(x, bins=100, density=True)
cdf = np.cumsum(hist * np.diff(bin_edges))
fig = go.Figure(data=[
    go.Bar(x=bin_edges, y=hist, name='Histogram'),
    go.Scatter(x=bin_edges, y=cdf, name='CDF')
])
fig.show()

Note that the CDF is a broken line. This is due to the fact that this is not an approximate function for the unknown distribution.
To get a smooth function, you need to know the distribution law.


removeChild only works once

Question: I have a test input form where a child select box is created depending on the value of one of the choices in the parent select box. Selecting any of the other choices in the parent select box should remove the child. It works, but only once. If the child select box is created a second time, then it is not removed by selecting one of the other choices.
Here is the code:

<form action="" method="get" name="myform">
<SELECT id = "s" name="s" size=3 onChange="createtext()" ><OPTION>Visa    Card<OPTION>Mastercard<OPTION>American Express</SELECT>
</form>

And here it is in action... http://www.crazyforstamps.com/test-form-6.htm
Comment: Side note, your HTML is invalid. Where's gift defined in `myform.removeChild(gift)`?
Comment: The link you posted works fine for me
Comment: I don't observe your problem ... It works well
Comment: which is the browser used? it seems to be fine in chrome
Comment: Nevermind, I just tried firefox and i see what you mean:)
Comment: where do you define `gift`
Comment: [elements with id/name](http://www.w3.org/html/wg/drafts/html/master/Overview.html#named-access-on-the-window-object) properties will be added to the [window object](http://stackoverflow.com/questions/3434278/ie-chrome-are-dom-tree-elements-global-variables-here)
Answer: Try
var gel = document.getElementById('gift');
if(gel){
    myform.removeChild(gel);
}

Update:
<!DOCTYPE html>

<form action="" method="get" name="myform">
    <SELECT id="s" name="s" size=3 onChange="createtext()">
        <OPTION>Visa Card</OPTION>
        <OPTION>Mastercard</OPTION>
        <OPTION>American Express</OPTION>
    </SELECT>
</form>

Demo: Plunker
Comment: Thanks - that got it working perfectly in Firefox, and it also works in Chrome. I can't get it to work in IE though, up to version 9 which is the latest we have. In those versions of IE, I can even get the appendChild to work. I'm thinking I can probably just ignore IE8 and below, but it should at least work in IE9 and above. Does it work in your version of IE?
Comment: @PaulCompton it might be because your html is invlaid
Comment: It can't be too invalid - it even works on my iPhone! So that's FF, Chrome and Safari all ok. I agree it's obviously "invalid" for IE, but the question of course is how is it invalid?
Comment: @PaulCompton in your markup the `` start tag is missing
Answer: Assuming you have defined gift somewhere which I don't see it in the question.
Removing all child elements
var gift = document.getElementById("gift");
while (gift.firstChild) {
    gift.removeChild(gift.firstChild);
}

Or another alternative is to simply assign innerHTML to an empty string
var gift = document.getElementById("gift");
gift.innerHTML = '';

Comment: A few posters have mention that gift is not defined, but I was assuming that selector.name = 'gift'; was what defined it. So where in the code and how exactly should it be defined?
Comment: @PaulCompton - that is different.. you have defined **selector** but when you say removeChild(gift) it is a variable not a selector.
Answer: First of all you have to keep in mind, that each browser has it's own js compiler. Some can use properties without getting browsers dom element via JS, by just referencing their name. But in order to write all browsers supported code, you have to keep in mind JS specifications.
 In your current example on JSFiddle you have to always get your elements before you try to perform any actions on them.
      var myform = document.getElementById('myform');
      var gift = document.getElementById('gift');

Comment: Thanks. Do you mean that I should get those elements just before I attempt the removeChild?
Comment: Yes, you have to obtain a pointer to those elements via all browser supporte func `getElementById`. Or simply add reference to jQuery, it has already implemented all cross browser funtionality.

removeChild only works once


How do I launch Civ 5 in the tablet / touch mode by default

Question: I just got a Windows 8 touch screen laptop, and playing Civ V in the Touch Enabled mode is great. But every time I launch it from within Steam, it prompts me to pick either DirectX9, DirectX 10 & 11, or Windows 8 - Touch Enabled (recommended).
I went into the folder where Civ V is installed on my hard drive and found  CivilizationV_Tablet.exe. I made a shortcut for that, but still got prompted!
My google search only found me a bunch of people talking about how to run it on a Surface Pro.
Answer: Right-click on the small window prompting you to pick DirectX version or Windows 8 touch mode, and select "Create Windows 8 Desktop shortcut". This will create a Desktop shortcut with the path steam://rungameid/8930//%5Cwin8
You can then turn that into a Start screen tile with the application of your choice (I used OblyTile)
If you also wish to make this the default when launching the app from within Steam, you can use the method described here: How can I stop Civilization 5 from asking me twice which DirectX mode to play in?

In Steam, right click on Civilization 5 and chose "Properties"
Click "Set Launch Options"
In the box, type the following: /win8 (exactly like that, no quotes, no spaces, just a slash and win8)
Press "OK" to exit the launch options dialog
Press "Close" to exit the properties dialog


Searching for matches: Array vs Individual

Question: Here's the code in question:
Dim rr23WS As Worksheet, rrCell As Range
Dim rrCheck As Range
Dim r As Long
Dim rrMatch
Dim openWKBK as String

openWKBK = "X:\Resulting\Test.xlsx"
Workbooks.Open (openWKBK)
Set rr23WS = Workbooks("Test.xlsx").Sheets("January")
Set rrCheck = rr23WS.Columns(1)

For r = 1 To 4

    For Each rrCell In Worksheets("RACK " & r).Range("C6:N13").Cells

        rrCell.Borders.Color = RGB(0, 0, 0)
        rrCell.Borders.Weight = xlThin

        rrMatch = Application.Match(rrCell, rrCheck, 0)               'search Col A of Test.xlsx for matches

            If Not IsError(rrMatch) Then

                rrCell.Borders.Color = RGB(0, 0, 192)     'if match found, apply border to cell located in the range of ("C6:N13")
                rrCell.Borders.Weight = xlThick

            End If

    Next rrCell

Next r
End Sub

Everything works fine but, every time the button is clicked it's always searching Test.xlsx wkbk for ~350-400 matches, but the searchable range on Test.xlsx is growing rapidly and I'm starting to notice the macro slow down a bit (takes about 10seconds which I understand is not a long time at all, I'm just thinking for the future as the searchable range continues to increase).
From my understanding of how my code is actually working, it seems the macro is constantly jumping back and forth between the 2 workbooks looking for matches.  If that's correct, it just sounds inefficient.
I'm wondering if it would make sense to set the entire range of ("C6:N13") for all 4 worksheets to an array so it can search for everything at once and not jump between the 2 workbooks.
With my current, inexperienced, understanding of how excel performs step-by-step execution, I would think this would help speed it up.
Which is the lesser evil:

searching a large range for multiple matches in an array of ~400 values?
searching a large range for multiple matches for ~400 cells individually?
Answer: Match against a worksheet is typically very fast - more likely it's the formatting of the cells which is slow. You can set the cell border to black for C6:N13 before entering the loop over that range: no need to set each cell individually.
Likewise set all the matched cells for any given sheet in one operation not individually
Sub lookitup()

    Const WB_PATH As String = "X:\Resulting\Test.xlsx" 'use constants for fixed values
    Const RNG_RACK As String = "C6:N13"

    Dim rr23WS As Worksheet, rrCell As Range, rngRack As Range
    Dim rrCheck As Range, rngMatched As Range
    Dim r As Long

    Set rr23WS = Workbooks.Open(WB_PATH).Sheets("January") 'get return value from Open()
    Set rrCheck = rr23WS.Columns(1)

    For r = 1 To 4
        'always qualify worksheets with a workbook object
        Set rngRack = ThisWorkbook.Worksheets("RACK " & r).Range(RNG_RACK)

        'reset to defaults...
        rngRack.Borders.Color = RGB(0, 0, 0)
        rngRack.Borders.Weight = xlThin

        Set rngMatched = Nothing
        For Each rrCell In rngRack.Cells
            If Not IsError(Application.Match(rrCell, rrCheck, 0)) Then
                'collect cell for later formatting
                If rngMatched Is Nothing Then
                    Set rngMatched = rrCell
                Else
                    Set rngMatched = Application.Union(rrCell, rngMatched)
                End If
            End If
        Next rrCell

        'format matched cells if any
        If Not rngMatched Is Nothing Then
            With rngMatched.Borders
                .Color = RGB(0, 0, 192)
                .Weight = xlThick
            End With
        End If
    Next r 'next sheet

    rr23WS.Parent.Close False 'close lookup workbook

End Sub

Comment: OK - glad you figured it out.
Comment: Sorry to come back to this for so long, I just have another clarification question.  After Application.match, the rrCell being set to rngMatched are the matches found, correct?  If so, then that part + "if not rngMatched is nothing" block make sense.  Then I'm not sure the need for the application.union.  Or is my thinking reversed?
Comment: Others have said they have encountered errors using this part of the macro but I'm never around to see exactly where the error is and I can't replicate it, so I just want to make sure I understand it correctly.
Comment: `rngMatched` is for collecting all of the cells which need formatting, so you can format them on one operation after the loop.  Initially within the `rrCell` loop `rngMatched` will be `Nothing` so we can just set it to the first cell we find: after that you need to use Union to add in any other cells.   As for the errors you mention - I have no idea about that without some more information.
Comment: Okay, so the Union method is sort of (but not really) acting like a ".select" for all the matches and combining them into one range/storing that combined range in rngMatched.  Then apply borders to rngMatched to format all at once.  Gotcha.  It's odd because I've been told the error will pop up but then they try the macro again and it works, very well could be user error.
Comment: Sorry can't really help without knowing what the error message is or exactly where it occurs
Comment: Right, I get that.  I don't even know what the error is, but I'm unable to figure it out once I know I should at least be able to give more info.  Thanks for the explanation though.
Comment: I think I got it fixed, thinking it was a matter of editing macros on what I assumed was office 365, but was actually 2016.. had to have been the only PC with 16 installed.


How to display line numbers in Nano text editor

Question: When using Nano text editor, how can I display line numbers so I can see the lines that I am getting error messages about.  I have a lengthy program and am getting an error message for line 95 and 125 for example.
Answer: Ctrl+C will show the current line/column once, and Meta+C (usually Alt+C) will toggle a continuous line/column display on and off.
Ctrl+_ (that's underscore, so on most keyboard layouts that's Ctrl+Shift+-) will prompt you to jump to a specific line number.
Answer: Non permanent
nano -c /path/to/file

Permanent
edit ~/.nanorc and add the following
set const

For more details - as mentioned by Nick - check this perfect answer.
Comment: set constantshow


Would pipe from radiator to bottom of hot water tank be supply or return?

Question: I have one radiator that does not work at all (although it has worked in the past). Unlike all the other radiators that come directly of the main supply and return pipe from the boiler I can see that one end of the radiator is connected to a pipe that runs directly to the bottom of the hot water tank. I cannot trace where the other pipes goes, it seems to run towards the back of the hot water tank but cannot see where it goes after this point. Because this radiator is newly installed we don't actually know which pipe is the supply and which is the return, both pipes are stone cold. Its replacing a previous one but the installer didn't make note of which end had the thermostatic valve before he removed it and redid the pipes.
My questions are:

Why has this radiator been attached directly to hot water cylinder
Will the pipe attached to the bottom of the hot water cylinder be
supply or return ?
Where logically should other pipe attach.
What could stop it from working ?
Answer:
Why has this radiator been attached directly to hot water cylinder

Seems like a bodge to me.
Traditional UK systems have the radiators completely separate from the hot-water (which supplies taps only). The radiator system is usually a closed loop - with some means of topping up the water - either a header tank in the loft (US: attic) or a valve next to a pressure vessel with a pressure gauge.
 Source: Honeywell
The hot water tank usually has four connections, two for supply and return from boiler which connect to an internal helical loop, there is no transfer of water from this loop into the tank, only a transfer of heat.
The tank is supplied with cold water at the bottom (e.g. from a separate header tank) and hot water to taps is drawn out the top.
 Source: Potterton, modified to show pump, three-port zone-valve, vents and cold water to taps

Will the pipe attached to the bottom of the hot water cylinder be supply or return ?

Generally you remove hot water from the top and supply cold water into the bottom.

Where logically should other pipe attach.

Your arrangement seems illogical. Probably the top of the cylinder.

What could stop it from working?

Sediment clogging the supply pipe or radiator
A valve turned off, blocked or broken.
Lockshield valve (that "other" radiator-valve) needs adjusting?
Air in the radiator
Failure of a circulation pump (if present†)
Bad design or design reliant on specific characteristics of removed radiator.
Programmer/timer set to CH on but HW off.
Failure of HW thermostat or set too low for magic radiator to do its thing.
HW thermostat set too high or insufficient call for HW to sustain temperature gradient in tank needed to support magic for radiator?

† I believe some very old heating systems used natural convection but I've never seen one‡.
‡ I'm not a plumber.
Comment: I think it is a bit bodgy, essentially there is a supply and return pipe from the bolier than runs along the first floor, This has radiators pipe coming off the supply and onto the return and it also connects to the hot water tank, and then further radiators run of the supply pipe  and onto the return past the tank. There is a a T-Valve ( I think that its name) that is controlled by the heating panel so that if you can have both, just central heating or just hot water and that controls the supply pipe to the hot water tank.
Comment: There is only one pipe coming out of top of hot water tank and that connects directly to hot water pipe. So I guess the pipe I see is the return pipe and the radiator is connected to a supply pipe somewhere, there is one pipe in the airing cupboard that disappears into the floor and I dont know where it goes afterwards so perhaps it could be that one.
Comment: If I understand you correctly I didn't realize that the supply pipe doesnt actually fill the tank with hot water but just heats an element that then heats hot water tank supplied by the cold tank
Comment: Is the radiator return into the hot water tank just a way of dealing with excess water in the central heating system ?
Comment: @Paul. Normally no radiator pipework is connected to the hot-water tank at all. In a traditional system, excess water is vented into the header tank in the loft.
Comment: I know nowdays it doesn;t happen, but Im sure there was some reason for it at the time since technically there would be no problem plumbing from the central heating supply since the radiator is actually nearer to that then the hot water cylinder.
Comment: @Paul, perhaps there was some need to have a radiator that was on when other radiators are off? It is dependent on the HW settings and usage though.
Comment: I have looked at it again. There is a supply pipe (the same pipe that supplies the radiators but the t-valve lets its supply only radiators or only hot water or both). There is hot water pipe, hot water produced by cylinder and a cold water pipe going up to the cold water tank. And  then this second pipe that may actually be going to the return pipe (orange line on your diagram), I just cannot tell if it going into the return pipe or the radiator return as they are close together right at the back of the airing cupboard. Either way I cannot tell what is supplying this radiator


Face detection using opencv

Question: I am using haarcascade_frontalface_default cascade for face detection using Viola Jones Object Detector.
Can anyone suggest any other method/xml file to increase the range (unto 20ft) (maximum distance from the camera at which a user can be detectted) of face detection for the same camera
Answer: 1. You should try haarcascade_frontalface_alt2.xml.
2. Depending on your application needs, you could try to filte the detection results w.r.t. the scale of the corresponding bounding boxes, in order to decrease the false positive rate of your system.

Face detection using opencv


On the relation of Completeness Axiom of real numbers and Well Ordering Axiom

Question: In my abstract algebra book one of the first facts stated is the Well Ordering Principle:
(*) Every non-empty set of positive integers has a smallest member.
In real analysis on the other hand one of the first things introduced are the real numbers and their Completeness Axiom:
Every nonempty set of real numbers having an upper bound must have a least upper bound.
Which is equivalent to:
(**) Every nonempty set of real numbers having a lower bound must have a biggest lower bound (infimum).
It has never been mentioned in any book I've read and I don't know if they have anything to do with each other but (*) and (**) seem to me to be such that (**) implies (*).

Is the Well Ordering Principle a consequence of the Completeness of
  the real numbers? Or do they have nothing to do with each other? How
  should I think of them in terms of how they relate to each other?

Is it okay to see one as a consequence of the other?
Comment: There is a crucial difference between `(**)` and `(*)`, which is that in `(*)` the least element is required to be an element of the set, whereas in `(**)` the infimum is not required to be an element of the set.  If you somehow define the natural numbers in terms of the real numbers, you will be able to prove `(*)` from `(**)` (and the other axioms of the real numbers), but the proof will take some work.
Comment: Intuitively it is obvious that the inf of a set of natural numbers is in the set, but it is something you have to prove.  To emphasize why you should be careful here, you're trying to _prove_ the well-ordering principle, so you must make sure you aren't using any facts (no matter how basic or familiar) that can themselves only be proven _using_ the well-ordering principle.  Instead, you have to rely on whatever your definition of the natural numbers as a subset of the real numbers is, and properties of the real numbers that you are assuming as axioms or have otherwise proven.
Comment: I don't understand your comment Normal Human. I don't have any formulae in the question. I understand math jax is for latex formulae?
Comment: Never mind the comment, it was an erroneous one.
Comment: @EricWofsey I think the fact that the least element is in the set follows from the fact that the sets in (*) consist of integers. Of course the $\inf$ of a set of integers is in the set. Or am I missing something?
Answer: If you define $\Bbb{R}$ using Dedekind cuts over $\mathbb{Q}$, then $(**)$ can be proven without using $(*)$. (the Dedekind completion of a dense linear order without endpoints always has the least upper bound property).
It is tricky to say that $(*)$ follows from $(**)$ because  $(*)$ is a defining caracteristic of $\mathbb{N}$ so in a way you summon $(*)$ as soon as you talk about $\mathbb{N}$. I am not sure you can define $\mathbb{N}$ knowing only that $\mathbb{R}$ is an ordered field with property $(**)$ in a way that would make the proof $(**) \rightarrow (*)$ possible.
Answer: I see the completeness axiom of $\mathbb{R}$ as a generalisation of the well ordering principle of $\mathbb{N}$. As every subset $S\subset\mathbb{Z}$ is bounded below, this condition need to be imposed on $S\subset\mathbb{R}$ to make the extension possible even though the bound doesn't have to be in $S$.


Method to draw a line

Question: My Professor gave us this question

Write a method called Drawline that accepts as input an integer n and generates a line of output in lstOutput with n hyphens.  That is, if n = 5 we have a line of '-----' displayed in the list box.

Basically he wants me to type a number in a text box and when i click the button it should display that many hyphens in a list box. Using visual Studio C# WindowsFormApp.
Here's my code:
private void btn3_Click(object sender, EventArgs e)
{
    double n;
    Drawline(out n);
}

private void Drawline(out double n)
{
    n = double.Parse(textBox1.Text);
    string strline = "";
    for (n = 1; n <= 5; n++);
    strline += '-';
    lstOutput.Items.Add(String.Format(strline, n));
}

It works but no matter what number i put in the text box only one hyphen shows up. Can anyone help me?
Comment: `for (n = 1; n <= 5; n++);` Note the semi-colon.
Comment: Also, `String.Format` doesn't seem needed here.
Comment: What's the use of `out n` here? Your `Drawline()` method should return a string that is then added to a ListBox in the `btn3_Click` handler. You can just return `new string('-', n);` and of course you should use `int.TryParse()`, not `double.Parse()`, but in `btn3_Click` (your `Drawline` method should know nothing about `textBox1` and `lstOutput`).
Answer: The problem is with your for loop in DrawLine method.
You need to remove the semi-colon at the end of the for statement, so the strLine += '-'; will belong to the loop, not just be executed once.
private void Drawline(out double n)
{
    n = double.Parse(textBox1.Text);
    string strline = "";
    for (i = 1; i <= 5; i++)
        strline += '-';
    lstOutput.Items.Add(String.Format(strline, n));
}

Comment: this helped but, it gives me 5 hyphens no matter what number i put in. i dont know if my numbers are messed up or what. any idea for that? sorry this is my first C# class and this is new stuff to me
Comment: I misread your code, I have just fixed it. You need a temporary variable to act as a counter.
Answer: It appears you may be making this more complicated than it has to be.
It is unclear "why" the DrawLine method returns a double value using the out property? Is this a requirement? If it is not a requirement, then it is unnecessary.
Also, as per the requirement… "Write a method called Drawline that accepts as input an integer n" … if this is the requirement, I have to ask why is the method accepting a double value? This would not fit with the requirement.
Below is a simplified version and should fit your requirements. First in the button click event, we want to get the integer value from the text box. We need to assume the user typed in a value that is NOT a valid integer. If the value is NOT a valid integer greater than zero (0), then we will display a message box indicating such.
private void button1_Click(object sender, EventArgs e) {
  if ((int.TryParse(textBox1.Text, out int value)) && value > 0) {
    Drawline(value);
  }
  else {
    MessageBox.Show("String is not a number or is less than 1 : " + textBox1.Text);
  }
}

Next the DrawLine method that simply adds a string of "-" character(s) to the list box. Note the passed-in/accepted value of n has already been verified as a valid integer number greater than 0.
private void Drawline(int n) {
  lstOutput.Items.Add(new string('-', n));
}

If you MUST use a for loop to generate the string, it may look something like…
private void Drawline(int n) {
  StringBuilder sb = new StringBuilder();
  for (int i = 0; i < n; i++) {
    sb.Append("-");
  }
  lstOutput.Items.Add(sb.ToString());
}

Method to draw a line


Let $x, y, z$ be real numbers. If $x + y + z = 1$ and $x^2 + y^2 + z^2 = 1$, then what is the minimum value of $x^3 + y^3 + z^3$?

Question: Through manipulation, I got as far as $x^3 +y^3 + z^3 = 1 + 3xyz$
I tried solving it using AM - GM inequality but it only gave me the maximum value.
GM - HM does not to help either.
Comment: Is your second equation $$x^2+y^2+z^3=1$$? or $$x^2+y^2+z^2=1$$?
Comment: It should be the latter. Edited it for clarity. Thanks
Answer: The intersection of sphere and plane is a smooth curve, one can apply standard optimization methods.
With the Lagrange functional
$$
L(x,y,z,\lambda,\mu)=x^3+x^3+z^3+λ(x^2+y^2+z^2-1)+μ(x+y+z-1)
$$
one gets the equilibrium conditions
\begin{align}
3x^2+2λx+μ&=0\\
3y^2+2λy+μ&=0\\
3z^2+2λz+μ&=0
\end{align}
As now $x,y,z$ are solutions of the same quadratic polynomial, two of them have to be equal, wlog. $y=z$. Then from the original equations $x=1-2y$ so that
$$
(1-2y)^2=x^2=1-2y^2\\
6y^2-4y=0\\
y=z=0\lor y=z=\frac23
$$
which gives $x=0$ in the first case with cubic sum $1$ and in the second case $x=-\frac13$ with cubic sum $\frac{5}{9}$. These are the extremal values that the cubic sum function takes on the circle given by the constraints.
Answer: Since you got that $x^3+y^3+z^3=1+3xyz$, easy to understand that you meant $x^2+y^2+z^2=1,$ which gives $xy+xz+yz=0.$
Now, let $x+y+z=3u$, $xy+xz+yz=3v^2$ and $xyz=w^3$.
Thus, $u=\frac{1}{3},$ $v^2=0$ and we obtain:  $$0\leq\prod_{cyc}(x-y)^2=27(3u^2v^4-4v^6-4u^3w^3+6uv^2w^3-w^6)=27\left(-\frac{4}{27}w^3-w^6\right),$$ which gives
$$-\frac{4}{27}\leq w^3\leq0$$ and we obtain:
$$x^3+y^3+z^3=27u^3-27uv^2+3w^3=1+3w^3\geq1-\frac{4}{9}=\frac{5}{9}.$$
The equality occurs for example for $(x,y,z)=\left(-\frac{1}{3},\frac{2}{3},\frac{2}{3}\right),$ which says that we got a minimal value.
Comment: A classical Rozenberg, +1.
Answer: You can use Cauchy-Schwarz inequality. $X+y=1-z$, thus $(1-z)^2 = (x+y)^2$ is less than or equal to $(1+1)(x^2+y^2)=2 (1-z^2)$. I get $z$ more than or equal to $-1/3$. $x^3+y^3+z^3= (x^3+y^3)+z^3=(x+y)(x^2-xy+y^2)+z^3= (3(x^2+y^2)-(x+y)^2)/2 + z^3$ doing the necessary substitutions I get $1-3 z^2 +3 z^3$, equals $5/9$.


xcalib stops working at random Ubuntu 18.04

Question: I have just upgraded my ubuntu (Ubuntu 18.04.2 LTS, bionic). I am using xcalib -i -a to reverse the colors of my screen. Unfortunately, since the upgrade, something seems to have broken: xcalib stops working at random (and this is a little nightmare for my eyes). I don't really know which information is relevant for this question. Here are the last modules installed (obtained with : find /var/lib/dpkg/info/ -name \*.list -mtime -3 | sed 's#.list$##;s#.*/##' ) :
libmng2:amd64
libnss-systemd:amd64
libgimp2.0
libkf5kdelibs4support-data
libpam-systemd:amd64
systemd
pciutils
libbabl-0.1-0:amd64
libkf5kdelibs4support5:amd64
systemd-sysv
libgegl-0.3-0:amd64
libnss-myhostname:amd64
libsystemd0:amd64
libcurl4:amd64
libpci3:amd64
libudev1:amd64
libkf5sane-data
libcogl20:amd64
libkf5sane5
libcogl-pango20:amd64
gir1.2-coglpango-1.0:amd64
libkf5kdelibs4support5-bin
gir1.2-cogl-1.0:amd64
gdm3
initramfs-tools
initramfs-tools-core
initramfs-tools-bin
libgdm1
libcogl-common
gir1.2-gdm-1.0
libcogl-path20:amd64
libcurl3-gnutls:amd64
gnome-software-plugin-snap
libvulkan1:amd64
gnome-software
gnome-software-common
ubuntu-software

If someone has an idea, I would really appreciate. A little detail : when xcalib stops, I run it again with a shortcut of mine and it stops immediately again. When  I use again the shortcut, it waits approximately one minute to stop again. :(
Thanks in advance.

Edit 23/02/2019 : the problem did not disappear, and this is still a nightmare. :( :( :( I'm starting to loose hope.  I removed and reinstalled xcalib, with no effect of course. Right now, I am trying to see which processes appear (in top) when I keep changing the color of the screen.
Potentially linked due to activity : irq/71-brcmf_pc (by the way, I have a mac with Ubuntu installed on it, I should have precised that from the start ; this is my professional laptop, I couldn't choose :[ ), iio-sensor-prox, colord, gsd-xsettings, gsd-media-keys, gsd-clipboard, at-spi2-registr.
I had a look on the internet to see what these processes were doing, but I have not a single clue. So, I start a bounty.

Edit 01/03/2019 : The problem occurred again, but this time, thanks to Sam Wheel and his command line ( tail -f /var/log/syslog ), I managed to capture the problematic process. Here is a sample of what precisely occurred when xcalib stopped :

Mar  1 01:31:14 Synia dhclient[7120]: DHCPREQUEST of ***.***.19.90 on ens9 to ***.***.64.51 port 67 (xid=0x5bce959f)
Mar  1 01:34:18 Synia dhclient[7120]: message repeated 15 times: [ DHCPREQUEST of ***.***.19.90 on ens9 to ***.***.64.51 port 67 (xid=0x5bce959f)]

After what I set xcalib again :

Mar  1 01:34:38 Synia /usr/lib/gdm3/gdm-x-session[1341]: (II) modeset(0): EDID vendor "APP", prod id 41001
Mar  1 01:34:38 Synia /usr/lib/gdm3/gdm-x-session[1341]: (II) modeset(0): Printing DDC gathered Modelines:
Mar  1 01:34:38 Synia /usr/lib/gdm3/gdm-x-session[1341]: (II) modeset(0): Modeline "2560x1600"x0.0  268.50  2560 2608 2640 2720  1600 1603 1609 1646 +hsync -vsync (98.7 kHz eP)

And the DHCP request continues, over and over again, with the same effect on xcalib :

Mar  1 01:34:39 Synia dhclient[7120]: DHCPREQUEST of ***.***.19.90 on ens9 to ***.***.64.51 port 67 (xid=0x5bce959f)
Mar  1 01:35:55 Synia dhclient[7120]: message repeated 6 times: [ DHCPREQUEST of ***.***.19.90 on ens9 to ***.***.64.51 port 67 (xid=0x5bce959f)]

Mar  1 01:36:09 Synia dhclient[7120]: DHCPREQUEST of ***.***.19.90 on ens9 to ***.***.64.51 port 67 (xid=0x5bce959f)
Mar  1 01:36:47 Synia dhclient[7120]: message repeated 3 times: [ DHCPREQUEST of ***.***.19.90 on ens9 to ***.***.64.51 port 67 (xid=0x5bce959f)]

etc.
At some point (10 minutes later), I also had a DHCPACK :

Mar  1 01:44:03 Synia dhclient[7120]: DHCPREQUEST of ***.***.19.90 on ens9 to ***.***.64.51 port 67 (xid=0x5bce959f)
Mar  1 01:44:31 Synia dhclient[7120]: message repeated 3 times: [ DHCPREQUEST of ***.***.19.90 on ens9 to ***.***.64.51 port 67 (xid=0x5bce959f)]
Mar  1 01:44:50 Synia dhclient[7120]: DHCPREQUEST of ***.***.19.90 on ens9 to 255.255.255.255 port 67 (xid=0x5bce959f)
Mar  1 01:44:50 Synia dhclient[7120]: DHCPACK of ***.***.19.90 from ***.***.19.81
Mar  1 01:44:50 Synia NetworkManager[858]: <info>  [1551401090.2999] dhcp4 (ens9):   address ***.***.19.90
Mar  1 01:44:50 Synia NetworkManager[858]: <info>  [1551401090.2999] dhcp4 (ens9):   plen 28 (255.255.255.240)
Mar  1 01:44:50 Synia NetworkManager[858]: <info>  [1551401090.3000] dhcp4 (ens9):   gateway ***.***.19.81
Mar  1 01:44:50 Synia NetworkManager[858]: <info>  [1551401090.3000] dhcp4 (ens9):   lease time 1800
Mar  1 01:44:50 Synia NetworkManager[858]: <info>  [1551401090.3000] dhcp4 (ens9):   hostname 'mb27'
Mar  1 01:44:50 Synia NetworkManager[858]: <info>  [1551401090.3000] dhcp4 (ens9):   nameserver '***.***.32.40'
Mar  1 01:44:50 Synia NetworkManager[858]: <info>  [1551401090.3000] dhcp4 (ens9):   nameserver '***.***.222.4'
Mar  1 01:44:50 Synia NetworkManager[858]: <info>  [1551401090.3000] dhcp4 (ens9):   domain name 'mg09.***.**'
Mar  1 01:44:50 Synia dbus-daemon[811]: [system] Activating via systemd: service name='org.freedesktop.nm_dispatcher' unit='dbus-org.freedesktop.nm-dispatcher.service' requested by ':1.11' (uid=0 pid=858 comm="/usr/sbin/NetworkManager --no-daemon " label="unconfined")
Mar  1 01:44:50 Synia NetworkManager[858]: <info>  [1551401090.3000] dhcp4 (ens9): state changed bound -> bound
Mar  1 01:44:50 Synia systemd[1]: Starting Network Manager Script Dispatcher Service...
Mar  1 01:44:50 Synia dbus-daemon[811]: [system] Successfully activated service 'org.freedesktop.nm_dispatcher'
Mar  1 01:44:50 Synia systemd[1]: Started Network Manager Script Dispatcher Service.
Mar  1 01:44:50 Synia nm-dispatcher: req:1 'dhcp4-change' [ens9]: new request (1 scripts)
Mar  1 01:44:50 Synia nm-dispatcher: req:1 'dhcp4-change' [ens9]: start running ordered scripts...
Mar  1 01:44:50 Synia dhclient[7120]: bound to ***.***.19.90 -- renewal in 846 seconds.

This seems thus to be a DHCP request that prevents xcalib from working correctly (at least, the "randomness" is explained). No idea what this is precisely (I see that everything happens on the port 67 which is used, amongst others, by Apple NetBoot ; since I have a Mac with dual boot Linux-Mac, could it be linked by means of some firmware ?). I also precise that I have a special cable that has its own IP to connect to my network (a Mac device).
Any suggestions ?

Edit 02/03/2019 : New day, new problem (it always occurs around midnight, seemingly). This time, the log gives another problem :

Error: Error invoking IBus.set_global_engine_async: Expected function
  for callback argument callback, got
  undefined#012setEngine@resource:///org/gnome/shell/misc/ibusManager.js:207:9#012wrapper@resource:///org/gnome/gjs/modules/_legacy.js:82:22#012activateInputSource@resource:///org/gnome/shell/ui/status/keyboard.js:490:13#012wrapper@resource:///org/gnome/gjs/modules/_legacy.js:82:22#012_emit@resource:///org/gnome/gjs/modules/signals.js:128:27#012activate@resource:///org/gnome/shell/ui/status/keyboard.js:65:9#012wrapper@resource:///org/gnome/gjs/modules/_legacy.js:82:22#012_inputSourcesChanged@resource:///org/gnome/shell/ui/status/keyboard.js:620:13#012wrapper@resource:///org/gnome/gjs/modules/_legacy.js:82:22#012reload@resource:///org/gnome/shell/ui/status/keyboard.js:369:9#012wrapper@resource:///org/gnome/gjs/modules/_legacy.js:82:22#012_ibusSetContentType@resource:///org/gnome/shell/ui/status/keyboard.js:691:9#012wrapper@resource:///org/gnome/gjs/modules/_legacy.js:82:22#012_emit@resource:///org/gnome/gjs/modules/signals.js:128:27#012_setContentType@resource:///org/gnome/shell/misc/ibusManager.js:183:9#012wrapper@resource:///org/gnome/gjs/modules/_legacy.js:82:22

Apart from this novelty, this is the same problem as yesterday. I'll try the solutions given by sancho.s tomorrow morning (the first one was not successful so far).
Comment: Try looking at logs by entering following cmd in terminal window and show what error occurs when it happens:    tail -f /var/log/syslog
Comment: Strangely, the problem solved itself yesterday after an update... Still no explanation of which process was problematic. Nevertheless, these new packages were added :
'libisccfg160:amd64
libisccc160:amd64
libirs160:amd64
libdns1100:amd64
libisc169:amd64
liblwres160:amd64 '
Comment: Well, I was too optimistic. It's still there. And I don't believe it will go away by pure magic.
Comment: Thanks a lot for the command. I am waiting for it again. The word "at random" in the title makes plainly sense. It only happened once again, when I closed the lid of my laptop, and I was unable to track down the process.
Comment: I'm assuming you require xcalib because your eyes are sensitive to white or nearly white backgrounds. If that is correct, with a little trouble you can find dark themes or dark settings for most applications. And, though this is just my opinion, using dark themes/settings is visually more satisfying.
Comment: Indeed, this is because my eyes are sensitive to white backgrounds. Unfortunately, I had the hardest trouble in the world to find, for example, a software that colors webpages on Firefox/Tor (this webpage of StackExchange is quite white, and I have it completely black with the inversion of colors). Usually, I never switch to normal colour, except if there is a picture that I want to see in its original form.
Answer: You may try resetting values to their default with
xcalib -c

Clearly, this precludes using xcalib for what you mean, but it may help in getting rid of the problem and/or diagnosing it.
You may also try alternative ways to control screen output, with xrandr and other commands, which may even have some advantages ("... use xrandr instead of xcalib since, among other limitations, the latter doesn't provide a proper way to query its state.")
See
https://askubuntu.com/a/401845/226614
https://www.reddit.com/r/linux/comments/27b0k0/xrandr_and_screen_color_inversion_setting_is_fine/
For your specific use, see
Easiest way to invert colors on Ubuntu 18.04
Admittedly, I am not providing an answer to
What is the problem?,
but the request is
If someone has an idea, I would really appreciate
Comment: Thanks for your suggestions. Indeed, the solution is maybe to switch to another program. Zoltan Padrah's program seems to be a good alternative (this is the only use I have of xcalib).

I also used your command `xcalib -c` and it resulted in killing the night mode. :P But I had this problem before I became aware of the existence of the night mode (well, this could still be related, but I now believe this is a DHCP request that triggers that).
Comment: @Synia - Well, that is what `xcalib -c` does... Please post feedback if you try some of the alternatives here.
Comment: Right now, this is becoming crazy again, so I am using all your solutions one by one. I can already tell that the first one gives unfortunately nothing. I have the following problem `xrandr: Need crtc to set gamma on`.
Comment: @Synia - Which is the first one? What do you mean by "gives unfortunately nothing"? Do you get only that message? Googling suggests that it is a problem possibly related to drivers+hardware+kernel+versions. Please post exactly what you are doing and what you get.
Comment: E.g., http://forums.debian.net/viewtopic.php?f=5&t=112860#p538805
http://forums.debian.net/viewtopic.php?f=5&t=110388#p551779


How to capture std::unique_ptr "by move" for a lambda in std::for_each

Question: I am learning the new features in c++11 and came across this problem.  I'd like to capture an unique_ptr by moving it inside a lambda as an argument for for_each.
set up:
std::array<int,4> arr = {1,3,5,6};
std::unique_ptr<int> p(new int);  (*p) = 3;

attempt 1 - doesn't work because unique_ptr doesn't have a copy constructor.  c++0x doesn't specify the pass by move syntax.
std::for_each(arr.begin(), arr.end(), [p](int& i) { i+=*p; });

attempt 2 - use bind to bind a moved copy of p to a function that takes int&:
std::for_each(arr.begin(), arr.end(),
     std::bind([](const unique_ptr<int>& p, int& i){
          i += (*p);
     }, std::move(p))
);

Compiler complains that 'result' : symbol is neither a class template nor a function template.
The main purpose of the exercise is to understand how a movable variable be captured in a lambda that's cached for later use.
Comment: This question has already been asked [here](http://stackoverflow.com/q/8640393/20984). However, I don't vote to close since your question contains an alternative (though not-working) solution.
Comment: See also [here](http://stackoverflow.com/q/8236521/20984).
Answer: Update: you can capture a movable variable in a lambda from C++14 onwards.
std::for_each(arr.begin(), arr.end(), [p=std::move(p)](int& i) { i+=*p; });

You cannot capture a movable variable into a lambda in any straightforward way in C++11.
Lambdas capture by copy or by reference. Thus, to capture a move-only variable, you have to wrap it in an object where copying => moving (such as std::auto_ptr). This is a nasty hack.
In your example, you can just capture by reference, but if this was just simplified code it may not do what you wanted with the real code:
std::for_each(arr.begin(), arr.end(), [&p](int& i) { i+=*p; });

Here's a copy-move-only wrapper:
template<typename T>
struct move_on_copy_wrapper
{
    mutable T value;

    move_on_copy_wrapper(T&& t):
        value(std::move(t))
    {}

    move_on_copy_wrapper(move_on_copy_wrapper const& other):
        value(std::move(other.value))
    {}

    move_on_copy_wrapper(move_on_copy_wrapper&& other):
        value(std::move(other.value))
    {}

    move_on_copy_wrapper& operator=(move_on_copy_wrapper const& other)
    {
        value=std::move(other.value);
        return *this;
    }

    move_on_copy_wrapper& operator=(move_on_copy_wrapper&& other)
    {
        value=std::move(other.value);
        return *this;
    }

};

You can then use it like this:
int main()
{
    std::unique_ptr<int> p(new int(3));
    move_on_copy_wrapper<std::unique_ptr<int>> mp(std::move(p));

    [mp]()
    {
        std::cout<<"*mp.value="<<*mp.value<<std::endl;
    }
    ();

    std::cout<<"p="<<p.get()<<", mp="<<mp.value.get()<<std::endl;
}

Comment: The compiler won't generate them due to the existence of the copy constructor and copy assignment operator.
Comment: "Note that std::bind also requires that its arguments are copyable." That's not true. `std::bind` is usable with move-only types.
Comment: OK, I checked: `std::bind` should be usable with move-only arguments, it just creates a move-only result. However, it fails in practice with MSVC 2010 and g++ 4.7.
Comment: Do you really *need* to implement the move-semantic functions, i.e `move_on_copy_wrapper(move_on_copy_wrapper&&)` and `move_on_copy_wrapper& operator=(move_on_copy_wrapper&&)`? The compiler generated ones are not enough?
Comment: AFAIK, std::bind should work on movable arguments. However, MSDN's documentation says all arguments should be copy constructible. Anthony, which compiler do you use?   http://msdn.microsoft.com/en-us/library/bb982702(v=vs.100).aspx
Comment: Sample code didn't compile: error C2558: struct 'move_on_copy_wrapper' : no copy constructor available or copy constructor is declared 'explicit' with [T=std::unique_ptr]
Comment: Interesting. It appears MSVC 2010 requires the copy constructor to take `const` arg. Easily fixed: make `value` `mutable`, and add `const` to the copy constructor and copy-assignment operator.
Comment: GCC 4.7 can certainly correctly deal with move-only types with `std::bind`. However be careful of the peculiar way `std::bind` forwards the bound arguments to the functor: try for instance `pointer_type p; auto f = std::bind([](pointer_type& p) {}, std::move(p)); f();` with some appropriate `pointer_type`.
Comment: @AnthonyWilliams, you defined the move ctors by hand.  Doesn't `=default` force the compiler to generate the move ctors for you?
Comment: Yes, I could have used `=default` for the move constructor and move assignment operator.
Answer: Your attempt 2 will almost work.
What's missing is you haven't told your bind call to expect a parameter:
std::for_each(arr.begin(), arr.end(),
   std::bind([](const unique_ptr<int>& p, int& i){
      i += (*p);
   }, std::move(p), std::placeholders::_1)
);

The placeholders::_1 is necessary to tell the result of bind that it should expect a parameter passed to it for its operator().
This is also the suggestion given in @marton78's answer here.