Can I still share data tables with multisite, using shared database, in Drupal 8 or do I need to use 'Domains' contrib module?

Question: I have a multi-site setup that is working in Drupal 8 (8.6.13) - all of the sites share the code-base and database happily but I cannot seem to share data tables between the sites using the prefix array method - has this changed in Drupal 8 since older versions?
... I start off asking this since most of the data I am finding is for Drupal 7 or older and the solutions given seem valid but are not fully working when I try to implement them.
For example - I want a base (default) site to handle taxonomy, content types, and some admin functions like REST APIs. Each site can handle it's own content and theme (there are no users to worry about) and the sites/multi-site-1/settings.php is configured to handle this properly (I think).
in the base settings.php:
$databases['default']['default'] = array(
  'database' => 'base_database',
  'username' => 'db_user',
  'password' => 'db_password',
  'prefix' => array(
    'default'             => 'base_',
// ** content type and fields seem to share okay!
    'content_type_' => 'shared_',
    'content_field_' => 'shared_',

// ** the other tables with 'shared_' prefix that do not work shown below

and in the sites/multi-site-1/settings.php:
$databases['default']['default'] = array (
  'database' => 'base_database',
  'username' => 'db_user',
  'password' => 'db_password',
  'prefix' => array(
    'default'         => 'site_1_',

// ** can these even be shared?
    // 'config'              => 'shared_',
    // 'config_snapshot'     => 'shared_',

// ** users related things have errors when installing multi-site-1
    //'authmap' => 'shared_',
    //'profile_fields' => 'shared_',
    //'profile_values' => 'shared_',
    //'permission' => 'shared_',
    //'role' => 'shared_',
    //'sessions' => 'shared_',    //1. error - if sharing site won't even start install
    //'user' => 'shared_',        //3. error - "EntityStorageException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0' for key 'PRIMARY': "
    //'users' => 'shared_',
    //'users_roles' => 'shared_', //2. error - "The "user_role" entity type does not exist."
    //'users_data' => 'shared_',  //2. error - "Table users_data already exists"
    //'users_field_data' => 'shared_',

// ** taxonomy related share seems okay but not working?
    //'taxonomy_index' => 'shared_',
    //'taxonomy_term_data' => 'shared_',
    //'taxonomy_term_field_data' => 'shared_',
    //'taxonomy_term__parent' => 'shared_',
    //'vocabulary' => 'shared_',       // 1. install error - not present in D8 db?
    //'vocabulary_node_types' => 'shared_',
    //'term_data' => 'shared_', // not present in D8?
    //'term_hierarchy' => 'shared_', // not present in D8?
    //'term_image' => 'shared_', // not present - n/a?
    //'term_lineage' => 'shared_', // not present - n/a?
    //'term_node' => 'shared_', // not present - n/a?
    //'term_relation' => 'shared_', // not present - n/a?
    //'term_synonym' => 'shared_', // not present - n/a?
  ),
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
  'collation' => 'utf8mb4_unicode_ci',
);

Should I abandon the multi-site config in this manner and rely on a contrib module like Domain Access?  (I have tried to set this up but cannot seem to get it configured properly - or am not even sure what it is supposed to be doing for me).
Is this still a good way to share data in the database in Drupal 8 or am I missing something?
Am I adding in too much of the old v7 and v6 multi-site logic and Drupal 8 handles this differently?

any insights into how to do this better would be greatly appreciated!

some answers already read and referenced:

How to share user and user profile in a multisite environment?
How do I create a multisite with  shared users and nodes?
Deprecate multisite in 8.x for removal in 9.x
and of course from Drupal.org => Share tables across instances (not recommended)
Comment: Yes, partially, together with the [Features](https://www.drupal.org//features) module. When you have for example a content type that will be the same on all instances, you export the content type on one instance into a feature (which basically is just a module), then enable (or import) that feature in another instance, and on both instances finally export config. So you can use Features to sync certain features across multiple sites, but still rely on config for each site. And important to note: Features can't sync content (nodes, terms, users).
Comment: I think this is the module you meant to link => https://www.drupal.org/project/features. I will try like how you described
Comment: As from reading the linked resources it sounds shared database tables is considered a bad thing and probably will be removed from Drupal someday.
Comment: I might need to rethink how we are setting this up then - @leymannx you also have a good answer about multi-site [here](https://drupal.stackexchange.com/questions/197784/multisite-config-directories-of-subsides/278290#278290) could config splitting and sharing perhaps work better in this case?
Comment: Oops, yes, absolutely.
Answer: posting my own answer with a brief explanation...
I have investigated the Config Split and Features modules and found that they are not providing what we need for this instance of Drupal running a set of sites.
The shared data and other interoperability that I need to be common between sites is not handled as I expect it to be... so my solution will be to have the Drupal instance direct users to the appropriate content on the site via redirects at the web server and then appropriate usage of paths and contextual filters.
If any other people find themselves here trying to answer similar questions with regards to Drupal 8 please take these into consideration:

do you need to 'multi-site'? read "When to multisite" => https://www.drupal.org/docs/7/multisite/multi-site-sharing-the-same-code-base#when
maybe you are looking for something like the Domain Access module instead? check out this module and read => Sharing the same code base and one database
can you achieve what your site needs from the web 'server' instead of forcing through the web 'app'? Apache virtual hosts are not that hard to learn => https://www.drupal.org/node/111238 and .htaccess can do wonderful things => https://code.tutsplus.com/tutorials/an-in-depth-guide-to-mod_rewrite-for-apache--net-6708

    ## multi-site-1 ==> _workspace/base-site/web/sites/multi-site-1
       <VirtualHost *:80>
          DocumentRoot "/var/www/base-site.com/web"
          ServerName multi-site-1.com
          ServerAlias www.multi-site-1.com

          <Directory />
            Options FollowSymLinks
            AllowOverride None
          </Directory>

          <Directory "/var/www/base-site.com/web">
              Options FollowSymLinks Multiviews Indexes
              AllowOverride All
              Order allow,deny
              Allow from all
              Require all granted
              MultiviewsMatch Any
          </Directory>

          ErrorLog "/private/var/log/apache2/multi-site-1.com-error_log"
          CustomLog "/private/var/log/apache2/multi-site-1.com-access_log" common
      </VirtualHost>

and maybe something like this in .htaccess:
RewriteCond %{HTTP_HOST} ^(?:www\.)?multi-site-1\.com(.*)$ [NC]
RewriteRule ^(.*)$ https://www.base-site.com/multi-site-1/$1 [L]

and thanks again to @leymannx for your help on this!


Get execution time of code x amount of times

Question: What I am trying to do is run this program, get the execution time of it, and then continue to do that 9 more times. How would I go about iterating over it to get it to print out 10 different execution times? I'm not quite sure how I need to structure the program in order to accomplish this.
import time
start_time = time.time()

def fibonacci():
    previous_num, result = 0, 1
    user = 1000
    iteration = 10
    while len(str(result)) < user:
        previous_num, result = result, previous_num + result
        while iteration != 0:
            iteration -= 1
            end = time.time()
            print(start_time - end)
    return result

print(fibonacci())
print("--- %s seconds ---" % (time.time() - start_time))

Comment: you could think about using timeit module if you don't need every execution time and only care about an average time
Comment: Note that there are handy timer decorators such as @timeit (https://stackoverflow.com/questions/1622943/timeit-versus-timing-decorator)
Comment: Does this answer your question? [Measure time elapsed in Python](https://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python)
Comment: Or this one? [Repeating a function a set amount of times in python](https://stackoverflow.com/questions/24570393/repeating-a-function-a-set-amount-of-times-in-python)
Comment: @wwii Those helped slightly, could you please explain or help me understand better why I would want to use timeit rather than a different module/decorator?
Answer: All you need to do is create a for loop and put your code in it.
import time

def fibonacci(start_time):
    previous_num, result = 0, 1
    user = 1000
    iteration = 10
    while len(str(result)) < user:
        previous_num, result = result, previous_num + result
        while iteration != 0:
            iteration -= 1
            end = time.time()
            print(start_time - end)
    return result

for i in range(0, 10):
    start_time = time.time()
    print(fibonacci(start_time))
    print("--- %s seconds ---" % (time.time() - start_time))


ViewFlipper caching issue

Question: The views are not cached in a ViewFlipper. Is there a way wherein we can get an image of the view and show it to user so that he sees the Ui as we see on Home scrren(when we swipe the previous view also moves along and when we lift our finger, only then the next view is shown completely.)
What I want to do is that when the user starts moving his finegr on screen, the view should also move along(create an image of view).
I am not getting to do this, as when we swipe the present view goes and next view comes, we do not get both visible when we r moving our finger on screen.
Please if anyone gets what I am trying to do, do help me.
Thanks,
Farha
Answer: It's tricky to get scroll and swipe tracking working on Android, while using ViewAnimator or its subclasses.
They allow you to set in and out animations and start them at a given moment, but they work with discrete, either-this-or-the-other-view animations. They are actually using FrameLayout and after in or out animation is executed, other views' visibility is set to View.GONE to hide them from showing up under/over your current View.
The Launcher and the Gallery application are actually doing the functionality you want, by using a different approach.
They track the user touch input (onTouchEvent()), on MotionEvent.ACTION_MOVE they perform animations manually and on MotionEvent.ACTION_UP snap to the appropriate view, just like in the iPhone.
Unfortunately, this approach is actually more complicated than it looks like.
With the manual handling, you have to ensure that you are taking care of everything related to the touch input. This includes a lot of flag-raising, value-checking, event-delegating, etc.
If you want to get better acquainted with this, take a look at these classes from Gallery3D or Launcher's source code.
One other way to get nice horizontal scrolling is to use HorizontalScrollView.
You have to figure out a way to recycle your views, like you would with a ListView and you have to add the snap-to-view logic, but if you have to take care of a small number of views it could be the easiest approach.
Hope that helps.

ViewFlipper caching issue


Problemas com Jquery load e append ao carregar outra pagina php

Question: Se possível alguém me ajudar,estou com o seguinte problema.
Ao clicar no menu que se encontra o id de referencia para meu jquery ele carrega
a página apenas com vários cliques no menu e quando aparece eu clico novamente a página some.
Utilizei dois códigos diferentes mas me resultam no mesmo problema.
segue abaixo os códigos.
Script Jquery

Menu

Premium

Premium

Ajuda

Baixar

Increver-se

Entar

Comment: Obrigado pela ajuda, era somente o '#' que esqueci de colocar no href.
Comment: `$('#cliente1').html(retorno);` faça essa alteração
Comment: ola, esta a mesma coisa, eu clico aparece uma vez e depois some ai depois dou vários clicks e aparece e quando clico de novo desaparece.
Comment: agora que eu vi! você ta chamando duas funções de ajax no mesmo click???? acho que só precisa disso. `$('#link1').click(function(event){
         $( "#cliente1" ).load( "c_cliente.php" );});`
Answer: Você tem um elemento  dentro do seu
, que está sendo executado quando você clica no parent.
Sugiro a seguinte abordagem:

Passe a interceptar o click no anchor (), e não no list item (
), passando o id para o elemento ;
Coloque um href dummy (que não leva a lugar nenhum). O padrão é colocar um hash #, e não deixar em branco (embora '' seja um href sintativamente válido, de acordo com essa resposta);
Cancele o evento que vem do clique. Assim, você trata o callback do clique da maneira que quiser e cancela o evento padrão do navegador. Este cancelamento pode ser feito com um return false; ou chamar o método .preventDefault() no objeto event.
Escolha uma dos métodos jQuery (ajax ou load). Usei aqui o load.

Algo assim:

$(document).ready(function(){

    $('#link1').click(function(event){

       $( "#cliente1" ).load( "c_cliente.php" );

       event.preventDefault();
    });

});

Premium

Premium

Ajuda

Baixar

Increver-se

Entar

Comment: Cara realmente esqueci do '#'...estava codificando muito rápido é esqueci desse detalhe.Funcionou  das duas maneiras perfeitamente,faltou somente o "#'.Muito obrigado pela ajuda.


Proof of contemporaneous exogeneity, and its implications for an AR(1) model

Question: It can be shown by contradiction that exogeneity fails to hold for an AR(1) model.
Is there any proof that contemporaneous exogeneity does not fail to hold?
All I've come across is assuming it does hold and showing that the contradiction for the strict exogeneity case does not apply to this case, which isn't really a proof?
Assuming that,
Say we have a weakly stationary and weakly dependent AR(1) model:
$y_t=\beta_0+\beta_1y_{t-1}+u_t$ with
$E[u_t|y_{t-1}]=0$
$E[u_t]=0$
$E[u_t^2]=\sigma^2$
Since we have $E[u_t|\beta_0+\beta_1y_{t-2}+u_{t-1}]=0$ and so on, does this imply:
$E[u_t|y_{t-1},y_{t-2},...,u_{t-1},u_{t-2},...]=0$
?
Answer: The reason you mostly encounter contemporaneous exogeneity as an assumption is - in my view - that it amounts to assuming that the model is not dynamically misspecified.
By way of example, let us consider the case that the process is in fact generated as an AR(2) process,
$$
y_t=\phi_1y_{t-1}+\phi_2y_{t-2}+u_t,
$$
where $u_t$ satisfies the assumptions you present, in particular that $E(u_t|y_{t-1}, y_{t-2})=0$.
Now, suppose that the statistician fits an AR(1) model to $y_t$,
$$
y_t=\phi y_{t-1}+\tilde u_t.
$$
Then, $\tilde u_t=\phi_2y_{t-2}+u_t$, so that, evidently, $E(\tilde u_t|y_{t-1}, y_{t-2})\neq0$.
Hence, if you were to fit a regression to the AR(1) specification, you would get an inconsistent estimator of $\phi_1$, the coefficient in the actual AR(2) model, as the error term of the AR(1) regression specification, $\tilde u_t$, is correlated with the regressor $y_{t-1}$, because $y_{t-1}$ and $y_{t-2}$ are correlated in an AR-process.


Cannot find system alert using Xcode Tests

Question: How do you tap on "OK" on the iOS system alert asking "Photos access" using Xcode Tests?
There are many many such questions on SO, but none of the answers worked for me.
Tests always fail - I.E. they cannot find the alert at all.
Xcode 13.4
Swift 5
Answer: Just a simple tap on any alert would be:
XCUIApplication(bundleIdentifier: "com.apple.springboard").buttons["OK"].tap()

If you want to ensure the correct alert is shown, you can build a more complex query like:
XCUIApplication(bundleIdentifier: "com.apple.springboard").alerts.matching(NSPredicate(format: "label CONTAINS[c] %@", "Access Photos")).element.buttons["OK"].tap()

Comment: this does not work for Touch ID alert, the tests just hang
Comment: And not for the alert prompted by UIClipboard in UITest either. No solution yet. Sometimes apples privacy features makes it more fragile
Comment: Doesn't seem to work for a notification alert either.


Statistic test to prove if there is a difference between A and B from answers A>B, A<B and A=B

Question: The conducted test allow participants to respond with the following three answers:
- a) A is better than B (A > B)
- b) B is better than A (A < B)
- c) A is equal to B (A = B)
The first approach I have taken is to run a binomial test only using the information a) and b), proving the null hypothesis
Ho: There is no statistically significant difference between A and B
Still, considering this two scenarios:
a) 10 answers A=B, 30 answers A>B, 80 answers B>A
b) 300 answers A=B, 30 answers A>B, 80 answers B>A
Doing the binomial test between A>B and B>A (not counting A=B) obviously yields the same result for both scenarios. Still, it feels like this difference is more relevant in scenario a. Is there a way to test for this?.
I have also though of running two binomials (comparing first A=B to A>B+B>A) and, in case this one is significant, comparing A>B to B>A) but I'm not sure if I commit any errors or loss of statistical significance this way OR testing with a Chi Squared GOF and applying post hoc testing in case it is significant, but there is not much info on post hoc tests for GOF.
Comment: Why not test $A \ge B$ and $B \ge A$ instead?
Comment: Wouldn't testing for A >= B or viceversa be too conservative? edit: Sorry I can't seem to write the bigger-equal symbol.
Comment: use the \ge or \le instructions in math mode (between \$ signs) to make $\ge$ and $\le$
Comment: Use McNemar's test. Maybe  it is your binomial test. The number of participants with A=B does not provide any information. If you want to understand why A=B is useless, you can check the process of development of McNemar's test.
Comment: That is what I am trying to understand, how to make sense of the A=B participants. Just to give an example, if I were to put the A product on the market and wanted to compare it with B, I could conduct a research test in which I ask participants if A=B, AB. In a case of n(A=B)=5, n(A>B)=30 and n(BB)=30 and n(B>A)=5, not as much. I understand I am trying to do two things at once (relevance+preference) so maybe two different tests should be carried out.
Answer: An intuitive way of treating this would be to assume that, if the participants answer $A=B$, they are as likely to think $A > B$ as to think $B > A$. Then, you could stick with your single binomial test with 2 subsets instead of 3:

$card(A \ge B) \sim card(A>B) + 0.5 \cdot card(A=B)$
$card(A \le B) \sim card(A<B) + 0.5 \cdot card(A=B)$

This would yield quite different results from one scenario to the other.


How do I get the client id in a Laravel app?

Question: I've set up a laravel app with client authentification. I send it my client id and client secret and it gives me a token. I'm able to log in to my laravel app, but I can't figure out how to get the id of the client that's been authorized.
I've seen hints to use auth()->user()->Token()->getAttribute('client_id') to get the client id, but since I'm only using clients there is no user and I get an error about trying to call Token() on a null object. Auth::id() also returned nothing. I grabbed the token from the header with Request::header('Authorization'), but it didn't match anything in the database.
Comment: What are you using for client Auth
Comment: Have you tried `Auth::user()->id`?
Comment: Yes, it tells me that Auth::user() is null. Which I suppose is expected since I don't have any users, just clients.
Comment: Did you use the `php artisan make:auth` command? Or have you written the client authentication from scratch?
Answer: I'm assuming you're using client credentials grant tokens, and the CheckClientCredentials middleware.
You can get this information from the bearer token, but it's not that straightforward. You would need to create a new PSR7 request with the token, and send it off to the oauth server to have it converted to readable data.
This is already done inside the CheckClientCredentials middleware provided by Passport. So, one way to do this would be to extend the CheckClientCredentials middleware and just manually set the needed fields on the request object from inside the middleware.
First, create app/Http/Middleware/MyCheckClientCredentials.php:
namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\AuthenticationException;
use League\OAuth2\Server\Exception\OAuthServerException;
use Symfony\Bridge\PsrHttpMessage\Factory\DiactorosFactory;
use Laravel\Passport\Http\Middleware\CheckClientCredentials;

class MyCheckClientCredentials extends CheckClientCredentials
{
    /**
     * The Resource Server instance.
     *
     * @var \League\OAuth2\Server\ResourceServer
     */
    private $server;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  mixed  ...$scopes
     * @return mixed
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function handle($request, Closure $next, ...$scopes)
    {
        $psr = (new DiactorosFactory)->createRequest($request);

        try {
            $psr = $this->server->validateAuthenticatedRequest($psr);

            // This is the custom line. Set an "oauth_client_id" field on the
            // request with the client id determined by the bearer token.
            $request['oauth_client_id'] = $psr->getAttribute('oauth_client_id');

        } catch (OAuthServerException $e) {
            throw new AuthenticationException;
        }

        $this->validateScopes($psr, $scopes);

        return $next($request);
    }
}

Next, update your app/Http/Kernel.php to use your custom middleware instead of the build in Passport middleware:
protected $routeMiddleware = [
    'client' => \App\Http\Middleware\MyCheckClientCredentials::class,
];

Apply the middleware to your route as normal:
Route::get('/user', function(Request $request) {
    // Should show "oauth_client_id" field.
    dd($request->all());
})->middleware('client');

If you don't want to do this inside a middleware, you can study how the Passport middleware works and reuse this code in some type of service if you'd like.
NB: all untested.
Comment: That ended up crashing on me on the line `$psr = $this->server->validateAuthenticatedRequest($psr);`, so I just pulled all of CheckClientCredentials instead of extending it. It's working well now, thank you very much.
Comment: @Califer I see. I didn't see before, but evidently the `$server` property is defined as `private`, so it doesn't come over when extended. You just need to redefine the property in your child class. I have updated my answer to reflect this. But, glad you got it working either way.
Answer: I had to do something similar in a logger middleware of mine:
.......................
    $user = $request->user();

    if($user) {
        // assume the authorization header exists, since the user is authenticated
        $header = $request->headers->get('authorization');

        if($header) { // authorization header is not set when testing via Passport::actingAs()
            /**
             * Stolen from League\OAuth2\Server\AuthorizationValidators\BearerTokenValidator#63
             */

            // Get the actual jwt string from the header
            $jwt = trim(preg_replace('/^(?:\s+)?Bearer\s/', '', $header));

            // Parse the token from the string
            $token = (new Lcobucci\JWT\Parser())->parse($jwt);

            // Get the ID from the token
            $oauthClientId = $token->getClaim('aud');
        }
    }
.......................

Comment: This doesn't work as of now, as the Parser is an interface, and the actual implementation Lcobucci\JWT\Token\Parser takes additional parameters
Comment: Took a lot longer to break than I thought it would


How to auto fit recyclerview items to the width of screen android?

Question: I am trying to implement below layout. I want to position the items in such a way that it takes full width of the screen:
Expected Layout:

Actual Layout:

This is the code for item of my Recyclerview:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools">

  <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/size_8dp"
    android:paddingStart="@dimen/size_20dp"
    android:paddingEnd="@dimen/size_20dp"
    android:paddingBottom="@dimen/size_8dp">

    <ImageView
      android:id="@+id/legendsItemIcon"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:layout_constraintTop_toTopOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintBottom_toTopOf="@+id/text_legend_status_name"
      />
    <TextView
      android:id="@+id/text_legend_status_name"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      tools:text="Low"
      android:textSize="@dimen/text_size_8sp"
      app:layout_constraintTop_toBottomOf="@+id/legendsItemIcon"
      app:layout_constraintStart_toStartOf="@+id/legendsItemIcon"
      app:layout_constraintEnd_toEndOf="@+id/legendsItemIcon"
      app:layout_constraintBottom_toBottomOf="parent"
      android:textColor="@color/legends_item_status_text_color"
      android:layout_marginTop="@dimen/size_4dp"
      />

  </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

How can I achieve this?
Comment: Is your recyclerview is in horizontal orientation?
Comment: do you want to align each recyclerview row items to left(start) ?
Comment: @DhavalSolanki yes
Comment: I want to expand them to the screen's width @Fartab
Comment: do you have two items in each row? and want each one to expand to half of parent's width?
Comment: do you want to have a 3 items in each row and  repeat it in vertical recycler view?
Comment: Its can have more then that @nicej
Comment: I have a child `RecyclerView` inside a parent `RecyclerView`
Comment: How many items can a row have? is it scroll-able?
Comment: Yeah it is scrollable @user10284284
Answer: This custom class will help you https://gist.github.com/heinrichreimer/39f9d2f9023a184d96f8
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.ViewGroup;

public class SpanningLinearLayoutManager extends LinearLayoutManager {

public SpanningLinearLayoutManager(Context context) {
    super(context);
}

public SpanningLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
    super(context, orientation, reverseLayout);
}

public SpanningLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
}

@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
    return spanLayoutSize(super.generateDefaultLayoutParams());
}

@Override
public RecyclerView.LayoutParams generateLayoutParams(Context c, AttributeSet attrs) {
    return spanLayoutSize(super.generateLayoutParams(c, attrs));
}

@Override
public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
    return spanLayoutSize(super.generateLayoutParams(lp));
}

@Override
public boolean checkLayoutParams(RecyclerView.LayoutParams lp) {
    return super.checkLayoutParams(lp);
}

private RecyclerView.LayoutParams spanLayoutSize(RecyclerView.LayoutParams layoutParams){
    if(getOrientation() == HORIZONTAL){
        layoutParams.width = (int) Math.round(getHorizontalSpace() / (double) getItemCount());
    }
    else if(getOrientation() == VERTICAL){
        layoutParams.height = (int) Math.round(getVerticalSpace() /  (double) getItemCount());
    }
    return layoutParams;
}

@Override
public boolean canScrollVertically() {
    return false;
}
@Override
public boolean canScrollHorizontally() {
    return false;
}

private int getHorizontalSpace() {
    return getWidth() - getPaddingRight() - getPaddingLeft();
}

private int getVerticalSpace() {
    return getHeight() - getPaddingBottom() - getPaddingTop();
}
}

Set RecyclerView layoutManager to SpanningLinearLayoutManager to instead of LinearLayoutManager
Comment: It's close enough. How can I evenly distribute the items and still make the content scrollable? I have more then 10 items and it will get really close to each other. @SSB
Comment: @SSB can you look this [issue](https://stackoverflow.com/q/71380874/11560810)
Comment: Works like wonders.
Answer: If I understand correctly  you need a horizontal recycler view..
So set your layout manager as below:
    LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
    linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
    recyclerView.setLayoutManager(mHorizontalLayoutManager);

if your items have been more than your screen size it will scrollable
Comment: Hey. can you look this [issue](https://stackoverflow.com/q/71380874/11560810)
Answer: You simply use GridLayoutManager instead of LinearLayoutManager
 /**
 * Creates a vertical GridLayoutManager
 *
 * @param context Current context, will be used to access resources.
 * @param spanCount The number of columns in the grid
 */
public GridLayoutManager(Context context, int spanCount) {
    super(context);
    setSpanCount(spanCount);
}

Answer: If you want Recyclerview wrap its content (full height stretch wrap its content). Just wrap it with NestedScrollView. I tested and its work.
<androidx.core.widget.NestedScrollView
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  >

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <RecyclerView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Bayar SPP"
        style="@style/FontStyleSubtitle"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/recyclerView" />

   </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.core.widget.NestedScrollView>

Answer: Use this code:
recyclerView.layoutManager = GridLayoutManager(context, splitcount)

This worked for me.


In Views, display additional fields from an entity reference

Question: I have a content type with a field that is an entity reference to another content type called "URLs", and the "Allowed number of values" is set to "Unlimited", meaning that one record can have multiple URLs associated to it.
When I come to the View for this node, I have added a Field for "URLs", and under "MULTIPLE FIELD SETTINGS" I have ticked "Display all values in the same row", and Display type: Unordered list.
This works well, and I get the the list of associated URLs in an unordered list, like so:

www.domain1.com
www.domain2.com
www.domain3.com

Where it gets complicated, my "URLs" content type has another field called "field_url_type", which is a field type "List (text)". This contains the type of URL, (eg. Production, Development, Staging, Decommissioned, etc).
In the main content type display View, I would like to display this additional field from the URL content type next to the URL values, like so:

www.domain1.com (Production)
www.domain2.com (Development)
www.domain3.com (Decommissioned)

I tried using the Views > Configure Field > REWRITE RESULTS panel to include the REPLACEMENT PATTERNS for both fields, like so:
<code>{{ field_url }} ({{ field_url_type }})
</code>
... but this didn't work. I'm guessing it is more complicated than that!
Does anyone know how I can display this additional field from a content type referenced by an entity reference field in a node view?
Answer: Many solutions for this but to pick one :)

Download and enable Display Suite https://www.drupal.org/project/ds
Go to admin/structure/ds/fields and a token field (see screenshot #2 for values, adjust according to your field names)
Go to view mode of your Url content type and create a seperate view mode, e.g. called entity_reference_url_view or something (I just picked teaser for this example) . Make sure to select One column layout so Display suite will make your custom token field available to you (see screenshot #1)
add the custom token field you added earlier to the visible section
Now go to your other content type view at e.g. admin/structure/types/manage/your_content_type/display/full and select Rendered Entity as the format and choose your previously created view mode of the URL content type (see screenshot #3
Now view your content type and the entity reference fields should show up in the format you defined in your custom Display suite field

Screenshot #1

Screenshot #2

Screenshot #3
Comment: Thanks @undersound, I will give this a go and report back!


Twig invalid render array keys from a valid array

Question: In hook_preprocess_menu I am creating an array to send to the menu twig tpl (eventually it will be entity paragraph data but for now they are hard values as examples). However, I just receive array key invalid errors. How should this be formatted correctly for the template?
function hook_preprocess_menu__main_menu(&$vars) {

  $node = \Drupal::routeMatch()->getParameter('node');
  if($node->field_menu_highlights){
    $highlight_values = $node->get('field_menu_highlights')->getValue();

    foreach ($highlight_values as $key => $item){
      $ent = \Drupal\paragraphs\Entity\Paragraph::load($item['target_id']);
      $vars['highlight'][$key]['title'] = 'Title here';
      $vars['highlight'][$key]['desc'] = 'Description here';

    }
  }
}

The template:
{% for value in highlight %}
    {{ value }}
{% endfor %}

Error eg:
User error: "title" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

Comment: try value.title
Comment: thanks, but the error still persists
Answer: Build the array with renderable children:
  $vars['highlight'][$key] = [
    'title' => [
      '#markup' => 'Title here',
    ],
    'desc' => [
      '#markup' => 'Description here',
    ],
  ];

Now the loop to render each value separately should work or have the same result by rendering the complete render array:
{{ highlight }}


Stretch image to fit in specific div

Question: I have the following div which is containing an image:

And here's the HTML and styles to it:

                                                                                <button title="Close (Esc)" type="button" class="popup-close">×</button>

I want to make the image to be equal size as the div with id

noty_677289985142816800
  Also, i've added
Comment: "noty_677289985142816800 Also, i've added" => also you've added what?
Comment: Inspect (f12, in most browser) and see if the image or the div container has a margin or padding, algo, you need to use width:100% to strecht the image at full size
Comment: Have you tried `object-fit: cover;` on your image?
Answer:

<button title="Close (Esc)" type="button" class="popup-close">×</button>

try this code.
Answer: you can set it as the background image for the above div link below.

                            <button title="Close (Esc)" type="button" class="popup-close">×</button>

css added:
background: url('https://img.alleop.bg/catalog/Banners-Front/Popup-Product-banners/IMG_27082018_165243_0.png');
background-size: 100%;
height: 220px;

Stretch image to fit in specific div


Marca de página atual errada na paginação do Bootstrap4

Question: Estou tentando usar a paginação do bootstrap4 mas a página ativa está vindo errada. Por exemplo, a primeira página vem como página 2. Meu código está assim:

                  <a href="?id=45&pg=<?php echo $num_paginas-1; ?>" aria-label="Anterior">
                    «

                <?php
                for($i=0;$i<$num_paginas;$i++){
                $estilo = "";
                if($pagina == $i)
                    $estilo = "class=\"active\"";
                ?>
                <li <?php echo $estilo; ?> ><a href="?id=45&pg=<?php echo $i; ?>"><?php echo $i+1; ?>

                <?php } ?>

                  <a href="?id=45&pg=<?php echo $num_paginas+1; ?>" aria-label="Próximo">
                    »

Answer: Pelo que entendi a variável $pagina está sendo capturada via GET como sendo a pagina atual, certo?
Supondo que o get está sendo passada como ?id=45&pg=1, para a pagina 1, nesse caso quando $i for 1 ele vai entrar no if
if($pagina == $i)
                    $estilo = "class=\"active\"";

e vai colocar o estilo para sendo pagina ativa, porém, na hora de exibir, $i está recebendo +1, logo, $i+1 = 2.
Ou você pode exibir o $i sem adicionar o valor ou contar o 0 como sendo pagina 1.


Icacls to change only files without full control permission

Question: I have a folder in my inetpub which holds thousands of images automatically copied from a dropbox account every 30 minutes.
In order for my IIS users to access those files, I need to give full control permissions to those files. I have a scheduled task running the following command every ten minutes to ensure proper permissions at all times.
The problem is that it seems to slow down my server when it runs. It's taking longer and longer to run too.
Is there a way to tell icacls to only change the files which don't have full control permissions?
icacls c:\inetpub\wwwroot\production\DigitalImages\*.* /grant builtin\iis_iusrs:f

Answer: First idea: set up icacls action in synchronization clientside hook in dro[box client. But dropbox client hasn't this kind of hooks.
In my opinion the most correct way: once to set up access rights to the root folder and enable rights inheritance.
icacls "c:\inetpub\wwwroot\production\DigitalImages" /grant "builtin\iis_iusrs:f" /inheritance:e

If the inheritance rights is disabled, you may need to reset it once to existing files.
icacls "c:\inetpub\wwwroot\production\DigitalImages\*.*" /q /c /t /reset


Prove that multiplication is well defined

Question:
Let $M = \mathbb{N} \ \mathbb{x} \ \mathbb{N}$. We define the following relation on $M$. Let $(a,b)R(a',b')$ iff $a + b'=a'+b$
  We define the set of intergers $\mathbb{Z}$, to be the set of equivalence classes of $M$ under the equivalence relation above. We try to define the arithmetic operations of addition and multiplication in the following way $$[(a,b)] + [(a',b')] := [(a+a',b+b')]$$ and $$[(a,b)] \cdot [(a',b')] := [(aa'+ bb',a'b+ab')] $$

I should prove that multiplication is well defined. If I understand this correctly i should given that $$(a,b) \sim (c,d) \ i.e \ a+d =c+b$$ and $$(a',b') \sim (c',d') \ i.e \ a'+d'=c'+b'$$ I should prove that $$(ac+bd,cb+ad) \sim (a'c' +b'd',c'b'+a'd')$$ which means that $$ ac+bd+c'b'+b'd' = a'c' +b'd'+cb+ad$$
I dont know how to do this?
Comment: It is probably easiest to prove it in two steps: First, if $(a,b)\sim(a',b')$ then $(a,b)(c,d)\sim(a',b')(c,d)$. Then the same thing to the other side: if $(c,d)\sim(c',d')$ then $(a',b')(c,d)\sim(a',b')(c',d')$. Splitting it up like this will allow you to attack each part with the distributive law.
Comment: Yes, I made a typo.
Comment: In this situation, it probably helps to "cheat": Multiply out $(a - b)(c - d)$ as if you know about integer arithmetic, then interpret the result as an ordered pair of natural numbers. Then use the fact that $(a - b) = (a' - b')$, etc. As long as the end result refers only to pairs of natural numbers, you haven't technically done anything illogical.
Comment: Could you Henning please explain more careful, I am really confused. If $(a,b) \sim (a',b')$ then $(a,b)(a,d) \sim (a',b')(c,d)$ is this multiplicative cancellation law?
Comment: By "well-defined", do you mean it satisfies certain axioms, such as associativity and commutativity, and distributivity over addition? By the way, you're working with [split-complex numbers](https://en.wikipedia.org/wiki/Split-complex_number).
Answer: I'll prove that multiplication is well-defined which is more difficult and leave addition as exercise.
You want to show that
$(a, b)\cdot (c, d) \sim (a', b')\cdot(c', d')$
supposing that
$(a,b) \sim (a', b') \Longleftrightarrow a + b'= b + a', \qquad   (c,d) \sim (c', d') \Longleftrightarrow c+d' = d+c' \quad (\mathbf{1.0})$
i.e. multiplication does not depend on the particular choice of representatives.
We start by showing that $(a,b)\cdot(c,d) \sim (a,b)\cdot(c',d')$ and then use commutativity of the product to show the previous follows.
By expanding the multiplication, it is equivalent to show that $(ac+bd,ad+bc) \sim (ac+bd, ad+bc)$, which by the definition of ~ is the same as showing that
$ac + bd + ad' + bc = ad + bc + ac' + bd' \quad (\mathbf{2.0})$
Multiplying $c+d' = d+c'$ by $a$ in 1.0 yields
$ac + ad' = ad + ac'$
Multiplying $d + c' = c + d'$ by $b$ in 1.0 yields
$bd + bc' = bc + bd'$
Summing up the two equations, you obtain 2.0.
By commutativity of the product (left as exercise to verify), we have also $(a, b)\cdot(c, d) \sim (a, b)\cdot(c', d') = (c', d')\cdot(a, b) \sim (c', d')\cdot(a', b') = (a', b')(c', d')$.
Comment: You write this as though the product were defined two pairs of naturel numbers; it's not, it's defined on two equivalence classes of such pairs. And you seem to have lost either equal or equivalence signs at various stages.
Comment: there were two missing relations, I hope it is ok now


Como retirar cabeçalho da tela em algumas rotas

Question: Bom dia pessoal, no meu projeto angular 4 completei a tela de adm e gostaria que o cabeçalho não aparecesse nela, sei que poderia fazer isso com o ngIf mas estou perdido >_>, Alguém pode dar uma luz?
O app module.html estar assim
<app-navbar></app-navbar>

  <flash-messages></flash-messages>
  <router-outlet></router-outlet>

Answer: Você gostaria de remover o <app-navbar> ou o cabeçalho vem desse <router-outlet>?
Comment: gostaria de remover o
Comment: Realmente a melhor opção nesse caso seria um `*ngIf`. Se você quer simplesmente sumir com ela sem dinamismo, pode colocar ``. Agora se você quer que esse comportamento ocorra sempre que você faça uma ação você terá que em algum método alterar seu valor. Por exemplo, supondo que você tenha o método `(click)="mostrarCabecalho()"`, dentro desse método você deve setar uma outra variável, por exemplo `isCabecalho` que estará como `false` e passará para `true`. Essa variável deverá estar no seu cabeçalho, assim:  ``


transposition while playing

Question: I have sheet music for a song in F major. The original recording of the song is in E so I want to play in that key. All I know is that E is a half step below F. I could just look at all the notes on the sheet music and think that they should be played a semitone lower. What would a professional do?
I was also trying to play the G major minuet (BWV anh. 114) in D major. I did manage to play some measures of the right hand. The first note in the original key is a fifth above the G. And thus I started on A which is a fifth above D.
How would a professional have done?
Do you professionals transpose before playing or while playing?
Comment: I do it while playing. I have experience as a church pianist, and quite often will transpose a piece for the last verse, without it written out. Also when accompanying another instrument I sometimes will transpose it as well, but then again to be fair I am arranging on the fly and am picking out only the melody, bass, and chords, so it is easier than on a note by note basis.
Comment: I occasionally work with a keyboard player who sort of does the opposite. He likes C, and transposes each song so he's in C. He uses the transpose button.
Answer: Many professionals need to be adept at sight transposing.  Accompanists need to be able to change the key to fit singers, and anyone playing a transposing instrument needs to be able to read concert pitch music at the very least.  And anyone who plays in any kind of ensemble with transposing instruments will find it handy to be able to read other people's music at times.
There are a few different strategies.  For a transposition of a half or whole step, it might be easiest to simply "move the note" mechanically as you describe in your first paragraph.  I also personally find it easy to move by a perfect fourth or fifth, partly because the key signature change is easy, but mentally moving by a third or tritone is gross.
The more general strategy is to do a harmonic analysis on the fly, and re-realize the music in the new key.  This isn't as hard as it sounds--you learn to recognize chunks of music instead of individual notes, so you can apply one mental process to an entire phrase.  For example, if I see a scale run, I don't have to analyze every individual note, I can simply play the same scale in the target key.
Finally, in some situations you can use a "clef trick", where pretending that the music is in another clef achieves the desired transposition.  This only really works if something is convenient; it's not any help if the transposition means you have to pretend it's French violin clef or something esoteric like that.  It's rarely usable by keyboard instruments, since you have to find a favorable clef for both hands.  And if there are accidentals it can get weird fast.
Answer: I play trumpet, and have transposed quite a lot, playing Bb parts on a C trumpet, and the contrary. Also older symphonic parts would notate everything in C and just write "in Eb" when the tonality changed to Eb.
I have only used the clef trick described by @MattPutnam, and wanted to add to it for accidentals. He is right that this strategy applies mostly for monophonic instruments, but I guess it's not impossible to use on keyboards.
Know which accidentals are associated with this specific transposition. Keep any other accidental as they are in the original music. For these "transposition accidentals", you need to either raise or lower half a step compared to the original accidental (even natural).
Example:
You want to transpose a tune a fourth up. If the original was in C, you want to play it in F. Find the clef that makes a notated C turn into an F (it's the second C-clef, mezzo-soprano). This means you need to be comfortable reading in other clefs.
The key signature difference between C and F is one added flat. This means that every time you'd play a B according to your new clef, play a Bb. Every time you'd play a Bb, play a Bbb. Everytime you'd play a B#, play a B. You lower the accidental (even natural) of any B.
Another way to look at it is that you change the key signature according to the transposition. Transposing a fourth upwards means adding a flat to the key signature. Assume original tonality of G major, one sharp. Adding a flat to a key signature is the same as removing a sharp, so your "one sharp" key signature of G major becomes "all natural" key signature. Again, the accidentals are unchanged except for all notated F.

F# -> B natural
F natural -> Bb
Fb -> Bbb

(you lower the accidentals whenever you play any kind of B)
Answer: There are several reasons for people to be good in on-the-fly transpositions (not exhaustive):

They play an instrument, which transposes, but frequently like to play pieces without having access to properly transposed scores
They play an instrument, where transposition is a frequent requirement (e. g. French horn)
They are used to it (piano acommpanists, which have to adapt to the vocal range of the singer)

In my opinion, none of these reasons helps you for your decision, and the same holds for the way a considered professional decides.
If are under stress (like in a public performance), you may not be able to concentrate in the same degree as in your exercise room. In that case I would always transpose it first.
Then there are cases, where transposition is really cheap, for example, because the score is already provided in a digital format, which can be transposed by a click of the proper menu option.
In the remaining cases simply try it, so over the time you'll improve in mental transposition.

transposition while playing


Lebesgue measure of $\big\{\frac{1}{n} : n \in \mathbb{N}\big\}$

Question:
What is the Lebesgue measure of $\big\{\frac{1}{n} : n \in \mathbb{N}\big\}$?

Now my intuition would be that this is $0$, since that you can write this set as the union of individual points?
However I am unsure, any clarification would be helpful!
Comment: Note my edit to the question. In proper MathJax usage, the $\{\text{curly braces}\}$ are inside of MathJax, not separate from it. $$ \left\{ \frac 1 n : n\in\mathbb N \right\} $$
Answer: Note that $\{\frac{1}{n}\}$ has a limit point $0$ so if we consider the ball $(-\epsilon,\epsilon)$  for arbitrary $\epsilon >0$ then except finite number of terms of sequence all are inside that and hence ..
Answer: Every set is a union of sets containing only one point, but not every set is a union of only countably many of them. This one is a union of only countably many such sets.
$$
m\left(\left\{ \frac 1 n : n \in \mathbb N \right\} \right) = m\left( \bigcup_{n\,\in\,\mathbb N} \left\{ \frac 1 n \right\} \right) = \sum_{n\,\in\,\mathbb N} m\left( \left\{ \frac 1 n \right\} \right) = \sum_{n\,\in\,\mathbb N} 0 = 0.
$$
Answer: A countable union of null sets has Lebesgue measure $0$.
Comment: Ah I see, yes thank you!
Comment: That's what I thought, so this set is countable? because that may be where my understanding has faltered
Comment: @Geoff: Is ${\mathbb N}$ countable?


Using Google Analytics for android, redirected to firebase?

Question: I'm trying to add Google Analytics(GA) into my android project. But I couldn't find where to generate a google-services.json file. (I did generate it in another project before, but it seems that Google remove the link in guides.)
Comment: as per updated google play service you no need to create google-services.json file.
Comment: you just need to sign up for this google analytics link : https://analytics.google.com/analytics/web/provision/?authuser=0#provision/SignUp/ and you will get the tracking id
Comment: Thanks for your reply, but I'm handling a new project which i didn't get the json file and registered in the website......
Answer: As per developer.android.com blog now google analytics service are deprecated and about to close around 11 April 2019.
And as per their document If you have implemented google analytics then migrate to firebase.
And if you are fresh to implement then try firebase.
That document provide all information about your query.
Steps to implement firebase analytics to your app.

simply implement firebase analytics just click on android studio's Tools menu.
Then select firebase and it show one firebase assistant in your android studio window.
Select firebase analytics option from them and it show the instruction how to implement it.
That's it. It will tack around just 5 minutes.

Hope this will help you
Comment: Okay...Actually, I did find serval links in google analytics link to firebase website. Thank you.
Comment: There's no single word about analytics in that blog post, they deprecate GCM, not GA


Convex Hull vs Convex Polygon and how to calculate it?

Question: I was given some points to calculate the convex hull. So when I try to find that on internet I also saw that a question which has asked what is the difference of convex hull and convex polygon.
According to my knowledge convex hull is the set of points in convex set and polygon is the representation of them in 2D plane. (PLEASE CORRECT ME IF IM WRONG)
However my given points are below and how I tried do calculate convex hull is given below.
Points
$P1=(1,1) , P2=(2,2)$ , $P3=(1.5,3)$ , $P4=(2.5,5)$ , $P5=(3,4)$, $P6=(3,2)$ , $P7=(5,4)$ , $P8=(6,2)$ , $P9=(4,1)$
Tried way
By plotting them in 2D space and going to each point, tried to draw lines to each remaining points and tried to find the internal angle less than 180 while being the largest one among other angles.
Problem
I'm not 100% sure that my method is correct. So if someone can please tell me how to find the convex hull by hand (not with programs) and tell me the difference between convex hull and polygon (if my interpretation is wrong).
Thank you
Answer: The convex hull of a subset $S$ of the plane is the smallest convex set that contains all of them.  If $S$ is finite, this is a convex polygon whose vertices form some subset of $S$.
In your case, the points look like

Start from, say, the highest point $P_4$, which must be one of the vertices of the convex hull (it wouldn't be in the convex hull of lower points).  Think of a line through $P_4$ that starts out horizontal and pivots clockwise.  The first point it hits will be $P_7$, so that's the next point of your polygon.

Draw the line segment $P_4, P_7$.  This will be an edge of your polygon.
Now pivot the line, still clockwise, around $P_7$.  The next point it hits will be $P_8$.

Draw the segment $P_7, P_8$, and continue in this way
until you come back to $P_4$.
And there's your convex hull.
Comment: Thanks alot for images and great clarification. So convex polygon is the representation and hull is the smallest set that has every point in it? Is that right? Also is there any wrong with the way I explained in question? Thank you
Comment: A convex polygon is a polygon that is a convex set.  The convex hull is the smallest **convex** set that has all your points in it.
Answer: Start with a line parallel to the $x$ axis and far enough up so that all the points are below it. Then imagine that line dropping until it touches one (or maybe more) of the points. That will be the "highest" point $P=P4$. Now pivot that line around $P$ until it meets another point, say $Q$. Then $PQ$ is one of the edges of the polygon that is the boundary of the convex hull. Now pivot around $Q$ to find the next point $R$, and so on until you get back to $P$.
If I had time I'd draw the picture. Maybe someone will edit this and to that. In any case you should.
Comment: This is called the [Gift Wrapping Algorithm](https://en.wikipedia.org/wiki/Gift_wrapping_algorithm) in the literature. There's a nice illustration on the page of an algorithm running, but Ethan's method of doing this by hand is just fine. As for the difference between "Convex Hull" and "Convex Polygon": A convex hull is a type of convex polygon, but we usually refer to "hulls" when we work with a set of points and "polygon" when we work with the shape per-se.
Comment: The polygon is the boundary of the convex hull. Both are sets of points in the plane.
Comment: Thank you. Before more questions about that could you please tell me what I described about convex hull and polygon is right or wrong?
Comment: Thanks alot. But can you explain it a little bit more? What does that mean convex hull is a type of convex polygon?
Comment: @LarryB. I didn't think my algorithm was new - now I know it has a name. Thanks. I don't think a convex hull is a type of convex polygon, since the hull includes the interior. A convex polygon together with its interior is a kind of convex set.
Comment: @EthanBolker It sometimes is confusing when I read stuff about polygons, because some authors use the boundary-only definition, while others include the interior. I don't know of any standard across literature regarding polygons, let alone convex hulls. When I use the term convex hull, there's the possibility of a set of points related to the hull that don't all lie on the boundary. With a convex polygon, all the points related to the polygon are on the boundary.


Trying to suppress ggplot2 warning about introducing infinite values in log-transformed axis

Question: I'm trying to suppress a ggplot2 warning about infinite values being introduced with no luck. Here are some dummy data:
DF <- data.frame(X = 1:10, Y = -1:8)
ggplot(DF, aes(x = X, y = Y)) +
   geom_point() + scale_y_log10()

Since I've log transformed the y axis, that's a problem for -1 (NaN) and for 0 (-Inf). I know ggplot2 is trying to be helpful when it warns

Warning messages:
1: In self$trans$transform(x) : NaNs produced
2: Transformation introduced infinite values in continuous y-axis
3: Removed 1 rows containing missing values (geom_point()).

but these graphs are part of a function with multiple graphs, and I don't want multiples of the same warning, especially since other people will use this function and may be confused by it.
How can I suppress this warning?
This does not work:
suppressWarnings(ggplot(DF, aes(x = X, y = Y)) +
   geom_point() + scale_y_log10())

Nor does this:
ggplot(DF, aes(x = X, y = Y)) +
geom_point() + scale_y_log10(oob = scales::oob_censor_any)

And this other question doesn't actually give a good answer for when ggplot is called within a function: how to suppress warning messages from `ggplot2`
Comment: Would you be open to modifying your data before the `ggplot` to avoid warnings? You could just run `DF %>% filter(Y > 0) %>% ggplot(aes(x = X, y = Y)) + geom_point() + scale_y_log10()` -- it won't make any lasting changes to your data and will give you no warnings
Comment: I suppose that *is* a possible workaround. Hmm... Good, straightforward way to address this!
Comment: Ah, yes, I remembered when I went to implement this that I had added a spot in my function where I've *intentionally* set an x value to -Inf because I'm plotting with geom_rect and I want the left edge of the rectangle to be right at the y axis. This won't solve that problem.
Answer: You might consider my favorite scale transformation, which is mostly log but smoothly converts to a linear scale for the range near zero (within +/- sigma). This allows it to gracefully accept and display zeros and negative numbers, while still keeping a log appearance for larger values.
ggplot(DF, aes(x = X, y = Y)) +
  geom_point() +
  # scale_y_log10()
  scale_y_continuous(trans = scales::pseudo_log_trans(sigma = 0.01),
                     breaks = c(-1, -0.1, 0, 0.1, 1, 10), minor_breaks = NULL)

Comment: Oh, interesting! I hadn't been aware of scales::pseudo_log_trans! I'll see if that will work.
Comment: Actually, hold up: This changes the visual distance between the intervals at the lower end of the scale. That won't work. I need the distance between, e.g., 0.1 and 1 to be the same as the distance between 1 and 10. That's the whole reason for log transforming that axis in the first place. Sorry! I didn't notice this at first!
Comment: Updated with adjustment to make the space from 0.1 to 1 match the space from 1 to 10. The tricky part here is how you want to treat 0 to 0.1. With sigma at 0.01, the space from 0 to 0.1 is about (exactly?) the same as the 10x changes beyond that range.


Continuous monitoring of KMeans model post production

Question: In the process of deploying a KMeans model for a customer segmentation use case into production. KMeans doesn't produce the same results every time and after production cluster sizes and arrangements are bound to change.
What are some considerations to take into account after deploying a KMeans model into production and what metrics do you monitor?
Anyone have any experience with this/have any recourses to share?
Comment: See modified answer - to some extent your OP is an open-ended question, since you didn't report the variation in results as a function of feature transformation, cluster initiation method, distance metric used, or cluster validity method used.  As usual, the answer is: "It depends."
Answer: Firstly, whenever the training data change you will experience "concept drift," where the model prediction changes with the input data.  Secondly, are you performing cluster validity analysis to determine the optimal number of clusters for your benchmark dataset?
An example cluster validity run output is shown below, and you can see that cluster validity based on Canberra and Chebychev distance metrics indicate that the bend in the "knee" occurs at about k=3 clusters.  If you're not first establishing the optimal number of clusters from a consensus benchmark training dataset from your cloud/server farm, then your K-means assessment can be all over the map.

As far as monitoring, I would periodically determine the optimal number of clusters and track the value of the silhouette distance, which gives an overall picture for how well the model clusters the data.  Lastly, there are a lot of methodologic issues which affect deployment outcomes related to your question, such as feature transformations employed, cluster (prototype) initiation method, distance metric employed, and cluster validity method used.
FYI - K-means is one of the worst clustering methods that can reveal the cluster separation of objects for datasets with known class separation.
Comment: Yes - I plotted the elbow curve and got that number at 5 clusters.


References for Lagrangian and Hamiltonian mechanics

Question: What are good references for learning about Lagrangian and Hamiltonian mechanics, for someone with a mathematical background?
Mathematically I'm learning and working on holomorphically symplectic manifolds/projective varieties, and I would like to understand the physical background, which is classical mechanics. Can anyone suggest a reference for learning mechanics, which a mathematician might enjoy?
Comment: Arnold - Mathematical Methods of Classical Mechanics
Comment: You may like to look at the (lengthy) classic by Abraham and Marsden; it covers Lagrangian (quite briefly) and Hamiltonian mechanics (in much more detail), symmetries using Lie groups and so on. Another book you could look at is J.M. Souriau's Structure of Dynamical Systems. Lastly a *very* rapid treatment can be found in George Mackey's Mathematical Foundations of Quantum Mechanics; this is either a hit or a miss. I found it's like Spivak's Calculus on Manifolds: short, old, but to the point (usually), and I also despised it at times :)
Answer: For Hamiltonian Mechanics there are actually quite a few books from the mathematical point of view. I personally really like

G. Rudolph, M. Schmidt: Differential Geometry and Mathematical Physics. Part I. Manifolds, Lie Groups and Hamiltonian Systems, Springer, 2013.

This books also contains a lot of background material from differential and symplectic geometry. Furthermore, you might be interested in

T. Lee, M. Leok and H. McClamroch: Global Formulations of Lagrangian and Hamiltonian Dynamics on Manifolds, A Geometric Approach to Modeling and Analysis, Springer, 2018.

Last but not least, you might have a look at

A. Knauf: Mathematical Physics: Classical Mechanics, Springer, 2018.

This book is not only for Lagrangian and Hamiltonian mechanics, but also contains many other topics of classical mechanics in a mathematical precise language.
There are of course also much more books on this topic out there, for example also the classical book by V. Arnold mentioned in the comments. The books above a just books, which I personally really like and which seem to be not so well known compared to other more classical references.


Proving equivalence of natural deduction and Hilbert systems for classical logic

Question: I was reading this question which asks how to prove equivalence of natural deduction and Hilbert systems in the sense:

For all formulas, $M$, $\hspace{0.3cm} \Gamma \vdash_{H} M$ iff $\Gamma  \vdash_N M$ is derivable, where $\Gamma$ is finite and $M$ contains at most one formula.

That question deals with intuitionistic logic. I had a similar question about classical logic. The answer there describes a proof strategy involving deriving each system's axioms and rules in the other. Wouldn't it be easier to just use soundness and completeness:
If $\Gamma \vdash_H \varphi$, then $\Gamma \models \varphi$ by soundness of the Hilbert system $H$. By completeness of the natural deduction system $N$, we have $\Gamma \vdash_N \varphi$. The reverse direction can be proven likewise.
This should be possible since the meaning of $\models$ does not rely on the deduction system. Moreover, it would work for any logic where both soundness and completeness are available, like classical and intuitionistic logic. Am I missing something? Why is the long winded approach in the other answer better?
Comment: Two different strategies: the "syntactical" one gives you a procedure that converts a derivation in $H$ into a derivation in $N$ and vice versa. The "semantical" one does not give us that info and in addition needs the preliminary proof of the two **S & C Theorems**. It depends on the point in the development of the basic tiopics of ML where the equivalence has to be proved...
Comment: @MauroALLEGRANZA Thanks, that answers the question.
Answer: Sure, if you already have soundness and completeness theorems, you're happy with using them, and you primarily care just about the brute fact that the derivability relations are equivalent, then the approach you suggest works fine. Now let's see why each of these assumptions might not hold.
Obviously, the first problem is that you may not have proven soundness or completeness yet, and, in general, you may not even have a completeness result. Regardless, proving completeness is likely to be more involved than directly proving the equivalence of the derivability relations.
One philosophical issue with using soundness and completeness is that it means going through a semantics. Typically semantics is formulated in a much more powerful language than the languages you're talking about, usually set theory. A direct proof, on the other hand, is basically just a matter of replacing parts of a proof with fragments of proofs in the other language. This can be done in very weak frameworks (e.g. primitive recursive arithmetic (PRA)). Using semantics is then looks like pulling out a sledgehammer to crack a nut. More precise delineation of the requirements of theorems is also useful for reasons unrelated to philosophy. At a more pragmatic level a direct proof can be done without needing to even introduce any of the machinery of semantics. It's certainly not worth introducing semantics just for this.
Finally, a direct proof will almost certainly be constructive and informative as it will e.g. involve proving the deduction theorem explicitly. That is, not only will you know that a proof can be translated, you'll know what the translation looks like. Now, it's not hard to find proofs of the completeness theorems that are constructive, i.e. that will (if you unfold enough) produce an actual proof. In that case, the route through soundness and completeness will produce an actual explicit translation. It will, however, be terrible. All structure of the original proof that is being "translated" will be obliterated. The completeness theorem has no way of knowing about the original proof; it will output the same proof no matter what you started with. And those proofs are likely to be ugly to boot. For example, the proof of completeness (of just propositional logic) might do a case analysis over all variable assignments as the first proof here does. This means all produced proofs are exponentially large relative to the number of propositional variables.


How to format HTML with CSS for column layout

Question: I'm trying to do some simple HTML and CSS to get a page to layout something like the image below, but I'm way out of my element and not even sure how to get it started. Right now, my biggest problem is I can't get the Client Birth Date, and Spouse First Name to appear on its own line. I feel like I could add divs, but then I'd probably have divs everywhere (I'm assuming that's a bad thing.)
Here's a JSFiddle of what I have started.

  Name
  <input type="text" id="WebName" />

  Email
  <input type="text" id="WebEmail" />

  Phone
  <input type="text" id="WebPhone" />

    Client First Name*
    <input type="text" id="ClientFirstName" />

    Client Birth Date
    <input type="text" id="ClientBirthDate" />

    Client Last Name*
    <input type="text" id="ClientLastName" />
    Client Age
    <input type="text" id="ClientAge" />

  Appointment Date
  <input type="text" id="AppointmentDate" />
  Goals
  <textarea id="Goals" rows="4" cols="80">
                </textarea>

Answer: I would add divs in those specific cases. Form elements can be messy when it comes to layout. I've found that wrapping a label + input inside a div is the best practice here. And since you've already done that in the first section you might as well follow the pattern.

 Some Text
 <input type="text" name="thisInputName" value="" placeholder="What displays />

You could technically also wrap everything in the label instead of a div. This has some pros and cons mostly in that it makes everything clickable and adds focus. It's especially good for checkboxes and radio buttons as the hit area is bigger.

 Your label text
 <input type="text" name="thisInputName" value="" placeholder="What displays />


What are some reasons not to alter js prototypes?

Question: I use certain algorithms so often that I am considering adding them to prototypes in my app. For example, the last value in an array. array.last() is so convenient compared to writing arr[arr.length -1] every time I want the last value in the array.
I would do this when my app first loads.
Object.defineProperty(Array.prototype, 'last', {
   value: function(){return this[this.length -1]} })

Are there functional reasons not to do this?
Comment: What happens when the next library you load *also* wants to add a helper function called "last" to Arrays and their function signature doesn't match your own?
Comment: It is fine to add it if you do it in an application and not a library, also do it like polyfills, first check if `array.prototype.last` exists, then add it if it doesn't. If another library that you depend on is overriding core functionality, then you should probably not use it, unless the library literally focused on overriding certain parts, because it cam create side effects for other libraries as well as your application.
Comment: @Pavlo Until some future ES standard specifies a native `Array.prototype.last` and libraries that you want to use begin to depend on it. And no, you should *not* check if it exists, you should always install your own version as that's the functionality your code will expect.
Answer: Yes, there are reasons to not do this, one that immediately jumps out is that you will inevitably collide with another library that also thinks it is easier to adjust built-in prototypes.
Consider the following:
// my-cool-library.js

// Returns the last value in an array
Array.prototype.last = function() {
    return this[this.length - 1];
}

// some-other-cool-library.js

// Returns the last possible index of the array
Array.prototype.last = function() {
    return this.length - 1;
}

// some-consumer.js

import "my-cool-library.js";
import "some-other-cool-library.js";

const a = ["a", "b", "c"];

// You would probably expect it to print "c", but it prints 2
console.log(a.last());

You might think that this is unlikely, but what if you utilize really big frameworks?  Let's say you use both Angular and lodash.  It isn't all the unlikely that a huge framework like Angular would want to make life easier by adding some helper functions to certain Object prototypes.  However, lodash is a very broad scoped library that also adds helper functions for just about every operation you might want to perform on a collection.
It is very likely that both of those libraries would want to use the same, terse helper function names but might not have the same function signature.  Suddenly it becomes non-apparent how you should call and use Array.prototype.last.
Instead, it is more appreciated when you leverage dependency injection and write functions that take all the arguments needed to perform the calculation and don't pollute the prototype.  In that way, you get to decide exactly which last function is used and when.
You can potentially also leverage the benefits of tree shaking.
Consider the non-polluting example:
// my-cool-library.js

// Returns the last value in an array
export function last(arr) {
    return arr[arr.length - 1];
}

// some-other-cool-library.js

// Returns the last possible index of the array
export function last(arr) {
    return arr.length - 1;
}

// some-consumer.js

import {last as myLast} from "my-cool-library.js";
import {last} from "some-other-cool-library.js";

const a = ["a", "b", "c"];

// You know that you're going to use myLast
// and how it is going to act
console.log(myLast(a));

Comment: Not sure why anyone would downvote this. But since everyone knows you shouldn't mutate the prototype, "you will inevitably collide with another library" isn't necessarily true. Which means it's ok to do now... right? /s


Multiple Counts On Same Row With Conditions

Question: I am trying to calculate a summarised view of the data in my table, at the moment the query works but it isn't very efficient seeing as my table will eventually hold 10,000 + contracts.  I also need to filter each by the same date, I realise I could do this in the where statement for each count but this isn't very efficient.
Also the final calculation at the end would be much easier if I could operate on fields rather than selects.
<code>(SELECT COUNT (*) FROM Contracts WHERE contractWon = 1) Won,
(SELECT COUNT (*) FROM Contracts WHERE contractPassedToCS = 1) PassedtoCS,
(SELECT COUNT (*) FROM Contracts WHERE contractPassedToCS = 0) as OutstandingWithSales,
(SELECT COUNT (*) FROM Contracts WHERE contractIssued = 1) as ContractsIssued,
(SELECT COUNT (*) FROM Contracts WHERE contractReturned = 1) as ContractsReturned,
(CONVERT(decimal, (SELECT COUNT (*) FROM Contracts WHERE contractReturned = 1)) /         CONVERT(decimal, (SELECT COUNT (*) FROM Contracts WHERE contractIssued = 1))) * 100 as '% Outstanding'
</code>
I understand there is probably some joining needed but I'm a little confused.
Thanks.
Answer: <code>SELECT
    SUM(contractWon) AS Won,
    SUM(contractPassedToCS ) AS PassedtoCS,
    SUM(1-contractPassedToCS) AS OutstandingWithSales,
    SUM(contractIssued) AS contractIssued ,
    SUM(contractReturned) AS contractReturned,
    100.0 * SUM(contractReturned) / SUM(contractIssued) AS '% Outstanding'
FROM
    Mytable
</code>
Alternate formulations for "bit" datatypes which can not be aggregated. If the columns are int, say, then the above query works
<code>    --Either CAST first to a type that aggregates...
    SUM(CAST(contractWon AS int)) AS Won,

    -- .. or rely on COUNT ignores NULL values
    COUNT(CASE contractWon WHEN 1 THEN 1 ELSE NULL END) AS Won,
</code>
Comment: Wrap each of those in a SUM() and I'll +1 it :-)
Comment: I will +1 one if you comment on your (albeit fair) assumption that the columns are booleans represented by 1/0, (which the OP did not state).
Comment: Apologies, they were all indeed booleans.


How to set up a two-way mixed ANOVA with a covariate  in SPSS?

Question: I wanted to carry out a two-way ANCOVA for my data. However, SPSS isn't liking that I have only one IV.
I have

One IV: Group (3 levels, i.e. 2 experimental groups and a control group),
One DV: outcome measure (2 levels, i.e. time 1 and time 2),
One covariate (I have checked and this demographic continuous variable moderately correlates with the DV).

Please could someone help as to whether I am missing something in terms of putting this into SPSS?
Comment: you sound strange. "Two way" ANOVA or ANCOVA needs 2 independent categorical vars ("factors") by definition. Your data is one-way ANCOVA. Next, because your predictant is only 2 levels (fixed, I assume) you'd better go to Binary Logistic regression procedure instead of GLM.
Comment: @ttnphns Assuming "you sound strange" means "let me correct you on some points" and "predictant" means "dependent variable," I agree with what you're saying.
Comment: I think the confusion here is a matter of language. "Time" is your second IV. The DV does not have two levels. "Time" has two levels. Your DV, I am assuming, is metric.
Answer: I am guessing that you have your data in wide format.
This seems to be causing you confusion because in wide format it is less obvious that "time" is your second independent variable.
One option in SPSS for doing what it sounds like you want to do:

Analyze -- GLM -- Repeated Measures
Enter time as repeated measures factor with two levels
Enter Group as a between subjects factor
Enter the dependent variable (presumably represented as two variables in SPSS as your two times points)
Enter your covariate in the covariate box

For more information, see Andy Field's SPSS Repeated Measures tutorial.
However, given that repeated measures ANOVA already controls for individual differences in some respect, you may want to think about the meaning of including a time-invariant covariate in such a model. See here for a discussion of the issues related to covariates in repeated measures ANOVA.
Answer: Set it up as a regular regression, they are mathematically equivalent, just make sure your non-continuous variables are defined appropriately (as categorical or whatever) to SPSS.
Comment: this question was dramatically altered after this answer was made


Weak-*-Topology and sequences

Question: Let $X$ be a Banach Space , $x\in X$ and $(x^{*}_{n})_{n\in\mathbb{N}}$ a sequence in $X'$ with
a weak-$*$-clusterpoint $x^{*}$. Does this imply that $x^{*}(x)$ is a clusterpoint of $(x^{*}_{n}(x))_{n\in\mathbb{N}}$ (which is a sequence in $\mathbb{R}$)?
I have difficulties with this topology beacause i don't know which norm or metric i have to use (if there is any). How does a neighbourhood in the weak-*-topology look like?
Answer: Weak* topology is neither normable nor metrizable. A basic neighborhood of $x^{*}$ is of the form $\{y^{*}: |y^{*}(x_i)-x^{*}(x_i)|<r_i \forall i \in \{1,2,...,N\}\}$ for some integer $N$, some positive numbers $r_i$ and some vectors $x_1,x_2,..,x_n \in X$. To answer your question take a neighborhod with $N=1$ and $x_1=x$.
Comment: thank you very much!

Weak-*-Topology and sequences


Performance testing on host intrusion prevention system

Question: I need some help here. In my current project we are replacing a Host Intrusion Prevention Software (HIPS) and I need to do performance testing on its server. Wondering if you can throw some light on what type of performance testing can be done on the server and also what kind of comparison test I can do wrt perf test for already existing HIPS server?
Answer: It depends on what you are trying to achieve, actually. Are you guys developing a Host Intrusion Prevention Software or just replacing an existing one for another from other vendor or version?
As your topic says you want to do performance testing, I will ignore all the functional testing and security testing you could do.
One thing I think you can measure is the resource consumption by the HIPS, you could compare with the previous version to know if it will need a more robust host than you actually have or if it will have some performance impact over the other applications running in the same host.


Como renderizar um array utilizando o React?

Question: Eu estou desenvolvendo um app simples utilizando o ReactJS e estou tentando utilizar um [filter()] para renderizar os resultados de um array utilizando um campo de busca. Mas quando eu utilizo o [map()] funciona perfeitamente, porque os resultados do [filter()] aparecem no console.log() mas não na minha pagina HTML ?
app.js
import React , { useState, useEffect } from 'react';

import List from './components/list';

const App = () => {

  const [name, setName] = useState('');
  const [age, setAge] = useState('');

  return (
    <>
      <form>
        <input type="text" className="names" onChange = { e =>  setName( e.target.value ) }  />
        <input type="text" className="ages" onChange = { e =>  setAge( e.target.value ) }  />
      </form>
      {/* My User List */}

        <List data = { { name, age } } />

    </>
  );
}

export default App;

components/list.jsx
import React, { useState, useEffect } from 'react';

const List = ({ data }) => {

    // The states
    const [filtro, setFiltro] = useState([]);

    // All registers
    let cadastros = [
        { id: 0, name: "David", age: '20' },
        { id: 1, name: "Bob", age: '20' },
        { id: 2, name: "Bob", age: '10' },
        { id: 3, name: "Bob", age: '20' },
        { id: 4, name: "Chris", age: '10' },
    ];

// const result = cadastros.map( user => user.name );
const result = cadastros.filter( user => user.name === data.name );

console.log( result );

return
 { result.name }
;

}

// Export component
export default List;

Answer: O ponto ai é que o retorno do seu filter também é um array, para exibir em tela você precisa percorrer esse array e retornar o JSX.
const results = cadastros.filter( user => user.name === data.name );

return results.map(result =>
 { result.name }
);

Comment: Verdade, faz sentido. Obrigado


Having an issue getting ANYTHING to apply styles within nested DIVs

Question: I've already asked Google about this, and I've spent quite a long time experimenting. I can't possibly recreate the entire HTML and CSS environment this is occurring in, but this is part of it:

#footer-copyright{
    clear:both;
    color:black !important;
    font-size: 12px !important;
    text-align:center !important;
}

            <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section One')) : endif; ?>

            <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section Two')) : endif; ?>

This text is immune to formatting

No matter what I've tried, the text "This text is immune to formatting" is displayed in the p style for the footer object. I've tried making the CSS ID more specific (footer.footer-copyright). I've tried putting the ID on the DIV, and then specifying the style is for "#footer-copyright p{". I've tried footer-copyright as a class style and as a style for that particular ID (as it is now). I don't want to bore you listing all the things I've tried, but think permutations and combinations.
I've spent quite a bit of time in Chrome inspecting the paragraph, and it mostly seems to have no style at all, or to take the style defined by #footer p.
The only thing that I've found works is to completely override the CSS and put the style info into the paragraph itself ("

If you can, please explain why I can't seem to override the parent object's CSS style, and how to use Chrome's reporting of the HTML hierarchy to understand how to specify the CSS style.
THANKS!
Comment: https://jsfiddle.net/5z8xznj7/ seems to work fine.
Comment: You need to provide an example the demonstrates the problem. I applaud your attempt at brevity here but it does not show the actual problem. Try and expand your example to actually show the problem. Doing this one step at a time on your end may actually show you where the problem lies. Without more info we are guessing.
Comment: OK, perhaps in an isolated environment, the CSS works as designed. In the actual site, it just f'ing doesn't, and that's what I'm trying to understand. The site's in Beta (not released), so I have uploaded the "ideal" footer.php, just as in the pseudo-code above, but in this site, the text is WHITE and the wrong size, and ... Here's the URL to the site: http://dothemostgood.staging.wpengine.com.
Comment: On the real site, the only rule that matches that element is `#footer p { color: #fff }`. The HTML tag doesn't have the id `footer-copyright`. it's just a plain `` tag and the rule doesn't apply.
Answer: It does work in the snippet which uses your code (see below)
If you need a more specific selector, you can use this one:
footer#footer > div.container > p#footer-copyright { ... }

This takes into account all tags, classes and IDs you included in your code.
(I added a background color to the rule to verify it)

footer#footer > div.container > p#footer-copyright {
  clear: both;
  color: black !important;
  font-size: 12px !important;
  text-align: center !important;
  background: #fa0;
}

      <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section One')) : endif; ?>

      <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer Section Two')) : endif; ?>

This text is actually NOT immune to formatting

Comment: I might give that a try. Can you explain how this relates to what I see in Chrome? The Chrome CSS hierarchy shows html body footer#footer.fullwidth div.container p.
Comment: That's even more specific, using every element, class and ID that's there for this particular filepath. `html body` are simply the parent elements of `footer`, `footer#footer.fullwidth` adds the class which is assigned to `footer` in addition to the ID which is already assigned to it. The one thing it *doesn't`add (I don't know why) is the ID of `p`, i.e. `footer-copyright` which I added in the selector. Anyway, both selectors are extremely specific. If there isn't any other selector which deliberately  tries to be even more specific, both should work.
Comment: Interestingly (if this weren't driving me crazy, that is), this works on Edge on Windows 10, and does not work in Chrome.
Answer: In your sample above you have this....

This text is actually NOT immune to formatting

In your ACTUAL page you have this...

Copyright © 2017 - Do The Most Good, Montgomery County, MD

The element (the P tag) in the ACTUAL page is being rendered/styled using these statements...
#footer p
{
  color:#fff;
}

When, what you want is for it to be styled with this style...
#footer-copyright p
{
  clear:both;
  color:black !important;
  font-size: 12px !important;
 text-align:center !important;
}

So all you need is for your code to be thus....

Copyright © 2017 - Do The Most Good, Montgomery County, MD

It is simply a case of, that the footer-copyright element (the P tag) was not assigned the style because the ID tag was not set.
Comment: Please see the actual website at http://dothemostgood.staging.wpengine.com. There you will see that it does not work. The text is white, and large, rather then black and small. Why is that? If I attach a specific ID to that paragraph, or DIV, or a SPAN, and then set a style for that ID, why is it ignored? I would REALLY like to know. BTW, since you're not in my head I should tell you that the text is the copyright message at the very bottom of every page.  Oh, and I did try setting the paragraph class (instead of the ID) and defining the style using a period. That does not work either!
Answer: I am looking at the HTML on the page you sent, versus the code you posted.
The declaration dictating the style is:
#footer p{
    color:#fff;
}

Actually, the following code is not running at all:
#footer-copyright p{
    clear:both;
    color:black !important;
    font-size:12px !important;
    text-align:center !important;
}

You can see that there is no #footer-copyright in your code.
You can run the following in your console:
$('#footer-copyright p').length;
$('#footer p').length;

#footer-copyright returns a length of zero.
Comment: Thanks! That should be helpful.


25 people form some committees following a bunch of rules

Question: (Yufei Zhao) Twenty-five people form some committees with each committee has 5 members and each pair of committees have at most one common member. Determine, with justification, the maximum number of committees.
My approach: Let $m$ be the maximum number of committees. If there are more than 7 committees, then the number of duplicates is at most $\frac{m(m-1)}{2}$ but then I'm stuck. I'm guessing the answer is 10.
Am I right? Am I on the right track? Can you give me a hint if I'm not?
Answer: Each committee has $\binom{5}2=10$ pairs of people. No two committees contain the same pair of people. Since there are only $\binom{25}2=300$ pairs total, there can be at most $300/10=30$ committees.
This can be accomplished using the affine plane of order $5$. Identify the people with the set of order pairs $(x,y)$ for $x,y\in \mathbb Z/\mathbb 5\mathbb Z$. The committees are the set of "lines" over $\mathbb Z/\mathbb 5\mathbb Z$, where there $25$ lines of the form $L_{m,b}=\{(x,mx+b)\mid x\in \mathbb Z/\mathbb 5\mathbb Z\}$, where $m,b\in \mathbb Z/\mathbb 5\mathbb Z$, and $5$ vertical lines of the form $V_x=\{(x,y)\mid y\in \mathbb Z/\mathbb 5\mathbb Z\}$ for $x\in \mathbb Z/\mathbb 5\mathbb Z$.
Comment: Thank you so much! That is some great insight!


Restrict User Type to buy a Product Type in Drupal Commerce

Question: I am selling membership type without using subscription module as it doesn't fit into my scenario. I am assiging role by help of rules as per Randy screencast & it works nice for me.
Now the problem is with renewal of the membership. So I have to set up another kind of product type, which will work for renewing the membership.
So is there any way to restrict usertype to buy any product type ?
Thanks :)
Answer: You can create a different product display type (i.e. content type) for the renewal product (at admin/structure/types). Then you can restrict that content type to those with the members role (in admin/people/permissions).
Or, if you want to show the product display type, but restrict the actual purchase, I think you have to resort to custom code like this:
<code><?php
/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Alter the Commerce 'Add to Cart' form.
 */
function custom_module_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
  global $user;
  $roles_allowed_to_buy = array(
    'Some Custom Member Role',
    'administrator',
  );
  if (!array_intersect($user->roles, $roles_allowed_to_buy)) {
    // Display a help message.
    $form['help'] = array(
      '#markup' => t('You do not have permission to buy this product.'),
    );
    // Disable the whole form.
    $form['#disabled'] = TRUE;
    // Remove any submit button(s).
    unset($form['submit']);
  }
}
</code>
(that's an example you would put inside a module called custom_module)


Generate installed modules into a composer.json for existing site: I need to manage via Composer, not via UI

Question: I have a Drupal 8 site up and running with modules that were manually installed. I want to generate an appropriate composer.json file to manage these using Composer.
The closest I could find to achieve this is an old Drupal 7 module, Composer Generate, mentioned in how to install package via composer? but that only works with Drupal 7 and it isn't any longer developed.
How to move Composer created folder of drupal-8.x.x up one level to html? suggests that third-party modules can/should be handled with Composer, but I would like to not have to manually rewrite the composer.json file to achieve this.
Is there a Drupal 8 / Composer / Drush way to accomplish this, or is manually updating the composer.json the only option?
Comment: yes - thank you @kiamlaluno! apparently that was exactly what I was looking for! you should set that as the answer ==> https://www.drupal.org/project/composerize
Comment: By drupal console drupal composerize https://drupalconsole.com/docs/en/commands/composerize
Answer: Composer Generate is a Drush extension. It can be used either with Drupal 7 or Drupal 8. Considering that the latest release available on drupal.org is dated Febrary 25, 2016, it's probable it is not compatible with the Drush version you would be use on your site.
The project page for Composer Generate suggests using the Composerize module, which is available for Drupal 8.

This module can generate a composer.json from your installed Drupal code base, which can be used to regenerate that code base by running composer install.

Be careful of the warning reported in the project page.

This module is still in development. It supports very basic Drupal 8 setups, but there are many necessary features it still lacks (e.g., support for patches, JavaScript libraries, distributions, etc). We're working on all that stuff, but this module is definitely not ready for prime time.

The module is supported by Acquia, and the development version has been updated on March 20, 2018.
Alternatively, as the project page suggests, you could use Composerize Drupal, a Composer plugin for converting a non-Composer-managed Drupal site to a Composer-managed Drupal site.
Comment: thank you again @kiamlaluno - exactly what I was looking for!


Homomorphism of matrix groups is determined by its differential

Question: May I use some help on how to prove the Ex 7.15 in page 111 from "Matrix groups for undergraduate, 1st" by Tapp ?

Let $G_1$ and $G_2$ be matrix groups with Lie algebras $g_1$ and $g_2$ respectively. Let $f:G_1\rightarrow G_2$ be a $C^1$ homomorphism. Denote the differential of $f$ at unit element $I$ by $df_I:g_1\rightarrow g_2$. Prove that for all $v\in g_1$,
  $$f(e^v)=e^{df_I(v)}.$$

I attempted to expand the exponential on both sides using the formula

$e^v = I+v+1/2v^2+1/6v^3 +...$

and got

$f(v)=df_I(v)$

which I have no clue to prove.
Any tips ?
Comment: There are many ways to define the exponential map and the differential of a function and how you answer this question is gonna depend on which of those definitions you are using.  I don't have access to Tapp's book, can you say what your definitions are?
Comment: @Jim Thanks for interest. The matrix exponential is defined as I wrote in the post. The differential is defined as in manifold, which is a linear map from a tangent space to another tangent space.
Answer: If $v\in g_1$ then $t\mapsto e^{tv}$ is a Lie group homomorphism
from $\Bbb R$ (under addition) to $G_1$, and all Lie group
homomorphisms from $\Bbb R$ to $G_1$ are of this form. Take the
composition with this with $f$ and we get the a Lie group homomorphism
from $\Bbb R$ to $G_2$. It must equal $t\mapsto e^{tw}$ for some $w\in G_2$.
But considering the derivative ay zero gives us $w=df(v)$. Thus
$$f(e^{tv})=e^{t df(v)}.$$
Now take $t=1$.
Comment: Thanks ! I got it. And there is typo at the third line to last. It should be **at zero**.


Cheerio get class properties

Question: How can I get css property for selector?
having html

and some properties for my_class
.my_class {
  color: red
}

in JS code I'm using cheerio lib:
var content = cheerio.load(html_content_page);
var selector = "a.my_class";

So, how can I get color property using above selector?
Comment: Ok, answer on similar question from maintainers: https://github.com/cheeriojs/cheerio/issues/357#issuecomment-31659300
Answer: Try this:
$('.my_class').css('color')

Comment: Possible duplicate of http://stackoverflow.com/questions/20377835/how-to-get-css-class-property-in-javascript
Comment: Guys, thank for fast reply, it doesn't work for me because  I'm using 'cheerio' lib rather than 'jquery', so it seems to me that this lib can only parse css properties enclosed in 'style' tag within html, but in my case they are in separated css file.
Answer: Javascript, you can use getComputedStyle() for inline styling or rules declared in stylesheet
Snippet below

var a=document.getElementsByTagName('a')[0]
console.log(getComputedStyle(a).color);
console.log(getComputedStyle(a).backgroundColor);
.my_class {
  color: red
}

Comment: I think that I couldn't pass Cheerio object into getComputedStyle function?!
Comment: I'm using cheerio lib for parsing html page (from arbitrary site), so this page keeps css rules in separated file
I've found desired answer there: https://github.com/cheeriojs/cheerio/issues/357#issuecomment-31659300

Cheerio get class properties