问:
RuntimeException: cannot find implementation for MovieDatabase. MovieDatabase_Impl does not exist
I'm using Hilt as Dependency Injection to inject Room, ViewModel, Repositories, and other components but I'm getting the following exception while injecting Database module.

Exception

```<code>Caused by: java.lang.RuntimeException: cannot find implementation for
com.qst.qstmoviesapp.db.MovieDatabase. MovieDatabase_Impl does not exist
at androidx.room.Room.getGeneratedImplementation(Room.java:100)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1486)
at com.qst.qstmoviesapp.di.DatabaseModule.provideDatabase(DatabaseModule.kt:28)
atcom.qst.qstmoviesapp.di.DatabaseModule_ProvideDatabaseFactory.provideDatabase(DatabaseModule_ProvideDatabaseFactory.java:37)
at com.qst.qstmoviesapp.DaggerMovieApp_HiltComponents_SingletonC$SingletonCImpl$SwitchingProvider.get(DaggerMovieApp_HiltComponents_SingletonC.java:656)
at dagger.internal.DoubleCheck.get(DoubleCheck.java:47)                                                                                at
com.qst.qstmoviesapp.DaggerMovieApp_HiltComponents_SingletonC$SingletonCImpl.movieDao(DaggerMovieApp_HiltComponents_SingletonC.java:610)
atcom.qst.qstmoviesapp.DaggerMovieApp_HiltComponents_SingletonC$SingletonCImpl.access$1700(DaggerMovieApp_HiltComponents_SingletonC.java:594)
at com.qst.qstmoviesapp.DaggerMovieApp_HiltComponents_SingletonC$SingletonCImpl$SwitchingProvider.get(DaggerMovieApp_HiltComponents_SingletonC.java:653)                                                                                at
dagger.internal.DoubleCheck.get(DoubleCheck.java:47)                                                                                atcom.qst.qstmoviesapp.DaggerMovieApp_HiltComponents_SingletonC$ViewModelCImpl$SwitchingProvider.get(DaggerMovieApp_HiltComponents_SingletonC.java:518)                                                                                at dagger.hilt.android.internal.lifecycle.HiltViewModelFactory$1.create(HiltViewModelFactory.java:104)
at androidx.lifecycle.AbstractSavedStateViewModelFactory.create(AbstractSavedStateViewModelFactory.java:89)
at dagger.hilt.android.internal.lifecycle.HiltViewModelFactory.create(HiltViewModelFactory.java:116)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:153)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.kt:53)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.kt:35)
at com.qst.qstmoviesapp.ui.MovieFragment.getMovieViewModel(MovieFragment.kt:30)
</code>```

ViewModel.kt

```<code>@HiltViewModel
class MovieViewModel @Inject constructor(
    private val movieRepository: MovieRepository
): ViewModel(){
    val movies = movieRepository.movies
}
</code>```

Repository

```<code>@Singleton
class MovieRepository @Inject constructor(movieDao: MovieDao) {
    val movies: LiveData<List<Movie>> = movieDao.getMovies()
}
</code>```

Database Module

```<code>@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
    @Provides
    fun provideMovieDao(movieDatabase: MovieDatabase) = movieDatabase.movieDao()

    @Singleton
    @Provides
    fun provideDatabase(@ApplicationContext context: Context): MovieDatabase {
        return Room.databaseBuilder(
            context,
            MovieDatabase::class.java,
            "qst_movies.db")
            .build()
    }
}
</code>```

Movie DAO

```<code>@Dao
interface MovieDao {
    @Query("SELECT * FROM movies")
    fun getMovies(): LiveData<List<Movie>>
}
</code>```

Movie Database

```<code>@Database(entities = arrayOf(Movie::class), version = 1, exportSchema = false)
abstract class MovieDatabase: RoomDatabase(){
    abstract fun movieDao(): MovieDao
}
</code>```

Fragment

```<code>@AndroidEntryPoint
class MovieFragment : Fragment() {

    private var _binding: FragmentMovieBinding? = null
    private val binding get() = _binding!!

    @Inject lateinit var movieAdapter: MoviesAdapter

    val movieViewModel: MovieViewModel by viewModels()
}
</code>```

dependencies from app/build.gradle

```<code>dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.0'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation "androidx.fragment:fragment-ktx:1.5.2"
    implementation 'androidx.navigation:navigation-fragment-ktx:2.4.1'
    implementation 'androidx.navigation:navigation-ui-ktx:2.4.1'
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1"
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'

    implementation("com.google.dagger:hilt-android:2.44")
    kapt("com.google.dagger:hilt-android-compiler:2.44")

    testImplementation 'junit:junit:4.13.2'

    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'

    implementation 'com.github.bumptech.glide:glide:4.14.2'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.14.2'

    implementation "androidx.recyclerview:recyclerview:1.2.0-alpha06"

    implementation platform('com.google.firebase:firebase-bom:31.1.1')
    implementation 'com.google.firebase:firebase-firestore-ktx'

    implementation("androidx.room:room-runtime:2.4.3")
    annotationProcessor("androidx.room:room-compiler:2.4.3")
}
</code>```

Can someone please point out what might be missing? Thanks!

Body:
I'm using Hilt as Dependency Injection to inject Room, ViewModel, Repositories, and other components but I'm getting the following exception while injecting Database module.

Exception

Caused by: java.lang.RuntimeException: cannot find implementation for
com.qst.qstmoviesapp.db.MovieDatabase. MovieDatabase_Impl does not exist
at androidx.room.Room.getGeneratedImplementation(Room.java:100)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:1486)
at com.qst.qstmoviesapp.di.DatabaseModule.provideDatabase(DatabaseModule.kt:28)
atcom.qst.qstmoviesapp.di.DatabaseModule_ProvideDatabaseFactory.provideDatabase(DatabaseModule_ProvideDatabaseFactory.java:37)
at com.qst.qstmoviesapp.DaggerMovieApp_HiltComponents_SingletonC$SingletonCImpl$SwitchingProvider.get(DaggerMovieApp_HiltComponents_SingletonC.java:656)
at dagger.internal.DoubleCheck.get(DoubleCheck.java:47)                                                                                at
com.qst.qstmoviesapp.DaggerMovieApp_HiltComponents_SingletonC$SingletonCImpl.movieDao(DaggerMovieApp_HiltComponents_SingletonC.java:610)
atcom.qst.qstmoviesapp.DaggerMovieApp_HiltComponents_SingletonC$SingletonCImpl.access$1700(DaggerMovieApp_HiltComponents_SingletonC.java:594)
at com.qst.qstmoviesapp.DaggerMovieApp_HiltComponents_SingletonC$SingletonCImpl$SwitchingProvider.get(DaggerMovieApp_HiltComponents_SingletonC.java:653)                                                                                at
dagger.internal.DoubleCheck.get(DoubleCheck.java:47)                                                                                atcom.qst.qstmoviesapp.DaggerMovieApp_HiltComponents_SingletonC$ViewModelCImpl$SwitchingProvider.get(DaggerMovieApp_HiltComponents_SingletonC.java:518)                                                                                at dagger.hilt.android.internal.lifecycle.HiltViewModelFactory$1.create(HiltViewModelFactory.java:104)
at androidx.lifecycle.AbstractSavedStateViewModelFactory.create(AbstractSavedStateViewModelFactory.java:89)
at dagger.hilt.android.internal.lifecycle.HiltViewModelFactory.create(HiltViewModelFactory.java:116)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:187)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.kt:153)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.kt:53)
at androidx.lifecycle.ViewModelLazy.getValue(ViewModelLazy.kt:35)
at com.qst.qstmoviesapp.ui.MovieFragment.getMovieViewModel(MovieFragment.kt:30)

ViewModel.kt

@HiltViewModel
class MovieViewModel @Inject constructor(
    private val movieRepository: MovieRepository
): ViewModel(){
    val movies = movieRepository.movies
}

Repository

@Singleton
class MovieRepository @Inject constructor(movieDao: MovieDao) {
    val movies: LiveData<List<Movie>> = movieDao.getMovies()
}

Database Module

@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
    @Provides
    fun provideMovieDao(movieDatabase: MovieDatabase) = movieDatabase.movieDao()

    @Singleton
    @Provides
    fun provideDatabase(@ApplicationContext context: Context): MovieDatabase {
        return Room.databaseBuilder(
            context,
            MovieDatabase::class.java,
            "qst_movies.db")
            .build()
    }
}

Movie DAO

@Dao
interface MovieDao {
    @Query("SELECT * FROM movies")
    fun getMovies(): LiveData<List<Movie>>
}

Movie Database

@Database(entities = arrayOf(Movie::class), version = 1, exportSchema = false)
abstract class MovieDatabase: RoomDatabase(){
    abstract fun movieDao(): MovieDao
}

Fragment

@AndroidEntryPoint
class MovieFragment : Fragment() {

    private var _binding: FragmentMovieBinding? = null
    private val binding get() = _binding!!

    @Inject lateinit var movieAdapter: MoviesAdapter

    val movieViewModel: MovieViewModel by viewModels()
}

dependencies from app/build.gradle

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.0'
    implementation 'com.google.android.material:material:1.5.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation "androidx.fragment:fragment-ktx:1.5.2"
    implementation 'androidx.navigation:navigation-fragment-ktx:2.4.1'
    implementation 'androidx.navigation:navigation-ui-ktx:2.4.1'
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.5.1"
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'

    implementation("com.google.dagger:hilt-android:2.44")
    kapt("com.google.dagger:hilt-android-compiler:2.44")

    testImplementation 'junit:junit:4.13.2'

    androidTestImplementation 'androidx.test.ext:junit:1.1.4'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.0'

    implementation 'com.github.bumptech.glide:glide:4.14.2'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.14.2'

    implementation "androidx.recyclerview:recyclerview:1.2.0-alpha06"

    implementation platform('com.google.firebase:firebase-bom:31.1.1')
    implementation 'com.google.firebase:firebase-firestore-ktx'

    implementation("androidx.room:room-runtime:2.4.3")
    annotationProcessor("androidx.room:room-compiler:2.4.3")
}

Can someone please point out what might be missing? Thanks!


来源: stackexchange

问:
Flutter-MySql: how to insert int from a flutter app in a mysql table using php
Good morning all!
First of all sorry if my question is not so clear but it is the first time I ask something here.

It is about 8-9 months that I work (just for fun) on flutter app development. Mainly I used firebase database and averything was ok but now I need to work with a relational database so I started to go through flutter and MySql connection.
Everything seems to work fine when I try to insert/update/delete String fields but now I'm really struggling with integer insert.
When I click on Save button I have the following error: E/flutter (17407):

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'int' is not a subtype of type 'String' in type cast

but I don't understand where is the problem.

I tried several possible solutions but now I'm really confused on how to proceede, here you can find my flutter and php codes (I think I have mistakes in both):

`<?php

```<code>include 'database.php';

$championship_name = $_POST['championship_name'];
$championship_year = (int) $_POST['championship_year'];
$championship_type = $_POST['championship_type'];
$query = $link->query("INSERT INTO championships(championship_name,championship_year,championship_type) VALUES('".$championship_name."', $championship_year,'".$championship_type."',)");
</code>```

?>`

Here is the integer part of flutter code:

```<code>Padding(
  padding: const EdgeInsets.all(8),
  child: DropdownButton<int>(
    hint: Text('Year'),
    value: championship_year,
    items: <int> [2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026].map((int value) {
       return DropdownMenuItem<int>(
          value: value,
          child: Text(value.toString()),
       );
     }).toList(),
     onChanged: (value) {
       championship_year = value as int;
    },
  ),
),
</code>```

And below full flutter code:

```<code>import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'create_Championship.dart';

class ChampionshipAddPage extends StatefulWidget {
  ChampionshipAddPage({Key? key}) : super(key: key);

  @override
  State<ChampionshipAddPage> createState() => _ChampionshipAddPageState();
}

class _ChampionshipAddPageState extends State<ChampionshipAddPage> {

  late TextEditingController championship_name;
  late int championship_year;

  bool editMode = false;

  addData(){
    var url = 'http://xxxxxxxxxxxxxxx/add_championship.php';
    http.post(Uri.parse(url), body: {
      'championship_name' : championship_name.text,
      'championship_year' : championship_year.toInt(),
      'championship_type' : championship_type,
    });
  }

  String? championship_type;

  Future getAllTypes()async{
    var url = 'http://xxxxxxxxxxxxxxx/read_championship_types.php';
    var response = await http.get(Uri.parse(url), headers: {"Accept":"application/json"});
    var jsonBody = response.body;
    var jsonData = json.decode(jsonBody);

    setState(() {
      categoryChampionshipList = jsonData;
    });

    print(jsonData);
    return "success";

  }

  @override
  void initState() {
    championship_name = TextEditingController(text: '');
    championship_year = 2016;
    getAllTypes();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(editMode ? 'Update' : 'Add Data'),
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: () => Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => const Championships()),
          ),
        ),
      ),
      body: ListView(
        children: <Widget>[
          Padding(
              padding: const EdgeInsets.all(8),
            child: TextField(
              controller: championship_name,
              decoration: InputDecoration(
                labelText: 'Championship name',
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8),
            child: DropdownButton<int>(
              // menuMaxHeight: 250,
              hint: Text('Year'),
              value: championship_year,
              // decoration: InputDecoration(labelText:'Year'),
              items: <int> [2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026].map((int value) {
                return DropdownMenuItem<int>(
                  value: value,
                  child: Text(value.toString()),
                  // child: Text('${value}'),
                );
              }).toList(),
              onChanged: (value) {
                championship_year = value as int;
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8),
            child: DropdownButton(
              value: championship_type,
              hint: Text('Select Type'),
              items: categoryChampionshipList.map((championship_types){
                return DropdownMenuItem(
                  child: Text(championship_types['championship_type']),
                  value: championship_types['championship_type'],
                );
              },).toList(),
              onChanged: (value){
                setState(() {
                  championship_type = value as String?;
                });
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8),
            child: ElevatedButton(
              onPressed: () {
                setState(() {
                  addData();
                });
                Navigator.push(context, MaterialPageRoute(builder: (context) => Championships(),),);
                debugPrint('Clicked Update/Save button');
              },
              child: Text(editMode ? 'Update' : 'Save', style: TextStyle(color: Colors.white),),
            )
          ),
        ],
      )
    );
  }
}
</code>```

Thanks in advance for your help, I really appreciate it!

ContentLicense: CC BY-SA 4.0

Body:
Good morning all!
First of all sorry if my question is not so clear but it is the first time I ask something here.

It is about 8-9 months that I work (just for fun) on flutter app development. Mainly I used firebase database and averything was ok but now I need to work with a relational database so I started to go through flutter and MySql connection.
Everything seems to work fine when I try to insert/update/delete String fields but now I'm really struggling with integer insert.
When I click on Save button I have the following error: E/flutter (17407):

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'int' is not a subtype of type 'String' in type cast

but I don't understand where is the problem.

I tried several possible solutions but now I'm really confused on how to proceede, here you can find my flutter and php codes (I think I have mistakes in both):

`<?php

include 'database.php';

$championship_name = $_POST['championship_name'];
$championship_year = (int) $_POST['championship_year'];
$championship_type = $_POST['championship_type'];
$query = $link->query("INSERT INTO championships(championship_name,championship_year,championship_type) VALUES('".$championship_name."', $championship_year,'".$championship_type."',)");

?>`

Here is the integer part of flutter code:

Padding(
  padding: const EdgeInsets.all(8),
  child: DropdownButton<int>(
    hint: Text('Year'),
    value: championship_year,
    items: <int> [2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026].map((int value) {
       return DropdownMenuItem<int>(
          value: value,
          child: Text(value.toString()),
       );
     }).toList(),
     onChanged: (value) {
       championship_year = value as int;
    },
  ),
),

And below full flutter code:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'create_Championship.dart';

class ChampionshipAddPage extends StatefulWidget {
  ChampionshipAddPage({Key? key}) : super(key: key);

  @override
  State<ChampionshipAddPage> createState() => _ChampionshipAddPageState();
}

class _ChampionshipAddPageState extends State<ChampionshipAddPage> {

  late TextEditingController championship_name;
  late int championship_year;

  bool editMode = false;

  addData(){
    var url = 'http://xxxxxxxxxxxxxxx/add_championship.php';
    http.post(Uri.parse(url), body: {
      'championship_name' : championship_name.text,
      'championship_year' : championship_year.toInt(),
      'championship_type' : championship_type,
    });
  }

  String? championship_type;

  Future getAllTypes()async{
    var url = 'http://xxxxxxxxxxxxxxx/read_championship_types.php';
    var response = await http.get(Uri.parse(url), headers: {"Accept":"application/json"});
    var jsonBody = response.body;
    var jsonData = json.decode(jsonBody);

    setState(() {
      categoryChampionshipList = jsonData;
    });

    print(jsonData);
    return "success";

  }

  @override
  void initState() {
    championship_name = TextEditingController(text: '');
    championship_year = 2016;
    getAllTypes();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(editMode ? 'Update' : 'Add Data'),
        leading: IconButton(
          icon: Icon(Icons.arrow_back),
          onPressed: () => Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => const Championships()),
          ),
        ),
      ),
      body: ListView(
        children: <Widget>[
          Padding(
              padding: const EdgeInsets.all(8),
            child: TextField(
              controller: championship_name,
              decoration: InputDecoration(
                labelText: 'Championship name',
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8),
            child: DropdownButton<int>(
              // menuMaxHeight: 250,
              hint: Text('Year'),
              value: championship_year,
              // decoration: InputDecoration(labelText:'Year'),
              items: <int> [2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026].map((int value) {
                return DropdownMenuItem<int>(
                  value: value,
                  child: Text(value.toString()),
                  // child: Text('${value}'),
                );
              }).toList(),
              onChanged: (value) {
                championship_year = value as int;
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8),
            child: DropdownButton(
              value: championship_type,
              hint: Text('Select Type'),
              items: categoryChampionshipList.map((championship_types){
                return DropdownMenuItem(
                  child: Text(championship_types['championship_type']),
                  value: championship_types['championship_type'],
                );
              },).toList(),
              onChanged: (value){
                setState(() {
                  championship_type = value as String?;
                });
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(8),
            child: ElevatedButton(
              onPressed: () {
                setState(() {
                  addData();
                });
                Navigator.push(context, MaterialPageRoute(builder: (context) => Championships(),),);
                debugPrint('Clicked Update/Save button');
              },
              child: Text(editMode ? 'Update' : 'Save', style: TextStyle(color: Colors.white),),
            )
          ),
        ],
      )
    );
  }
}

Thanks in advance for your help, I really appreciate it!


问:
How to make icons?
I use the controlP5 library and have not found how to make .addTab icons or replace it with a picture!

```<code>import controlP5.*;

ControlP5 cp5;
int myColorBackground = color(128);
int sliderValue = 100;

void setup() {
  size(700,400);
  noStroke();
  cp5 = new ControlP5(this);

  // By default all controllers are stored inside Tab 'default'
  // add a second tab with name 'extra'
  cp5.addTab("extra")
     .setColorBackground(color(0, 160, 100))
     .setColorLabel(color(255))
     .setColorActive(color(255,128,0))
     ;

  // if you want to receive a controlEvent when
  // a  tab is clicked, use activeEvent(true)
  cp5.getTab("default")
     .activateEvent(true)
     .setLabel("my default tab")
     .setId(1)
     ;

  cp5.getTab("extra")
     .activateEvent(true)
     .setId(2)
     ;

  // create a few controllers
  cp5.addButton("button")
     .setBroadcast(false)
     .setPosition(100,100)
     .setSize(80,40)
     .setValue(1)
     .setBroadcast(true)
     .getCaptionLabel().align(CENTER,CENTER)
     ;

  cp5.addButton("buttonValue")
     .setBroadcast(false)
     .setPosition(220,100)
     .setSize(80,40)
     .setValue(2)
     .setBroadcast(true)
     .getCaptionLabel().align(CENTER,CENTER)
     ;

  cp5.addSlider("slider")
     .setBroadcast(false)
     .setRange(100,200)
     .setValue(128)
     .setPosition(100,160)
     .setSize(200,20)
     .setBroadcast(true)
     ;

  cp5.addSlider("sliderValue")
     .setBroadcast(false)
     .setRange(0,255)
     .setValue(128)
     .setPosition(100,200)
     .setSize(200,20)
     .setBroadcast(true)
     ;

  // arrange controller in separate tabs
  cp5.getController("sliderValue").moveTo("extra");
  cp5.getController("slider").moveTo("global");

  // Tab 'global' is a tab that lies on top of any
  // other tab and is always visible
}

void draw() {
  background(myColorBackground);
  fill(sliderValue);
  rect(0,0,width,100);
}

void controlEvent(ControlEvent theControlEvent) {
  if (theControlEvent.isTab()) {
    println("got an event from tab : "+theControlEvent.getTab().getName()+" with id "+theControlEvent.getTab().getId());
  }
}

void slider(int theColor) {
  myColorBackground = color(theColor);
  println("a slider event. setting background to "+theColor);
}

void keyPressed() {
  if(keyCode==TAB) {
    cp5.getTab("extra").bringToFront();
  }
}
</code>```

Title: How to make icons?

Body:
I use the controlP5 library and have not found how to make .addTab icons or replace it with a picture!

import controlP5.*;

ControlP5 cp5;
int myColorBackground = color(128);
int sliderValue = 100;

void setup() {
  size(700,400);
  noStroke();
  cp5 = new ControlP5(this);

  // By default all controllers are stored inside Tab 'default'
  // add a second tab with name 'extra'
  cp5.addTab("extra")
     .setColorBackground(color(0, 160, 100))
     .setColorLabel(color(255))
     .setColorActive(color(255,128,0))
     ;

  // if you want to receive a controlEvent when
  // a  tab is clicked, use activeEvent(true)
  cp5.getTab("default")
     .activateEvent(true)
     .setLabel("my default tab")
     .setId(1)
     ;

  cp5.getTab("extra")
     .activateEvent(true)
     .setId(2)
     ;

  // create a few controllers
  cp5.addButton("button")
     .setBroadcast(false)
     .setPosition(100,100)
     .setSize(80,40)
     .setValue(1)
     .setBroadcast(true)
     .getCaptionLabel().align(CENTER,CENTER)
     ;

  cp5.addButton("buttonValue")
     .setBroadcast(false)
     .setPosition(220,100)
     .setSize(80,40)
     .setValue(2)
     .setBroadcast(true)
     .getCaptionLabel().align(CENTER,CENTER)
     ;

  cp5.addSlider("slider")
     .setBroadcast(false)
     .setRange(100,200)
     .setValue(128)
     .setPosition(100,160)
     .setSize(200,20)
     .setBroadcast(true)
     ;

  cp5.addSlider("sliderValue")
     .setBroadcast(false)
     .setRange(0,255)
     .setValue(128)
     .setPosition(100,200)
     .setSize(200,20)
     .setBroadcast(true)
     ;

  // arrange controller in separate tabs
  cp5.getController("sliderValue").moveTo("extra");
  cp5.getController("slider").moveTo("global");

  // Tab 'global' is a tab that lies on top of any
  // other tab and is always visible
}

void draw() {
  background(myColorBackground);
  fill(sliderValue);
  rect(0,0,width,100);
}

void controlEvent(ControlEvent theControlEvent) {
  if (theControlEvent.isTab()) {
    println("got an event from tab : "+theControlEvent.getTab().getName()+" with id "+theControlEvent.getTab().getId());
  }
}

void slider(int theColor) {
  myColorBackground = color(theColor);
  println("a slider event. setting background to "+theColor);
}

void keyPressed() {
  if(keyCode==TAB) {
    cp5.getTab("extra").bringToFront();
  }
}


问:
LINE_MAX not declared in scope
How do I declare LINE_MAX in this scope?
Input data as well not declared

```<code>unsigned  int numsData[3];
    char inputdata[LINE_MAX];
    FILE *inputfile;
    if ((inputfile = fopen(fileInput, "r")) == NULL){
            cout <<"File not found...Terminating";
            exit(1);
    }
    else{

        while (fgets(inputdata, LINE_MAX, inputfile) != NULL) {
            sscanf(inputdata,"%d:%d:%d\n",&numsData[0],&numsData[1],&numsData[2]);
            header = insertback(header, ++processes, numsData[0], numsData[1], numsData[2]);

        }
        fclose(inputfile);
</code>```

gcc file.cpp -o test

Title: LINE_MAX not declared in scope

Body:
How do I declare LINE_MAX in this scope?
Input data as well not declared

unsigned  int numsData[3];
    char inputdata[LINE_MAX];
    FILE *inputfile;
    if ((inputfile = fopen(fileInput, "r")) == NULL){
            cout <<"File not found...Terminating";
            exit(1);
    }
    else{

        while (fgets(inputdata, LINE_MAX, inputfile) != NULL) {
            sscanf(inputdata,"%d:%d:%d\n",&numsData[0],&numsData[1],&numsData[2]);
            header = insertback(header, ++processes, numsData[0], numsData[1], numsData[2]);

        }
        fclose(inputfile);

gcc file.cpp -o test


问:
how to add a field on to book records which are in a user library from the whole collection
I have a route genre which lists all the books of that genre. Now, on front end, users can add book to his library on a button click. But I want the books already added in the user library db to be shown as already added. And I am confused on how to implement this efficiently. For info, I am using express for backend, mongodb as db and react for front end.


问:
Testing code inside a Timer.Periodic flutter
I am showing a timer in the UI with hours, minutes and seconds. How do I test this properly in unit tests?

 void startShiftTimeTimer() {
    timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      seconds = seconds + 1;
      if (seconds == 60) {
        minutes = minutes + 1;
        seconds = 0;
      }
      if (minutes == 60) {
        hours = hours + 1;
        minutes = 0;
      }
      checkedInTimeSecs = checkedInTimeSecs + 1;

      notifyListeners();
      if (hours == 24) {
        endTimer();
      }
    });

  }

```

I think unit tests have to be independent but here I am updating the state i.e. hours, minutes and seconds directly inside, is there any work around, so I can use variable received as parameters and return them. I am not sure if this is possible. Any and all help is appreciated.

Body:
I am showing a timer in the UI with hours, minutes and seconds. How do I test this properly in unit tests?

 void startShiftTimeTimer() {
    timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      seconds = seconds + 1;
      if (seconds == 60) {
        minutes = minutes + 1;
        seconds = 0;
      }
      if (minutes == 60) {
        hours = hours + 1;
        minutes = 0;
      }
      checkedInTimeSecs = checkedInTimeSecs + 1;

      notifyListeners();
      if (hours == 24) {
        endTimer();
      }
    });

  }

I think unit tests have to be independent but here I am updating the state i.e. hours, minutes and seconds directly inside, is there any work around, so I can use variable received as parameters and return them. I am not sure if this is possible. Any and all help is appreciated.


问:
Does anyone have a method for aligning matrix output data?
For example, let us say that I am outputting

```<code>std::vector<std::vector<double>> A;
</code>```

by the following:

```<code>for (int i = 0 ; i < rows ; i ++){
    for (int j = 0 ; j < cols ; j ++){
         cout << A[i][j] << " ";
         }
     std::cout << std::endl;
}
</code>```

for a 3 x 3 matrix, the output would look something like:

```<code>1 3.7 2.89
3 4.85 12.34
4 5 6
</code>```

as a contrived example.

I'd like to get it to look like:

```<code>1 3.7   2.89
3 4.85 12.34
4 5     6
</code>```

Aligning the 1's position of the data so as to make it a bit more nicely formatted.

Does anyone have any suggestion for how to go about it? Something hidden in the iomanip library maybe?

I'm currently working on the following implementation:

transfer each row to string data

check sizes of strings

pick largest row (lr)

for every prior column element, find the element in that column with max length, compare it to length of lr's column element, and add that many spaces between that output of lr and the prior element

do some complex indexing :(

Body:
For example, let us say that I am outputting

std::vector<std::vector<double>> A;

by the following:

for (int i = 0 ; i < rows ; i ++){
    for (int j = 0 ; j < cols ; j ++){
         cout << A[i][j] << " ";
         }
     std::cout << std::endl;
}

for a 3 x 3 matrix, the output would look something like:

1 3.7 2.89
3 4.85 12.34
4 5 6

as a contrived example.

I'd like to get it to look like:

1 3.7   2.89
3 4.85 12.34
4 5     6

Aligning the 1's position of the data so as to make it a bit more nicely formatted.

Does anyone have any suggestion for how to go about it? Something hidden in the iomanip library maybe?

I'm currently working on the following implementation:

transfer each row to string data

check sizes of strings

pick largest row (lr)

for every prior column element, find the element in that column with max length, compare it to length of lr's column element, and add that many spaces between that output of lr and the prior element

do some complex indexing :(


问:
How to output text from the Database in InlineKeyboardButton?
I want to ask a question how to output data from the database to the button, I need to output the name of the processor, it turned out to do so in the form of text, but I can't attach how to insert the mind into the button

```<code>    elif call.data == "own1":
      reply_markup1 = types.InlineKeyboardMarkup(row_width=2)
      for value in cur.execute("SELECT name FROM Processor where category_g='gaming';"):
            item = types.InlineKeyboardButton(text=value, callback_data= value)
            reply_markup1.add(item)
            bot.send_message(call.message.chat.id, value, reply_markup=reply_markup1)
</code>```

Where is my mistake?

I managed to get the processor name from the database in the form of text and everything worked out, but I can't do it in the form of a button

Body:
I want to ask a question how to output data from the database to the button, I need to output the name of the processor, it turned out to do so in the form of text, but I can't attach how to insert the mind into the button

    elif call.data == "own1":
      reply_markup1 = types.InlineKeyboardMarkup(row_width=2)
      for value in cur.execute("SELECT name FROM Processor where category_g='gaming';"):
            item = types.InlineKeyboardButton(text=value, callback_data= value)
            reply_markup1.add(item)
            bot.send_message(call.message.chat.id, value, reply_markup=reply_markup1)

Where is my mistake?

I managed to get the processor name from the database in the form of text and everything worked out, but I can't do it in the form of a button


问:
How to rain and use object detection model in Java for dummies?
I'm struggling a bit to modify the project of mine. In general, I have this simple desktop Java app for Windows I have written some time ago for me and a couple of guys I know and one part of the app is responsible for object detection in the image.

Right now object detection is happening with some voodoo-like loops that are scanning the whole image looking for some key pixel patterns and second-guessing if the object is there or not. As you may realize not the finest way to do the job but the app has been in use for quite some time and most of the time that method is more or less fine.

So recently I thought maybe it would be nice to expand my knowledge and learn some of that fancy object detection stuff that is using those models etc. I'm not familiar with that so I may mess up definitions, sorry for that.

I don't need anything fancy, it's not for a business, just to improve some piece of code, has to be at least as fast as pixel scanning but better with detection. I don't need to be an expert in that.

I did some reading, and find out that I need a model, there are some pre-trained models, but for my case, I need to teach it to recognize another 'class' of an object, and in order to do that I need to train it with some data. The data should be a set of images with objects manually marked by me and I should have as many of those images as possible. I understand the concept and I decided I'm going to collect a couple of dozen images for initial training, no idea if that's enough for my case but I decided I will start with that and if that's not enough I will get more.

I looked around for some software and since I'm also familiar with Python, I went with something called Detecto docs https://detecto.readthedocs.io/en/latest/ . My initial experience was: it's great, not only in a few hours I trained some model but I get nice results with that, learned how to mark my training data and use validation sets. I learned that Detecto is built on top of PyTorch and torchvision and that those are quite powerful tools.

Now I spend some time learning about saving and loading those models because my initial thought was that maybe I will be able to use that model in my Java application. I learned that for Java there is something called DJL - Deep Java Library, and it's supporting (py)torch(vision), great.

And this is where things failed, after a few days of trying I was not able to make that model work in Java, read a couple of dozen threads over the Internet, and while they described my issue none of them really helped me go forward.

I also spend some time with DJL to figure out if it's possible to maybe do all of that training directly in Java, with literally anything that will do object detection, but all the texts are covering cases a bit beyond my knowledge and understanding like e.g. images have to be of the same size, while with Detecto I could use images of any size to train my model.

I am a bit crushed that there is no simple explanation of how to do those stuff right away, Detecto case was brilliant but I see that it was rather an exception and I haven't seen something similar for Java.

Maybe you will have some suggestions for me, what should I do to achieve my goal in the Java app? What simple tutorial, or articles should I read to learn how to train a simple model to detect objects in custom images?


问:
Sort data ignoring case
I use blazebit in my project and I am faced with the task of making data sorting case insensitive. Solving a problem using blazebit does not seem like a primitive task. Tried to solve with Like but no luck. How can I sort by sortBy ignoring the case? Thanks in advance!</p>
```<code>public <T> getResultForQuery(
    CriteriaBuilder<T> criteriaBuilder,
    String sortBy,
    boolean asc
) {

    CriteriaBuilder<T> tCriteriaBuilder = criteriaBuilder.orderBy(sortBy, asc).getResultList();
    ...
}
</code>```

Title: Sort data ignoring case

Body:
I use blazebit in my project and I am faced with the task of making data sorting case insensitive. Solving a problem using blazebit does not seem like a primitive task. Tried to solve with Like but no luck. How can I sort by sortBy ignoring the case? Thanks in advance!

public <T> getResultForQuery(
    CriteriaBuilder<T> criteriaBuilder,
    String sortBy,
    boolean asc
) {

    CriteriaBuilder<T> tCriteriaBuilder = criteriaBuilder.orderBy(sortBy, asc).getResultList();
    ...
}


问:
Error in FUN(X[[i]], ...) : no method or default for coercing “try-error” to “GRanges”
Using DMRcaller in R(4.2.2), I am computing DMRs using 3 replicates per group. So far I have computed DMRs in the context "CG", but when I change the context to "CHG" there is an error. Please help me.

This command:

DMRs_bins_replicates_Scaffold_1531_CpG <- computeDMRsReplicates(metAllData, condition = condition, regions = Scaffold_1531,
    context = "CG", method = "bins", binSize = 100, test = "betareg",
    pseudocountM = 1, pseudocountN = 2, pValueThreshold = 0.05,
    minCytosinesCount = 4, minProportionDifference = 0.15, minGap = 200, minSize = 50,
    minReadsPerCytosine = 4, cores = 50)
```
<p>worked just fine!</p>
<p>This command (change from "CG" to "CHG"):</p>
<pre class="lang-r prettyprint-override"><code>DMRs_bins_replicates_Scaffold_1531_CHG <- computeDMRsReplicates(metAllData, condition = condition, regions = Scaffold_1531,
    context = "CHG", method = "bins", binSize = 100, test = "betareg",
    pseudocountM = 1, pseudocountN = 2, pValueThreshold = 0.05,
    minCytosinesCount = 4, minProportionDifference = 0.15, minGap = 200, minSize = 50,
    minReadsPerCytosine = 4, cores = 50)
</code>```

returns this:

```<code>Parameters checking ...
Extract methylation in the corresponding context
Compute the DMRs using  50 cores
Computing DMRs at  Scaffold_1531:1..9529912
Count inside each bin...
Computing DMRs at  Scaffold_1531:9529913..19059825
Count inside each bin...
Computing DMRs at  Scaffold_1531:19059826..28589738
Count inside each bin...
Computing DMRs at  Scaffold_1531:28589739..38119651
Count inside each bin...
Computing DMRs at  Scaffold_1531:38119652..47649564
Count inside each bin...
Computing DMRs at  Scaffold_1531:47649565..57179477
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:57179478..66709390
Count inside each bin...
Computing DMRs at  Scaffold_1531:66709391..76239303
Filter the bins...
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:76239304..85769215
Count inside each bin...
Computing DMRs at  Scaffold_1531:85769216..95299128
Filter the bins...
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:95299129..104829041
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:104829042..114358954
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:114358955..123888867
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:123888868..133418780
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:133418781..142948693
Count inside each bin...
Computing DMRs at  Scaffold_1531:142948694..152478606
Filter the bins...
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:152478607..162008518
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:162008519..171538431
Filter the bins...
Identifying DMRs...
Count inside each bin...
Computing DMRs at  Scaffold_1531:171538432..181068344
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:181068345..190598257
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:190598258..200128170
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:200128171..209658083
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:209658084..219187996
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:219187997..228717909
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:228717910..238247822
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:238247823..247777734
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:247777735..257307647
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:257307648..266837560
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:266837561..276367473
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:276367474..285897386
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:285897387..295427299
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:295427300..304957212
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:304957213..314487125
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:314487126..324017037
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:324017038..333546950
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:333546951..343076863
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:343076864..352606776
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:352606777..362136689
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:362136690..371666602
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:371666603..381196515
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:381196516..390726428
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:390726429..400256340
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:400256341..409786253
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:409786254..419316166
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:419316167..428846079
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:428846080..438375992
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:438375993..447905905
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:447905906..457435818
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:457435819..466965731
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:466965732..476495644
Filter the bins...
Count inside each bin...
Filter the bins...
Filter the bins...
Filter the bins...
Filter the bins...
Filter the bins...
Error in FUN(X[[i]], ...) :
  no method or default for coercing “try-error” to “GRanges”
Calls: computeDMRsReplicates ... .computeDMRsReplicatesBins -> unlist -> GRangesList
In addition: Warning message:
In parallel::mclapply(1:length(regionsList), .computeDMRsReplicatesBinsLoop,  :
  scheduled core 13 encountered error in user code, all values of the job will be affected
Execution halted
</code>```

Body:
Using DMRcaller in R(4.2.2), I am computing DMRs using 3 replicates per group. So far I have computed DMRs in the context "CG", but when I change the context to "CHG" there is an error. Please help me.

This command:

DMRs_bins_replicates_Scaffold_1531_CpG <- computeDMRsReplicates(metAllData, condition = condition, regions = Scaffold_1531,
    context = "CG", method = "bins", binSize = 100, test = "betareg",
    pseudocountM = 1, pseudocountN = 2, pValueThreshold = 0.05,
    minCytosinesCount = 4, minProportionDifference = 0.15, minGap = 200, minSize = 50,
    minReadsPerCytosine = 4, cores = 50)

worked just fine!

This command (change from "CG" to "CHG"):

DMRs_bins_replicates_Scaffold_1531_CHG <- computeDMRsReplicates(metAllData, condition = condition, regions = Scaffold_1531,
    context = "CHG", method = "bins", binSize = 100, test = "betareg",
    pseudocountM = 1, pseudocountN = 2, pValueThreshold = 0.05,
    minCytosinesCount = 4, minProportionDifference = 0.15, minGap = 200, minSize = 50,
    minReadsPerCytosine = 4, cores = 50)

returns this:

Parameters checking ...
Extract methylation in the corresponding context
Compute the DMRs using  50 cores
Computing DMRs at  Scaffold_1531:1..9529912
Count inside each bin...
Computing DMRs at  Scaffold_1531:9529913..19059825
Count inside each bin...
Computing DMRs at  Scaffold_1531:19059826..28589738
Count inside each bin...
Computing DMRs at  Scaffold_1531:28589739..38119651
Count inside each bin...
Computing DMRs at  Scaffold_1531:38119652..47649564
Count inside each bin...
Computing DMRs at  Scaffold_1531:47649565..57179477
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:57179478..66709390
Count inside each bin...
Computing DMRs at  Scaffold_1531:66709391..76239303
Filter the bins...
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:76239304..85769215
Count inside each bin...
Computing DMRs at  Scaffold_1531:85769216..95299128
Filter the bins...
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:95299129..104829041
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:104829042..114358954
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:114358955..123888867
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:123888868..133418780
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:133418781..142948693
Count inside each bin...
Computing DMRs at  Scaffold_1531:142948694..152478606
Filter the bins...
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:152478607..162008518
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:162008519..171538431
Filter the bins...
Identifying DMRs...
Count inside each bin...
Computing DMRs at  Scaffold_1531:171538432..181068344
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:181068345..190598257
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:190598258..200128170
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:200128171..209658083
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:209658084..219187996
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:219187997..228717909
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:228717910..238247822
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:238247823..247777734
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:247777735..257307647
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:257307648..266837560
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:266837561..276367473
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:276367474..285897386
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:285897387..295427299
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:295427300..304957212
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:304957213..314487125
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:314487126..324017037
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:324017038..333546950
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:333546951..343076863
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:343076864..352606776
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:352606777..362136689
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:362136690..371666602
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:371666603..381196515
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:381196516..390726428
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:390726429..400256340
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:400256341..409786253
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:409786254..419316166
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:419316167..428846079
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:428846080..438375992
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:438375993..447905905
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:447905906..457435818
Count inside each bin...
Filter the bins...
Computing DMRs at  Scaffold_1531:457435819..466965731
Filter the bins...
Count inside each bin...
Computing DMRs at  Scaffold_1531:466965732..476495644
Filter the bins...
Count inside each bin...
Filter the bins...
Filter the bins...
Filter the bins...
Filter the bins...
Filter the bins...
Error in FUN(X[[i]], ...) :
  no method or default for coercing “try-error” to “GRanges”
Calls: computeDMRsReplicates ... .computeDMRsReplicatesBins -> unlist -> GRangesList
In addition: Warning message:
In parallel::mclapply(1:length(regionsList), .computeDMRsReplicatesBinsLoop,  :
  scheduled core 13 encountered error in user code, all values of the job will be affected
Execution halted


问:
Aggregated with top 2
I have a question how to write query to show me top 2 total by num for each id and department (dep).
here is example of data:

```<code>  id    dep num
288610  101 95
334028  101 64
480492  101 61
259007  102 215
333655  102 177
369079  102 146
128672  102 103
398319  103 247
384462  103 222
448798  103 204
430841  103 133
387829  103 62
</code>```

and my select

```<code>select  a.id, a.dep, COUNT(b.units) as num
from id a
  JOIN dev b ON(a.id = b.id)
where  b.units is null
group by a.id, a.dep
having COUNT(a.enota) >10
order by  a.dep, COUNT(b.units) desc
</code>```

the result should be:

```<code>id  dep num
288610  101 95
334028  101 64
259007  102 215
333655  102 177
398319  103 247
384462  103 222
</code>```

Title: Aggregated with top 2

Body:
I have a question how to write query to show me top 2 total by num for each id and department (dep).
here is example of data:

  id    dep num
288610  101 95
334028  101 64
480492  101 61
259007  102 215
333655  102 177
369079  102 146
128672  102 103
398319  103 247
384462  103 222
448798  103 204
430841  103 133
387829  103 62

and my select

select  a.id, a.dep, COUNT(b.units) as num
from id a
  JOIN dev b ON(a.id = b.id)
where  b.units is null
group by a.id, a.dep
having COUNT(a.enota) >10
order by  a.dep, COUNT(b.units) desc

the result should be:

id  dep num
288610  101 95
334028  101 64
259007  102 215
333655  102 177
398319  103 247
384462  103 222


问:
How to disable swipe gesture to go back when interacting with victory chart
I have created a victory chart in react native using Victory Native package. I have an interaction where the user can drag a vertical cursor to know about detail at different data points. This chart stretches the entire width of the screen.

The issue with ios is that ios by default has swipe left from right side of the screen to go back to previous screen. Now when the user starts to drag the cursor close to the right end of the screen this action to go back also happens.

Is there a way to stop this from happening if the user is interacting with the chart?

Any help with this will be highly appreciated.


问:
Django, nginx StreamingHttpResponse Giving 502 Time Out
I am unable to figure out why the server is crashing.

Below is the code:

class Echo:
def write(self, value):
return value

@api_view(['GET'])
@permission_classes([AllowAny, ])
def export_report(request):
import csv
from django.db import connection

```<code>cursor = connection.cursor()
try:
    cursor.execute('select query here')
except Exception:
    cursor.close()
    raise

echo_buffer = Echo()

def cursor_generator(cursor, echo_buffer, arraysize=30):
   'An iterator that uses fetchmany to keep memory usage down'
    writer = csv.writer(echo_buffer)
    header = True
    while True:

        if header:
            header = False
            yield writer.writerow(['first_nama', 'last_name'])
        results = cursor.fetchmany(arraysize)
        if not results:
            cursor.close()
            break
        for result in results:
            yield writer.writerow(result)

response_list = []

response = StreamingHttpResponse(cursor_generator(cursor, echo_buffer), content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="report.csv"'

return response
</code>```

Body:
I am unable to figure out why the server is crashing.

Below is the code:

class Echo:
def write(self, value):
return value

@api_view(['GET'])
@permission_classes([AllowAny, ])
def export_report(request):
import csv
from django.db import connection

cursor = connection.cursor()
try:
    cursor.execute('select query here')
except Exception:
    cursor.close()
    raise

echo_buffer = Echo()

def cursor_generator(cursor, echo_buffer, arraysize=30):
   'An iterator that uses fetchmany to keep memory usage down'
    writer = csv.writer(echo_buffer)
    header = True
    while True:

        if header:
            header = False
            yield writer.writerow(['first_nama', 'last_name'])
        results = cursor.fetchmany(arraysize)
        if not results:
            cursor.close()
            break
        for result in results:
            yield writer.writerow(result)

response_list = []

response = StreamingHttpResponse(cursor_generator(cursor, echo_buffer), content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="report.csv"'

return response


问:
Save data to firebase realtime from a picker's item which data is retrieved from firebase also, in xamarin form
My problem is how to save data from picker's value to firebase realtime. Anyway, Im super beginner to xamarin and so far I cant find any solution to my problem.

This is what I tried.
//my model
`

```<code>public int DeliveryPrice { get; set; }
    public int PickUp_Price { get; set; }
    public string gallonType { get; set; }
    public string refillName { get; set; }

    public int refill_id { get; set; }
    public string waterType { get; set; }
</code>```

`

//Code how I get the data from my firebase realtime db
`

```<code>public async Task<List<PRODUCT_REFILL>> GetAllProductRefill()
    {
        return
            (await firebaseClient.Child
            (nameof(PRODUCT_REFILL))
            .OnceAsync<PRODUCT_REFILL>()).Select(item => new PRODUCT_REFILL
        {

          DeliveryPrice=item.Object.DeliveryPrice,
          PickUp_Price=item.Object.PickUp_Price,
          gallonType=item.Object.gallonType,
          refillName=item.Object.refillName,
          waterType=item.Object.waterType,
          refill_id=item.Object.refill_id

        }).ToList();
    }
</code>```

`

//my picker design UI
`

```<code><Picker x:Name="Picker_ProductType"
       ItemsSource="{Binding refillName}"
      ItemDisplayBinding="{Binding refillName}">
     <Picker.Items  >                                                       <x:String >
                                                                           </x:String>
<x:String>
                                                                          </x:String>
</Picker.Items>
</Picker>
</code>```

`

//my codebehind
`

```<code>Product_RefillRepo productrefill = new Product_RefillRepo();
async protected override void OnAppearing()
    {
     var productRefill = await productrefill.GetAllProductRefill();
        Picker_ProductType.ItemsSource = productRefill;

     }
</code>```

`

//in my order button, which is also inside in code behind.cs
string orderProductType = Picker_ProductType.SelectedItem.ToString();
Then if click the order button, I got this error.
Edit; This is the error----- Error says; System.InvalidCastException: 'Specified cast is not valid.'

any link that will be commented that are related to my post, will highly appreciated, Thank you so much.

Body:
My problem is how to save data from picker's value to firebase realtime. Anyway, Im super beginner to xamarin and so far I cant find any solution to my problem.

This is what I tried.
//my model
`

public int DeliveryPrice { get; set; }
    public int PickUp_Price { get; set; }
    public string gallonType { get; set; }
    public string refillName { get; set; }

    public int refill_id { get; set; }
    public string waterType { get; set; }

`

//Code how I get the data from my firebase realtime db
`

public async Task<List<PRODUCT_REFILL>> GetAllProductRefill()
    {
        return
            (await firebaseClient.Child
            (nameof(PRODUCT_REFILL))
            .OnceAsync<PRODUCT_REFILL>()).Select(item => new PRODUCT_REFILL
        {

          DeliveryPrice=item.Object.DeliveryPrice,
          PickUp_Price=item.Object.PickUp_Price,
          gallonType=item.Object.gallonType,
          refillName=item.Object.refillName,
          waterType=item.Object.waterType,
          refill_id=item.Object.refill_id

        }).ToList();
    }

`

//my picker design UI
`

<Picker x:Name="Picker_ProductType"
       ItemsSource="{Binding refillName}"
      ItemDisplayBinding="{Binding refillName}">
     <Picker.Items  >                                                       <x:String >
                                                                           </x:String>
<x:String>
                                                                          </x:String>
</Picker.Items>
</Picker>

`

//my codebehind
`

Product_RefillRepo productrefill = new Product_RefillRepo();
async protected override void OnAppearing()
    {
     var productRefill = await productrefill.GetAllProductRefill();
        Picker_ProductType.ItemsSource = productRefill;

     }

`

//in my order button, which is also inside in code behind.cs
string orderProductType = Picker_ProductType.SelectedItem.ToString();
Then if click the order button, I got this error.
Edit; This is the error----- Error says; System.InvalidCastException: 'Specified cast is not valid.'

any link that will be commented that are related to my post, will highly appreciated, Thank you so much.


问:
How to create entity with self-referencing (with many To many mapping)
```<code>@Entity
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @ManyToMany(mappedBy = "departements")
    private List<Department> departements;

</code>```

I don't know how  to implement this association .In my situation I have the same entity mapped by itself by many to many

Body:
@Entity
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @ManyToMany(mappedBy = "departements")
    private List<Department> departements;

I don't know how  to implement this association .In my situation I have the same entity mapped by itself by many to many


问:
Error - No Dialect mapping for JDBC type: 1111 while using Projection in JPARepository for jsonb type column
I have a jsonb column in my postgres db When I use findAll() method of JPA Repository to retrieve all data everything works like charm.

My Entity is as follows

```<code>@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "steps")
public class Steps {

    @EmbeddedId
    private StepsId id;

    @Column(name = "steps_name")
    private String steps_name;

    @Column(name = "sub_steps",columnDefinition = "jsonb")
    @Convert(converter = SubStepsConverter.class)
    private List<Substeps> sub_steps;

    @Column(name = "status")
    private String status;
}
</code>```

When I use a Projection to retrieve selected data then it gives error No Dialect mapping for JDBC type: 1111

```<code>public interface StepsProjection {
    String getid();
    String getSteps_name();
    @Convert(converter = SubStepsConverter.class)
    List<Substeps> getSub_steps();
}
</code>```

So if I remove List<Substeps> getSub_steps(); from above class and from my query everything works good so I guess the issue is with sub_steps field only which is a jsonb field while using Projection?

I have tried changing the Type to String in NotesProjection for substeps but no result.
I need to return only selected fields to the client.

Body:
I have a jsonb column in my postgres db When I use findAll() method of JPA Repository to retrieve all data everything works like charm.

My Entity is as follows

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "steps")
public class Steps {

    @EmbeddedId
    private StepsId id;

    @Column(name = "steps_name")
    private String steps_name;

    @Column(name = "sub_steps",columnDefinition = "jsonb")
    @Convert(converter = SubStepsConverter.class)
    private List<Substeps> sub_steps;

    @Column(name = "status")
    private String status;
}

When I use a Projection to retrieve selected data then it gives error No Dialect mapping for JDBC type: 1111

public interface StepsProjection {
    String getid();
    String getSteps_name();
    @Convert(converter = SubStepsConverter.class)
    List<Substeps> getSub_steps();
}

So if I remove List<Substeps> getSub_steps(); from above class and from my query everything works good so I guess the issue is with sub_steps field only which is a jsonb field while using Projection?

I have tried changing the Type to String in NotesProjection for substeps but no result.
I need to return only selected fields to the client.


问:
Show custom edit page for data stored outside wp_posts table
Good morning everyone.
I had to manage a custom post type with a lot of fields (maybe 80 fields!) and I believe that using the canonical method will lead to slow performances for querying/filtering all results, because of the large amount of metadata to put together.

I'm thinking about storing my information in a separate table, let's call it wp_contracts, but I'm not sure about how I can show the single post data on the backend.
I'm ok with the listing page (that will use WP_List_Table to show a summary of the whole contract), but I cannot figure out how to create the show/edit page.

It's maybe only a stupid idea?

Thanks


问:
How to access nested screen using expo linking
Here you can see in the last I tried to pass the URL of PaymenntMethod screen which is already defined in the stacks, I have the structure like this I am using the tabs in my react native application Home > More (Tab) > MyWallet (Screen) > PaymentMethod (Screen)

```<code>export const WalletStackScreen = () => {
  return (
    <EnterprisePromotionStack.Navigator screenOptions={stackOptions}>
      <EnterprisePromotionStack.Screen name='MyWallet' component={MyWallet} />
      <EnterprisePromotionStack.Screen name='PaymentMethod' component={PaymentMethod} />
    </EnterprisePromotionStack.Navigator>
  )
}
</code>```

Above I mentioned the stacks, and the linking config are as follows

```<code>export const LinkingConfig = {
  prefixes: [Linking.createURL('/')],
  config: {
    screens: {
      Home: {
        path: 'home',
        screens: {
          'PROMOTIONS': {
            path:'Promotions',
            screens: {
              PromotionDetails:':id'
            }
          },
          'MENU': {
            path: 'More/MyWallet',
            // screens: 'PaymentMethod'
            screens: {
              PaymentMethod: ''
            }
          },
        }
      },
      Login: 'login'
    }
  }
}
</code>```

I want the exact structure and the path which will be redirected to PaymentMehod Screen

Body:
Here you can see in the last I tried to pass the URL of PaymenntMethod screen which is already defined in the stacks, I have the structure like this I am using the tabs in my react native application Home > More (Tab) > MyWallet (Screen) > PaymentMethod (Screen)

export const WalletStackScreen = () => {
  return (
    <EnterprisePromotionStack.Navigator screenOptions={stackOptions}>
      <EnterprisePromotionStack.Screen name='MyWallet' component={MyWallet} />
      <EnterprisePromotionStack.Screen name='PaymentMethod' component={PaymentMethod} />
    </EnterprisePromotionStack.Navigator>
  )
}

Above I mentioned the stacks, and the linking config are as follows

export const LinkingConfig = {
  prefixes: [Linking.createURL('/')],
  config: {
    screens: {
      Home: {
        path: 'home',
        screens: {
          'PROMOTIONS': {
            path:'Promotions',
            screens: {
              PromotionDetails:':id'
            }
          },
          'MENU': {
            path: 'More/MyWallet',
            // screens: 'PaymentMethod'
            screens: {
              PaymentMethod: ''
            }
          },
        }
      },
      Login: 'login'
    }
  }
}

I want the exact structure and the path which will be redirected to PaymentMehod Screen


问:
How to get data via bluetooth from another device to iphone?
In my application i want to get the data from a measuring device using bluetooth and update the iphone GUI accordingly.How could i do this communication using bluetooth.Is it supports all bluetooth profile.
Pls help me as i'm new iphone programmin.</p>

ContentLicense: CC BY-SA 3.0


问:
in Machine Learning for Audio Classification, in stage of taring our model we stuck with an error
we are working on machine learning for audio classification. we want to classify some human voices with The MFCC feature.

```<code>ValueError: Shapes (None, 10) and (None, 2) are incompatible
</code>```

The relevent Code is

num_epochs = 200
num_batch_size = 32

checkpointer = ModelCheckpoint(filepath='saved_models/audio_classification.hdf5',
verbose=1, save_best_only=True)
start = datetime.now()
model.fit(X_train, y_train, batch_size=num_batch_size, epochs=num_epochs, validation_data=(X_test, y_test), callbacks=[checkpointer], verbose=1)

duration = datetime.now() - start
print("Training completed in time: ", duration)

Body:
we are working on machine learning for audio classification. we want to classify some human voices with The MFCC feature.

ValueError: Shapes (None, 10) and (None, 2) are incompatible

The relevent Code is

num_epochs = 200
num_batch_size = 32

checkpointer = ModelCheckpoint(filepath='saved_models/audio_classification.hdf5',
verbose=1, save_best_only=True)
start = datetime.now()
model.fit(X_train, y_train, batch_size=num_batch_size, epochs=num_epochs, validation_data=(X_test, y_test), callbacks=[checkpointer], verbose=1)

duration = datetime.now() - start
print("Training completed in time: ", duration)


问:
Bug: ERROR in [eslint] Failed to load config "react-app" to extend from package.json
I am getting this error after saving any changes inside code files::

```<code>ERROR in [eslint] Failed to load config "react-app" to extend from.
Referenced from: /Users/archana/Documents/Workspace/my-app/package.json
</code>```

Steps to Reproduce::

I have migrated from npm to yarn

and then install the package dependencies. Everything is working fine except this. Every time I made changes and save them it shows me an error.

Versions I am using::

React version: 18.2.0

Yarn version: 3.3.1

node version: 18.12.1

## It worked in two cases, which are basically temporary solutions::

It will resolve if I will save the package.json file after saving any changes. Basically, I need to press "ctrl + s" inside "package.json" after any changes made inside the workspace otherwise above error occurred.
If I remove the below lines from "package.json". But after removing this it gives me an error for the "react-hook/exhaust-deps" ignore script lines.

```<code>"eslintConfig": {
        "extends": [
            "react-app",
            "react-app/jest"
        ]
    },
</code>```

Please suggest what should I do to resolve this error?

Body:
I am getting this error after saving any changes inside code files::

ERROR in [eslint] Failed to load config "react-app" to extend from.
Referenced from: /Users/archana/Documents/Workspace/my-app/package.json

Steps to Reproduce::

I have migrated from npm to yarn

and then install the package dependencies. Everything is working fine except this. Every time I made changes and save them it shows me an error.

Versions I am using::

React version: 18.2.0

Yarn version: 3.3.1

node version: 18.12.1

## It worked in two cases, which are basically temporary solutions::

It will resolve if I will save the package.json file after saving any changes. Basically, I need to press "ctrl + s" inside "package.json" after any changes made inside the workspace otherwise above error occurred.
If I remove the below lines from "package.json". But after removing this it gives me an error for the "react-hook/exhaust-deps" ignore script lines.

"eslintConfig": {
        "extends": [
            "react-app",
            "react-app/jest"
        ]
    },

Please suggest what should I do to resolve this error?


问:
React class component not updating fully when Redux state has changed
I need a help with a bug,or problem I have. Have read already a lot of articlas about immutable Redux state update, but solutions did not work. Looks like I am doning something wrong, but cant figure where. So, I have a nav panel with 3 links. Based on cliked link, it loads data from back and sets to state ( In console.log I see that state.products updates, but component does not rerenders( only partially, when list of products is shorter or longer.):

Redux:

```<code>import { createReducer } from "@reduxjs/toolkit";

const initialState = {

  selectedCategory: "all",
  products: [],

};

const reducer = createReducer(initialState, {

  SET_SELECTED_CATEGORY: (state, action) => {
    state.selectedCategory = action.value;
  },
  SET_PRODUCTS: (state, action) => {
    state.products = action.value;
  }

});

export default reducer;

</code>```

This is function that dispatch to Redux(Fecht works ok. And data is dispatched to Redux also. Even State changes, but that not cause rerender of component.):

```<code>const categoryChange = () => {
      console.log(this.props.header_category);
      this.props.dispatch({
        type: "SET_SELECTED_CATEGORY",
        value: this.props.header_category,
      });

      fetch("http://localhost:4000/", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          query: GET_PRODUCTS,
          variables: {
            categorie: this.props.header_category,
          },
        }),
      })
        .then((res) => res.json())
        .then((data) => {
          console.log(data);
          this.props.dispatch({
            type: "SET_PRODUCTS",
            value: data.data.category.products,
          });
        });
    };
</code>```

This a component that supose to rerender:

```<code>class MainPage extends Component {
  render() {
    console.log(this.props.state.products);
    return (
      <Container>
        <Title>
          {this.props.state.selectedCategory[0].toUpperCase() +
            this.props.state.selectedCategory.slice(1)}
        </Title>
        <ProductContainer>
          {this.props.state.products &&
            this.props.state.products.map((product, index) => (
              <SingleProduct key={index} product={product} />
            ))}
        </ProductContainer>
      </Container>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    state,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    dispatch,
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(MainPage);
</code>```

Rerendering should cause reload of a  coponent. But it dont.
I am using createReducer ,that in teory shuld not mutate state.

Body:
I need a help with a bug,or problem I have. Have read already a lot of articlas about immutable Redux state update, but solutions did not work. Looks like I am doning something wrong, but cant figure where. So, I have a nav panel with 3 links. Based on cliked link, it loads data from back and sets to state ( In console.log I see that state.products updates, but component does not rerenders( only partially, when list of products is shorter or longer.):

Redux:

import { createReducer } from "@reduxjs/toolkit";

const initialState = {

  selectedCategory: "all",
  products: [],

};

const reducer = createReducer(initialState, {

  SET_SELECTED_CATEGORY: (state, action) => {
    state.selectedCategory = action.value;
  },
  SET_PRODUCTS: (state, action) => {
    state.products = action.value;
  }

});

export default reducer;

This is function that dispatch to Redux(Fecht works ok. And data is dispatched to Redux also. Even State changes, but that not cause rerender of component.):

const categoryChange = () => {
      console.log(this.props.header_category);
      this.props.dispatch({
        type: "SET_SELECTED_CATEGORY",
        value: this.props.header_category,
      });

      fetch("http://localhost:4000/", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          query: GET_PRODUCTS,
          variables: {
            categorie: this.props.header_category,
          },
        }),
      })
        .then((res) => res.json())
        .then((data) => {
          console.log(data);
          this.props.dispatch({
            type: "SET_PRODUCTS",
            value: data.data.category.products,
          });
        });
    };

This a component that supose to rerender:

class MainPage extends Component {
  render() {
    console.log(this.props.state.products);
    return (
      <Container>
        <Title>
          {this.props.state.selectedCategory[0].toUpperCase() +
            this.props.state.selectedCategory.slice(1)}
        </Title>
        <ProductContainer>
          {this.props.state.products &&
            this.props.state.products.map((product, index) => (
              <SingleProduct key={index} product={product} />
            ))}
        </ProductContainer>
      </Container>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    state,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    dispatch,
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(MainPage);

Rerendering should cause reload of a  coponent. But it dont.
I am using createReducer ,that in teory shuld not mutate state.


问:
YARP authentication: how to refresh auth token
YARP-based service(just YARP) proxies a request to Service1. And what is important YARP authenticates on Service1. What is the best way to implement token refresh (see scheme)? In middleware? Another way? Would be grateful for an example.

scheme

I tried to do something like this:

```<code>endpoints.MapReverseProxy(proxyPipeline =>
{
    proxyPipeline.Use((context, next) =>
    {
      await _next(context);

      if (context.Response.StatusCode == StatusCodes.Status401Unauthorized)
      {
        // requset NEW_Yarp-Service1_Token on Service1
        // set "Bearer NEW_Yarp-Service1_Token" to Header

        await _next(context);
      }
    });
    proxyPipeline.UseSessionAffinity();
    proxyPipeline.UseLoadBalancing();
    proxyPipeline.UsePassiveHealthChecks();
});
</code>```

This leads to 502 Bad Gateway.

Body:
YARP-based service(just YARP) proxies a request to Service1. And what is important YARP authenticates on Service1. What is the best way to implement token refresh (see scheme)? In middleware? Another way? Would be grateful for an example.

scheme

I tried to do something like this:

endpoints.MapReverseProxy(proxyPipeline =>
{
    proxyPipeline.Use((context, next) =>
    {
      await _next(context);

      if (context.Response.StatusCode == StatusCodes.Status401Unauthorized)
      {
        // requset NEW_Yarp-Service1_Token on Service1
        // set "Bearer NEW_Yarp-Service1_Token" to Header

        await _next(context);
      }
    });
    proxyPipeline.UseSessionAffinity();
    proxyPipeline.UseLoadBalancing();
    proxyPipeline.UsePassiveHealthChecks();
});

This leads to 502 Bad Gateway.


问:
Writing a for loop to append randomly altered lists to a two dimensional list a given number of times
I am writing my first python program for a school project. It is a program to simulate an experiment where you randomly move ones and zeroes around in a matrix. I already wrote 90 % of it and it works ok. I am struggling with one last part - I wrote a for loop that swaps the positions of all ones and zeroes in a list, nested it in a loop which repeats that process a number of times, and am trying to nest it in another loop which would append the resulting lists to an empty matrix one after another a given number of times. The problem I am facing is that all these lists are the same and are supposed to be different.

this is the piece of code I am using. n is the number of the matrix' s columns, m is the number of rows and x is the number of times the ones and zeroes get swapped around in a single row. I am using a swap positions function from geeksforgeeks.

for example when we have a 4x4 matrix and want to mix 2 times:

```<code>n = 4
m = 4
x = 2
podlista = [0, 0, 1, 1]

def swapPositions(list, pos1, pos2):
    first_ele = list.pop(pos1)
    second_ele = list.pop(pos2 - 1)

    list.insert(pos1, second_ele)
    list.insert(pos2, first_ele)

    return list

macierz = []

for w in range(m):
    for y in range(x):
        for k in range(n):
            import random
            swapPositions(podlista, k, random.randint(0, (n - 1)))
    macierz.append(podlista)

print(macierz)
</code>```

where podlista means row and macierz is matrix
This is the only way I can think of doing this
I would really apreciate some help on this matter

Body:
I am writing my first python program for a school project. It is a program to simulate an experiment where you randomly move ones and zeroes around in a matrix. I already wrote 90 % of it and it works ok. I am struggling with one last part - I wrote a for loop that swaps the positions of all ones and zeroes in a list, nested it in a loop which repeats that process a number of times, and am trying to nest it in another loop which would append the resulting lists to an empty matrix one after another a given number of times. The problem I am facing is that all these lists are the same and are supposed to be different.

this is the piece of code I am using. n is the number of the matrix' s columns, m is the number of rows and x is the number of times the ones and zeroes get swapped around in a single row. I am using a swap positions function from geeksforgeeks.

for example when we have a 4x4 matrix and want to mix 2 times:

n = 4
m = 4
x = 2
podlista = [0, 0, 1, 1]

def swapPositions(list, pos1, pos2):
    first_ele = list.pop(pos1)
    second_ele = list.pop(pos2 - 1)

    list.insert(pos1, second_ele)
    list.insert(pos2, first_ele)

    return list

macierz = []

for w in range(m):
    for y in range(x):
        for k in range(n):
            import random
            swapPositions(podlista, k, random.randint(0, (n - 1)))
    macierz.append(podlista)

print(macierz)

where podlista means row and macierz is matrix
This is the only way I can think of doing this
I would really apreciate some help on this matter


问:
upload image from pixabay api to wordpress using rest api and python
I am new to python,and want to know upload image from pixabay api or others source to wordpress using rest api and python.

When i use this :

url=url_image  = "https://pixabay.com/api/?key={API_KEY}&q={keyword}.jpg"

They show this message "

{"code":"rest_upload_unknown_error","message":"Sorry, you are not
allowed to upload this file type.","data":{"status":500}}"

```<code>import base64, requests
from tempfile import NamedTemporaryFile
# keyword = input('Enter Your name')

keyword = 'flower'
def header(user, password):
    credentials = user + ':' + password
    token = base64.b64encode(credentials.encode())
    header_json = {'Authorization': 'Basic ' + token.decode('utf-8'),
                   'Content-Disposition' : 'attachment; filename=%s'% "test1.jpg"}
    return header_json

def upload_image_to_wordpress(file_path, header_json):
    media = {'file': file_path,'caption': 'f{keyword}'}
    responce = requests.post("https://yourwebsite.com/wp-json/wp/v2/media", headers = header_json, files = media)
    print(responce.text)

heder = header("username","password") #username, application password

url_image  = "https://pixabay.com/api/?key={API_KEY}&q={keyword}.jpg"
# url="https://cdn.pixabay.com/photo/2021/11/30/08/24/strawberries-6834750_1280.jpg"
raw = requests.get(f'{url_image}').content
with NamedTemporaryFile(delete=False,mode="wb",suffix=".jpg") as img :
    img.write(raw)

    # print(f.file())

    c  =  open(img.name,"rb")

    upload_image_to_wordpress(c,heder)
</code>```

Body:
I am new to python,and want to know upload image from pixabay api or others source to wordpress using rest api and python.

When i use this :

url=url_image  = "https://pixabay.com/api/?key={API_KEY}&q={keyword}.jpg"

They show this message "

{"code":"rest_upload_unknown_error","message":"Sorry, you are not
allowed to upload this file type.","data":{"status":500}}"

import base64, requests
from tempfile import NamedTemporaryFile
# keyword = input('Enter Your name')

keyword = 'flower'
def header(user, password):
    credentials = user + ':' + password
    token = base64.b64encode(credentials.encode())
    header_json = {'Authorization': 'Basic ' + token.decode('utf-8'),
                   'Content-Disposition' : 'attachment; filename=%s'% "test1.jpg"}
    return header_json

def upload_image_to_wordpress(file_path, header_json):
    media = {'file': file_path,'caption': 'f{keyword}'}
    responce = requests.post("https://yourwebsite.com/wp-json/wp/v2/media", headers = header_json, files = media)
    print(responce.text)

heder = header("username","password") #username, application password

url_image  = "https://pixabay.com/api/?key={API_KEY}&q={keyword}.jpg"
# url="https://cdn.pixabay.com/photo/2021/11/30/08/24/strawberries-6834750_1280.jpg"
raw = requests.get(f'{url_image}').content
with NamedTemporaryFile(delete=False,mode="wb",suffix=".jpg") as img :
    img.write(raw)

    # print(f.file())

    c  =  open(img.name,"rb")

    upload_image_to_wordpress(c,heder)


问:
Wildfly 27.0.1 serves blank page instead of administration console
I think I lost some hair on this one. I'm having a problem with Wildfly - I installed it on a remote server, however, when I try to enter the administration console it gives me a blank page only.

Wildfly version 27.0.1.Final

Problem:

I visit MYDOMAIN.XYZ where I should see the administration console

I pass the authorization with user details created via ssh

I'm redirected to MYDOMAIN.XYZ/console/index.html

The loader is briefly visible, but it disappears very soon

As a final result this document is served:

```<code><!DOCTYPE html\>
<html class="layout-pf layout-pf-fixed" lang="en"\>
<head\>
<title\>HAL Management Console\</title\>
<meta charset="utf-8"\>
<meta http-equiv="x-ua-compatible" content="ie=edge"\>
<meta name="viewport" content="width=device-width, initial-scale=1"\>
<link rel="icon shortcut" type="image/x-icon" href="favicon.db74b3b0.ico"\>
<link rel="apple-touch-icon" href="apple-touch-icon.fedc4af6.png"\>
<link rel="stylesheet" href="dev.291b1e16.css" media="screen"\>
<script type="module" src="dev.75953f7e.js"\>\</script\>\<script src="dev.159a2c8f.js" nomodule defer\>\</script\>\<script src="hal.nocache.js"\>\</script\>
</head\>
<body\> \</body\>
</html\>
</code>```

Here's a log from console

```<code>index.html:1          GET https://MYDOMAIN.XYZ/console/dev.75953f7e.js net::ERR_ABORTED 403
hal-0.js:10337 Set log level to INFO
hal.nocache.js:6 \[Violation\] 'readystatechange' handler took 202ms
hal-0.js:10706          GET https://MYDOMAIN.XYZ/keycloak/adapter/wildfly-console 404
hal-0.js:10713 10:09:20.670 ERROR o.j.h.c.b.endpoint.EndpointManager       Keycloak adapter 'https://MYDOMAIN.XYZ/keycloak/adapter/wildfly-console' doesn't exist - status: 404
hal-0.js:8553          POST https://MYDOMAIN.XYZ/management 403
hal-0.js:10713 10:09:20.730 ERROR o.j.h.d.dispatch.Dispatcher              Dispatcher error: Authentication required.
hal-0.js:10713 10:09:20.730 ERROR o.j.h.c.bootstrap.HalBootstrapper        Bootstrap error: Dispatcher error: Authentication required.
dev.291b1e16.css:1          GET https://MYDOMAIN.XYZ/console/OpenSans-Regular-webfont.b6d3c411.woff2 net::ERR_ABORTED 403
dev.291b1e16.css:1          GET https://MYDOMAIN.XYZ/console/OpenSans-Regular-webfont.e5de314f.woff net::ERR_ABORTED 403
dev.291b1e16.css:1          GET https://MYDOMAIN.XYZ/console/OpenSans-Regular-webfont.8bd2b33b.ttf net::ERR_ABORTED 403
</code>```

When I start wildfly several warnings are logged:

```<code>10:08:17,750 WARN  \[org.jboss.as.warn.fd-limit\] (main) WFLYSRV0071: The operating system has limited the number of open files to 3000 for this process; a value of at least 4096 is recommended 10:08:19,117 WARN  \[org.jboss.as.controller\] (ServerService Thread Pool -- 26) WFLYCTL0481: The runtime dependency package 'io.smallrye.opentracing-contrib' is already registered at location '/subsystem=microprofile-opentracing-smallrye' 10:08:19,126 WARN  \[org.jboss.as.controller\] (ServerService Thread Pool -- 26) WFLYCTL0481: The runtime dependency package 'io.smallrye.opentracing-contrib' is already registered at location '/subsystem=microprofile-opentracing-smallrye' 10:08:19,821 WARN  \[org.jboss.as.txn\] (ServerService Thread Pool -- 76) WFLYTX0013: The node-identifier attribute on the /subsystem=transactions is set to the default value. This is a danger for environments running multiple servers. Please make sure the attribute value is unique. 10:08:20,355 WARN  \[org.wildfly.extension.elytron\] (MSC service thread 1-6) WFLYELY00023: KeyStore file '/home/FOLDER/wildfly/standalone/configuration/application.keystore' does not exist. Used blank. 10:08:20,372 WARN  \[org.wildfly.extension.elytron\] (MSC service thread 1-1) WFLYELY01084: KeyStore /home/FOLDER/wildfly/standalone/configuration/application.keystore not found, it will be auto generated on first use with a self-signed certificate for host localhost
</code>```

I tried disabling WAF and changing the configuration in standalone.xml from:

```<code><interface name="management">
            <inet-address value="${jboss.bind.address.management:127.0.0.1}"/>
        </interface>
</code>```

to

```<code><interface name="management">
            <inet-address value="${jboss.bind.address.management:0.0.0.0}"/>
        </interface>
</code>```

However, this did not have any effect.

These keycloak errors are suspicious, especially that Wildfly moved to elytrum (from what I read). However, I'm not sure how I should handle them. What can be the problem? Is there something I can do to fix this? I really appreciate any help you can provide.

Body:
I think I lost some hair on this one. I'm having a problem with Wildfly - I installed it on a remote server, however, when I try to enter the administration console it gives me a blank page only.

Wildfly version 27.0.1.Final

Problem:

I visit MYDOMAIN.XYZ where I should see the administration console

I pass the authorization with user details created via ssh

I'm redirected to MYDOMAIN.XYZ/console/index.html

The loader is briefly visible, but it disappears very soon

As a final result this document is served:

<!DOCTYPE html\>

<title\>HAL Management Console\</title\>
<meta charset="utf-8"\>
<meta http-equiv="x-ua-compatible" content="ie=edge"\>
<meta name="viewport" content="width=device-width, initial-scale=1"\>
<link rel="icon shortcut" type="image/x-icon" href="favicon.db74b3b0.ico"\>
<link rel="apple-touch-icon" href="apple-touch-icon.fedc4af6.png"\>
<link rel="stylesheet" href="dev.291b1e16.css" media="screen"\>
\\

 \

Here's a log from console

index.html:1          GET https://MYDOMAIN.XYZ/console/dev.75953f7e.js net::ERR_ABORTED 403
hal-0.js:10337 Set log level to INFO
hal.nocache.js:6 \[Violation\] 'readystatechange' handler took 202ms
hal-0.js:10706          GET https://MYDOMAIN.XYZ/keycloak/adapter/wildfly-console 404
hal-0.js:10713 10:09:20.670 ERROR o.j.h.c.b.endpoint.EndpointManager       Keycloak adapter 'https://MYDOMAIN.XYZ/keycloak/adapter/wildfly-console' doesn't exist - status: 404
hal-0.js:8553          POST https://MYDOMAIN.XYZ/management 403
hal-0.js:10713 10:09:20.730 ERROR o.j.h.d.dispatch.Dispatcher              Dispatcher error: Authentication required.
hal-0.js:10713 10:09:20.730 ERROR o.j.h.c.bootstrap.HalBootstrapper        Bootstrap error: Dispatcher error: Authentication required.
dev.291b1e16.css:1          GET https://MYDOMAIN.XYZ/console/OpenSans-Regular-webfont.b6d3c411.woff2 net::ERR_ABORTED 403
dev.291b1e16.css:1          GET https://MYDOMAIN.XYZ/console/OpenSans-Regular-webfont.e5de314f.woff net::ERR_ABORTED 403
dev.291b1e16.css:1          GET https://MYDOMAIN.XYZ/console/OpenSans-Regular-webfont.8bd2b33b.ttf net::ERR_ABORTED 403

When I start wildfly several warnings are logged:

10:08:17,750 WARN  \[org.jboss.as.warn.fd-limit\] (main) WFLYSRV0071: The operating system has limited the number of open files to 3000 for this process; a value of at least 4096 is recommended 10:08:19,117 WARN  \[org.jboss.as.controller\] (ServerService Thread Pool -- 26) WFLYCTL0481: The runtime dependency package 'io.smallrye.opentracing-contrib' is already registered at location '/subsystem=microprofile-opentracing-smallrye' 10:08:19,126 WARN  \[org.jboss.as.controller\] (ServerService Thread Pool -- 26) WFLYCTL0481: The runtime dependency package 'io.smallrye.opentracing-contrib' is already registered at location '/subsystem=microprofile-opentracing-smallrye' 10:08:19,821 WARN  \[org.jboss.as.txn\] (ServerService Thread Pool -- 76) WFLYTX0013: The node-identifier attribute on the /subsystem=transactions is set to the default value. This is a danger for environments running multiple servers. Please make sure the attribute value is unique. 10:08:20,355 WARN  \[org.wildfly.extension.elytron\] (MSC service thread 1-6) WFLYELY00023: KeyStore file '/home/FOLDER/wildfly/standalone/configuration/application.keystore' does not exist. Used blank. 10:08:20,372 WARN  \[org.wildfly.extension.elytron\] (MSC service thread 1-1) WFLYELY01084: KeyStore /home/FOLDER/wildfly/standalone/configuration/application.keystore not found, it will be auto generated on first use with a self-signed certificate for host localhost

I tried disabling WAF and changing the configuration in standalone.xml from:

<interface name="management">
            <inet-address value="${jboss.bind.address.management:127.0.0.1}"/>
        </interface>

to

<interface name="management">
            <inet-address value="${jboss.bind.address.management:0.0.0.0}"/>
        </interface>

However, this did not have any effect.

These keycloak errors are suspicious, especially that Wildfly moved to elytrum (from what I read). However, I'm not sure how I should handle them. What can be the problem? Is there something I can do to fix this? I really appreciate any help you can provide.