【Rust】型エイリアス(type)

fn main(){

    let x = 123;
    println!("{}", type_of(x));
}

fn type_of<T>(_: T) -> &'static str {
    std::any::type_name::<T>()
}

c++だと、typeid

#include <iostream>
#include <typeinfo>

struct Base {};
struct Derived : public Base {};

struct PolyBase {virtual void member(){}};
struct PolyDerived : public PolyBase {};


int main() {
    int i;
    int* pi;
    std::cout << "int is: " << typeid(int).name() << std::endl;
    std::cout << "i is: " << typeid(i).name() << std::endl;
    std::cout << "pi is: " << typeid(pi).name() << std::endl;
    std::cout << "*pi is: " << typeid(*pi).name() << std::endl;
    std::cout << std::endl;

    Derived derived;
    Base *pbase = &derived;
    std::cout << "derived is: " << typeid(derived).name() << std::endl;
    std::cout << "*pbase is: " << typeid(*pbase).name() << std::endl;
    std::cout << std::boolalpha << "same type? " << (typeid(derived) == typeid(*pbase)) << std::endl;
    std::cout << std::endl;

    PolyDerived polyderived;
    PolyBase* ppolybase = &polyderived;
    std::cout << "polyderived is: " << typeid(polyderived).name() << std::endl;
    std::cout << "*ppolybase is: " << typeid(*ppolybase).name() << std::endl;
    std::cout << std::boolalpha << "same type? " << (typeid(polyderived) == typeid(*ppolybase)) << std::endl;
}
fn main(){
    let i = 10;
    let j = 3.14;
    println!("{}", type_of(i));
    println!("{}", type_of(j));
}

fn type_of<T>(_: T) -> &'static str {
    std::any::type_name::<T>()
}

derivedは派生。rustはclassがなくstructとimplなので、baseとderivedという概念があるか不明。。

【Rust】スライス


fn main(){
    let s = String::from("ABCDEFGH");
    let s1 = &s[0..3];
    let s2 = &s[3..6];
    println!("{} {}", s1, s2);


}

c++でsliceはないので、関数で書いている場合

#include <iostream>
#include <vector>

template<typename T>
void print(std::vector<T> const &v)
{
    for (auto i: v) {
        std::cout << i << ' ';
    }
    std::cout << std::endl;
}

template<typename T>
std::vector<T> slice(std::vector<T> const &v, int m, int n)
{
    auto first = v.cbegin() + m;
    auto last = v.cbegin() + n + 1;

    std::vector<T> vec(first, last);
    return vec;
}

int main()
{
    std::vector<int> v = {1, 2, 3, 4, 2, 2, 4, 6, 5};

    int m = 4, n = 7;
    std::vector<int> sub_vec = slice(v, m, n);
    print(sub_vec);
    return 0;
}
fn print(v: Vec<i32>) {
    for &i in & v {
        print!("{} ", &i);
    }
    print!("\n");
}

fn slicing(v: Vec<i32>, m: i32, n: i32) -> Vec<i32>
{
    let vec = &v[m..n];
    return vec.to_vec();
}

fn main(){
    let mut vect = vec![1, 2, 3, 4, 2, 2, 4, 6, 5];
    let v = slicing(vect, 4, 7);
    print(v);
}

>> slice indices are of type `usize` or ranges of `usize`

これでなぜ引数i32がエラーになるか理解できん…

[shell] コマンドを実行する

シェルでのコマンドの実行はevalで実行する

command="echo hoge"
eval $command

$ ./test.sh
hoge

終了コードで処理を変える

command="echo hoge"
eval $command

retval=$?

if [ $retval -eq 0 ]
then
    echo "成功しました!"
else
    echo "失敗しました"
fi

これをechoではなく、bitcoin-core.cli –getinfoにします。

command="bitcoin-core.cli --getinfo"
eval $command

retval=$?

if [ $retval -eq 0 ]
then
    echo "成功しました!"
else
    echo "失敗しました"
fi

値が1の時に起動するように書けばよさそうですね。

[bitcoin] Berkeley DB

Bitcoincoreで使用されているBerkeley DBについて

– Cで記述されたソフトウェアライブラリ
– Key/value API
– SQL APIとしてSQLiteが組み込まれている
– Bツリー、ハッシュ、キュー、RECNOストレージ
– C++, Java/JNI, C#, Python, Perlなど
– Java Direct Persistence Layer
– JavaコレクションAPI
– レプリケーション
– Berkeley DB is not a relational database, although it has database features including database transactions, multiversion concurrency control and write-ahead logging. BDB runs on a wide variety of operating systems including most Unix-like and Windows systems, and real-time operating systems.
– SQLのようなデータ操作言語を持たず、データベースへのアクセスは全てサブルーチン呼び出しによって行う。しかしdbmとは異なり、データ操作機能にトランザクションやレプリケーションに対応するインタフェースが備わっている
– Berkeley DB本体が対応するプログラミング言語はCおよびC++だけだが、Perl、Python、Tcl他多くの言語にバインディングが用意されており、それらから容易に利用することができる。

概要はわかったので、使い方ですな。

Pythonで有限体

ecc.py

class FieldElement:
    
    def __init__(self, num, prime):
        if num >= prime or num < 0:
            error = 'Num {} not in field range 0 to {}'.format(num, prime - 1)
            raise ValueError(error)
        self.num = num
        self.prime = prime

    def __repr__(self):
        return 'FieldElement_{}({})'.format(self.prime, self.num)

    def __eq__(self, other):
        if other is None:
            return False
        return self.num == other.num and self.prime == other.prime

main.py

from ecc import FieldElement
a = FieldElement(7, 13)
b = FieldElement(6, 13)
print(a==b)
print(a==a)

Pythonの__eq__メソッド

__eq__メソッド は等価の条件を定める

class Person:

    def __init__(self, firstname, lastname, email):
        self.firstname = firstname
        self.lastname = lastname
        self.email = email

    def __eq__(self, other):
        if other is None or not isinstance(other, Person): return False

        return self.firstname == other.firstname and \
            self.lastname == other.lastname and \
            self.email == other.email

    def __ne__(self, other):
        return not self.__eq__(other)
    

mike = Person('Mike', 'Peter', 'mike@gmail.com')
peter = Person('Mike', 'Peter', 'mike@gmail.com')
print(mike)
print(peter)
print(mike == peter)

eqの他にも、lt, ne, le, gt, geなどがある。

class Item(object):

    def __init__(self, price):
        self.price = price

    def __eq__(self, other):
        if not isinstance(other, Item):
            return NotImplemented
        return self.price == other.price

    def __lt__(self, other):
        if not isinstance(other, Item):
            return NotImplemented
        return self.price < other.price
    
    def __ne__(self, other):
        return not self.__eq__(other)

    def __le__(self, other):
        return self.__lt__(other) or self.__eq__(other)
    
    def __gt__(self, other):
        return not self.__le__(other)
    
    def __ge__(self, other):
        return not self.__lt__(other)

【Flutter】バリデーション その2

class MyCustomFormState extends State<MyCustomForm>{
  final _formKey = GlobalKey<FormState>();
  final textValidator = MultiValidator([
    RequiredValidator(errorText: '入力必須の項目です。'),
    MinLengthValidator(8, errorText: '8文字以上で入力してください。'),
  ]);

  @override
  Widget build(BuildContext context){
    return Form(
      key: _formKey,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          TextFormField(
                  validator: textValidator,
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 16.0),
            child: ElevatedButton(
              onPressed:() {
                if(_formKey.currentState!.validate()){
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('送信完了')),
                  );
                }
              },
              child: const Text('送信'),
            )
          )
        ]
      )
    );
  }
}

【flutter】グラフィック描画のイベント処理

class _MyHomePageState extends State<MyHomePage>{
  static List<Offset> _points = [];

  @override
  void initState(){
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromARGB(255, 255,255,255),
      appBar: AppBar(
        title: Text('App Name', style: TextStyle(fontSize: 30.0),),
      ),
      body: Center(
        child: Listener(
          onPointerDown: _addPoint,
          child: CustomPaint(
            painter: MyPainter(_points),
            child: Center(),
          ),
        ),
      )
    );
  }
  void _addPoint(PointerDownEvent event) {
    setState((){
      _points.add(event.localPosition);
    });
  }
}

class MyPainter extends CustomPainter {
  final List<Offset> _points;

  MyPainter(this._points);

  @override
  void paint(Canvas canvas, Size size){
    Paint p = Paint();

    p.style = PaintingStyle.fill;
    p.color = Color.fromARGB(100, 0, 200, 100);
    for(var pos in _points) {
      Rect r = Rect.fromLTWH(pos.dx - 25, pos.dy - 25, 50.0, 50.0);
      canvas.drawOval(r, p);
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

UIウィジェットで操作

class _MyHomePageState extends State<MyHomePage>{
  static double _value = 0;
  static double _opaq = 0;

  @override
  void initState(){
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromARGB(255, 255,255,255),
      appBar: AppBar(
        title: Text('App Name', style: TextStyle(fontSize: 30.0),),
      ),
      body: Column(
        children: [
          Padding(padding: EdgeInsets.all(10)),
          Container(
            width: 300,
            height: 300,
            child: CustomPaint(
              painter: MyPainter(_value, _opaq.toInt()),
              child: Center(),
            ),
          ),
          Slider(
            min: 0.0,
            max: 300.0,
            value:_value,
            onChanged: _changeVal,
          ),
          Slider(
            min:0.0,
            max:255.0,
            value:_opaq,
            onChanged: _changeOpaq,
          ),
        ],
      ),
    );
  }
  void _changeVal(double value) {
    setState((){
      _value = value;
    });
  }
  void _changeOpaq(double value) {
    setState((){
      _opaq = value;
    });
  }
}

class MyPainter extends CustomPainter {
  final double _value;
  final int _opaq;

  MyPainter(this._value, this._opaq);

  @override
  void paint(Canvas canvas, Size size){
    Paint p = Paint();

    p.style = PaintingStyle.fill;
    p.color = Color.fromARGB(_opaq, 0, 200, 100);
    Rect r = Rect.fromLTWH(
        (size.width - _value) / 2,
        (size.height - _value) / 2,
      _value, _value);
    canvas.drawOval(r, p);

    r = Rect.fromLTWH(0, 0, size.width, size.height);
    p.style = PaintingStyle.stroke;
    p.color = Color.fromARGB(255, 100, 100, 100);
    canvas.drawRect(r, p);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

ValueNotifierによる更新

class _MyHomePageState extends State<MyHomePage>{
  static ValueNotifier<int> _value = ValueNotifier<int>(0);

  @override
  void initState(){
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromARGB(255, 255,255,255),
      appBar: AppBar(
        title: Text('App Name', style: TextStyle(fontSize: 30.0),),
      ),
      body: Center(
        child:Column(
          children: [
            Padding(padding: EdgeInsets.all(10)),
            Container(
              width: 300,
              height: 300,
              child: CustomPaint(
                painter: MyPainter(_value),
                child: Center(),
              ),
            ),
            Padding(padding: EdgeInsets.all(5)),
            ElevatedButton(
              child: Text("Click",
              style: TextStyle(fontSize: 32),),
              onPressed: ()=> _value.value++,
            ),
          ],
        ),
      ),
    );
  }
}

class MyPainter extends CustomPainter {
  final ValueNotifier<int> _value;

  MyPainter(this._value);

  @override
  void paint(Canvas canvas, Size size){
    Paint p = Paint();

    p.style = PaintingStyle.fill;
    p.color = Color.fromARGB(50, 0, 255, 255);
    Rect r;
    for (var i = 0 ; i < _value.value; i++){
      r = Rect.fromLTWH(10+i*20, 10+i*20, 100, 100);
      canvas.drawRect(r, p);
    }
    r = Rect.fromLTWH(0, 0, size.width, size.height);
    p.style = PaintingStyle.stroke;
    p.color = Color.fromARGB(255, 100, 100, 100);
    canvas.drawRect(r, p);
    if (_value.value > 10) _value.value = 0;
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}