问:
How can i delete an item inside a nested recycler view using ItemTouchHelper?
I'm actually using Groupie library, and I'm trying to delete a nested item inside a group adapter.

But when I use ItemTouchHelper, it only deletes the parent items(Objetos) or the nested items(Produtos), basically the first one that I try to swipe. It attaches just one of the ItemTouchHelpers to my RecyclerView.

Here is my Fragment Code:

```<code>@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

    metodos = new OSMetodos(requireContext(), requireActivity(), codOS);
    adapter = new GroupAdapter<>();

    adcTipoServ = view.findViewById(R.id.adcTipoServico);
    adcTipoServ.setOnClickListener(view1 -> metodos.addService());
    recyclerViewOS = view.findViewById(R.id.recyclerViewOSServ);
    recyclerViewOS.setLayoutManager(new LinearLayoutManager(requireContext()));
    setAdapter();

}

@Override
public void onResume() {
    super.onResume();
    setAdapter();
}

public void setAdapter() {
    oldList.clear();
    adapter.clear();
    oldList = repo.getObjetoTipoServicoServicoCompleteWrappers(codOS, "D");
    for (ObjetoTipoServicoServicoCompleteWrapper wrapper : oldList) {
        servico = new OSServicoItem(wrapper, requireContext(), this);
        objGroup = new ExpandableGroup(servico, false);
        produtos = new ArrayList\<\>();
        garantias = new ArrayList\<\>();
        for (ProdutoServicoWithComodoProduto prod :             wrapper.produtoServicoWithComodoProdutos) {
            produtoItem = new OSServProdutoItem(prod, requireContext(), this);
            produtoDetalhes = new OSServProdutoDetalhes(prod, requireContext(), requireActivity(), codOS);
            prodGroup = new ExpandableGroup(produtoItem, false);
            prodGroup.add(produtoDetalhes);
            produtos.add(prodGroup);
            }
        for (GarantiaServicoClienteNewEntity garan :     wrapper.garantiaServicoClienteNewEntities) {
                garantiaItem = new OSServGarantiaItem(garan, requireContext());
                garantias.add(garantiaItem);
           }
            prodSection = new Section(new OSServProdBtn(this), produtos);
            garanSection = new Section(new OSServGaranBtn(this), garantias);
            objGroup.add(prodSection);
            objGroup.add(garanSection);
            adapter.add(objGroup);
    }
recyclerViewOS.setAdapter(adapter);
}

@Override
public void onSwiped(@Nullable ObjetoTipoServicoServicoCompleteWrapper objeto, @Nullable ProdutoServicoWithComodoProduto wrapper, int op) {
if (op == 0) {
SwipeToDelete swipeToDelete = new SwipeToDelete(0, ItemTouchHelper.LEFT, requireContext(), adapter, wrapper, null, oldList, requireActivity(), repo, op);
ItemTouchHelper itemTouchhelper = new ItemTouchHelper(swipeToDelete);
itemTouchhelper.attachToRecyclerView(recyclerViewOS);
} else {
SwipeToDelete swipeToDelete = new SwipeToDelete(0, ItemTouchHelper.LEFT, requireContext(), adapter, null, objeto, oldList, requireActivity(), repo, op);
ItemTouchHelper itemTouchhelper = new ItemTouchHelper(swipeToDelete);
itemTouchhelper.attachToRecyclerView(recyclerViewOS);
}
}
</code>```

Here's my ParentItem GestureHelper:

```<code>
public class GestureHelper implements View.OnTouchListener {

    private final GestureDetector mGestureDetector;
    private ObjetoTipoServicoServicoCompleteWrapper objeto;

    public GestureHelper(Context context, ObjetoTipoServicoServicoCompleteWrapper objeto) {
        mGestureDetector = new GestureDetector(context, new GestureListener(this));
        this.objeto = objeto;
    }

    public void onSwipeRight() {
    }

    public void onSwipeLeft() {
        onSwipe.onSwiped(objeto, null, 1);
    }

    public void onSwipeTop() {
    }

    public void onSwipeBottom() {
    }

    public void onDoubleTap() {
    }

    public void onClick() {
        expandableGroup.onToggleExpanded();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }

    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;
        private GestureHelper mHelper;

        public GestureListener(GestureHelper helper) {
            mHelper = helper;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            mHelper.onClick();
            return true;
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            mHelper.onDoubleTap();
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            mHelper.onSwipeRight();
                        } else {
                            mHelper.onSwipeLeft();
                        }
                    }
                } else {
                    if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffY > 0) {
                            mHelper.onSwipeBottom();
                        } else {
                            mHelper.onSwipeTop();
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return result;
        }
    }

}
</code>```

And finally my NestedItem GestureHelper:

```<code>
public class GestureHelper implements View.OnTouchListener {

    private final GestureDetector mGestureDetector;
    private ProdutoServicoWithComodoProduto wrapper;

    public GestureHelper(ProdutoServicoWithComodoProduto wrapper) {
        mGestureDetector = new GestureDetector(context, new GestureListener(this));
        this.wrapper = wrapper;
    }

    public void onSwipeRight() {
    }

    public void onSwipeLeft() {
        onSwipeProduto.onSwiped(null, wrapper, 0);
    }

    public void onSwipeTop() {
    }

    public void onSwipeBottom() {
    }

    public void onDoubleTap() {
    }

    public void onClick() {
        expandableGroup.onToggleExpanded();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }

    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;
        private GestureHelper mHelper;

        public GestureListener(GestureHelper helper) {
            mHelper = helper;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            mHelper.onClick();
            return true;
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            mHelper.onDoubleTap();
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            mHelper.onSwipeRight();
                        } else {
                            mHelper.onSwipeLeft();
                        }
                    }
                } else {
                    if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffY > 0) {
                            mHelper.onSwipeBottom();
                        } else {
                            mHelper.onSwipeTop();
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return result;
        }
    }

}
</code>```

Body:
I'm actually using Groupie library, and I'm trying to delete a nested item inside a group adapter.

But when I use ItemTouchHelper, it only deletes the parent items(Objetos) or the nested items(Produtos), basically the first one that I try to swipe. It attaches just one of the ItemTouchHelpers to my RecyclerView.

Here is my Fragment Code:

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

    metodos = new OSMetodos(requireContext(), requireActivity(), codOS);
    adapter = new GroupAdapter<>();

    adcTipoServ = view.findViewById(R.id.adcTipoServico);
    adcTipoServ.setOnClickListener(view1 -> metodos.addService());
    recyclerViewOS = view.findViewById(R.id.recyclerViewOSServ);
    recyclerViewOS.setLayoutManager(new LinearLayoutManager(requireContext()));
    setAdapter();

}

@Override
public void onResume() {
    super.onResume();
    setAdapter();
}

public void setAdapter() {
    oldList.clear();
    adapter.clear();
    oldList = repo.getObjetoTipoServicoServicoCompleteWrappers(codOS, "D");
    for (ObjetoTipoServicoServicoCompleteWrapper wrapper : oldList) {
        servico = new OSServicoItem(wrapper, requireContext(), this);
        objGroup = new ExpandableGroup(servico, false);
        produtos = new ArrayList\<\>();
        garantias = new ArrayList\<\>();
        for (ProdutoServicoWithComodoProduto prod :             wrapper.produtoServicoWithComodoProdutos) {
            produtoItem = new OSServProdutoItem(prod, requireContext(), this);
            produtoDetalhes = new OSServProdutoDetalhes(prod, requireContext(), requireActivity(), codOS);
            prodGroup = new ExpandableGroup(produtoItem, false);
            prodGroup.add(produtoDetalhes);
            produtos.add(prodGroup);
            }
        for (GarantiaServicoClienteNewEntity garan :     wrapper.garantiaServicoClienteNewEntities) {
                garantiaItem = new OSServGarantiaItem(garan, requireContext());
                garantias.add(garantiaItem);
           }
            prodSection = new Section(new OSServProdBtn(this), produtos);
            garanSection = new Section(new OSServGaranBtn(this), garantias);
            objGroup.add(prodSection);
            objGroup.add(garanSection);
            adapter.add(objGroup);
    }
recyclerViewOS.setAdapter(adapter);
}

@Override
public void onSwiped(@Nullable ObjetoTipoServicoServicoCompleteWrapper objeto, @Nullable ProdutoServicoWithComodoProduto wrapper, int op) {
if (op == 0) {
SwipeToDelete swipeToDelete = new SwipeToDelete(0, ItemTouchHelper.LEFT, requireContext(), adapter, wrapper, null, oldList, requireActivity(), repo, op);
ItemTouchHelper itemTouchhelper = new ItemTouchHelper(swipeToDelete);
itemTouchhelper.attachToRecyclerView(recyclerViewOS);
} else {
SwipeToDelete swipeToDelete = new SwipeToDelete(0, ItemTouchHelper.LEFT, requireContext(), adapter, null, objeto, oldList, requireActivity(), repo, op);
ItemTouchHelper itemTouchhelper = new ItemTouchHelper(swipeToDelete);
itemTouchhelper.attachToRecyclerView(recyclerViewOS);
}
}

Here's my ParentItem GestureHelper:

public class GestureHelper implements View.OnTouchListener {

    private final GestureDetector mGestureDetector;
    private ObjetoTipoServicoServicoCompleteWrapper objeto;

    public GestureHelper(Context context, ObjetoTipoServicoServicoCompleteWrapper objeto) {
        mGestureDetector = new GestureDetector(context, new GestureListener(this));
        this.objeto = objeto;
    }

    public void onSwipeRight() {
    }

    public void onSwipeLeft() {
        onSwipe.onSwiped(objeto, null, 1);
    }

    public void onSwipeTop() {
    }

    public void onSwipeBottom() {
    }

    public void onDoubleTap() {
    }

    public void onClick() {
        expandableGroup.onToggleExpanded();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }

    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;
        private GestureHelper mHelper;

        public GestureListener(GestureHelper helper) {
            mHelper = helper;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            mHelper.onClick();
            return true;
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            mHelper.onDoubleTap();
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            mHelper.onSwipeRight();
                        } else {
                            mHelper.onSwipeLeft();
                        }
                    }
                } else {
                    if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffY > 0) {
                            mHelper.onSwipeBottom();
                        } else {
                            mHelper.onSwipeTop();
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return result;
        }
    }

}

And finally my NestedItem GestureHelper:

public class GestureHelper implements View.OnTouchListener {

    private final GestureDetector mGestureDetector;
    private ProdutoServicoWithComodoProduto wrapper;

    public GestureHelper(ProdutoServicoWithComodoProduto wrapper) {
        mGestureDetector = new GestureDetector(context, new GestureListener(this));
        this.wrapper = wrapper;
    }

    public void onSwipeRight() {
    }

    public void onSwipeLeft() {
        onSwipeProduto.onSwiped(null, wrapper, 0);
    }

    public void onSwipeTop() {
    }

    public void onSwipeBottom() {
    }

    public void onDoubleTap() {
    }

    public void onClick() {
        expandableGroup.onToggleExpanded();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return mGestureDetector.onTouchEvent(event);
    }

    private final class GestureListener extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 100;
        private static final int SWIPE_VELOCITY_THRESHOLD = 100;
        private GestureHelper mHelper;

        public GestureListener(GestureHelper helper) {
            mHelper = helper;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            mHelper.onClick();
            return true;
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            mHelper.onDoubleTap();
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            mHelper.onSwipeRight();
                        } else {
                            mHelper.onSwipeLeft();
                        }
                    }
                } else {
                    if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffY > 0) {
                            mHelper.onSwipeBottom();
                        } else {
                            mHelper.onSwipeTop();
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return result;
        }
    }

}


来源: stackexchange

问:
how to write >1 file from a partition
First I wanted to spit a partition by a prefixed size, so I can update the file system. For example if a partition data size is 200MB(each row in the partition RDD can be different size), I want to write 4 files in that partition, each file 50MB, while trying to avoid shuffle. Is it possible to do that without a repartition or a coelesce which would cause shuffle? I dont have a fixed row size I cant really use the maxRecordsPerFile spark config.

Next option is to repartition the entire dataset causing shuffle. So to calculate the size I did the following, but it fails with: "Local variable numOfPartitions defined in an enclosing scope must be final or effectively final". what am I doing wrong. How can I fix this code?
...

```<code>int numOfPartitions = 1;
JavaRDD<String> tgg = xmlDataSet.toJavaRDD().mapPartitions ( xmlRows -> {
    long totalSize = 0;
    List<String> strLst = new ArrayList<String>();
    while (xmlRows.hasNext()) {
        String xmlString = xmlString = blobToString(xmlRows.next());
        totalSize = totalSize + xmlString.getBytes().length;
        strLst.add(xmlString);
        if (totalSize > 10000) {
            numOfPartitions++;
        }

    }
    return strLst.iterator();
});
</code>```

...

ContentLicense: CC BY-SA 4.0

Title: how to write >1 file from a partition

Body:
First I wanted to spit a partition by a prefixed size, so I can update the file system. For example if a partition data size is 200MB(each row in the partition RDD can be different size), I want to write 4 files in that partition, each file 50MB, while trying to avoid shuffle. Is it possible to do that without a repartition or a coelesce which would cause shuffle? I dont have a fixed row size I cant really use the maxRecordsPerFile spark config.

Next option is to repartition the entire dataset causing shuffle. So to calculate the size I did the following, but it fails with: "Local variable numOfPartitions defined in an enclosing scope must be final or effectively final". what am I doing wrong. How can I fix this code?
...

int numOfPartitions = 1;
JavaRDD<String> tgg = xmlDataSet.toJavaRDD().mapPartitions ( xmlRows -> {
    long totalSize = 0;
    List<String> strLst = new ArrayList<String>();
    while (xmlRows.hasNext()) {
        String xmlString = xmlString = blobToString(xmlRows.next());
        totalSize = totalSize + xmlString.getBytes().length;
        strLst.add(xmlString);
        if (totalSize > 10000) {
            numOfPartitions++;
        }

    }
    return strLst.iterator();
});

...


问:
Sort ACF Field Choices for Filters by Key Value
I've setup an ACF Select field to associate grades for each school program. Those grades can then be used to filter programs for the school by grade. The program finder page can be found here. The problem is that the order of the grades are incorrect.

What it is:

What it should be:

These are the settings for the ACF All Included Grades field I created:

I followed the documentation here to set the value of each of the choices by a numeric value. So PreK becomes 1 : PreK. The value of the choice becomes 1. This makes it easier for sorting.

I created this function to set the sort order of the choices to their given values, but it doesn't appear to be working.

```<code>        /* Sorting ACF Field Choices by Key Value*/
        add_filter('wpc_terms_before_display', 'wpc_sort_terms_as_needed', 10, 2);
        function wpc_sort_terms_as_needed($terms, $filter){
            // all_included_grades_for_filters - is desired ACF Field
            if ($filter['e_name'] === 'all_included_grades_for_filters') {
                $newTerms = [];
                $gradeField = get_field_object('all_included_grades_for_filters');
                $term = $gradeField['choices'];
                foreach ($terms as $k => $term) {
                    $termOrder = get_term_meta($term->value, 'order', true);
                    $term->menu_order = ($termOrder !== false) ? $termOrder : 0;
                    $newTerms[$k] = $term;
                }

                // To sort in descending order
                usort( $newTerms, \FilterEverything\Filter\EntityManager::compareDesc('menu_order') );
                // To sort in ascending order
                //usort($newTerms, \FilterEverything\Filter\EntityManager::compareAsc('menu_order'));

                return $newTerms;
            }

            return $terms;
        }
</code>```

Any guidance on what I should change here would be helpful.

Body:
I've setup an ACF Select field to associate grades for each school program. Those grades can then be used to filter programs for the school by grade. The program finder page can be found here. The problem is that the order of the grades are incorrect.

What it is:

What it should be:

These are the settings for the ACF All Included Grades field I created:

I followed the documentation here to set the value of each of the choices by a numeric value. So PreK becomes 1 : PreK. The value of the choice becomes 1. This makes it easier for sorting.

I created this function to set the sort order of the choices to their given values, but it doesn't appear to be working.

        /* Sorting ACF Field Choices by Key Value*/
        add_filter('wpc_terms_before_display', 'wpc_sort_terms_as_needed', 10, 2);
        function wpc_sort_terms_as_needed($terms, $filter){
            // all_included_grades_for_filters - is desired ACF Field
            if ($filter['e_name'] === 'all_included_grades_for_filters') {
                $newTerms = [];
                $gradeField = get_field_object('all_included_grades_for_filters');
                $term = $gradeField['choices'];
                foreach ($terms as $k => $term) {
                    $termOrder = get_term_meta($term->value, 'order', true);
                    $term->menu_order = ($termOrder !== false) ? $termOrder : 0;
                    $newTerms[$k] = $term;
                }

                // To sort in descending order
                usort( $newTerms, \FilterEverything\Filter\EntityManager::compareDesc('menu_order') );
                // To sort in ascending order
                //usort($newTerms, \FilterEverything\Filter\EntityManager::compareAsc('menu_order'));

                return $newTerms;
            }

            return $terms;
        }

Any guidance on what I should change here would be helpful.


问:
spaCy cannot find method add_label for EntityRecognizer class in python
I want to update the entity recognizer in spaCy with an own example. After getting the instance of the Named Entity Recognizer pipeline component I want to call the method add_label() on it:

```<code>import spacy

nlp = spacy.load('en_core_web_sm')
ner = nlp.get_pipe('ner')
ner.add_label()
</code>```

I cannot call add_label(), because it Cannot find reference 'add_label' in 'Pipe | Pipe. I first thought that add_label() might be deprecated in spaCy v3, but the docs implies that it is not. The pipeline also includes the ner component:

```<code>print(nlp.pipe_names)
output: ['tok2vec', 'tagger', 'parser', 'attribute_ruler', 'lemmatizer', 'ner']
</code>```

Further informations:

spaCy version 3.4.3

Pipelines en_core_web_sm (3.4.1)

Python version 3.10.4

Does anyone have an idea why I cannot call add_label() on the EntityRecognizer?

Update: Seems to be a problem with PyCharm (17.0.5+1-b653.14 x86_64). Cannot reproduce the issue using VS Code.

Body:
I want to update the entity recognizer in spaCy with an own example. After getting the instance of the Named Entity Recognizer pipeline component I want to call the method add_label() on it:

import spacy

nlp = spacy.load('en_core_web_sm')
ner = nlp.get_pipe('ner')
ner.add_label()

I cannot call add_label(), because it Cannot find reference 'add_label' in 'Pipe | Pipe. I first thought that add_label() might be deprecated in spaCy v3, but the docs implies that it is not. The pipeline also includes the ner component:

print(nlp.pipe_names)
output: ['tok2vec', 'tagger', 'parser', 'attribute_ruler', 'lemmatizer', 'ner']

Further informations:

spaCy version 3.4.3

Pipelines en_core_web_sm (3.4.1)

Python version 3.10.4

Does anyone have an idea why I cannot call add_label() on the EntityRecognizer?

Update: Seems to be a problem with PyCharm (17.0.5+1-b653.14 x86_64). Cannot reproduce the issue using VS Code.


问:
Trying to wrap my head around observer class
I'm trying to understand an observer class, but I don't understand how to implement it in practice.

I have a class that has 4 functions in relation to a .txt database- add student, delete student, sort and show student database, and search a student. I want it to send out an automatic message to all students when another student is added or deleted.

This is what I have so far, based off a guide I've been looking at:

```<code>class ObservableEvent:
    def __init__(self):
        self.students = []

    def register_student(self, student):
        self.students.append(student)

    def notify_allStudents(self, *args, **kwargs):
        for student in self.students:
            student.notify(self, *args, **kwargs)

class Observer:
    def __init__(self, observable):
        observable.register_student(self)

    def notify(self, message, observable):
        print("Got", message, "From", observable)

subject = ObservableEvent()
student = Observer(subject)
</code>```

I think its just the last part I'm having the biggest issue with (I hope), concerning the notify_allStudents part. Whenever I try to pass more than 1 positional argument, it doesn't work. So far I have this:

```<code>class Student():

    def __init__(self, data):
        self.data = data
    pass

    def AddStudent(self, data):

        firstName = input('First Name: ')
        lastName = input("\nLast Name: ")
        email = input('\nEmail Address: ')
        campus = input('\nCampus: ')

        year = '22'

        generated_id = firstName[0:3] + lastName[0:3] + year

        newStudent = [generated_id, firstName, lastName, email, campus]

        f = open(data, "a")
        f.write('\n')
        for info in newStudent:
            f.write(info)
            f.write('\t')
        f.close()
        pass
</code>```

Then here is where I have the above ObserverEvent and Observer classes.
And here is the rest:

```<code>ans=True
while ans:
    print ("""
    ---------------------------------------------------
    Welcome to the QUICK SORT / LINEAR SEARCH Program

    1.ADD NEW STUDENT
    2.DELETE STUDENT
    3.SHOW STUDENTS
    4.SEARCH STUDENT
    5.ADD COURSE TO STUDENT
    Type EXIT to quit the application
    """)

    ans=input("What would you like to do? ")

    if ans=="1":
        print("""
        *******************

        STUDENT ADD MENU

        *******************
        """)

        Student.AddStudent(input, "studentMockData_AS2.txt")
        print("\nStudent Added")
        subject.notify_allStudents("A student has been added to the database.")
</code>```

I'm currently getting this in the console: Got <__main__.ObservableEvent object at 0x00000154909BB460> From A student has been added to the database.

I'm honestly really lost on this. The example I was given was subject.notify_observers("test", kw="python"), but the *args and **kwargs are really throwing me. It throws an error of too many positional arguments if I include more than 1, but I thought the whole point of kwargs was to input more than 1. I'm also not sure why I would need to use a dict in this scenario. I don't even understand what I'm not understanding about this, but clearly I'm not doing it right. Any assistance would be hugely appreciated.

EDIT: I'm aware that my class Student is badly done, but I have to leave it as is.

Body:
I'm trying to understand an observer class, but I don't understand how to implement it in practice.

I have a class that has 4 functions in relation to a .txt database- add student, delete student, sort and show student database, and search a student. I want it to send out an automatic message to all students when another student is added or deleted.

This is what I have so far, based off a guide I've been looking at:

class ObservableEvent:
    def __init__(self):
        self.students = []

    def register_student(self, student):
        self.students.append(student)

    def notify_allStudents(self, *args, **kwargs):
        for student in self.students:
            student.notify(self, *args, **kwargs)

class Observer:
    def __init__(self, observable):
        observable.register_student(self)

    def notify(self, message, observable):
        print("Got", message, "From", observable)

subject = ObservableEvent()
student = Observer(subject)

I think its just the last part I'm having the biggest issue with (I hope), concerning the notify_allStudents part. Whenever I try to pass more than 1 positional argument, it doesn't work. So far I have this:

class Student():

    def __init__(self, data):
        self.data = data
    pass

    def AddStudent(self, data):

        firstName = input('First Name: ')
        lastName = input("\nLast Name: ")
        email = input('\nEmail Address: ')
        campus = input('\nCampus: ')

        year = '22'

        generated_id = firstName[0:3] + lastName[0:3] + year

        newStudent = [generated_id, firstName, lastName, email, campus]

        f = open(data, "a")
        f.write('\n')
        for info in newStudent:
            f.write(info)
            f.write('\t')
        f.close()
        pass

Then here is where I have the above ObserverEvent and Observer classes.
And here is the rest:

ans=True
while ans:
    print ("""
    ---------------------------------------------------
    Welcome to the QUICK SORT / LINEAR SEARCH Program

    1.ADD NEW STUDENT
    2.DELETE STUDENT
    3.SHOW STUDENTS
    4.SEARCH STUDENT
    5.ADD COURSE TO STUDENT
    Type EXIT to quit the application
    """)

    ans=input("What would you like to do? ")

    if ans=="1":
        print("""
        *******************

        STUDENT ADD MENU

        *******************
        """)

        Student.AddStudent(input, "studentMockData_AS2.txt")
        print("\nStudent Added")
        subject.notify_allStudents("A student has been added to the database.")

I'm currently getting this in the console: Got <__main__.ObservableEvent object at 0x00000154909BB460> From A student has been added to the database.

I'm honestly really lost on this. The example I was given was subject.notify_observers("test", kw="python"), but the *args and **kwargs are really throwing me. It throws an error of too many positional arguments if I include more than 1, but I thought the whole point of kwargs was to input more than 1. I'm also not sure why I would need to use a dict in this scenario. I don't even understand what I'm not understanding about this, but clearly I'm not doing it right. Any assistance would be hugely appreciated.

EDIT: I'm aware that my class Student is badly done, but I have to leave it as is.


问:
Get GCLID thru Measurement Protocol
Is it possible to pull users GCLID thru the Measurment Protocol? I found this docs https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters but not sure if they reference exact params

I tried hitting the endpoint but I'm not seeing the param

Title: Get GCLID thru Measurement Protocol


问:
How do I get custom fonts to work on matplotlib via OSx?
I am trying to install a font for matplotlib, and am running in to trouble trying to get matplotlib to find it.

via font_manager

```<code>from matplotlib import font_manager
font_manager.findSystemFonts(fontpaths=None, fontext = 'ttf')
</code>```

yields all system (and user fonts).

with font_manager.findfont('my_font'), it returns nothing, despite the font being listed from the findSystemFonts function, and I can't quite figure out why.

I tried clearing the cache and reloading, but that didn't resolve anything.

Could it be due to the location of

System/Library/Fonts/not_the_font_i_want.ttf vs
Users/my_name/Library/Fonts/font_i_do_want.ttf?

If so, how would I get that to register on OSx?

Thank you in advance.

Edit: I don't understand why this isn't working

```<code>from matplotlib import font_manager
font_manager.findSystemFonts(fontpaths='/Users/my_name/Library/Fonts/', fontext="ttf")
</code>```

Output: ['/Users/my_name/Library/Fonts/Proxima Soft Bold.ttf']

```<code>font_manager.findfont("Proxima Soft Bold.ttf", directory = '/Users/my_name/Library/Fonts/')
</code>```

Output: findfont: Font family ['Proxima Soft Bold.ttf'] not found. Falling back to DejaVu Sans.

Body:
I am trying to install a font for matplotlib, and am running in to trouble trying to get matplotlib to find it.

via font_manager

from matplotlib import font_manager
font_manager.findSystemFonts(fontpaths=None, fontext = 'ttf')

yields all system (and user fonts).

with font_manager.findfont('my_font'), it returns nothing, despite the font being listed from the findSystemFonts function, and I can't quite figure out why.

I tried clearing the cache and reloading, but that didn't resolve anything.

Could it be due to the location of

System/Library/Fonts/not_the_font_i_want.ttf vs
Users/my_name/Library/Fonts/font_i_do_want.ttf?

If so, how would I get that to register on OSx?

Thank you in advance.

Edit: I don't understand why this isn't working

from matplotlib import font_manager
font_manager.findSystemFonts(fontpaths='/Users/my_name/Library/Fonts/', fontext="ttf")

Output: ['/Users/my_name/Library/Fonts/Proxima Soft Bold.ttf']

font_manager.findfont("Proxima Soft Bold.ttf", directory = '/Users/my_name/Library/Fonts/')

Output: findfont: Font family ['Proxima Soft Bold.ttf'] not found. Falling back to DejaVu Sans.


问:
Random Search hyperparameter tuning shows 'NameError: name 'x' is not defined'
I am trying to solve minimize optimization problem with 'Random Search' and 'Simulated Annealing' method. I have written the functions, although the bounds are not defined.

```<code>def min_f(x):
    x= [[x1],
        [x2],
        [x3],
        [x4]]
    return 1.10471*(x1**2)*x2+0.04811*x3*x4*(14.0+x2)
</code>```

Now, I tried Random search and tried hyper-parameter tuning with following lines of code,

```<code># define hyper-paramters
number_of_samples = 1000
lower_bound = np.array([0.125,5])
upper_bound = np.array([0.1,10])
res = random_search(min_f, number_of_samples,
                    lower_bound, upper_bound,
                    fargs=(x))
</code>```

The line shows following error

```<code>NameError                                 Traceback (most recent call last)
<ipython-input-75-84d31b22940c> in <module>
      5 res = random_search(min_f, number_of_samples,
      6                     lower_bound, upper_bound,
----> 7                     fargs=(x))

NameError: name 'x' is not defined
</code>```

What could be appropriate to solve this issue?

I tried changing the format of x and also it says, the value should be iterable. I hope I could know if I should be using x in fargs.

Body:
I am trying to solve minimize optimization problem with 'Random Search' and 'Simulated Annealing' method. I have written the functions, although the bounds are not defined.

def min_f(x):
    x= [[x1],
        [x2],
        [x3],
        [x4]]
    return 1.10471*(x1**2)*x2+0.04811*x3*x4*(14.0+x2)

Now, I tried Random search and tried hyper-parameter tuning with following lines of code,

# define hyper-paramters
number_of_samples = 1000
lower_bound = np.array([0.125,5])
upper_bound = np.array([0.1,10])
res = random_search(min_f, number_of_samples,
                    lower_bound, upper_bound,
                    fargs=(x))

The line shows following error

NameError                                 Traceback (most recent call last)
<ipython-input-75-84d31b22940c> in <module>
      5 res = random_search(min_f, number_of_samples,
      6                     lower_bound, upper_bound,
----> 7                     fargs=(x))

NameError: name 'x' is not defined

What could be appropriate to solve this issue?

I tried changing the format of x and also it says, the value should be iterable. I hope I could know if I should be using x in fargs.


问:
Text not aligning to bootstrap 5 checkboxes inside modal
Problem
I have the following HTML which is inside the modal, but although the checkboxes are left justified the associated text (labels) remain centred:

Options

    <input class="form-check-input" type="checkbox" value="" id="flexCheckChecked1" checked>
    Option 1

AND

    <input class="form-check-input" type="checkbox" value="" id="flexCheckChecked2" checked>
    Option 2

OR

    <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault1">
    Option 3

OR

    <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault2">
    Option 4

```
</div>
</div>
</p>
<p>The CSS I have is as follows, which I thought would have aligned the label text to the left (like the .modal-body-text) so it appears adjacent to the associated checkboxes:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.form-check-input {
    display: inline-block;
    text-align: left;
}

.form-check-label {
    display: inline-block;
    text-align: left;
}

.modal-body-text{
    text-align: left;
    display: block;
    margin-block-start: 1em;
    margin-block-end: 1em;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    color: black;
}</code>```

You can see what the current output is and what needs to be achieved here...

Suggestions on how to fix welcomed. Thanks in advance

Body:
Problem
I have the following HTML which is inside the modal, but although the checkboxes are left justified the associated text (labels) remain centred:

Options

    <input class="form-check-input" type="checkbox" value="" id="flexCheckChecked1" checked>
    Option 1

AND

    <input class="form-check-input" type="checkbox" value="" id="flexCheckChecked2" checked>
    Option 2

OR

    <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault1">
    Option 3

OR

    <input class="form-check-input" type="checkbox" value="" id="flexCheckDefault2">
    Option 4

The CSS I have is as follows, which I thought would have aligned the label text to the left (like the .modal-body-text) so it appears adjacent to the associated checkboxes:

.form-check-input {
    display: inline-block;
    text-align: left;
}

.form-check-label {
    display: inline-block;
    text-align: left;
}

.modal-body-text{
    text-align: left;
    display: block;
    margin-block-start: 1em;
    margin-block-end: 1em;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    color: black;
}

You can see what the current output is and what needs to be achieved here...

Suggestions on how to fix welcomed. Thanks in advance


问:
This App is blocked error while extracting lifetime refresh token using OAuth Playground to supply to Azure Google Adwords linked service connector
While authorizing my Google Ads Account using OAuth Playground to retrieve a lifetime refresh token which could used to further create access tokens, the authorization is throwing This app is blocked security error. I think this is because the GCP OAuth consent screen is not verified. But how do I verify my OAuth consent screen when I don't have an App domain name, since I'm using this as a one time activity to retrieve my refresh token using OAuth Playground?


问:
I am looking for suggestions for better way of writing my code as I know its not too efficient program gets votes and adds to count
At the bottom I am working on the function vote, which when accessing candidates[i].name and making it equal to the input (name) for ex. ./plurality (name of the file) Alice bob jones and then inputting for name = Alice, it returns false rather than following the line candidates[0].name = Alice == name therefore adding to the vote count.

I am struggling to understand why it goes through my if statement from i = 0 to i = 50ish and doesn't equate Alice to  Alice. Sorry if this is noob question I appreciate any help!

```<code>#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Max number of candidates
#define MAX 9

// Candidates have name and vote count
typedef struct
{
    string name;
    int votes;
}
candidate;

// Array of candidates
candidate candidates[MAX];

// Number of candidates
int candidate_count;

// Function prototypes
bool vote(string name);
void print_winner(void);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: plurality [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
    }

    int voter_count = get_int("Number of voters: ");

    // Loop over all voters
    for (int i = 0; i < voter_count; i++)
    {
        string name = get_string("Vote: ");

        // Check for invalid vote
        if (!vote(name))
        {
            printf("Invalid vote.\n");
        }
    }

    // Display winner of election
    print_winner();
}

// Update vote totals given a new vote
bool vote(string name)               // this is the part *** im confused about
{
    // TODO
    //printf("%s\n", name);
    //printf("%s\n", candidates[0].name);
    for (int j = 0; j < sizeof(candidates); j++)
    {
        if (candidates[j].name == name)
        {
            candidates[j].votes = candidates[j].votes + 1;
            return true;
        }
    }
    printf("%i\n", candidates[0].votes);
    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    // TODO
    return;
}
</code>```

Printing multiple times and using a while loop however using a while loop led to the problem of having a name not in the candidates array at all and therefore running infinitely.

Body:
At the bottom I am working on the function vote, which when accessing candidates[i].name and making it equal to the input (name) for ex. ./plurality (name of the file) Alice bob jones and then inputting for name = Alice, it returns false rather than following the line candidates[0].name = Alice == name therefore adding to the vote count.

I am struggling to understand why it goes through my if statement from i = 0 to i = 50ish and doesn't equate Alice to  Alice. Sorry if this is noob question I appreciate any help!

#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Max number of candidates
#define MAX 9

// Candidates have name and vote count
typedef struct
{
    string name;
    int votes;
}
candidate;

// Array of candidates
candidate candidates[MAX];

// Number of candidates
int candidate_count;

// Function prototypes
bool vote(string name);
void print_winner(void);

int main(int argc, string argv[])
{
    // Check for invalid usage
    if (argc < 2)
    {
        printf("Usage: plurality [candidate ...]\n");
        return 1;
    }

    // Populate array of candidates
    candidate_count = argc - 1;
    if (candidate_count > MAX)
    {
        printf("Maximum number of candidates is %i\n", MAX);
        return 2;
    }
    for (int i = 0; i < candidate_count; i++)
    {
        candidates[i].name = argv[i + 1];
        candidates[i].votes = 0;
    }

    int voter_count = get_int("Number of voters: ");

    // Loop over all voters
    for (int i = 0; i < voter_count; i++)
    {
        string name = get_string("Vote: ");

        // Check for invalid vote
        if (!vote(name))
        {
            printf("Invalid vote.\n");
        }
    }

    // Display winner of election
    print_winner();
}

// Update vote totals given a new vote
bool vote(string name)               // this is the part *** im confused about
{
    // TODO
    //printf("%s\n", name);
    //printf("%s\n", candidates[0].name);
    for (int j = 0; j < sizeof(candidates); j++)
    {
        if (candidates[j].name == name)
        {
            candidates[j].votes = candidates[j].votes + 1;
            return true;
        }
    }
    printf("%i\n", candidates[0].votes);
    return false;
}

// Print the winner (or winners) of the election
void print_winner(void)
{
    // TODO
    return;
}

Printing multiple times and using a while loop however using a while loop led to the problem of having a name not in the candidates array at all and therefore running infinitely.


问:
Where are the “range” and “functional” aspects of ActivityPub properties defined?
Activity Vocabulary has tables which indicate several aspects (meta-properties?) of each property defined in Activity Streams 2.0. These aspects include:

functional — is it single-value, or not?

range — indicates the type of value the property term can have

subproperty of — meaning that the term is a specialization of the referenced term

Here's a good example.

I haven't been able to find something like this for the properties added by ActivityPub.

For example, take following. The ActivityPub Recommendation says:

A link to an [ActivityStreams] collection of the actors that this actor is following; see 5.4 Following Collection

...

Every actor SHOULD have a following collection. This is a list of everybody that the actor has followed, added as a side effect. The following collection MUST be either an OrderedCollection or a Collection and MAY be filtered on privileges of an authenticated user or as appropriate when no authentication is given.

And that's just about it. Based on the above, I would have thought the range was Collection (like it is for replies), but looking at the examples and data returned by a Mastodon instance, I see the following property being set like this:

"following": "https://example.org/users/johndoe/following",
```

So what's the correct range for the following property?

Also, can an Object have multiple values for following, or is it "functional"?

In general, where are these aspects of all of the ActivityPub properties defined?

Body:
Activity Vocabulary has tables which indicate several aspects (meta-properties?) of each property defined in Activity Streams 2.0. These aspects include:

functional — is it single-value, or not?

range — indicates the type of value the property term can have

subproperty of — meaning that the term is a specialization of the referenced term

Here's a good example.

I haven't been able to find something like this for the properties added by ActivityPub.

For example, take following. The ActivityPub Recommendation says:

A link to an [ActivityStreams] collection of the actors that this actor is following; see 5.4 Following Collection

...

Every actor SHOULD have a following collection. This is a list of everybody that the actor has followed, added as a side effect. The following collection MUST be either an OrderedCollection or a Collection and MAY be filtered on privileges of an authenticated user or as appropriate when no authentication is given.

And that's just about it. Based on the above, I would have thought the range was Collection (like it is for replies), but looking at the examples and data returned by a Mastodon instance, I see the following property being set like this:

"following": "https://example.org/users/johndoe/following",

So what's the correct range for the following property?

Also, can an Object have multiple values for following, or is it "functional"?

In general, where are these aspects of all of the ActivityPub properties defined?


问:
Spring using different Quartz job-store when running same code
tl;dr: Is there a way, in Spring / Java code using Quartz, to specify which job-store class gets used? This says to use this set property org.quartz.jobStore.class (e.g., =org.quartz.simpl.RAMJobStore) - but setting that doesn't seem to work for me.

My application uses Spring-Boot for its REST API and includes a process that uses Quartz for some scheduled jobs.

When I start up the api (mvn spring-boot:run), the log shows that it's using LocalDataSourceJobStore
for its job-store:

```<code>Using job-store 'org.springframework.scheduling.quartz.LocalDataSourceJobStore'
- which supports persistence. and is not clustered.
</code>```

But another dev on our team runs the same application and the startup log shows his instance is using RAMJobStore for its job-store:

```<code>Using job-store 'org.quartz.simpl.RAMJobStore'
- which does not support persistence. and is not clustered.
</code>```

Everything else in our logs is the same. This discrepancy between our instances occurs despite the fact that we're running the same code, with the same pom.xml, thus the same dependencies. This is confirmed by running mvn dependency:tree, which shows our dependencies match, including these the ones relevant to Quartz:

```<code>...
[INFO] \- org.springframework.boot:spring-boot-starter-quartz:jar:2.6.8:compile
[INFO]    +- org.springframework:spring-context-support:jar:5.3.20:compile
[INFO]    \- org.quartz-scheduler:quartz:jar:2.3.2:compile
[INFO]       \- com.mchange:mchange-commons-java:jar:0.2.15:compile
...
</code>```

I'm stumped as to why Spring-Boot chooses a different job-store class between our two identical instances. Is there any explanation for why this would happen when we're running the exact same app with the exact same code, including pom.xml?

The only difference between the 2 of us is that I run on Windows, whereas the other dev runs on Linux. Could the different OS cause Spring to choose different dependencies? Or could something else cause this?

Finding a way to specify the job-store class used would put us on the same page in terms of expecting the same behavior. (The instance that uses RAMJobStore throws errors, which could perhaps be attributed to the different job-store.)

(I tried excluding the spring-context-support jar within my pom to see if that forces Spring to choose RamJobStore, but that breaks the app, as other classes in that package are needed.)

Body:
tl;dr: Is there a way, in Spring / Java code using Quartz, to specify which job-store class gets used? This says to use this set property org.quartz.jobStore.class (e.g., =org.quartz.simpl.RAMJobStore) - but setting that doesn't seem to work for me.

My application uses Spring-Boot for its REST API and includes a process that uses Quartz for some scheduled jobs.

When I start up the api (mvn spring-boot:run), the log shows that it's using LocalDataSourceJobStore
for its job-store:

Using job-store 'org.springframework.scheduling.quartz.LocalDataSourceJobStore'
- which supports persistence. and is not clustered.

But another dev on our team runs the same application and the startup log shows his instance is using RAMJobStore for its job-store:

Using job-store 'org.quartz.simpl.RAMJobStore'
- which does not support persistence. and is not clustered.

Everything else in our logs is the same. This discrepancy between our instances occurs despite the fact that we're running the same code, with the same pom.xml, thus the same dependencies. This is confirmed by running mvn dependency:tree, which shows our dependencies match, including these the ones relevant to Quartz:

...
[INFO] \- org.springframework.boot:spring-boot-starter-quartz:jar:2.6.8:compile
[INFO]    +- org.springframework:spring-context-support:jar:5.3.20:compile
[INFO]    \- org.quartz-scheduler:quartz:jar:2.3.2:compile
[INFO]       \- com.mchange:mchange-commons-java:jar:0.2.15:compile
...

I'm stumped as to why Spring-Boot chooses a different job-store class between our two identical instances. Is there any explanation for why this would happen when we're running the exact same app with the exact same code, including pom.xml?

The only difference between the 2 of us is that I run on Windows, whereas the other dev runs on Linux. Could the different OS cause Spring to choose different dependencies? Or could something else cause this?

Finding a way to specify the job-store class used would put us on the same page in terms of expecting the same behavior. (The instance that uses RAMJobStore throws errors, which could perhaps be attributed to the different job-store.)

(I tried excluding the spring-context-support jar within my pom to see if that forces Spring to choose RamJobStore, but that breaks the app, as other classes in that package are needed.)


问:
When trying to automate several downloads with python and MegaCMD "Mega-get" command does not finish downloading the file
i'm trying to automate the processing of videos I have on Mega using MegaCMD with python.

The idea is for my computer to download a video locally, process it, and then upload the file to my Mega account.

Im having some trouble with downloading the video through the subprocess command in PowerShell. The download never seems to complete until I close the MegaCMD server using the Windows Task Manager. After that the file type ".getxfer.4528.1.mega" becomes the video. But the idea is to be able to automate the process as i don't have enough space to store all the videos on my computer.

Here is my code in jupyter-notebook:

```<code>import subprocess
link = 'https://mega.nz/file/...'
cmds = ['$env:PATH += ";$env:LOCALAPPDATA\MEGAcmd"','mega-get '+link]
encoding = 'latin1'
p = subprocess.Popen('powershell.exe', stdin=subprocess.PIPE,
             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for cmd in cmds:
    p.stdin.write(cmd.encode("utf-8") + b"\n")
p.stdin.close()
print(p.stdout.read())
</code>```
```<code></code>```

If anyone has any ideas on how to fix the problem it would be a great help!

Note: I dont use the Mega library of python because the videos contain sensitive research material and the account has double 2AF authentication and the library does not have the option to access it that way. Thats why im using Mega

Body:
i'm trying to automate the processing of videos I have on Mega using MegaCMD with python.

The idea is for my computer to download a video locally, process it, and then upload the file to my Mega account.

Im having some trouble with downloading the video through the subprocess command in PowerShell. The download never seems to complete until I close the MegaCMD server using the Windows Task Manager. After that the file type ".getxfer.4528.1.mega" becomes the video. But the idea is to be able to automate the process as i don't have enough space to store all the videos on my computer.

Here is my code in jupyter-notebook:

import subprocess
link = 'https://mega.nz/file/...'
cmds = ['$env:PATH += ";$env:LOCALAPPDATA\MEGAcmd"','mega-get '+link]
encoding = 'latin1'
p = subprocess.Popen('powershell.exe', stdin=subprocess.PIPE,
             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
for cmd in cmds:
    p.stdin.write(cmd.encode("utf-8") + b"\n")
p.stdin.close()
print(p.stdout.read())

If anyone has any ideas on how to fix the problem it would be a great help!

Note: I dont use the Mega library of python because the videos contain sensitive research material and the account has double 2AF authentication and the library does not have the option to access it that way. Thats why im using Mega


问:
allure report gives different total test cases count?
I have a Jenkins job that everyday at 12:00 AM, it checks out the regression test cases from our git repository and have them executed, and the allure report will be generated in the end. There are total 250 test cases, and the number is fixed as always.

But in some execution session, the generated allure report says there are total 252, 260, or even 280 test cases being executed.

What could be wrong for this number keep changing.

Thanks,

Chun


问:
Im really confused as to why Im getting an error here
I just dont understand why this wont run

```<code>import tkinter as tk

# Create the main window
root = tk.Tk()
root.title("Sign-up")

# Create the username and password labels and text fields
tk.Label(root, text="Username:").grid(row=0, column=0)
username_entry = tk.Entry(root)
username_entry.grid(row=0, column=1)

tk.Label(root, text="Password:").grid(row=1, column=0)
password_entry = tk.Entry(root, show="*")
password_entry.grid(row=1, column=1)

# Create the submit button
submit_button = tk.Button(root, text="Submit", command=write_to_file)
submit_button.grid(row=2, column=0, columnspan=2)

# Create the write_to_file function
def write_to_file():
    username = username_entry.get()
    password = password_entry.get()

    # Open the file in write mode
    with open("users.txt", "a") as file:
        file.write(f"{username},{password}\n")

    # Clear the text fields
    username_entry.delete(0, tk.END)
    password_entry.delete(0, tk.END)

# Start the program
root.mainloop()
</code>```

My IDE says there is an error on line 17 but im not sure what it is.
I have tried to run through debugging but I simply dont understand what is incorrect.

Body:
I just dont understand why this wont run

import tkinter as tk

# Create the main window
root = tk.Tk()
root.title("Sign-up")

# Create the username and password labels and text fields
tk.Label(root, text="Username:").grid(row=0, column=0)
username_entry = tk.Entry(root)
username_entry.grid(row=0, column=1)

tk.Label(root, text="Password:").grid(row=1, column=0)
password_entry = tk.Entry(root, show="*")
password_entry.grid(row=1, column=1)

# Create the submit button
submit_button = tk.Button(root, text="Submit", command=write_to_file)
submit_button.grid(row=2, column=0, columnspan=2)

# Create the write_to_file function
def write_to_file():
    username = username_entry.get()
    password = password_entry.get()

    # Open the file in write mode
    with open("users.txt", "a") as file:
        file.write(f"{username},{password}\n")

    # Clear the text fields
    username_entry.delete(0, tk.END)
    password_entry.delete(0, tk.END)

# Start the program
root.mainloop()

My IDE says there is an error on line 17 but im not sure what it is.
I have tried to run through debugging but I simply dont understand what is incorrect.


问:
How can I find a word and select the following input?
Is there a way to select the input following a given word?
For example, findInputAfter("Firstname") returns input 1 and findInputAfter("Lastaname") returns input 2.

This is to fill an online form that contains no label.

Thanks!

```<code><div id="form-with-simple-text-instead-of-label-before-the-input-field">
Firstname: <input type="text" name="1" />
Lastname: <input type="text" name="2" />
</div>
</code>```

PS : This is not my website and I can't access the source code so I can't add label or id to form...

Body:
Is there a way to select the input following a given word?
For example, findInputAfter("Firstname") returns input 1 and findInputAfter("Lastaname") returns input 2.

This is to fill an online form that contains no label.

Thanks!

Firstname: <input type="text" name="1" />
Lastname: <input type="text" name="2" />

PS : This is not my website and I can't access the source code so I can't add label or id to form...


问:
JMM: Observable Behavior and Nonterminating Executions
Can someone explain to me the meaning of 17.4.9. Observable Behavior and Nonterminating Executions.

What I understand (kind of):

this section exists because of the programs which never terminate:

For programs that always terminate in some bounded finite period of time, their behavior can be understood (informally) simply in terms of their allowable executions. For programs that can fail to terminate in a bounded amount of time, more subtle issues arise.

if a thread blocks indefinitely then no external action that goes after the place in the code should be executed:

An execution may result in a thread being blocked indefinitely and the execution's not terminating. In such cases, the actions generated by the blocked thread must consist of all actions generated by that thread up to and including the action that caused the thread to be blocked, and no actions that would be generated by the thread after that action.

To be honest, even with the above, I don't understand why this section exists.

For example, I don't understand what would break if the section was removed.

Also I don't understand why the rest of the JMM is not enough for nonterminating executions.


问:
Error "Feature rpath [...]" on building Qt6 project with CMake
I'm using Ubuntu 22.04 and Qt6 dev libs available on repo.
I've successfully configured a simple C++ project using Qt5 under Visual Source Code with a CMakeLists.txt.
Unfortunately, no luck with Qt6. I'm having the following error:

```<code>[cmake] CMake Error at /usr/lib/x86_64-linux-gnu/cmake/Qt6/QtFeature.cmake:1212 (message):
[cmake]   Feature rpath is already defined to be "ON" and should now be set to "OFF"
[cmake]   when importing features from Qt6::Core.
[cmake] Call Stack (most recent call first):
[cmake]   /usr/lib/x86_64-linux-gnu/cmake/Qt6Core/Qt6CoreConfig.cmake:128 (qt_make_features_available)
[cmake]   /usr/lib/x86_64-linux-gnu/cmake/Qt6/Qt6Config.cmake:219 (find_package)
[cmake]   CMakeLists.txt:10 (find_package)
</code>```

This is my CMakeLists.txt, according to Qt6 online documentation:

```<code>cmake_minimum_required(VERSION 3.16)
project(qt6_test01 VERSION 0.1.0 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

include(CTest)
enable_testing()

find_package(Qt6 REQUIRED COMPONENTS Core)
qt_standard_project_setup()

add_executable(qt6_test01 main.cpp)

target_link_libraries(qt6_test01 PRIVATE Qt6::Core)

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)
</code>```

Googling "Feature rpath [...] set to "OFF"" doesn't give any relevant result.

Anyone already experienced this?

Followed Qt6 CMake doc: https://doc.qt.io/qt-6/cmake-get-started.html
Also tried to reinstall qt6-base-dev package
Still the same error!

Body:
I'm using Ubuntu 22.04 and Qt6 dev libs available on repo.
I've successfully configured a simple C++ project using Qt5 under Visual Source Code with a CMakeLists.txt.
Unfortunately, no luck with Qt6. I'm having the following error:

[cmake] CMake Error at /usr/lib/x86_64-linux-gnu/cmake/Qt6/QtFeature.cmake:1212 (message):
[cmake]   Feature rpath is already defined to be "ON" and should now be set to "OFF"
[cmake]   when importing features from Qt6::Core.
[cmake] Call Stack (most recent call first):
[cmake]   /usr/lib/x86_64-linux-gnu/cmake/Qt6Core/Qt6CoreConfig.cmake:128 (qt_make_features_available)
[cmake]   /usr/lib/x86_64-linux-gnu/cmake/Qt6/Qt6Config.cmake:219 (find_package)
[cmake]   CMakeLists.txt:10 (find_package)

This is my CMakeLists.txt, according to Qt6 online documentation:

cmake_minimum_required(VERSION 3.16)
project(qt6_test01 VERSION 0.1.0 LANGUAGES CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

include(CTest)
enable_testing()

find_package(Qt6 REQUIRED COMPONENTS Core)
qt_standard_project_setup()

add_executable(qt6_test01 main.cpp)

target_link_libraries(qt6_test01 PRIVATE Qt6::Core)

set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)

Googling "Feature rpath [...] set to "OFF"" doesn't give any relevant result.

Anyone already experienced this?

Followed Qt6 CMake doc: https://doc.qt.io/qt-6/cmake-get-started.html
Also tried to reinstall qt6-base-dev package
Still the same error!


问:
What are the updates that wp_auto_update_core refers to?
My website is created with WordPress and as part of the Site Health Status report I see two critical problems regarding wp_auto_update_core:

Error The wp_auto_update_core constant is defined as false

WordPress security and maintenance releases are blocked by define( 'wp_auto_update_core', false );.

On the WordPress Website I have read that:

"In WordPress, there are four types of automatic background updates:
Core updates
Plugin updates
Theme updates
Translation file updates"

So the problems 1) and 2) that appear in my Site Health Status have to do with the automatic updating of WordPress, not with the update of plugins or themes, right? and Problem 1) and 2) refer to the same thing?

Thanks


问:
unknown type name "Engine"
I am getting an error:

```<code>engine/renderer/render.h:8:19: error: unknown type name ‘Engine’
    8 | void initRenderer(Engine* engine);
      |                   ^~~~~~
</code>```

Even though I have defined the type Engine and included it in the render.h file

app.h:

#pragma once

#include <defines.h>

#include <string.h>
#include <GLFW/glfw3.h>

#include <containers/vector.h>

typedef struct Engine {
    uint16 w;
    uint16 h;
    GLFWwindow* window;
    int backend;
    Vector entities;
    char* name;

    void* (*Update)();
    void* (*onStart)();
} Engine;
```
<p>render.h:</p>
<pre class="lang-c prettyprint-override"><code>#pragma once

#include <defines.h>

#include <renderer/backend/vulkan.h>
#include <app.h>

void initRenderer(Engine* engine);
</code>```

I have included <app.h> in the include directory of the project with -I and it works in all other files

Title: unknown type name "Engine"

Body:
I am getting an error:

engine/renderer/render.h:8:19: error: unknown type name ‘Engine’
    8 | void initRenderer(Engine* engine);
      |                   ^~~~~~

Even though I have defined the type Engine and included it in the render.h file

app.h:

#pragma once

#include <defines.h>

#include <string.h>
#include <GLFW/glfw3.h>

#include <containers/vector.h>

typedef struct Engine {
    uint16 w;
    uint16 h;
    GLFWwindow* window;
    int backend;
    Vector entities;
    char* name;

    void* (*Update)();
    void* (*onStart)();
} Engine;

render.h:

#pragma once

#include <defines.h>

#include <renderer/backend/vulkan.h>
#include <app.h>

void initRenderer(Engine* engine);

I have included <app.h> in the include directory of the project with -I and it works in all other files


问:
how to define swagger header to prevent empty or null value
I have the following below headers in my OpenAPI 2.0 definition,

```<code>  {
    "name": "key",
    "in": "header",
    "description": "v4 UUID ",
    "required": true,
    "type": "string",
    "format": "uuid",
    "x-example": "d1257cae-9814-90d0-89e0-abd9ae7b3375"
  }

</code>```

the below was generated one, it has required = true but not @valid. how to get @valid for headers since its allows me with null or empty value.

```<code>Mono<ResponseEntity<JResponse>> makeX(
        @Parameter(
        @Parameter(name = "idempotency-key", description = "v4 UUID ", required = true) @RequestHeader(value = "key",
         @Valid @RequestBody TnsRequest tnsRequest ,
        @Parameter(hidden = true) final ServerWebExchange exchange
    );
</code>```

I understand required = true just for validating the header and not for the value. when no header it returns 400.

400 BAD_REQUEST "Missing request header 'key'

Body:
I have the following below headers in my OpenAPI 2.0 definition,

  {
    "name": "key",
    "in": "header",
    "description": "v4 UUID ",
    "required": true,
    "type": "string",
    "format": "uuid",
    "x-example": "d1257cae-9814-90d0-89e0-abd9ae7b3375"
  }

the below was generated one, it has required = true but not @valid. how to get @valid for headers since its allows me with null or empty value.

Mono<ResponseEntity<JResponse>> makeX(
        @Parameter(
        @Parameter(name = "idempotency-key", description = "v4 UUID ", required = true) @RequestHeader(value = "key",
         @Valid @RequestBody TnsRequest tnsRequest ,
        @Parameter(hidden = true) final ServerWebExchange exchange
    );

I understand required = true just for validating the header and not for the value. when no header it returns 400.

400 BAD_REQUEST "Missing request header 'key'


问:
Python, drawing a polyline to a color detector code using webcam
I'm using Python3 and OpenCV (4.6.0) to realize a script that:

detects a specific color tone (green) and draw (with the use of the polyline) the path followed by the green object during the use of the webcam.

calculates the distance traveled by the object.

So far, I'm trying:

```<code>import numpy as np
import cv2
from math import dist

cap = cv2.VideoCapture(0)
distance=0
distcm=0
centroide={}
mask={}
centroide[0]=(0,0)
i=1

while True:
    ret, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    lower_green = np.array([50, 50, 50])
    upper_green = np.array([70, 255, 255])

    mask = cv2.inRange(hsv, lower_green, upper_green)
    result = cv2.bitwise_and(frame, frame, mask=mask)
    contourns,hierarchy = cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    cont_sorted = sorted(contourns, key=cv2.contourArea, reverse=True)[:5]
    for each in contourns:
        area= cv2.contourArea(each)
        if len(cont_sorted) > 0 and area>300 :
            x,y,w,h = cv2.boundingRect(cont_sorted[0])
            centroide[i]=[x+(w/2), y+(h/2)]
            distance+= dist(centroide[i],centroide[i-1])
            cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),5)
            mask=cv2.line(frame,(int(centroide[i-1][0]), int(centroide[i-1][1])),(int(centroide[i][0]),int(centroide[i][1])),(255,0,0),5)
            #mask=cv2.polylines(frame,np.int32(np.array(centroide)),(255,0,0),5)
            i=i+1
    cv2.imshow('orig',frame)
    distancecm=distance*0.0264583333;
    print('distancia en cm:',distancecm)

    if cv2.waitKey(30) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
</code>```

With the previous code what it does is only to create a line between one centroid and another but the line of previous centroids does not remain static to observe the path of the object. Any suggestions?
Thanks

LJ

Body:
I'm using Python3 and OpenCV (4.6.0) to realize a script that:

detects a specific color tone (green) and draw (with the use of the polyline) the path followed by the green object during the use of the webcam.

calculates the distance traveled by the object.

So far, I'm trying:

import numpy as np
import cv2
from math import dist

cap = cv2.VideoCapture(0)
distance=0
distcm=0
centroide={}
mask={}
centroide[0]=(0,0)
i=1

while True:
    ret, frame = cap.read()
    hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
    lower_green = np.array([50, 50, 50])
    upper_green = np.array([70, 255, 255])

    mask = cv2.inRange(hsv, lower_green, upper_green)
    result = cv2.bitwise_and(frame, frame, mask=mask)
    contourns,hierarchy = cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    cont_sorted = sorted(contourns, key=cv2.contourArea, reverse=True)[:5]
    for each in contourns:
        area= cv2.contourArea(each)
        if len(cont_sorted) > 0 and area>300 :
            x,y,w,h = cv2.boundingRect(cont_sorted[0])
            centroide[i]=[x+(w/2), y+(h/2)]
            distance+= dist(centroide[i],centroide[i-1])
            cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),5)
            mask=cv2.line(frame,(int(centroide[i-1][0]), int(centroide[i-1][1])),(int(centroide[i][0]),int(centroide[i][1])),(255,0,0),5)
            #mask=cv2.polylines(frame,np.int32(np.array(centroide)),(255,0,0),5)
            i=i+1
    cv2.imshow('orig',frame)
    distancecm=distance*0.0264583333;
    print('distancia en cm:',distancecm)

    if cv2.waitKey(30) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

With the previous code what it does is only to create a line between one centroid and another but the line of previous centroids does not remain static to observe the path of the object. Any suggestions?
Thanks

LJ


问:
__dirname always returns "/" no matter which file I console log it out
```<code>console.log("__dirname: ", __dirname);
</code>```

no matter which file or nested file I place the above code in, it always logs "/".

Body:
console.log("__dirname: ", __dirname);

no matter which file or nested file I place the above code in, it always logs "/".


问:
microsoft visual c++ 2005 and 2008 Installation error
I am trying to install microsoft visual c++ 2005 and 2008 but it gives error 1935. What are the methods to fix it?

I tried reintalling files but not from official webstie, but it is still not working.


问:
How to create the connection string for a database generated with pgAdmin4
I developed my app with SQLAlchemy testing it on an SQLite database.
Now I would like to testing more using PostgreSQL but in a localhost once again.
For this reason, I tried to create a local Postgre database with pdAdmin4 (my laptop has Windows 7 so I installed the v4 version of the database manager).

Now I am trying to generate the connection string for this Postgre database but I cannot understand how to do it.

This is what I created in pgAdmin4:

while the details of the server are these:

The connection string I am trying to use is this:

selected_engine = create_engine('postgresql+psycopg2://postgres:123@localhost/test_server/test_database')

The password 123 is the password I set at the first access to pgdAmin4.
However, I got this error:

OperationalError: (psycopg2.OperationalError) connection to server at "localhost" (::1), port 5432 failed: FATAL:  database "test_server/test_database" does not exist

I am sure I am wrong and I cannot figure out what is the correct URL for my database.


问:
How to render items using alternating colors based on the items.id in nextjs
When rendering a list of data, I need to return it with 2 different colors, for example: the first item background color should be white, and the second items should be gray.
This is what I tried

```<code>`
<div className={`cursor-pointer w-full my-1 ${event.id % 2 === 0 ? 'bg-white' : 'bg-gray50'}` } >
`
</code>```

It only works if the item id is odd, otherwise it does not work.
I would appreciate any suggestions you may have

Body:
When rendering a list of data, I need to return it with 2 different colors, for example: the first item background color should be white, and the second items should be gray.
This is what I tried

`
<div className={`cursor-pointer w-full my-1 ${event.id % 2 === 0 ? 'bg-white' : 'bg-gray50'}` } >
`

It only works if the item id is odd, otherwise it does not work.
I would appreciate any suggestions you may have