问:
Python argparse - Add mandatory arguments with condition
hi i want to add the following arguments:

```<code>parser = argparse.ArgumentParser()
parser.add_argument('-n','--name', required=True)
parser.add_argument("-sd", "--start_date", dest="start_date",
                        type=valid_date,
                        help="Date in the format yyyy-mm-dd")
parser.add_argument("-ed", "--end_date", dest="end_date",
                        type=valid_date,
                        help="Date in the format yyyy-mm-dd")
</code>```

i want that in case the name='test1' then start_date and end_date will be mandatory.
can it be done with arparse? or do i need some validation method to enforce it to be mandatory?

thanks

答:
You can check the condition and then check if the other arguments are both provided. </p>

```<code>import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-n','--name', required=True)
parser.add_argument("-sd", "--start_date", dest="start_date",
                        help="Date in the format yyyy-mm-dd")
parser.add_argument("-ed", "--end_date", dest="end_date",
                        help="Date in the format yyyy-mm-dd")

args = parser.parse_args()

if args.name == "test1":
    if args.start_date is None or args.end_date is None:
        parser.error('Requiring start and end date if test1 is provided')
</code>```

Body:
hi i want to add the following arguments:

parser = argparse.ArgumentParser()
parser.add_argument('-n','--name', required=True)
parser.add_argument("-sd", "--start_date", dest="start_date",
                        type=valid_date,
                        help="Date in the format yyyy-mm-dd")
parser.add_argument("-ed", "--end_date", dest="end_date",
                        type=valid_date,
                        help="Date in the format yyyy-mm-dd")

i want that in case the name='test1' then start_date and end_date will be mandatory.
can it be done with arparse? or do i need some validation method to enforce it to be mandatory?

thanks

Body:
You can check the condition and then check if the other arguments are both provided.

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-n','--name', required=True)
parser.add_argument("-sd", "--start_date", dest="start_date",
                        help="Date in the format yyyy-mm-dd")
parser.add_argument("-ed", "--end_date", dest="end_date",
                        help="Date in the format yyyy-mm-dd")

args = parser.parse_args()

if args.name == "test1":
    if args.start_date is None or args.end_date is None:
        parser.error('Requiring start and end date if test1 is provided')


来源: stackexchange

问:
syntax error, unexpected '?>' in Laravel View: D:..\WEB3\WEB\Pics\resources\views\home.blade.php
It looks like I have a little problem with which I can't find the solution. The only thing that I am finding on the net is that the problem can be from the PHP version if it's under 7.0, but mine is 7.4.5
This is the code in the home.blade.php file

```<code>@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">

        @if(count(#errors) -> 0)
                    @foreach(#errors->all() as $error)
                        <div class="alert alert-danger">{{$error}}
                        </div>
                    @endforeach
                @endif

                @if(session('response'))
                <div class="alert alert-success">
                {{session('response')}}
                </div>

            <div class="card">
                <div class="card-header">Dashboard</div>

                <div class="card-body">
                    @if (session('status'))
                        <div class="alert alert-success" role="alert">
                            {{ session('status') }}
                        </div>
                    @endif

                   <div class="col-md-4">
                   <img src="" alt="" />
                   </div>
                   <div class="col-md-4"></div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
</code>```

it gives me the mistake on the line with:

```<code> @if(count(#errors) -> 0)
</code>```

Do you have some suggestions on how can I fix it?

答:
You have not closed 'if condition' in a particular portion

Your Code :

```<code> @if(session('response'))
      <div class="alert alert-success">
            {{session('response')}}
      </div>
</code>```

This must be,

```<code>@if(session('response'))
     <div class="alert alert-success">
     {{session('response')}}
     </div>
@endif
</code>```

Note : syntax error, unexpected '?>' in Laravel View. This kind of errors occur If you have not closed 'if condition' properly.

ContentLicense: CC BY-SA 4.0

Body:
It looks like I have a little problem with which I can't find the solution. The only thing that I am finding on the net is that the problem can be from the PHP version if it's under 7.0, but mine is 7.4.5
This is the code in the home.blade.php file

@extends('layouts.app')

@section('content')

        @if(count(#errors) -> 0)
                    @foreach(#errors->all() as $error)

{{$error}}

                    @endforeach
                @endif

                @if(session('response'))

                {{session('response')}}

Dashboard

                    @if (session('status'))

                            {{ session('status') }}

                    @endif

@endsection

it gives me the mistake on the line with:

 @if(count(#errors) -> 0)

Do you have some suggestions on how can I fix it?

Body:
You have not closed 'if condition' in a particular portion

Your Code :

 @if(session('response'))
      <div class="alert alert-success">
            {{session('response')}}
      </div>

This must be,

@if(session('response'))
     <div class="alert alert-success">
     {{session('response')}}
     </div>
@endif

Note : syntax error, unexpected '?>' in Laravel View. This kind of errors occur If you have not closed 'if condition' properly.


问:
Fragment Does Not Appear In Android
I recently learned about Fragments in Android and was building a notepad application to practice them.

Idea: The idea behind the app is simple. I press the button to add a new note. A CardView Viewgroup turns visible. The fragment will be housed within this CardView.

Problem: When I press the button to add a new note, the fragment does not pop up.

MainActivity.java

```<code>import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.Objects;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private CardView fragmentCardView;
    private Button newNoteButton;
    private FragmentManager fragmentManager = getSupportFragmentManager();
    private FragmentTransaction fragmentTransaction;

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

        newNoteButton = findViewById(R.id.new_note_button);
        fragmentCardView = findViewById(R.id.fragment_cardView);
    }

    void setActionBar(){
        Objects.requireNonNull(getSupportActionBar()).setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.layout_custom_action_bar);
    }

    void showCreateNoteFragment(){
        CreateNoteFragment createNoteFragment = CreateNoteFragment.newInstance();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.fragment_cardView, createNoteFragment);
        fragmentTransaction.commit();
        fragmentCardView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        if (v == newNoteButton)
            showCreateNoteFragment();
    }
}
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F2F2F2"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/notes_listView"
        android:layout_width="match_parent"
        android:layout_height="667dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <Button
        android:id="@+id/new_note_button"
        android:layout_width="350dp"
        android:layout_height="50dp"
        android:layout_marginTop="27dp"
        android:fontFamily="@font/nunito_bold"
        android:text="@string/new_note_button_string"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/notes_listView"/>

    <androidx.cardview.widget.CardView
        android:id="@+id/fragment_cardView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="100dp"
        android:layout_marginBottom="100dp"
        android:layout_marginStart="25dp"
        android:layout_marginEnd="25dp"
        android:visibility="invisible"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

CreateNoteFragment.java

```<code>package com.example.notepadapplication;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class CreateNoteFragment extends Fragment implements View.OnClickListener {

    private EditText inputEditText;

    public CreateNoteFragment() {
        // Required empty public constructor
    }

    static CreateNoteFragment newInstance(){
        return new CreateNoteFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_create_note, container, false);
        inputEditText = rootView.findViewById(R.id.input_editText);
        Button saveButton = rootView.findViewById(R.id.save_button);
        saveButton.setOnClickListener(this);
        return rootView;
    }

    @Override
    public void onClick(View v) {
        String saveButtonText = inputEditText.getText().toString();
    }
}
</code>```

fragment_create_note.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_marginTop="100dp"
    android:layout_marginBottom="100dp"
    android:layout_marginStart="25dp"
    android:layout_marginEnd="25dp"
    android:background="#F2F2F2"
    tools:context=".CreateNoteFragment">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/header_textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:text="@string/display_fragment_header_string"
            android:layout_marginTop="10dp"
            android:textAlignment="center"
            android:textSize="20sp"
            android:fontFamily="@font/nunito_bold"/>

        <View
            android:id="@+id/divider_view"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="5dp"
            android:layout_marginStart="15dp"
            android:layout_marginEnd="15dp"
            android:layout_below="@id/header_textView"
            android:background="#000000" />

        <EditText
            android:id="@+id/input_editText"
            android:layout_width="match_parent"
            android:layout_height="475dp"
            android:layout_below="@id/divider_view"
            android:layout_alignParentStart="true"
            android:layout_alignParentEnd="true"
            android:layout_marginTop="20dp"
            android:layout_marginStart="5dp"
            android:layout_marginEnd="5dp"
            android:padding="10dp"
            android:inputType="textMultiLine"
            android:gravity="top"
            android:background="#FFFFFF"
            tools:ignore="Autofill,LabelFor,TextFields" />

        <Button
            android:id="@+id/save_button"
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="10dp"
            android:text="@string/save_button_string"
            android:fontFamily="@font/nunito_bold"/>

    </RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Could anyone check why the fragment isn't popping up? Thanks for the help, guys.

P.S.: I think that the application might become a little bloated because of all the ViewGroups that I'm using. If you guys have a better way to design this, by all means, I would love any input.

答:
When I press the button to add a new note, the fragment does not pop up.

This is expected since your button doesn't know what to do when pressed.

```<code>    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setActionBar();

        newNoteButton = findViewById(R.id.new_note_button);
        // Button will call activity's onClick whenever it's clicked
        newNoteButton.setOnClickListener(this);
        fragmentCardView = findViewById(R.id.fragment_cardView);
    }
</code>```

Title: Fragment Does Not Appear In Android

Body:
I recently learned about Fragments in Android and was building a notepad application to practice them.

Idea: The idea behind the app is simple. I press the button to add a new note. A CardView Viewgroup turns visible. The fragment will be housed within this CardView.

Problem: When I press the button to add a new note, the fragment does not pop up.

MainActivity.java

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.util.Objects;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private CardView fragmentCardView;
    private Button newNoteButton;
    private FragmentManager fragmentManager = getSupportFragmentManager();
    private FragmentTransaction fragmentTransaction;

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

        newNoteButton = findViewById(R.id.new_note_button);
        fragmentCardView = findViewById(R.id.fragment_cardView);
    }

    void setActionBar(){
        Objects.requireNonNull(getSupportActionBar()).setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.layout_custom_action_bar);
    }

    void showCreateNoteFragment(){
        CreateNoteFragment createNoteFragment = CreateNoteFragment.newInstance();
        fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.fragment_cardView, createNoteFragment);
        fragmentTransaction.commit();
        fragmentCardView.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        if (v == newNoteButton)
            showCreateNoteFragment();
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#F2F2F2"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/notes_listView"
        android:layout_width="match_parent"
        android:layout_height="667dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

    <Button
        android:id="@+id/new_note_button"
        android:layout_width="350dp"
        android:layout_height="50dp"
        android:layout_marginTop="27dp"
        android:fontFamily="@font/nunito_bold"
        android:text="@string/new_note_button_string"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/notes_listView"/>

    <androidx.cardview.widget.CardView
        android:id="@+id/fragment_cardView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="100dp"
        android:layout_marginBottom="100dp"
        android:layout_marginStart="25dp"
        android:layout_marginEnd="25dp"
        android:visibility="invisible"/>

</androidx.constraintlayout.widget.ConstraintLayout>

CreateNoteFragment.java

package com.example.notepadapplication;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

public class CreateNoteFragment extends Fragment implements View.OnClickListener {

    private EditText inputEditText;

    public CreateNoteFragment() {
        // Required empty public constructor
    }

    static CreateNoteFragment newInstance(){
        return new CreateNoteFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_create_note, container, false);
        inputEditText = rootView.findViewById(R.id.input_editText);
        Button saveButton = rootView.findViewById(R.id.save_button);
        saveButton.setOnClickListener(this);
        return rootView;
    }

    @Override
    public void onClick(View v) {
        String saveButtonText = inputEditText.getText().toString();
    }
}

fragment_create_note.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_marginTop="100dp"
    android:layout_marginBottom="100dp"
    android:layout_marginStart="25dp"
    android:layout_marginEnd="25dp"
    android:background="#F2F2F2"
    tools:context=".CreateNoteFragment">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/header_textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:text="@string/display_fragment_header_string"
            android:layout_marginTop="10dp"
            android:textAlignment="center"
            android:textSize="20sp"
            android:fontFamily="@font/nunito_bold"/>

        <View
            android:id="@+id/divider_view"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="5dp"
            android:layout_marginStart="15dp"
            android:layout_marginEnd="15dp"
            android:layout_below="@id/header_textView"
            android:background="#000000" />

        <EditText
            android:id="@+id/input_editText"
            android:layout_width="match_parent"
            android:layout_height="475dp"
            android:layout_below="@id/divider_view"
            android:layout_alignParentStart="true"
            android:layout_alignParentEnd="true"
            android:layout_marginTop="20dp"
            android:layout_marginStart="5dp"
            android:layout_marginEnd="5dp"
            android:padding="10dp"
            android:inputType="textMultiLine"
            android:gravity="top"
            android:background="#FFFFFF"
            tools:ignore="Autofill,LabelFor,TextFields" />

        <Button
            android:id="@+id/save_button"
            android:layout_width="250dp"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="10dp"
            android:text="@string/save_button_string"
            android:fontFamily="@font/nunito_bold"/>

    </RelativeLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Could anyone check why the fragment isn't popping up? Thanks for the help, guys.

P.S.: I think that the application might become a little bloated because of all the ViewGroups that I'm using. If you guys have a better way to design this, by all means, I would love any input.

Body:
When I press the button to add a new note, the fragment does not pop up.

This is expected since your button doesn't know what to do when pressed.

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

        newNoteButton = findViewById(R.id.new_note_button);
        // Button will call activity's onClick whenever it's clicked
        newNoteButton.setOnClickListener(this);
        fragmentCardView = findViewById(R.id.fragment_cardView);
    }


问:
GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'
I'm setting up a C++ project, on Ubuntu x64, using Eclipse-CDT.  I'm basically doing a hello world and linking to a commerical 3rd party library.

I've included the header files, linked to their libraries, but I still get linker errors.  Are there some possible problems here other than the obvious (e.g. I am 99% sure I'm linking to the correct library).

Is there a way to confirm the static libraries I am linking to are 64bit?

Is there a way to confirm that the library has the class (and methods) I am expecting it to have?

Eclipse says:

```
Building target: LinkProblem
Invoking: GCC C++ Linker
g++ -L/home/notroot/workspace/somelib-3/somelib/target/bin -o"LinkProblem"  ./src/LinkProblem.o   -lsomelib1 -lpthread -lsomelib2 -lsomelib3
./src/LinkProblem.o: In function `main':
/home/notroot/workspace/LinkProblem/Debug/../src/LinkProblem.cpp:17: undefined reference to `SomeClass::close()'
./src/LinkProblem.o: In function `SomeOtherClass':
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:148: undefined reference to `SomeClass::SomeClass()'
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:148: undefined reference to `vtable for SomeOtherClass'
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:151: undefined reference to `SomeClass::~SomeClass()'
./src/LinkProblem.o: In function `~SomeOtherClass':
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:140: undefined reference to `vtable for SomeOtherClass'
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:140: undefined reference to `SomeClass::~SomeClass()'
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:140: undefined reference to `SomeClass::~SomeClass()'
collect2: ld returned 1 exit status
make: *** [LinkProblem] Error 1
```

答:
In regards to problems with Qt4, I couldn't use the qmake moc option mentioned above. But that wasn't the problem anyway. I had the following code in the class definition:

```<code>class ScreenWidget : public QGLWidget
{
   Q_OBJECT        // must include this if you use Qt signals/slots
...
};
</code>```

I had to remove the line "Q_OBJECT" because I had no signals or slots defined.

ContentLicense: CC BY-SA 2.5

Body:
I'm setting up a C++ project, on Ubuntu x64, using Eclipse-CDT.  I'm basically doing a hello world and linking to a commerical 3rd party library.

I've included the header files, linked to their libraries, but I still get linker errors.  Are there some possible problems here other than the obvious (e.g. I am 99% sure I'm linking to the correct library).

Is there a way to confirm the static libraries I am linking to are 64bit?

Is there a way to confirm that the library has the class (and methods) I am expecting it to have?

Eclipse says:

Building target: LinkProblem
Invoking: GCC C++ Linker
g++ -L/home/notroot/workspace/somelib-3/somelib/target/bin -o"LinkProblem"  ./src/LinkProblem.o   -lsomelib1 -lpthread -lsomelib2 -lsomelib3
./src/LinkProblem.o: In function `main':
/home/notroot/workspace/LinkProblem/Debug/../src/LinkProblem.cpp:17: undefined reference to `SomeClass::close()'
./src/LinkProblem.o: In function `SomeOtherClass':
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:148: undefined reference to `SomeClass::SomeClass()'
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:148: undefined reference to `vtable for SomeOtherClass'
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:151: undefined reference to `SomeClass::~SomeClass()'
./src/LinkProblem.o: In function `~SomeOtherClass':
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:140: undefined reference to `vtable for SomeOtherClass'
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:140: undefined reference to `SomeClass::~SomeClass()'
/home/notroot/workspace/somelib-3/somelib/include/sql/somefile.h:140: undefined reference to `SomeClass::~SomeClass()'
collect2: ld returned 1 exit status
make: *** [LinkProblem] Error 1

Body:
In regards to problems with Qt4, I couldn't use the qmake moc option mentioned above. But that wasn't the problem anyway. I had the following code in the class definition:

class ScreenWidget : public QGLWidget
{
   Q_OBJECT        // must include this if you use Qt signals/slots
...
};

I had to remove the line "Q_OBJECT" because I had no signals or slots defined.

ContentLicense: CC BY-SA 3.0


问:
I'm getting an error when I open my WordPress site
Here is the error:

Warning: require(/home/****/public_html/wp-includes/load.php): failed to open stream: No such file or directory in /home/growfi5/public_html/wp-settings.php on line 21

Fatal error: require(): Failed opening required '/home/****/public_html/wp-includes/load.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/*****/public_html/wp-settings.php on line 21

line 21 says

```<code>require( ABSPATH . WPINC . '/load.php' )
</code>```

答:
I know this was asked and solved about 5 years ago but this solution might help somebody else...

I had the same issue on a Wordpress installed via SSH Terminal.  My problem in this case was the folders owner and permissions.  Make sure you install using the right user group.  In my case I had to change from the root user and root group to the current account user and group by typing:

chown -R youraccountuser:youraccountgroup ./

Then also make sure all your folders and files have the right permissions set.  For me it was:

```<code>find /path/to/your/wordpress/install/ -type d -exec chmod 755 {} \;
find /path/to/your/wordpress/install/ -type f -exec chmod 644 {} \;
</code>```

Body:
Here is the error:

Warning: require(/home/****/public_html/wp-includes/load.php): failed to open stream: No such file or directory in /home/growfi5/public_html/wp-settings.php on line 21

Fatal error: require(): Failed opening required '/home/****/public_html/wp-includes/load.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/*****/public_html/wp-settings.php on line 21

line 21 says

require( ABSPATH . WPINC . '/load.php' )

Body:
I know this was asked and solved about 5 years ago but this solution might help somebody else...

I had the same issue on a Wordpress installed via SSH Terminal.  My problem in this case was the folders owner and permissions.  Make sure you install using the right user group.  In my case I had to change from the root user and root group to the current account user and group by typing:

chown -R youraccountuser:youraccountgroup ./

Then also make sure all your folders and files have the right permissions set.  For me it was:

find /path/to/your/wordpress/install/ -type d -exec chmod 755 {} \;
find /path/to/your/wordpress/install/ -type f -exec chmod 644 {} \;


问:
How to use std::valarray in if statement without redundant computation?
I have the following code with float, for example:

```<code>std::vector<float> v = {0.f, 1.f, 2.f};
for(size_t i = 0; i < v.size(); ++i)
    if(v[i] != 0) // An optimization for `v[i] != 0`.
        v[i] = v[i] * v[i] * v[i]; // Time-consuming computation.
</code>```

Now I want to replace float with std::valarray<float>:

```<code>using vfloat = std::valarray<float>;
std::vector<vfloat> v = {vfloat{0.f, 0.f}, vfloat{1.f, 0.f}, vfloat{2.f, 0.f}};
for(size_t i = 0; i < v.size(); ++i)
    // if(v[i] != 0) // I want this optimization! ◀◀◀◄◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀
        v[i] = v[i] * v[i] * v[i]; // Time-consuming computation.
</code>```

Though the new code is correct logically, there are redundant computation for v[i][j] == 0.

So how to use std::valarray in if statement without the redundant computation?

答:
If you want to skip elemets in v[i] use a nested loop

```<code>using vfloat = std::valarray<float>;
std::vector<vfloat> v = {vfloat{0.f, 0.f}, vfloat{1.f, 0.f}, vfloat{2.f, 0.f}};
for(size_t i = 0; i < v.size(); ++i)
    for(size_t j = 0; j < v[i].size(); ++j)
        if (v[i][j] != 0)
            v[i][j] = v[i][j] * v[i][j] * v[i][j]; // Time-consuming computation.
</code>```

or apply:

```<code>using vfloat = std::valarray<float>;
std::vector<vfloat> v = {vfloat{0.f, 0.f}, vfloat{1.f, 0.f}, vfloat{2.f, 0.f}};
for(size_t i = 0; i < v.size(); ++i)
    v[i] = v[i].apply([](float n) -> float {
        if (n == 0) return 0;
        return n * n * n; // Time-consuming computation.
    });
</code>```

If you want to skip elements in v

```<code>using vfloat = std::valarray<float>;
std::vector<vfloat> v = {vfloat{0.f, 0.f}, vfloat{1.f, 0.f}, vfloat{2.f, 0.f}};
for(size_t i = 0; i < v.size(); ++i)
    if ((v[i] != 0).max() != 0)
        v[i] = v[i] * v[i] * v[i]; // Time-consuming computation.
</code>```

Body:
I have the following code with float, for example:

std::vector<float> v = {0.f, 1.f, 2.f};
for(size_t i = 0; i < v.size(); ++i)
    if(v[i] != 0) // An optimization for `v[i] != 0`.
        v[i] = v[i] * v[i] * v[i]; // Time-consuming computation.

Now I want to replace float with std::valarray<float>:

using vfloat = std::valarray<float>;
std::vector<vfloat> v = {vfloat{0.f, 0.f}, vfloat{1.f, 0.f}, vfloat{2.f, 0.f}};
for(size_t i = 0; i < v.size(); ++i)
    // if(v[i] != 0) // I want this optimization! ◀◀◀◄◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀◀
        v[i] = v[i] * v[i] * v[i]; // Time-consuming computation.

Though the new code is correct logically, there are redundant computation for v[i][j] == 0.

So how to use std::valarray in if statement without the redundant computation?

Body:
If you want to skip elemets in v[i] use a nested loop

using vfloat = std::valarray<float>;
std::vector<vfloat> v = {vfloat{0.f, 0.f}, vfloat{1.f, 0.f}, vfloat{2.f, 0.f}};
for(size_t i = 0; i < v.size(); ++i)
    for(size_t j = 0; j < v[i].size(); ++j)
        if (v[i][j] != 0)
            v[i][j] = v[i][j] * v[i][j] * v[i][j]; // Time-consuming computation.

or apply:

using vfloat = std::valarray<float>;
std::vector<vfloat> v = {vfloat{0.f, 0.f}, vfloat{1.f, 0.f}, vfloat{2.f, 0.f}};
for(size_t i = 0; i < v.size(); ++i)
    v[i] = v[i].apply([](float n) -> float {
        if (n == 0) return 0;
        return n * n * n; // Time-consuming computation.
    });

If you want to skip elements in v

using vfloat = std::valarray<float>;
std::vector<vfloat> v = {vfloat{0.f, 0.f}, vfloat{1.f, 0.f}, vfloat{2.f, 0.f}};
for(size_t i = 0; i < v.size(); ++i)
    if ((v[i] != 0).max() != 0)
        v[i] = v[i] * v[i] * v[i]; // Time-consuming computation.


问:
RESOLVED sleep methods hang the program threads in C pthreads (race condition, it had nothing to do with sleep)
I created a C program with pthreads, and it works perfectly until I add any sort of sleep function, whether it's be  sleep() or usleep() or  nanosleep().

Yes, before you ask, I know usleep() is deprecated and I have copied the correct usage of nanosleep() from another stackoferflow post, but even sleep() doesn't work.

The code (the critical section is in the "clients" thread, at line 99):

```<code>#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <time.h>

#define LIBERA 0
#define OCCUPATA 1
#define TUTTE_SEDIE_OCCUPATE -1
#define OCCUPATA_DA_BARBIERE -2

#define NRCLIENTI 10
#define NRSEDIE 5

pthread_mutex_t poltrona_m, dorme_m, get_sedia_m, occupa_sedia_m;
sem_t sem;
int sedia_taglio = LIBERA, sedia_attesa[NRSEDIE];

void init_attr(void) {
    int i;
    for (i = 0; i < NRSEDIE; i++)
        sedia_attesa[i] = LIBERA;
    sem_init(&sem, 0, NRSEDIE);
    pthread_mutex_unlock(&poltrona_m);
    pthread_mutex_unlock(&dorme_m);
    pthread_mutex_unlock(&get_sedia_m);
    pthread_mutex_unlock(&occupa_sedia_m);
}

int my_sleep(long millis) {
    struct timespec req, rem;

    if (millis > 999) {
        req.tv_sec = (int) (millis / 1000);
        req.tv_nsec = (millis - ((long) req.tv_sec * 1000)) * 1000000;
    } else {
        req.tv_sec = 0;
        req.tv_nsec = millis * 1000000;
    }

    return nanosleep(&req, &rem);
}

int get_sedia_libera() {
    pthread_mutex_lock(&get_sedia_m);
    int i;
    for (i = 0; i < NRSEDIE; i++)
        if (sedia_attesa[i] == LIBERA)
            return i;
    pthread_mutex_unlock(&get_sedia_m);
    return TUTTE_SEDIE_OCCUPATE;
}

int occupa_sedia(int index) {
    pthread_mutex_lock(&occupa_sedia_m);
    int result;
    if(sedia_attesa[index] == LIBERA){
        sedia_attesa[index] = OCCUPATA;
        result = 1;
    }else
        result = 0;
    pthread_mutex_unlock(&occupa_sedia_m);
    return result;
}

void libera_sedia(int index) {
    sedia_attesa[index] = LIBERA;
}

void *barbiere(void *arg) {
    while (1)
    {
        if (sedia_taglio == OCCUPATA) {
            pthread_mutex_lock(&poltrona_m);
            sedia_taglio = LIBERA;
            pthread_mutex_unlock(&poltrona_m);
        }

        if (get_sedia_libera() == 0 && sedia_taglio == LIBERA) {
            sedia_taglio = OCCUPATA_DA_BARBIERE;
            pthread_mutex_lock(&dorme_m);
            printf("[BARBIERE] il barbiere dorme...\n");
        }
    }
}

void *cliente(void *arg) {
    int n;
    int *id = (void *)arg;

    while (1)
    {
        if (sedia_taglio == LIBERA || sedia_taglio == OCCUPATA_DA_BARBIERE) {

            pthread_mutex_lock(&poltrona_m);
            pthread_mutex_unlock(&dorme_m);
            sedia_taglio = OCCUPATA;
            printf("----[CLIENTE] Cliente \"%d\" si taglia i capelli!\n", *id);
            my_sleep(2000);
            sedia_taglio = LIBERA;
            pthread_mutex_unlock(&poltrona_m);
            pthread_exit(0);

        } else {
            n = get_sedia_libera();
            if(n == TUTTE_SEDIE_OCCUPATE) {
                fprintf(stderr, "----[CLIENTE] No posti liberi cliente \"%d\" lascia il negozio\n", *id);
                pthread_exit((void *)1);
            } else {
                sem_wait(&sem);
                n = get_sedia_libera();
                if(occupa_sedia(n) && n != TUTTE_SEDIE_OCCUPATE){
                    printf("----[CLIENTE] Cliente \"%d\" aspetta su sedia #%d\n", *id, n+1);
                    while (sedia_taglio != LIBERA);
                    sem_post(&sem);
                    libera_sedia(n);
                } else {
                    sem_post(&sem);
                    fprintf(stderr, "----[CLIENTE] No posti liberi cliente \"%d\" lascia il negozio\n", *id);
                    pthread_exit(0);
                }
            }
        }

    }
}

int main(int argc, char **argv) {

    init_attr();

    int i, id[NRCLIENTI];
    pthread_t barbiere_thread, cliente_thread[NRCLIENTI];

    if(pthread_create(&barbiere_thread, NULL, barbiere, NULL ) < 0){
        fprintf(stderr, "[MAIN] Error creating \"barber\" thread!\n");
        exit(EXIT_FAILURE);
    }
    printf("[MAIN] thread \"barber\" creato\n\n");

    for (i = 0; i < NRCLIENTI; ++i) {
        id[i] = i+1;
        printf("[MAIN] thread \"client %d\" creato\n", id[i]);
        if(pthread_create(&cliente_thread[i], NULL, cliente, &id[i]) < 0){
            fprintf(stderr, "[MAIN] Error creating \"client %d\" thread!\n", id[i]);
            exit(EXIT_FAILURE);
        }
    }

    for (i = 0; i < NRCLIENTI; i++){
        pthread_join(cliente_thread[i], NULL);
        printf("[MAIN]Joined client \"%d\"\n", i+1);
    }

    //il programma non finira mai se sta ad aspettare un thread con un ciclo while(1) al suo interno
    //senza condizioni di break!!!
    pthread_join(barbiere_thread, NULL);

    return 0;
}
</code>```

Normal execution(this is how the program should work):

```<code>[MAIN] thread "client 1" creato
[BARBIERE] il barbiere dorme...
hey
[MAIN] thread "client 2" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "1" si taglia i capelli!
[MAIN] thread "client 3" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "2" si taglia i capelli!
[MAIN] thread "client 4" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "3" si taglia i capelli!
[MAIN] thread "client 5" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "4" si taglia i capelli!
[MAIN] thread "client 6" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "5" si taglia i capelli!
[MAIN] thread "client 7" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "6" si taglia i capelli!
[MAIN] thread "client 8" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "7" si taglia i capelli!
[MAIN] thread "client 9" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "8" si taglia i capelli!
[MAIN] thread "client 10" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "9" si taglia i capelli!
----<<<<<<<<<<<<[CLIENTE] Cliente "10" si taglia i capelli!
[MAIN]Joined client "1"
[MAIN]Joined client "2"
[MAIN]Joined client "3"
[MAIN]Joined client "4"
[MAIN]Joined client "5"
[MAIN]Joined client "6"
[MAIN]Joined client "7"
[MAIN]Joined client "8"
[MAIN]Joined client "9"
[MAIN]Joined client "10"
</code>```

Execution with any sleep method, sleep(1), nanosleep() with 1 second or 100k microsecond usleep()
but I don't take usleep() into consideration because a) *its deprecated and * b) you cant put more or equal than 1million microseconds; usleep(1000000) is NOT valid

```<code>[MAIN] thread "client 1" creato
[BARBIERE] il barbiere dorme...
[MAIN] thread "client 2" creato
----[CLIENTE] Cliente "1" si taglia i capelli!
[MAIN] thread "client 3" creato
[MAIN] thread "client 4" creato
[MAIN] thread "client 5" creato
[MAIN] thread "client 6" creato
[MAIN] thread "client 7" creato
[MAIN] thread "client 8" creato
[MAIN] thread "client 9" creato
[MAIN] thread "client 10" creato
[MAIN]Joined client "1"
</code>```

As you can see, the threads just... stall. I waited with the terminal open for 5 minutes, and still, nothing changed.
The strangest thing is that if I run this in windows IntelliJ Clion using MinGW, the sleep() functions seem totally ignored (the program executes itself in a fraction of a second)!

Thanks for reading through all of this, I hope we can find a solution and I'd be grateful for any help I get!

答:
You creates deadlock because you have race condition between threads.

Moving pthread_mutex_t poltrona_m, dorme_m, get_sedia_m, occupa_sedia_m;
 at global scope, adding these verbose functions:

```<code>const char * whoIam()
{
  if (pthread_self() == barbiere_thread)
    return "barbiere";

  for (int i = 0; i != NRCLIENTI; ++i) {
    if (pthread_self() == cliente_thread[i]) {
      static char str[NRCLIENTI][64];

      sprintf(str[i], "cliente %d", i+1); /* done several times but whatever */
      return str[i];
    }
  }

  return "unknown-thread";
}

const char * whoIsMutex(pthread_mutex_t * m)
{
  if (m == &poltrona_m)
    return "poltrona";
  if (m == &dorme_m)
    return "dorme";
  if (m == &get_sedia_m)
    return "sedia";
  if (m == &occupa_sedia_m)
    return "occupa_sedia";
  return "unknown-mutex";
}

void my_pthread_mutex_unlock(pthread_mutex_t * m)
{
  printf("%s unlock %s\n", whoIam(), whoIsMutex(m));
  pthread_mutex_unlock(m);
}

void my_pthread_mutex_lock(pthread_mutex_t * m)
{
  printf("%s want to lock %s\n", whoIam(), whoIsMutex(m));
  pthread_mutex_lock(m);
  printf("%s locked %s\n", whoIam(), whoIsMutex(m));
}
</code>```

and using my_pthread_mutex_lock and my_pthread_mutex_unlock out of init_attr the execution can be :

```<code>[MAIN] thread "barber" creato

[MAIN] thread "client 1" creato
barbiere want to lock sedia
barbiere locked sedia
barbiere want to lock dorme
barbiere locked dorme
cliente 1 want to lock poltrona
cliente 1 locked poltrona
cliente 1 unlock dorme           <<< does nothing because does not have it
----[CLIENTE] Cliente "1" si taglia i capelli!
[BARBIERE] il barbiere dorme...
barbiere want to lock poltrona   <<< wait while get by client 1
[MAIN] thread "client 2" creato
[MAIN] thread "client 3" creato
[MAIN] thread "client 4" creato
cliente 2 want to lock sedia
[MAIN] thread "client 5" creato
cliente 4 want to lock sedia
[MAIN] thread "client 6" creato
cliente 3 want to lock sedia
[MAIN] thread "client 7" creato
cliente 6 want to lock sedia
cliente 5 want to lock sedia
[MAIN] thread "client 8" creato
cliente 7 want to lock sedia
[MAIN] thread "client 9" creato
cliente 8 want to lock sedia
[MAIN] thread "client 10" creato
cliente 9 want to lock sedia
cliente 10 want to lock sedia
cliente 1 unlock poltrona     <<< finally unlock poltrona
barbiere locked poltrona      <<< wake up
barbiere unlock poltrona
barbiere want to lock sedia   <<< dead because get by itself
[MAIN]Joined client "1"
</code>```

Adding my_sleep(1000); before sedia_taglio = occupata; in cliente helps to not have the race condition :

```<code>bruno@bruno-XPS-8300:/tmp$ gcc -Wall t.c -lpthread
bruno@bruno-XPS-8300:/tmp$ ./a.out
[MAIN] thread "barber" creato

[MAIN] thread "client 1" creato
[BARBIERE] il barbiere dorme...
[MAIN] thread "client 2" creato
[MAIN] thread "client 3" creato
[MAIN] thread "client 4" creato
[MAIN] thread "client 5" creato
[MAIN] thread "client 6" creato
[MAIN] thread "client 7" creato
[MAIN] thread "client 8" creato
[MAIN] thread "client 9" creato
[MAIN] thread "client 10" creato
----[CLIENTE] Cliente "1" si taglia i capelli!
[MAIN]Joined client "1"
----[CLIENTE] Cliente "3" si taglia i capelli!
----[CLIENTE] Cliente "2" si taglia i capelli!
[MAIN]Joined client "2"
[MAIN]Joined client "3"
----[CLIENTE] Cliente "4" si taglia i capelli!
[MAIN]Joined client "4"
----[CLIENTE] Cliente "5" si taglia i capelli!
[MAIN]Joined client "5"
----[CLIENTE] Cliente "6" si taglia i capelli!
[MAIN]Joined client "6"
----[CLIENTE] Cliente "7" si taglia i capelli!
[MAIN]Joined client "7"
----[CLIENTE] Cliente "8" si taglia i capelli!
[MAIN]Joined client "8"
----[CLIENTE] Cliente "9" si taglia i capelli!
[MAIN]Joined client "9"
----[CLIENTE] Cliente "10" si taglia i capelli!
[MAIN]Joined client "10"
</code>```

Out of that, about the way to sleep, the function sleep blocks all the process, contrarily to usleep and nanosleep.

Here a proposal without race condition, nor making assumption on the mutex implementation (no undefined behavior).

There is only one mutex to protect datas consistency and for the conditions, I also use it to protect printing.

There are seats to wait, and one used to cut hairs. To manage clients in order of arrival they get a ticket having a number, when there is no free seat at all a client cannot get a ticket and will retry later. The number of the ticket of the client to have hairs cut is given by CurrentTicket (as a screen client read) and the signal NextClient is produced (as a beep) to allow clients to check if their turn comes. The number of the ticket in the distributor is managed by LastTicket. The signal HelloBarber is sent by a client when he reaches the barber and may be wake up him. The barber sleeps when there is no client.

I use a random time limited to 5 seconds for the delay used by a client to (re)try to get a place, and the barber cut hairs of a client in a random time limited to 3 seconds.

```<code>#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>

#define NCLIENT 10
#define NSEAT 5 /* seats to wait */

unsigned int Seed;
int Nseat = NSEAT  + 1; /* add 1 to have seat to cut hairs */
int CurrentTicket = 0;
int LastTicket = 0;

pthread_mutex_t Mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t NextClient = PTHREAD_COND_INITIALIZER;
pthread_cond_t HelloBarber = PTHREAD_COND_INITIALIZER;

/* return -1 is no seat, else ticket number */
int getTicket()
{
  int result;

  pthread_mutex_lock(&Mutex);
  if (Nseat == 0)
    result = -1;
  else {
    Nseat -= 1;
    result = ++LastTicket;
  }
  pthread_mutex_unlock(&Mutex);

  return result;
}

void randomSleep(int max)
{
  int millis = rand_r(&Seed) % (max * 1000);
  struct timespec req, rem;

  if (millis > 999) {
    req.tv_sec = (int) (millis / 1000);
    req.tv_nsec = (millis - ((long) req.tv_sec * 1000)) * 1000000;
  } else {
    req.tv_sec = 0;
    req.tv_nsec = millis * 1000000;
  }

  nanosleep(&req, &rem);
}

void * client(void * arg)
{
  int id = *((int *) arg);
  int ticket;
  int justArrived = 1;

  while (randomSleep(5), ((ticket = getTicket()) == -1)) {
    pthread_mutex_lock(&Mutex);
    printf("----[CLIENT] Client \"%d\" no place, will try again later\n", id);
    pthread_mutex_unlock(&Mutex);
  }

  pthread_mutex_lock(&Mutex);
  printf("----[CLIENT] Client \"%d\" got ticket number %d\n", id, ticket);

  while (ticket != CurrentTicket) {
    printf("----[CLIENT] Client \"%d\" not my turn\n", id);
    if (justArrived) {
      justArrived = 0;
      printf("----[CLIENT] Client \"%d\" seat to wait\n", id);
    }
    pthread_cond_wait(&NextClient, &Mutex);
  }
  printf("----[CLIENT] Client \"%d\" my turn\n", id);
  if (justArrived)
    printf("----[CLIENT] Client \"%d\" do not need to seat to wait\n", id);

  pthread_cond_signal(&HelloBarber);

  pthread_cond_wait(&NextClient, &Mutex);
  printf("----[CLIENT] Client \"%d\" done for me\n", id);
  pthread_mutex_unlock(&Mutex);

  return NULL;
}

void * barber(void * dummy)
{
  pthread_mutex_lock(&Mutex);

  puts("[BARBER] ready");
  CurrentTicket = 1;
  pthread_cond_signal(&NextClient);

  for (;;) {
    printf("[BARBER] screen indicates ticket %d\n", CurrentTicket);

    int sleep = (Nseat == NSEAT + 1);

    if (sleep)
      puts("[BARBER] no client, time to sleep");

    pthread_cond_wait(&HelloBarber, &Mutex); /* in all cases to be sure next client had time to see his turn */

    if (sleep)
      puts("[BARBER] woken up by a client");
    puts("[BARBER] cutting hairs");

    pthread_mutex_unlock(&Mutex);
    randomSleep(3); /* time to cut hairs of current client */
    pthread_mutex_lock(&Mutex);

    puts("[BARBER] haircut done");
    Nseat += 1;
    CurrentTicket += 1;
    pthread_cond_broadcast(&NextClient);
  }
}

int main()
{
  pthread_t barber_thread, client_thread[NCLIENT];
  int i, id[NCLIENT];

  Seed = time(NULL);

  if (pthread_create(&barber_thread, NULL, barber, NULL ) < 0){
    fprintf(stderr, "[MAIN] Error creating \"barber\" thread!\n");
    exit(EXIT_FAILURE);
  }

  pthread_mutex_lock(&Mutex);
  if (CurrentTicket == 0) {
    /* wait barber ready */
    pthread_cond_wait(&NextClient, &Mutex);
  }
  pthread_mutex_unlock(&Mutex);

  for (i = 0; i < NCLIENT; ++i) {
    id[i] = i+1;
    if (pthread_create(&client_thread[i], NULL, client, &id[i]) < 0) {
      fprintf(stderr, "[MAIN] Error creating \"client %d\" thread!\n", id[i]);
      exit(EXIT_FAILURE);
    }
  }

  for (i = 0; i < NCLIENT; i++) {
    pthread_join(client_thread[i], NULL);

    pthread_mutex_lock(&Mutex);
    printf("[MAIN] Joined client \"%d\"\n", i+1);
    pthread_mutex_unlock(&Mutex);
  }

  return 0;
}
</code>```

Compilation and example of execution :

```<code>pi@raspberrypi:~ $ gcc -Wall barber.c  -lpthread
pi@raspberrypi:~ $ ./a.out
[BARBER] ready
[BARBER] screen indicates ticket 1
[BARBER] no client, time to sleep
----[CLIENT] Client "7" got ticket number 1
----[CLIENT] Client "7" my turn
----[CLIENT] Client "7" do not need to seat to wait
[BARBER] woken up by a client
[BARBER] cutting hairs
----[CLIENT] Client "6" got ticket number 2
----[CLIENT] Client "6" not my turn
----[CLIENT] Client "6" seat to wait
----[CLIENT] Client "5" got ticket number 3
----[CLIENT] Client "5" not my turn
----[CLIENT] Client "5" seat to wait
----[CLIENT] Client "1" got ticket number 4
----[CLIENT] Client "1" not my turn
----[CLIENT] Client "1" seat to wait
----[CLIENT] Client "3" got ticket number 5
----[CLIENT] Client "3" not my turn
----[CLIENT] Client "3" seat to wait
[BARBER] haircut done
[BARBER] screen indicates ticket 2
----[CLIENT] Client "7" done for me
----[CLIENT] Client "3" not my turn
----[CLIENT] Client "1" not my turn
----[CLIENT] Client "6" my turn
----[CLIENT] Client "5" not my turn
[BARBER] cutting hairs
----[CLIENT] Client "9" got ticket number 6
----[CLIENT] Client "9" not my turn
----[CLIENT] Client "9" seat to wait
----[CLIENT] Client "8" got ticket number 7
----[CLIENT] Client "8" not my turn
----[CLIENT] Client "8" seat to wait
----[CLIENT] Client "4" no place, will try again later
----[CLIENT] Client "2" no place, will try again later
----[CLIENT] Client "10" no place, will try again later
[BARBER] haircut done
[BARBER] screen indicates ticket 3
----[CLIENT] Client "8" not my turn
----[CLIENT] Client "5" my turn
----[CLIENT] Client "9" not my turn
----[CLIENT] Client "1" not my turn
----[CLIENT] Client "6" done for me
[BARBER] cutting hairs
----[CLIENT] Client "3" not my turn
[BARBER] haircut done
[BARBER] screen indicates ticket 4
----[CLIENT] Client "9" not my turn
----[CLIENT] Client "1" my turn
----[CLIENT] Client "3" not my turn
----[CLIENT] Client "5" done for me
----[CLIENT] Client "8" not my turn
[BARBER] cutting hairs
[BARBER] haircut done
[BARBER] screen indicates ticket 5
----[CLIENT] Client "8" not my turn
----[CLIENT] Client "1" done for me
[MAIN] Joined client "1"
----[CLIENT] Client "9" not my turn
----[CLIENT] Client "3" my turn
[BARBER] cutting hairs
----[CLIENT] Client "10" got ticket number 8
----[CLIENT] Client "10" not my turn
----[CLIENT] Client "10" seat to wait
----[CLIENT] Client "2" got ticket number 9
----[CLIENT] Client "2" not my turn
----[CLIENT] Client "2" seat to wait
----[CLIENT] Client "4" got ticket number 10
----[CLIENT] Client "4" not my turn
----[CLIENT] Client "4" seat to wait
[BARBER] haircut done
[BARBER] screen indicates ticket 6
----[CLIENT] Client "2" not my turn
----[CLIENT] Client "3" done for me
----[CLIENT] Client "4" not my turn
----[CLIENT] Client "8" not my turn
----[CLIENT] Client "9" my turn
----[CLIENT] Client "10" not my turn
[BARBER] cutting hairs
[BARBER] haircut done
[BARBER] screen indicates ticket 7
----[CLIENT] Client "2" not my turn
----[CLIENT] Client "9" done for me
----[CLIENT] Client "4" not my turn
----[CLIENT] Client "8" my turn
[BARBER] cutting hairs
----[CLIENT] Client "10" not my turn
[BARBER] haircut done
[BARBER] screen indicates ticket 8
----[CLIENT] Client "10" my turn
[BARBER] cutting hairs
----[CLIENT] Client "2" not my turn
----[CLIENT] Client "8" done for me
----[CLIENT] Client "4" not my turn
[BARBER] haircut done
[BARBER] screen indicates ticket 9
----[CLIENT] Client "10" done for me
----[CLIENT] Client "2" my turn
----[CLIENT] Client "4" not my turn
[BARBER] cutting hairs
[BARBER] haircut done
[BARBER] screen indicates ticket 10
----[CLIENT] Client "2" done for me
----[CLIENT] Client "4" my turn
[BARBER] cutting hairs
[MAIN] Joined client "2"
[MAIN] Joined client "3"
[BARBER] haircut done
[BARBER] screen indicates ticket 11
[BARBER] no client, time to sleep
----[CLIENT] Client "4" done for me
[MAIN] Joined client "4"
[MAIN] Joined client "5"
[MAIN] Joined client "6"
[MAIN] Joined client "7"
[MAIN] Joined client "8"
[MAIN] Joined client "9"
[MAIN] Joined client "10"
pi@raspberrypi:~ $
</code>```

Body:
I created a C program with pthreads, and it works perfectly until I add any sort of sleep function, whether it's be  sleep() or usleep() or  nanosleep().

Yes, before you ask, I know usleep() is deprecated and I have copied the correct usage of nanosleep() from another stackoferflow post, but even sleep() doesn't work.

The code (the critical section is in the "clients" thread, at line 99):

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <time.h>

#define LIBERA 0
#define OCCUPATA 1
#define TUTTE_SEDIE_OCCUPATE -1
#define OCCUPATA_DA_BARBIERE -2

#define NRCLIENTI 10
#define NRSEDIE 5

pthread_mutex_t poltrona_m, dorme_m, get_sedia_m, occupa_sedia_m;
sem_t sem;
int sedia_taglio = LIBERA, sedia_attesa[NRSEDIE];

void init_attr(void) {
    int i;
    for (i = 0; i < NRSEDIE; i++)
        sedia_attesa[i] = LIBERA;
    sem_init(&sem, 0, NRSEDIE);
    pthread_mutex_unlock(&poltrona_m);
    pthread_mutex_unlock(&dorme_m);
    pthread_mutex_unlock(&get_sedia_m);
    pthread_mutex_unlock(&occupa_sedia_m);
}

int my_sleep(long millis) {
    struct timespec req, rem;

    if (millis > 999) {
        req.tv_sec = (int) (millis / 1000);
        req.tv_nsec = (millis - ((long) req.tv_sec * 1000)) * 1000000;
    } else {
        req.tv_sec = 0;
        req.tv_nsec = millis * 1000000;
    }

    return nanosleep(&req, &rem);
}

int get_sedia_libera() {
    pthread_mutex_lock(&get_sedia_m);
    int i;
    for (i = 0; i < NRSEDIE; i++)
        if (sedia_attesa[i] == LIBERA)
            return i;
    pthread_mutex_unlock(&get_sedia_m);
    return TUTTE_SEDIE_OCCUPATE;
}

int occupa_sedia(int index) {
    pthread_mutex_lock(&occupa_sedia_m);
    int result;
    if(sedia_attesa[index] == LIBERA){
        sedia_attesa[index] = OCCUPATA;
        result = 1;
    }else
        result = 0;
    pthread_mutex_unlock(&occupa_sedia_m);
    return result;
}

void libera_sedia(int index) {
    sedia_attesa[index] = LIBERA;
}

void *barbiere(void *arg) {
    while (1)
    {
        if (sedia_taglio == OCCUPATA) {
            pthread_mutex_lock(&poltrona_m);
            sedia_taglio = LIBERA;
            pthread_mutex_unlock(&poltrona_m);
        }

        if (get_sedia_libera() == 0 && sedia_taglio == LIBERA) {
            sedia_taglio = OCCUPATA_DA_BARBIERE;
            pthread_mutex_lock(&dorme_m);
            printf("[BARBIERE] il barbiere dorme...\n");
        }
    }
}

void *cliente(void *arg) {
    int n;
    int *id = (void *)arg;

    while (1)
    {
        if (sedia_taglio == LIBERA || sedia_taglio == OCCUPATA_DA_BARBIERE) {

            pthread_mutex_lock(&poltrona_m);
            pthread_mutex_unlock(&dorme_m);
            sedia_taglio = OCCUPATA;
            printf("----[CLIENTE] Cliente \"%d\" si taglia i capelli!\n", *id);
            my_sleep(2000);
            sedia_taglio = LIBERA;
            pthread_mutex_unlock(&poltrona_m);
            pthread_exit(0);

        } else {
            n = get_sedia_libera();
            if(n == TUTTE_SEDIE_OCCUPATE) {
                fprintf(stderr, "----[CLIENTE] No posti liberi cliente \"%d\" lascia il negozio\n", *id);
                pthread_exit((void *)1);
            } else {
                sem_wait(&sem);
                n = get_sedia_libera();
                if(occupa_sedia(n) && n != TUTTE_SEDIE_OCCUPATE){
                    printf("----[CLIENTE] Cliente \"%d\" aspetta su sedia #%d\n", *id, n+1);
                    while (sedia_taglio != LIBERA);
                    sem_post(&sem);
                    libera_sedia(n);
                } else {
                    sem_post(&sem);
                    fprintf(stderr, "----[CLIENTE] No posti liberi cliente \"%d\" lascia il negozio\n", *id);
                    pthread_exit(0);
                }
            }
        }

    }
}

int main(int argc, char **argv) {

    init_attr();

    int i, id[NRCLIENTI];
    pthread_t barbiere_thread, cliente_thread[NRCLIENTI];

    if(pthread_create(&barbiere_thread, NULL, barbiere, NULL ) < 0){
        fprintf(stderr, "[MAIN] Error creating \"barber\" thread!\n");
        exit(EXIT_FAILURE);
    }
    printf("[MAIN] thread \"barber\" creato\n\n");

    for (i = 0; i < NRCLIENTI; ++i) {
        id[i] = i+1;
        printf("[MAIN] thread \"client %d\" creato\n", id[i]);
        if(pthread_create(&cliente_thread[i], NULL, cliente, &id[i]) < 0){
            fprintf(stderr, "[MAIN] Error creating \"client %d\" thread!\n", id[i]);
            exit(EXIT_FAILURE);
        }
    }

    for (i = 0; i < NRCLIENTI; i++){
        pthread_join(cliente_thread[i], NULL);
        printf("[MAIN]Joined client \"%d\"\n", i+1);
    }

    //il programma non finira mai se sta ad aspettare un thread con un ciclo while(1) al suo interno
    //senza condizioni di break!!!
    pthread_join(barbiere_thread, NULL);

    return 0;
}

Normal execution(this is how the program should work):

[MAIN] thread "client 1" creato
[BARBIERE] il barbiere dorme...
hey
[MAIN] thread "client 2" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "1" si taglia i capelli!
[MAIN] thread "client 3" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "2" si taglia i capelli!
[MAIN] thread "client 4" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "3" si taglia i capelli!
[MAIN] thread "client 5" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "4" si taglia i capelli!
[MAIN] thread "client 6" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "5" si taglia i capelli!
[MAIN] thread "client 7" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "6" si taglia i capelli!
[MAIN] thread "client 8" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "7" si taglia i capelli!
[MAIN] thread "client 9" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "8" si taglia i capelli!
[MAIN] thread "client 10" creato
----<<<<<<<<<<<<[CLIENTE] Cliente "9" si taglia i capelli!
----<<<<<<<<<<<<[CLIENTE] Cliente "10" si taglia i capelli!
[MAIN]Joined client "1"
[MAIN]Joined client "2"
[MAIN]Joined client "3"
[MAIN]Joined client "4"
[MAIN]Joined client "5"
[MAIN]Joined client "6"
[MAIN]Joined client "7"
[MAIN]Joined client "8"
[MAIN]Joined client "9"
[MAIN]Joined client "10"

Execution with any sleep method, sleep(1), nanosleep() with 1 second or 100k microsecond usleep()
but I don't take usleep() into consideration because a) *its deprecated and * b) you cant put more or equal than 1million microseconds; usleep(1000000) is NOT valid

[MAIN] thread "client 1" creato
[BARBIERE] il barbiere dorme...
[MAIN] thread "client 2" creato
----[CLIENTE] Cliente "1" si taglia i capelli!
[MAIN] thread "client 3" creato
[MAIN] thread "client 4" creato
[MAIN] thread "client 5" creato
[MAIN] thread "client 6" creato
[MAIN] thread "client 7" creato
[MAIN] thread "client 8" creato
[MAIN] thread "client 9" creato
[MAIN] thread "client 10" creato
[MAIN]Joined client "1"

As you can see, the threads just... stall. I waited with the terminal open for 5 minutes, and still, nothing changed.
The strangest thing is that if I run this in windows IntelliJ Clion using MinGW, the sleep() functions seem totally ignored (the program executes itself in a fraction of a second)!

Thanks for reading through all of this, I hope we can find a solution and I'd be grateful for any help I get!

Body:
You creates deadlock because you have race condition between threads.

Moving pthread_mutex_t poltrona_m, dorme_m, get_sedia_m, occupa_sedia_m;
 at global scope, adding these verbose functions:

const char * whoIam()
{
  if (pthread_self() == barbiere_thread)
    return "barbiere";

  for (int i = 0; i != NRCLIENTI; ++i) {
    if (pthread_self() == cliente_thread[i]) {
      static char str[NRCLIENTI][64];

      sprintf(str[i], "cliente %d", i+1); /* done several times but whatever */
      return str[i];
    }
  }

  return "unknown-thread";
}

const char * whoIsMutex(pthread_mutex_t * m)
{
  if (m == &poltrona_m)
    return "poltrona";
  if (m == &dorme_m)
    return "dorme";
  if (m == &get_sedia_m)
    return "sedia";
  if (m == &occupa_sedia_m)
    return "occupa_sedia";
  return "unknown-mutex";
}

void my_pthread_mutex_unlock(pthread_mutex_t * m)
{
  printf("%s unlock %s\n", whoIam(), whoIsMutex(m));
  pthread_mutex_unlock(m);
}

void my_pthread_mutex_lock(pthread_mutex_t * m)
{
  printf("%s want to lock %s\n", whoIam(), whoIsMutex(m));
  pthread_mutex_lock(m);
  printf("%s locked %s\n", whoIam(), whoIsMutex(m));
}

and using my_pthread_mutex_lock and my_pthread_mutex_unlock out of init_attr the execution can be :

[MAIN] thread "barber" creato

[MAIN] thread "client 1" creato
barbiere want to lock sedia
barbiere locked sedia
barbiere want to lock dorme
barbiere locked dorme
cliente 1 want to lock poltrona
cliente 1 locked poltrona
cliente 1 unlock dorme           <<< does nothing because does not have it
----[CLIENTE] Cliente "1" si taglia i capelli!
[BARBIERE] il barbiere dorme...
barbiere want to lock poltrona   <<< wait while get by client 1
[MAIN] thread "client 2" creato
[MAIN] thread "client 3" creato
[MAIN] thread "client 4" creato
cliente 2 want to lock sedia
[MAIN] thread "client 5" creato
cliente 4 want to lock sedia
[MAIN] thread "client 6" creato
cliente 3 want to lock sedia
[MAIN] thread "client 7" creato
cliente 6 want to lock sedia
cliente 5 want to lock sedia
[MAIN] thread "client 8" creato
cliente 7 want to lock sedia
[MAIN] thread "client 9" creato
cliente 8 want to lock sedia
[MAIN] thread "client 10" creato
cliente 9 want to lock sedia
cliente 10 want to lock sedia
cliente 1 unlock poltrona     <<< finally unlock poltrona
barbiere locked poltrona      <<< wake up
barbiere unlock poltrona
barbiere want to lock sedia   <<< dead because get by itself
[MAIN]Joined client "1"

Adding my_sleep(1000); before sedia_taglio = occupata; in cliente helps to not have the race condition :

bruno@bruno-XPS-8300:/tmp$ gcc -Wall t.c -lpthread
bruno@bruno-XPS-8300:/tmp$ ./a.out
[MAIN] thread "barber" creato

[MAIN] thread "client 1" creato
[BARBIERE] il barbiere dorme...
[MAIN] thread "client 2" creato
[MAIN] thread "client 3" creato
[MAIN] thread "client 4" creato
[MAIN] thread "client 5" creato
[MAIN] thread "client 6" creato
[MAIN] thread "client 7" creato
[MAIN] thread "client 8" creato
[MAIN] thread "client 9" creato
[MAIN] thread "client 10" creato
----[CLIENTE] Cliente "1" si taglia i capelli!
[MAIN]Joined client "1"
----[CLIENTE] Cliente "3" si taglia i capelli!
----[CLIENTE] Cliente "2" si taglia i capelli!
[MAIN]Joined client "2"
[MAIN]Joined client "3"
----[CLIENTE] Cliente "4" si taglia i capelli!
[MAIN]Joined client "4"
----[CLIENTE] Cliente "5" si taglia i capelli!
[MAIN]Joined client "5"
----[CLIENTE] Cliente "6" si taglia i capelli!
[MAIN]Joined client "6"
----[CLIENTE] Cliente "7" si taglia i capelli!
[MAIN]Joined client "7"
----[CLIENTE] Cliente "8" si taglia i capelli!
[MAIN]Joined client "8"
----[CLIENTE] Cliente "9" si taglia i capelli!
[MAIN]Joined client "9"
----[CLIENTE] Cliente "10" si taglia i capelli!
[MAIN]Joined client "10"

Out of that, about the way to sleep, the function sleep blocks all the process, contrarily to usleep and nanosleep.

Here a proposal without race condition, nor making assumption on the mutex implementation (no undefined behavior).

There is only one mutex to protect datas consistency and for the conditions, I also use it to protect printing.

There are seats to wait, and one used to cut hairs. To manage clients in order of arrival they get a ticket having a number, when there is no free seat at all a client cannot get a ticket and will retry later. The number of the ticket of the client to have hairs cut is given by CurrentTicket (as a screen client read) and the signal NextClient is produced (as a beep) to allow clients to check if their turn comes. The number of the ticket in the distributor is managed by LastTicket. The signal HelloBarber is sent by a client when he reaches the barber and may be wake up him. The barber sleeps when there is no client.

I use a random time limited to 5 seconds for the delay used by a client to (re)try to get a place, and the barber cut hairs of a client in a random time limited to 3 seconds.

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>

#define NCLIENT 10
#define NSEAT 5 /* seats to wait */

unsigned int Seed;
int Nseat = NSEAT  + 1; /* add 1 to have seat to cut hairs */
int CurrentTicket = 0;
int LastTicket = 0;

pthread_mutex_t Mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t NextClient = PTHREAD_COND_INITIALIZER;
pthread_cond_t HelloBarber = PTHREAD_COND_INITIALIZER;

/* return -1 is no seat, else ticket number */
int getTicket()
{
  int result;

  pthread_mutex_lock(&Mutex);
  if (Nseat == 0)
    result = -1;
  else {
    Nseat -= 1;
    result = ++LastTicket;
  }
  pthread_mutex_unlock(&Mutex);

  return result;
}

void randomSleep(int max)
{
  int millis = rand_r(&Seed) % (max * 1000);
  struct timespec req, rem;

  if (millis > 999) {
    req.tv_sec = (int) (millis / 1000);
    req.tv_nsec = (millis - ((long) req.tv_sec * 1000)) * 1000000;
  } else {
    req.tv_sec = 0;
    req.tv_nsec = millis * 1000000;
  }

  nanosleep(&req, &rem);
}

void * client(void * arg)
{
  int id = *((int *) arg);
  int ticket;
  int justArrived = 1;

  while (randomSleep(5), ((ticket = getTicket()) == -1)) {
    pthread_mutex_lock(&Mutex);
    printf("----[CLIENT] Client \"%d\" no place, will try again later\n", id);
    pthread_mutex_unlock(&Mutex);
  }

  pthread_mutex_lock(&Mutex);
  printf("----[CLIENT] Client \"%d\" got ticket number %d\n", id, ticket);

  while (ticket != CurrentTicket) {
    printf("----[CLIENT] Client \"%d\" not my turn\n", id);
    if (justArrived) {
      justArrived = 0;
      printf("----[CLIENT] Client \"%d\" seat to wait\n", id);
    }
    pthread_cond_wait(&NextClient, &Mutex);
  }
  printf("----[CLIENT] Client \"%d\" my turn\n", id);
  if (justArrived)
    printf("----[CLIENT] Client \"%d\" do not need to seat to wait\n", id);

  pthread_cond_signal(&HelloBarber);

  pthread_cond_wait(&NextClient, &Mutex);
  printf("----[CLIENT] Client \"%d\" done for me\n", id);
  pthread_mutex_unlock(&Mutex);

  return NULL;
}

void * barber(void * dummy)
{
  pthread_mutex_lock(&Mutex);

  puts("[BARBER] ready");
  CurrentTicket = 1;
  pthread_cond_signal(&NextClient);

  for (;;) {
    printf("[BARBER] screen indicates ticket %d\n", CurrentTicket);

    int sleep = (Nseat == NSEAT + 1);

    if (sleep)
      puts("[BARBER] no client, time to sleep");

    pthread_cond_wait(&HelloBarber, &Mutex); /* in all cases to be sure next client had time to see his turn */

    if (sleep)
      puts("[BARBER] woken up by a client");
    puts("[BARBER] cutting hairs");

    pthread_mutex_unlock(&Mutex);
    randomSleep(3); /* time to cut hairs of current client */
    pthread_mutex_lock(&Mutex);

    puts("[BARBER] haircut done");
    Nseat += 1;
    CurrentTicket += 1;
    pthread_cond_broadcast(&NextClient);
  }
}

int main()
{
  pthread_t barber_thread, client_thread[NCLIENT];
  int i, id[NCLIENT];

  Seed = time(NULL);

  if (pthread_create(&barber_thread, NULL, barber, NULL ) < 0){
    fprintf(stderr, "[MAIN] Error creating \"barber\" thread!\n");
    exit(EXIT_FAILURE);
  }

  pthread_mutex_lock(&Mutex);
  if (CurrentTicket == 0) {
    /* wait barber ready */
    pthread_cond_wait(&NextClient, &Mutex);
  }
  pthread_mutex_unlock(&Mutex);

  for (i = 0; i < NCLIENT; ++i) {
    id[i] = i+1;
    if (pthread_create(&client_thread[i], NULL, client, &id[i]) < 0) {
      fprintf(stderr, "[MAIN] Error creating \"client %d\" thread!\n", id[i]);
      exit(EXIT_FAILURE);
    }
  }

  for (i = 0; i < NCLIENT; i++) {
    pthread_join(client_thread[i], NULL);

    pthread_mutex_lock(&Mutex);
    printf("[MAIN] Joined client \"%d\"\n", i+1);
    pthread_mutex_unlock(&Mutex);
  }

  return 0;
}

Compilation and example of execution :

pi@raspberrypi:~ $ gcc -Wall barber.c  -lpthread
pi@raspberrypi:~ $ ./a.out
[BARBER] ready
[BARBER] screen indicates ticket 1
[BARBER] no client, time to sleep
----[CLIENT] Client "7" got ticket number 1
----[CLIENT] Client "7" my turn
----[CLIENT] Client "7" do not need to seat to wait
[BARBER] woken up by a client
[BARBER] cutting hairs
----[CLIENT] Client "6" got ticket number 2
----[CLIENT] Client "6" not my turn
----[CLIENT] Client "6" seat to wait
----[CLIENT] Client "5" got ticket number 3
----[CLIENT] Client "5" not my turn
----[CLIENT] Client "5" seat to wait
----[CLIENT] Client "1" got ticket number 4
----[CLIENT] Client "1" not my turn
----[CLIENT] Client "1" seat to wait
----[CLIENT] Client "3" got ticket number 5
----[CLIENT] Client "3" not my turn
----[CLIENT] Client "3" seat to wait
[BARBER] haircut done
[BARBER] screen indicates ticket 2
----[CLIENT] Client "7" done for me
----[CLIENT] Client "3" not my turn
----[CLIENT] Client "1" not my turn
----[CLIENT] Client "6" my turn
----[CLIENT] Client "5" not my turn
[BARBER] cutting hairs
----[CLIENT] Client "9" got ticket number 6
----[CLIENT] Client "9" not my turn
----[CLIENT] Client "9" seat to wait
----[CLIENT] Client "8" got ticket number 7
----[CLIENT] Client "8" not my turn
----[CLIENT] Client "8" seat to wait
----[CLIENT] Client "4" no place, will try again later
----[CLIENT] Client "2" no place, will try again later
----[CLIENT] Client "10" no place, will try again later
[BARBER] haircut done
[BARBER] screen indicates ticket 3
----[CLIENT] Client "8" not my turn
----[CLIENT] Client "5" my turn
----[CLIENT] Client "9" not my turn
----[CLIENT] Client "1" not my turn
----[CLIENT] Client "6" done for me
[BARBER] cutting hairs
----[CLIENT] Client "3" not my turn
[BARBER] haircut done
[BARBER] screen indicates ticket 4
----[CLIENT] Client "9" not my turn
----[CLIENT] Client "1" my turn
----[CLIENT] Client "3" not my turn
----[CLIENT] Client "5" done for me
----[CLIENT] Client "8" not my turn
[BARBER] cutting hairs
[BARBER] haircut done
[BARBER] screen indicates ticket 5
----[CLIENT] Client "8" not my turn
----[CLIENT] Client "1" done for me
[MAIN] Joined client "1"
----[CLIENT] Client "9" not my turn
----[CLIENT] Client "3" my turn
[BARBER] cutting hairs
----[CLIENT] Client "10" got ticket number 8
----[CLIENT] Client "10" not my turn
----[CLIENT] Client "10" seat to wait
----[CLIENT] Client "2" got ticket number 9
----[CLIENT] Client "2" not my turn
----[CLIENT] Client "2" seat to wait
----[CLIENT] Client "4" got ticket number 10
----[CLIENT] Client "4" not my turn
----[CLIENT] Client "4" seat to wait
[BARBER] haircut done
[BARBER] screen indicates ticket 6
----[CLIENT] Client "2" not my turn
----[CLIENT] Client "3" done for me
----[CLIENT] Client "4" not my turn
----[CLIENT] Client "8" not my turn
----[CLIENT] Client "9" my turn
----[CLIENT] Client "10" not my turn
[BARBER] cutting hairs
[BARBER] haircut done
[BARBER] screen indicates ticket 7
----[CLIENT] Client "2" not my turn
----[CLIENT] Client "9" done for me
----[CLIENT] Client "4" not my turn
----[CLIENT] Client "8" my turn
[BARBER] cutting hairs
----[CLIENT] Client "10" not my turn
[BARBER] haircut done
[BARBER] screen indicates ticket 8
----[CLIENT] Client "10" my turn
[BARBER] cutting hairs
----[CLIENT] Client "2" not my turn
----[CLIENT] Client "8" done for me
----[CLIENT] Client "4" not my turn
[BARBER] haircut done
[BARBER] screen indicates ticket 9
----[CLIENT] Client "10" done for me
----[CLIENT] Client "2" my turn
----[CLIENT] Client "4" not my turn
[BARBER] cutting hairs
[BARBER] haircut done
[BARBER] screen indicates ticket 10
----[CLIENT] Client "2" done for me
----[CLIENT] Client "4" my turn
[BARBER] cutting hairs
[MAIN] Joined client "2"
[MAIN] Joined client "3"
[BARBER] haircut done
[BARBER] screen indicates ticket 11
[BARBER] no client, time to sleep
----[CLIENT] Client "4" done for me
[MAIN] Joined client "4"
[MAIN] Joined client "5"
[MAIN] Joined client "6"
[MAIN] Joined client "7"
[MAIN] Joined client "8"
[MAIN] Joined client "9"
[MAIN] Joined client "10"
pi@raspberrypi:~ $


问:
Elasticsearch aggregation on different search in same query
I want to make a query to aggregate base only on match no matter what other parameters(terms , term , etc...) are used.
To be more specific I have an online shop where I use multiple filters (color ,size etc..) If I check a field for example color : red the other colors are no longer aggregated.
A solution that I am using is to make 2 separated queries (one for search where filters are applied and other for aggregation. Any idea how can I combine the 2 separated queries ?</p>

答:
You can take advantage of post_filter which will not apply to your aggregations but will only filter the to-be-returned hits. For example:

Create a shop

```<code>PUT online_shop
{
  "mappings": {
    "properties": {
      "color": {
        "type": "keyword"
      },
      "size": {
        "type": "integer"
      },
      "name": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword"
          }
        }
      }
    }
  }
}
</code>```

Populate it w/ a few products

```<code>POST online_shop/_doc
{"color":"red","size":35,"name":"Louboutin High heels abc"}

POST online_shop/_doc
{"color":"black","size":34,"name":"Louboutin Boots abc"}

POST online_shop/_doc
{"color":"yellow","size":36,"name":"XYZ abc"}
</code>```

Apply a shared query to the hits as well as aggregations and use post_filter to ... post-filter the hits:

```<code>GET online_shop/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": "abc"
          }
        }
      ]
    }
  },
  "aggs": {
    "by_color": {
      "terms": {
        "field": "color"
      }
    },
    "by_size": {
      "terms": {
        "field": "size"
      }
    }
  },
  "post_filter": {
    "bool": {
      "must": [
        {
          "term": {
            "color": {
              "value": "red"
            }
          }
        }
      ]
    }
  }
}
</code>```

Expected result

```<code>{
  ...
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 0.11750763,
    "hits" : [
      {
        "_index" : "online_shop",
        "_type" : "_doc",
        "_id" : "cehma3IBG_KW3EFn1QYa",
        "_score" : 0.11750763,
        "_source" : {
          "color" : "red",
          "size" : 35,
          "name" : "Louboutin High heels abc"
        }
      }
    ]
  },
  "aggregations" : {
    "by_color" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "black",
          "doc_count" : 1
        },
        {
          "key" : "red",
          "doc_count" : 1
        },
        {
          "key" : "yellow",
          "doc_count" : 1
        }
      ]
    },
    "by_size" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : 34,
          "doc_count" : 1
        },
        {
          "key" : 35,
          "doc_count" : 1
        },
        {
          "key" : 36,
          "doc_count" : 1
        }
      ]
    }
  }
}

</code>```

Body:
You can take advantage of post_filter which will not apply to your aggregations but will only filter the to-be-returned hits. For example:

Create a shop

PUT online_shop
{
  "mappings": {
    "properties": {
      "color": {
        "type": "keyword"
      },
      "size": {
        "type": "integer"
      },
      "name": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword"
          }
        }
      }
    }
  }
}

Populate it w/ a few products

POST online_shop/_doc
{"color":"red","size":35,"name":"Louboutin High heels abc"}

POST online_shop/_doc
{"color":"black","size":34,"name":"Louboutin Boots abc"}

POST online_shop/_doc
{"color":"yellow","size":36,"name":"XYZ abc"}

Apply a shared query to the hits as well as aggregations and use post_filter to ... post-filter the hits:

GET online_shop/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": "abc"
          }
        }
      ]
    }
  },
  "aggs": {
    "by_color": {
      "terms": {
        "field": "color"
      }
    },
    "by_size": {
      "terms": {
        "field": "size"
      }
    }
  },
  "post_filter": {
    "bool": {
      "must": [
        {
          "term": {
            "color": {
              "value": "red"
            }
          }
        }
      ]
    }
  }
}

Expected result

{
  ...
  "hits" : {
    "total" : {
      "value" : 1,
      "relation" : "eq"
    },
    "max_score" : 0.11750763,
    "hits" : [
      {
        "_index" : "online_shop",
        "_type" : "_doc",
        "_id" : "cehma3IBG_KW3EFn1QYa",
        "_score" : 0.11750763,
        "_source" : {
          "color" : "red",
          "size" : 35,
          "name" : "Louboutin High heels abc"
        }
      }
    ]
  },
  "aggregations" : {
    "by_color" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "black",
          "doc_count" : 1
        },
        {
          "key" : "red",
          "doc_count" : 1
        },
        {
          "key" : "yellow",
          "doc_count" : 1
        }
      ]
    },
    "by_size" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : 34,
          "doc_count" : 1
        },
        {
          "key" : 35,
          "doc_count" : 1
        },
        {
          "key" : 36,
          "doc_count" : 1
        }
      ]
    }
  }
}


问:
sqlite-net-pcl SqliteAsyncConnection.CreateTableAsync<T> throws System.MissingMethodException
I am trying to create a table using the latest version of sqlite-net-pcl nuget package

```<code>var db = new SQLiteAsyncConnection("data.db");
await db.CreateTableAsync<Site>();
</code>```

The CreateTableAsync call throws the following exception:

System.MissingMethodException: 'Method not found: 'System.String
  SQLitePCL.raw.sqlite3_column_name(SQLitePCL.sqlite3_stmt, Int32)'.'

Here is the Site class

```<code>public class Site
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    public String Name;
    public String PriceCssSelector;
    public String URLRegex;

    public Site()
    {
    }
}
</code>```

I tried downgrading to the latest stable version of sqlite-net-pcl package.

答:
I have stumbled across this error after installing sqlite-net-pcl (for toying with SQLite) and after that I have installed Microsoft.Azure.Mobile.Client.SQLiteStore.

My solution was to uninstall both NuGet packages and install Microsoft.Azure.Mobile.Client.SQLiteStore only which installed the appropriate sqlite-net-pcl version.

Body:
I am trying to create a table using the latest version of sqlite-net-pcl nuget package

var db = new SQLiteAsyncConnection("data.db");
await db.CreateTableAsync<Site>();

The CreateTableAsync call throws the following exception:

System.MissingMethodException: 'Method not found: 'System.String
  SQLitePCL.raw.sqlite3_column_name(SQLitePCL.sqlite3_stmt, Int32)'.'

Here is the Site class

public class Site
{
    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }

    public String Name;
    public String PriceCssSelector;
    public String URLRegex;

    public Site()
    {
    }
}

I tried downgrading to the latest stable version of sqlite-net-pcl package.


问:
How to store data from string into array with delimiter

Possible Duplicate:

  separate the ids and store in two different array

```<code>String response=@" hr 123,124,125,126,127,128 hr st 234,235,236,237 st";
</code>```

from hr to hr i need to store in one array.

from st to st i need to store in another array.

My service provider is playing with response.....

Please help me out.

答:
There you go:</p>

```<code>    NSMutableString *response = [NSMutableString stringWithString: @" hr 123,124,125,126,127,128 hr st 234,235,236,237 st"];

    [response replaceOccurrencesOfString:@" "
                              withString:@""
                                 options:NSCaseInsensitiveSearch
                                   range:NSMakeRange(0, [response length])];

    NSRange firstAppearanceOfHr = [response rangeOfString:@"hr"];

    [response replaceCharactersInRange:firstAppearanceOfHr withString:@""];

    NSRange secondAppearanceOfHr = [response rangeOfString:@"hr"];

    NSString *hrString = [response substringWithRange:NSMakeRange(0, secondAppearanceOfHr.location)];

    NSArray *hrArray = [hrString componentsSeparatedByString:@","];

    NSLog(@"HrArray:%@",[hrArray description]);

    NSRange firstAppearaceOfSt = [response rangeOfString:@"st"];

    NSInteger startSt = firstAppearaceOfSt.location+firstAppearaceOfSt.length;
    NSString *stString  = [response substringWithRange:NSMakeRange(startSt, [response length] - startSt - 2)];

    NSArray *stArray = [stString componentsSeparatedByString:@","];

    NSLog(@"StArray:%@",[stArray description]);
</code>```

Body:
Possible Duplicate:

  separate the ids and store in two different array

String response=@" hr 123,124,125,126,127,128 hr st 234,235,236,237 st";

from hr to hr i need to store in one array.

from st to st i need to store in another array.

My service provider is playing with response.....

Please help me out.

Body:
There you go:

    NSMutableString *response = [NSMutableString stringWithString: @" hr 123,124,125,126,127,128 hr st 234,235,236,237 st"];

    [response replaceOccurrencesOfString:@" "
                              withString:@""
                                 options:NSCaseInsensitiveSearch
                                   range:NSMakeRange(0, [response length])];

    NSRange firstAppearanceOfHr = [response rangeOfString:@"hr"];

    [response replaceCharactersInRange:firstAppearanceOfHr withString:@""];

    NSRange secondAppearanceOfHr = [response rangeOfString:@"hr"];

    NSString *hrString = [response substringWithRange:NSMakeRange(0, secondAppearanceOfHr.location)];

    NSArray *hrArray = [hrString componentsSeparatedByString:@","];

    NSLog(@"HrArray:%@",[hrArray description]);

    NSRange firstAppearaceOfSt = [response rangeOfString:@"st"];

    NSInteger startSt = firstAppearaceOfSt.location+firstAppearaceOfSt.length;
    NSString *stString  = [response substringWithRange:NSMakeRange(startSt, [response length] - startSt - 2)];

    NSArray *stArray = [stString componentsSeparatedByString:@","];

    NSLog(@"StArray:%@",[stArray description]);


问:
In emacs, how do I highlight and flash current line with a changing backcolor as the following video did?
In this video: Org-roam-bibtex - Quick Presentation]1, the background color of the active line will be temporarily changed and flashed. Can anyone call tell me how to do it, pelase?</p>

答: That is Beacon mode. It eases finding the cursor (point) when changing windows or when scrolling.</p>


问:
multiple Promises in nodejs wait till they all finish
I have this snippet of code in my nodejs application.

The problem is that it doesn't wait before it renders the config page and passes the object thebalances.

```<code>app.get("/config", (req, res) => {
    var thebalances = [];
    client.rest.account.listAccounts().then(accounts => {

        accounts.forEach(element => {
            client.rest.product.getProductTicker(element.currency + '-USD').then(priceInfo => {

                thebalances.push({
                    currency: element.currency
            });
        });
        res.render("config", { balance: thebalances });
    })
});
</code>```

I have modified it to this now: but i think it errors out on some and like mentioned below it is all failing.

```<code>// GET /about
app.get("/config", (req, res) => {
    let thebalances = [];
    client.rest.account.listAccounts().then(async accounts => {
        let promises = [];
        accounts.forEach(element => {
            promises.push(client.rest.product.getProductTicker(element.currency + '-USD'));
        });
        await Promise.all(promises).then(
            results => {
                results.forEach(priceInfo => {
                    thebalances.push({ currency: element.currency });
                });
            }
        ).catch(
            error => {}
        )
        console.log(results);
        res.render("config", { balances: thebalances });
    })
});
</code>```

I'm not sure how i can handle the multiple variable# of promises inside the foreach loop. I need to let that do its thing first before i can render the config page.

Any help would be greatly appreciated. I'm using coinbase api.

答:
If it's really the case that one or more promise is failing, and it's really the case that this is okay from an app perspective, then...

```<code>// ...
let promises = accounts.map(element => {
    return getProductTicker(element.currency);
});
// ...

function getProductTicker(currency) {
    return client.rest.product.getProductTicker(currency + '-USD').catch(error => {
        // debug here, if the error is a problem, otherwise
        return null
    })
}
</code>```

Now promise all will contain proper resolutions of getProductTicker as well as nulls wherever that call failed.  To clean it up...

```<code>await Promise.all(promises).then(results => {
    let maybeWeShouldDebugHere = results.filter(r => !!!r)
})
</code>```

Body:
I have this snippet of code in my nodejs application.

The problem is that it doesn't wait before it renders the config page and passes the object thebalances.

app.get("/config", (req, res) => {
    var thebalances = [];
    client.rest.account.listAccounts().then(accounts => {

        accounts.forEach(element => {
            client.rest.product.getProductTicker(element.currency + '-USD').then(priceInfo => {

                thebalances.push({
                    currency: element.currency
            });
        });
        res.render("config", { balance: thebalances });
    })
});

I have modified it to this now: but i think it errors out on some and like mentioned below it is all failing.

// GET /about
app.get("/config", (req, res) => {
    let thebalances = [];
    client.rest.account.listAccounts().then(async accounts => {
        let promises = [];
        accounts.forEach(element => {
            promises.push(client.rest.product.getProductTicker(element.currency + '-USD'));
        });
        await Promise.all(promises).then(
            results => {
                results.forEach(priceInfo => {
                    thebalances.push({ currency: element.currency });
                });
            }
        ).catch(
            error => {}
        )
        console.log(results);
        res.render("config", { balances: thebalances });
    })
});

I'm not sure how i can handle the multiple variable# of promises inside the foreach loop. I need to let that do its thing first before i can render the config page.

Any help would be greatly appreciated. I'm using coinbase api.

Body:
If it's really the case that one or more promise is failing, and it's really the case that this is okay from an app perspective, then...

// ...
let promises = accounts.map(element => {
    return getProductTicker(element.currency);
});
// ...

function getProductTicker(currency) {
    return client.rest.product.getProductTicker(currency + '-USD').catch(error => {
        // debug here, if the error is a problem, otherwise
        return null
    })
}

Now promise all will contain proper resolutions of getProductTicker as well as nulls wherever that call failed.  To clean it up...

await Promise.all(promises).then(results => {
    let maybeWeShouldDebugHere = results.filter(r => !!!r)
})


问:
While sharing one image in linkedin, Oops ! error showing
While I am sharing any url in linkedin from my website, its working fine from QA host URL, but does n't work from local host/any other url.

Error:

Oops! Its not you its us, Give another try, please.

code for sharing url is common for both.
is there anything from linked in side to authenticate my host or anything else?

I expect its should show share page from localhost too.

For example: https://test.com/UserProfile/244/2321454

答:
Your link works perfectly fine for me.  This...

```<code>https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.test.com%2FUserProfile%2F244%2F2321454
</code>```

Shows me this...

URL formatting: Official Microsoft.com Linkedin Share Plugin Documentation

Adding prefilled parameters: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.

Body:
Your link works perfectly fine for me.  This...

https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fwww.test.com%2FUserProfile%2F244%2F2321454

Shows me this...

URL formatting: Official Microsoft.com Linkedin Share Plugin Documentation

Adding prefilled parameters: LinkedIn Developer Docs: Making Your Website Shareable on LinkedIn.


问:
How to check if any application is running in docker container?
How to check if any application is running in docker container ? What is the command for it.</p>

答:
You need to show auxiliary list of process. Try this.</p>

```<code>docker exec -it <name-of-your-container> /bin/bash
# ps aux | grep "application-name-here"
</code>```

Body:
You need to show auxiliary list of process. Try this.

docker exec -it <name-of-your-container> /bin/bash
# ps aux | grep "application-name-here"


问:
gzip: unexpected end of file when using gzip
I have to process a file using my Linux machine.

When I try to write my output to a csv file then gzip it in the same line of script:

processing > output.csv | gzip -f output.csv

I get an 'unexpected end of file' error. Even when I download the file using the Linux machine I get the same error.

When I do not gzip via terminal (or in a single line) everything works fine.

Why does it fail like this when the commands are all in a single line?

答:
When you redirect a process' IO with the > operator, its output cannot be used by a pipe afterwards (because there's no "output" anymore to be piped). You have two options:

```<code>processing > output.csv &&
gzip output.csv
</code>```

Writes the unprocessed output of your program to the file output.csv and then in a second task gzips this file, replacing it with output.gz. Depending on the amount of data, this might not be feasible (storage reqirements are the full uncompressed output PLUS the compressed size)

```<code>processing | gzip > output.csv.gz
</code>```

This will compress the output of your process in-line and write it directly to the output file, without storing the uncompressed output in an intermediate file.

Body:
When you redirect a process' IO with the > operator, its output cannot be used by a pipe afterwards (because there's no "output" anymore to be piped). You have two options:

processing > output.csv &&
gzip output.csv

Writes the unprocessed output of your program to the file output.csv and then in a second task gzips this file, replacing it with output.gz. Depending on the amount of data, this might not be feasible (storage reqirements are the full uncompressed output PLUS the compressed size)

processing | gzip > output.csv.gz

This will compress the output of your process in-line and write it directly to the output file, without storing the uncompressed output in an intermediate file.


问:
Restsharp raise SSL error when run on server
I am using Restsharp request to an API and codes are blow:

```<code>var client = new RestClient(baseURL);
var request = new RestRequest(url);
request.AddHeader("Authorization", authHeader);

var response = client.Get<T>(request);
return response;
</code>```

Same code did not raise any error on my test enviroment, but when I run the code on server, I get following error:

```<code>error message    : The SSL connection could not be established, see inner exception. The remote certificate is invalid according to the validation procedure.
exception        : System.Net.WebException: The SSL connection could not be established, see inner exception. The remote certificate is invalid according to the validation procedure. ---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
</code>```

I don't know what is wrong with that code and I don't understand why same codes run differently?

Any help for fix that?

答:
Seems like the service pointed by baseURL has invalid SSL certificate.
You can bypass SSL validation check by adding the following line of code before making the call.

```<code>ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
</code>```

This globally disables SSL validation. It will totally work fine even if the production service has valid SSL, but it will certainly introduce some vulnerability in your code. You can wrap it inside

```<code>#if DEBUG
#endif
</code>```

Body:
I am using Restsharp request to an API and codes are blow:

var client = new RestClient(baseURL);
var request = new RestRequest(url);
request.AddHeader("Authorization", authHeader);

var response = client.Get<T>(request);
return response;

Same code did not raise any error on my test enviroment, but when I run the code on server, I get following error:

error message    : The SSL connection could not be established, see inner exception. The remote certificate is invalid according to the validation procedure.
exception        : System.Net.WebException: The SSL connection could not be established, see inner exception. The remote certificate is invalid according to the validation procedure. ---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.

I don't know what is wrong with that code and I don't understand why same codes run differently?

Any help for fix that?

Body:
Seems like the service pointed by baseURL has invalid SSL certificate.
You can bypass SSL validation check by adding the following line of code before making the call.

ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;

This globally disables SSL validation. It will totally work fine even if the production service has valid SSL, but it will certainly introduce some vulnerability in your code. You can wrap it inside

#if DEBUG
#endif


问:
Function that shows all lists, which are ascending
I have to write a function, that check which lists of list are ascending and show them in list.
This is what I wrote, but it says "Non-exhaustive patterns in function f3"</p>

```<code>f :: [[Int]] -> [[Int]]
f [] = []
f [x:xs] =
 if helper (x:xs) == True
     then (x:xs) : f [xs]
     else f [xs]

helper :: [Int] -> Bool
helper [] = True
helper [x] = True
helper (x:y:xs) = x <= y && helper (y:xs)
</code>```

答:
This produces an error because [x:xs] will only match with a singleton list (a list with exactly one element), and that single item is a non-empty list.

You however do not need to match the inner list, you can filter with:

```<code>f :: [[Int]] -> [[Int]]
f [] = []
f (x:xs)
    | helper x = x : f xs
    | otherwise = f xs</code>```

which is a filter :: (a -> Bool) -> [a] -> [a] function:

```<code>f :: [[Int]] -> [[Int]]
f = <b>filter helper</b></code>```

You can further generalize this to work with a list of lists of items that are a member of the Ord typeclass:

```<code>helper :: <b>Ord a</b> => [<b>a</b>] -> Bool
helper [] = True
helper xa@(_:xs) = and (zipWith (<=) xa xs)</code>```

or as @DanielWagner says:

```<code>helper :: Ord a => [a] -> Bool
helper xs = and (zipWith (>=) xs (drop 1 xs))
</code>```

and then we can filter with the generalized helper:

```<code>f :: <b>Ord a</b> => [[<b>a</b>]] -> [[<b>a</b>]]
f = filter helper</code>```

Body:
I have to write a function, that check which lists of list are ascending and show them in list.
This is what I wrote, but it says "Non-exhaustive patterns in function f3"

f :: [[Int]] -> [[Int]]
f [] = []
f [x:xs] =
 if helper (x:xs) == True
     then (x:xs) : f [xs]
     else f [xs]

helper :: [Int] -> Bool
helper [] = True
helper [x] = True
helper (x:y:xs) = x <= y && helper (y:xs)

Body:
This produces an error because [x:xs] will only match with a singleton list (a list with exactly one element), and that single item is a non-empty list.

You however do not need to match the inner list, you can filter with:

f :: [[Int]] -> [[Int]]
f [] = []
f (x:xs)
    | helper x = x : f xs
    | otherwise = f xs

which is a filter :: (a -> Bool) -> [a] -> [a] function:

f :: [[Int]] -> [[Int]]
f = filter helper

You can further generalize this to work with a list of lists of items that are a member of the Ord typeclass:

helper :: Ord a => [a] -> Bool
helper [] = True
helper xa@(_:xs) = and (zipWith (<=) xa xs)

or as @DanielWagner says:

helper :: Ord a => [a] -> Bool
helper xs = and (zipWith (>=) xs (drop 1 xs))

and then we can filter with the generalized helper:

f :: Ord a => [[a]] -> [[a]]
f = filter helper