Extension methods vs. Static Class Methods

I’ve taken on a Visual Studio C# project where my previous colleague used a lot of Extension Methods in static classes over multiple files depending on the uses.

In my previous experience I would be more selective when using Extension methods but instead use a public static method in a static class.

It got me thinking if one is better than the other or does it really just come down to flavor or an industry standard that I am unaware of?

Thanks,

iterator class using generator function

It is sometimes necessary for a generator function to expose state. In those situations it is advised to wrap the generator function as method __iter__ in a class. Here is an example:

class C:     def __init__(self):         self.next = self.__iter__().__next__     def __iter__(self):         for i in range(4):             yield i                         self.state = i 

It is convenient to use this in a for loop since the for loop will call iter() on the object, however, the object itself is not an iterator, so you cannot do this:

c = C() print(next(c)) 

Which is inconvenient. To get around this inconvenience I have come up with the following class:

class C:     def __init__(self):         self.next = self.__iter__().__next__     def __iter__(self):         for i in range(4):             yield i                         self.state = i     def __next__(self):         return self.next() 

Usage example:

c = C() while 1:     try:         num = next(c)         print(num)         if num == 2:             print("state:", c.state)     except Exception:         break 

Is this the best way to design the class? I haven’t seen this technique used anywhere else so I’m wondering why everyone else isn’t using it, since the C objects can be used both as iterators and as iterables.

Include class oop php

Мне не совсем понятен один момент с ООП. Если я использую абстрактный класс, и пытаюсь в него подгрузить сторонний класс (не extends), находящийся в другом файле и делаю это через __construct, то мне выводится ошибка, Class 'Foo' not found in ... А вот если подключаюсь к файлу в нужном методе, то все ок. Просто выглядит не очень красиво, если использовать по 10 раз в одном файле подключение к одному и тому же файлу, для 10 разных методов. Возможно ли использовать одно подключение в __construct-е?

Покажу на примере. Вот такой код выведет ошибку:

abstract class Name {     public function __construct () {         require_once 'Foo.php';     }      public function func1 () {         $  foo = new Foo;          // ..     }      public function func2 () {         $  foo = new Foo;          // ..     }      // и т.д. } 

А вот этот пример отлично отработает:

abstract class Name {     public function __construct () {         // ..     }      public function func1 () {         require_once 'Foo.php';         $  foo = new Foo;          // ..     }      public function func2 () {         require_once 'Foo.php';         $  foo = new Foo;          // ..     }      // и т.д. } 

Подскажите пожалуйста, в чем собственно причина?

Designing a Bit and Byte manipulation class for QT


The situation

I am porting a legacy library from CoDeSys to QT. As I frequently have to deal with hardware related stuff like CAN messages (or other stuff), that contain a byte field for payload, I used a well-working class in the legacy system that allows for a nice manipulation of bits and bytes. As a base I used a stupid array of bytes over there to store the bytes. I had numerous methods like GetBoolOnBit(), SetRawByte(), SetByteOnBit(), SetU32() and stuff like that to provide a very well-typed access to the storage.

I started to bring similar functionality to my QT library and am looking for some feedback on my approach. I want to store the Data in a QByteArray (unless no one has a better suggestion) and I have written two basic methods to access the data, namely setByteOnBit() as well as getByteOnBit().

My concern(s)

Overall, handling of bits and bytes does look a bit complicated to me at the moment. I am not really unhappy with my code so far but where in CoDeSys I simply had to do some stupid bit shifting here and there, in Qt I need a slightly higher amount of lines of code. Maybe you have suggestions to thin my code a bit.

Code

Note that the code does not contain any input guards regarding sizes so far. This is intended as I first wanted to show my working outcome.

mybytecollection.h

#ifndef MYBYTECOLLECTION_H #define MYBYTECOLLECTION_H  #include "myutilities_global.h"  class UTILSLIBSHARED_EXPORT MyByteCollection { public:     MyByteCollection(const int size);     ~MyByteCollection();      int size();      bool setByteOnBit(const int bitPosition, const quint8 value);     quint8 getByteOnBit(const int bitPosition);  private:     QByteArray* mBa = nullptr; };  #endif // MYBYTECOLLECTION_H 

mybytecollection.cpp

#include "mybytecollection.h" #include <QBitArray> #include <QDataStream>  MyByteCollection::MyByteCollection(const int size) {     mBa = new QByteArray(size, 0x00); }  MyByteCollection::~MyByteCollection() {     delete mBa;     mBa = nullptr; }  int MyByteCollection::size() {     return mBa != nullptr ? mBa->size() : 0; }  bool MyByteCollection::setByteOnBit(const int bitPosition, const quint8 value) {     if (mBa != nullptr) {         // bit manipulation in 16 bits to fit in. Manipulate two bitarrays and finally re-inserting         int byteIndex = bitPosition / 8;         int bitPositionInBitArray = bitPosition % 8;         QByteArray workingBytes(mBa->mid(byteIndex, 2));         quint16 mask = static_cast<unsigned short>(0xFFFFFFFF);         mask >>= bitPositionInBitArray;         mask <<= 8;         mask >>= 8 - bitPositionInBitArray;         mask = ~mask;          quint16 bits = value;         bits <<= bitPositionInBitArray;          // weird shifting, unable to shift the whole QbyteArray         quint16 lowByte = static_cast<quint16>(workingBytes[0]);         quint16 highByte = static_cast<quint16>(workingBytes[1]);         lowByte >>= bitPositionInBitArray;         highByte <<= 8 - bitPositionInBitArray;         quint16 result = static_cast<quint16>(lowByte | highByte);         result &= mask;         result |= bits;          workingBytes.clear();         QDataStream out(&workingBytes, QIODevice::WriteOnly | QIODevice::Append);         out.setByteOrder(QDataStream::LittleEndian);         out << result;         mBa->replace(byteIndex, 2, workingBytes);         return true;     }     return false; }  quint8 MyByteCollection::getByteOnBit(const int bitPosition) {     if (mBa != nullptr) {          // getting 16 bits from bytes and shifting magic to finally return a byte         int byteIndex = bitPosition / 8;         int bitPositionInBitArray = bitPosition % 8;         QByteArray workingBytes(mBa->mid(byteIndex, 2));          // weird shifting, unable to shift the whole QbyteArray         quint16 lowByte = static_cast<quint16>(workingBytes[0]);         quint16 highByte = static_cast<quint16>(workingBytes[1]);         lowByte >>= bitPositionInBitArray;         highByte <<= 8 - bitPositionInBitArray;         quint16 result = static_cast<quint16>(lowByte | highByte);         return static_cast<quint8>(result);     }     return 0; } 

Base class for implementing IComparable

If I create a class that implements IComparable<T>, I must implement CompareTo<T>. It is also recommended that I implement IEquatable<T> and the non-generic IComparable. If I do all that, I am required or encouraged to:

  • Override GetHashCode()
  • Implement CompareTo(Object)
  • Override Equals(Object)
  • Implement Operator ==(T, T)
  • Implement Operator !=(T, T)
  • Implement Operator >(T, T)
  • Implement Operator <(T, T)
  • Implement Operator >=(T, T)
  • Implement Operator <=(T, T)

That’s 9 additional methods, most of which depend on the logic that compares two instances of the class. Rather than having to implement all those methods in any class that implements IComparable<T>, I decided to create a base class that implements IComparable<T> and the other recommended interfaces (similar to the way Microsoft provides Comparer as a base class for implementations of IComparer<T>)

It doesn’t make sense to compare instances of two different classes that each inherit from the base class. preventing that was the main reason for making the class generic (although it makes coding a derived class a little more complicate).

I would like to ask for a review of the code for the base class. Am I missing something? Can it be simplified? Is this a bad idea?

Here is the base class

public abstract class Comparable<T> : IComparable, IComparable<T>, IEquatable<T> where T: Comparable<T> {     public abstract override int GetHashCode();      public abstract int CompareTo(T other);      public int CompareTo(object obj) {         T other = obj as T;         if (other == null && obj != null) {             throw new ArgumentException($  "Objects of type {typeof(T).Name} can only be compared to objects of the same type", nameof(obj));         }         return CompareTo(other);     }      public override bool Equals(object obj) {         return CompareTo(obj) == 0;     }      new public bool Equals(T other) {         return CompareTo(other) == 0;     }      private static int Compare(Comparable<T> comp1, Comparable<T> comp2) {         if (comp1 == null) {             return ((comp2 == null) ? 0 : -1);         }         return comp1.CompareTo(comp2);     }      public static bool operator == (Comparable<T> comp1, Comparable<T> comp2) {         return Compare(comp1, comp2) == 0;     }      public static bool operator != (Comparable<T> comp1, Comparable<T> comp2) {         return Compare(comp1, comp2) != 0;     }      public static bool operator > (Comparable<T> comp1, Comparable<T> comp2) {         return Compare(comp1, comp2) > 0;     }      public static bool operator < (Comparable<T> comp1, Comparable<T> comp2) {         return Compare(comp1, comp2) < 0;     }      public static bool operator >= (Comparable<T> comp1, Comparable<T> comp2) {         return Compare(comp1, comp2) >= 0;     }      public static bool operator <= (Comparable<T> comp1, Comparable<T> comp2) {         return Compare(comp1, comp2) <= 0;     } } 

Below is a minimal implementation of the base class.

public class SeasonCompare : Comparable<SeasonCompare> {     public int Number {get; set;}      public override int GetHashCode() {         return Number;     }      public override int CompareTo(SeasonCompare other) {         if (other == null) {             return 1;         }         return Number.CompareTo(other.Number);     } } 

Do the class vector and character vector of a $p$-group determine each other?

To a finite $ p$ -group, we can associate two vectors $ (v_0,v_1,\dotsc)$ :

  1. The class vector – $ v_i$ is the number of conjugacy classesof order $ p^i$ .

  2. The character vector – $ v_i$ is the number of complex irreducible representations of dimension $ i$ up to isomorphism.

Question: Do these two invariants of the group determine each other? In other words, if two groups have the same class vector, do they have the same character vector and vice versa?

Getting “this class is not key value coding-compliant for the key backGroundView.'” when adding view from xib to scrollview


Getting error while adding subView

add ScrollView is for creating scrollview

  func addScrollView() {     self.scrollView.frame = CGRect(x: 0, y: 150, width: self.view.bounds.size.width, height: height)     self.scrollView.contentSize = CGSize(width: height * 3, height: self.view.bounds.size.width)     scrollView.isPagingEnabled = true     scrollView.backgroundColor = .orange     self.view.addSubview(scrollView)      var y = CGFloat(0.0)      for i in 0..<24 {         let customView = self.createCustomView(index: i)         customView.frame = CGRect(x: 0, y: y, width: 320, height: 200)         self.scrollView.addSubview(customView)          y += height     } } 

Here create custom view function is used to add custom subviews according to loop

func createCustomView(index: Int) -> UIView {      let eventView: EventView = Bundle.main.loadNibNamed("EventView", owner: self, options: nil)![0] as! EventView      if index == 0{         eventView.backgroundColor = UIColor.green     }      if index == 1{         eventView.backgroundColor = UIColor.red     }      return eventView } 

Deciding complexity class of a TM s.t M(0) = accept

Below is a sample of 2 homework TM where Im not sure what complexity class they fit in. Also have to decide the complexity class of the complement. These 2 in particular confuse me because I got a different answer so I feel I may be missing something:

S = { : M is a TM s.t. M(0) = accept} U = { : M is a TM s.t. M(0)[20000] = accept}

The options are P, NP, coNP, EXP, Decidable, Recognizable, lang (all strings).

S: I read this as ‘M checks if the input is 0, if yes accept’. My first instinct is that S is in P as it simply checks the if the input is 0 which is a single operation, so I would say it can be solved in polynomial time. Someone else decided RE for S and lang for S complement respectively, which I just dont understand if correct.

U: I read this same as S, but runs (to a maximum of?) 2000 steps. I’d also place this in P for both U and its complement. Other answer is P as well but I don’t see how the addendum of 2000 makes a difference.

Thanks for any clarification.

Hints about analyzing single (huge) C# class using SonarQube and related issues

I’m doing an internship into a small company which is working on part of a systems which runs on a base already written by another company (many company are working on the same project) which is basically a 1:1 translation from an old COBOL system into .NET technology. Since they have not been given enough time, they’re literally running producing as much working code as possible, so the code quality is not elevated. The objective of my internship is to produce a graduate thesis following my work in this little company, and will be based on refactoring some functions or classes (between those being developed in this small company) following the baselines of software engineering (patterns mainly), the branch to whom my thesis is related.

To underline the results of this work, my professor told me to use a static code analyzer such SonarQube or Kiuwan, I already configured and hosted on Amazon AWS a functioning SonarQube 7.4 server.

At this point of my work the question is: how can I analyze just this single class alone? Pro and Cons.

I’m in front of 2 choices:

1) Create a project in Visual Studio to make this class self-sustaining full of stubs and mocks to make it live by itself with the pourpose of being analyzed before and after the re-engineering.

–> The main issue with this option is that this class on which I am working is made of about 12000 lines of code, so it’s easy to think that it refers to many many other classes, thus creating stubs and mocks would be a pain…

2) Use an integrated feature in SonarQube, which should let exclude whole folders or analyze just selected files/folders.

–> I already analyzed the whole project, made of about 350k lines of code using the default SonarQube rules, it gave me a result in everyone of it’s fields (quality, bugs, security…), the problem is that even modifing and making this class (on which I am working) a diamond of engeneering, it wouldn’t change much the overall quality of the software (obviously).

The structure:

The project has three indipendent branches: Backend, Client, and DB communications, I’m working in the Backend part.

The Backend got its own .sln file (the one I used for the whole analysis of the project in SonarQube), which links to .csproj subprojects. I feeded SonarQube one of these .csproj and it was able to analyze it.

Applying option 2 :

In the Sonar server in the preferences of the project, there’s a tab in which you can exclude what you DON’T want to be analyzed and INCLUDE JUST what you want to analyze. Since I was interested in the second option, I inserted in the field sonar.inclusions the name of the class I want to be analyzed, then I builded the project, sent the blob to SonarQube server, which analyzed it and…nothing happened, in the project page of Sonar just appeared “No project Analyzed yet”.

So my questions are:

Question 1) Should I follow this way of analyzing a single class with SonarQube? By directly feeding it from the original bug project, or is it better to extract the class, place it into a new project and fulfill it with stubs and mocks? Considering the complexity of doing this.

Question 2) Following what I wrote above, how can make sonar analyze just the class I feeded? Is practically possible to do it? What did I do wrong?

I posted the same question to stackoverflow, but they told me to post it here!

Thanks in advance for all the help you will give me!

PHP Class – get current request

my first question at stackoverflow:

I have a class that loads JSON data.

I request data from outside the class with eg:

echo $ class->country->name

echo $ class->country->timezone

echo $ class->country->population

Now I need to check if the requested properties do exist and if there is a valid value. As there are hundreds of properties I try to find a way to check the requested properties (country, name – country, timezone – country, population) per request within the class.

Thank you, harry_bo