问:
RecyclerView in side a recyclerView
(https://i.stack.imgur.com/t5GM3.jpg)

RecyclerView in side a recyclerView.

The result is loading but not in the particular category. how to show results in a particular category? Can anyone have a solution?                                                                                ??

```<code>

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
    Context context;
    List<String> list;
    ArrayList<StoryModel> storyModels;
    StoryAdapter adapter;
    DatabaseReference reference;

    public CategoryAdapter(Context context, List<String> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public CategoryAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.category_item,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CategoryAdapter.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        holder.categoryTextView.setText(list.get(position));
        storyModels = new ArrayList<>();
        adapter = new StoryAdapter(context,storyModels);
        holder.categoryRelativeLayout.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        holder.categoryRelativeLayout.setAdapter(adapter);
        reference = FirebaseDatabase.getInstance().getReference().child("Stories").child(list.get(position));
        reference.addListenerForSingleValueEvent(new ValueEventListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot : snapshot.getChildren()){
                    StoryModel model = dataSnapshot.getValue(StoryModel.class);
                    storyModels.add(model);
                }
                adapter.notifyDataSetChanged();
                holder.categoryRelativeLayout.setVisibility(View.VISIBLE);
                holder.loadingCategoryStories.setVisibility(View.GONE);
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView categoryTextView;
        RecyclerView categoryRelativeLayout;
        ProgressBar loadingCategoryStories;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            categoryTextView = itemView.findViewById(R.id.categoryTextView);
            categoryRelativeLayout = itemView.findViewById(R.id.categoryRelativeLayout);
            loadingCategoryStories = itemView.findViewById(R.id.loadingCategoryStories);

        }
    }
}
</code>```
```<code>

public class StoryAdapter extends RecyclerView.Adapter<StoryAdapter.ViewHolder> {
    Context context;
    ArrayList<StoryModel> data;

    public StoryAdapter(Context context, ArrayList<StoryModel> data) {
        this.context = context;
        this.data = data;
    }

    @NonNull
    @Override
    public StoryAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.story_item_view,parent,false);
        return new StoryAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull StoryAdapter.ViewHolder holder, int position) {
        StoryModel storyModel = data.get(position);
        Picasso.get().load(storyModel.getImage())
                .placeholder(R.drawable.ic_launcher_background).into(holder.imageStoryItem);
        holder.storyItemTitle.setText(storyModel.getTittle());
        holder.storyItemAuthor.setText(storyModel.getAuthor());

        holder.storyItemTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(context, ReadingActivity.class);
                i.putExtra("author",storyModel.getAuthor());
                i.putExtra("title",storyModel.getTittle());
                i.putExtra("image",storyModel.getImage());
                i.putExtra("story",storyModel.getStory());
                i.putExtra("date",storyModel.getDate());
                i.putExtra("key",storyModel.getStoryKey());
                ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context,holder.imageStoryItem, ViewCompat.getTransitionName(holder.imageStoryItem));
                context.startActivity(i,optionsCompat.toBundle());
            }
        });
        holder.imageStoryItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(context, ReadingActivity.class);
                i.putExtra("author",storyModel.getAuthor());
                i.putExtra("title",storyModel.getTittle());
                i.putExtra("image",storyModel.getImage());
                i.putExtra("story",storyModel.getStory());
                i.putExtra("date",storyModel.getDate());
                i.putExtra("key",storyModel.getStoryKey());
                ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context,holder.imageStoryItem, ViewCompat.getTransitionName(holder.imageStoryItem));
                context.startActivity(i,optionsCompat.toBundle());
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageStoryItem;
        TextView storyItemTitle,storyItemAuthor;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            storyItemTitle = itemView.findViewById(R.id.storyItemTitle);
            imageStoryItem = itemView.findViewById(R.id.imageStoryItem);
            storyItemAuthor = itemView.findViewById(R.id.storyItemAuthor);
        }
    }
}
</code>```

Title: RecyclerView in side a recyclerView

Body:
(https://i.stack.imgur.com/t5GM3.jpg)

RecyclerView in side a recyclerView.

The result is loading but not in the particular category. how to show results in a particular category? Can anyone have a solution?                                                                                ??

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
    Context context;
    List<String> list;
    ArrayList<StoryModel> storyModels;
    StoryAdapter adapter;
    DatabaseReference reference;

    public CategoryAdapter(Context context, List<String> list) {
        this.context = context;
        this.list = list;
    }

    @NonNull
    @Override
    public CategoryAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.category_item,parent,false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CategoryAdapter.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
        holder.categoryTextView.setText(list.get(position));
        storyModels = new ArrayList<>();
        adapter = new StoryAdapter(context,storyModels);
        holder.categoryRelativeLayout.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        holder.categoryRelativeLayout.setAdapter(adapter);
        reference = FirebaseDatabase.getInstance().getReference().child("Stories").child(list.get(position));
        reference.addListenerForSingleValueEvent(new ValueEventListener() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for (DataSnapshot dataSnapshot : snapshot.getChildren()){
                    StoryModel model = dataSnapshot.getValue(StoryModel.class);
                    storyModels.add(model);
                }
                adapter.notifyDataSetChanged();
                holder.categoryRelativeLayout.setVisibility(View.VISIBLE);
                holder.loadingCategoryStories.setVisibility(View.GONE);
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView categoryTextView;
        RecyclerView categoryRelativeLayout;
        ProgressBar loadingCategoryStories;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            categoryTextView = itemView.findViewById(R.id.categoryTextView);
            categoryRelativeLayout = itemView.findViewById(R.id.categoryRelativeLayout);
            loadingCategoryStories = itemView.findViewById(R.id.loadingCategoryStories);

        }
    }
}

public class StoryAdapter extends RecyclerView.Adapter<StoryAdapter.ViewHolder> {
    Context context;
    ArrayList<StoryModel> data;

    public StoryAdapter(Context context, ArrayList<StoryModel> data) {
        this.context = context;
        this.data = data;
    }

    @NonNull
    @Override
    public StoryAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.story_item_view,parent,false);
        return new StoryAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull StoryAdapter.ViewHolder holder, int position) {
        StoryModel storyModel = data.get(position);
        Picasso.get().load(storyModel.getImage())
                .placeholder(R.drawable.ic_launcher_background).into(holder.imageStoryItem);
        holder.storyItemTitle.setText(storyModel.getTittle());
        holder.storyItemAuthor.setText(storyModel.getAuthor());

        holder.storyItemTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(context, ReadingActivity.class);
                i.putExtra("author",storyModel.getAuthor());
                i.putExtra("title",storyModel.getTittle());
                i.putExtra("image",storyModel.getImage());
                i.putExtra("story",storyModel.getStory());
                i.putExtra("date",storyModel.getDate());
                i.putExtra("key",storyModel.getStoryKey());
                ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context,holder.imageStoryItem, ViewCompat.getTransitionName(holder.imageStoryItem));
                context.startActivity(i,optionsCompat.toBundle());
            }
        });
        holder.imageStoryItem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(context, ReadingActivity.class);
                i.putExtra("author",storyModel.getAuthor());
                i.putExtra("title",storyModel.getTittle());
                i.putExtra("image",storyModel.getImage());
                i.putExtra("story",storyModel.getStory());
                i.putExtra("date",storyModel.getDate());
                i.putExtra("key",storyModel.getStoryKey());
                ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation((Activity) context,holder.imageStoryItem, ViewCompat.getTransitionName(holder.imageStoryItem));
                context.startActivity(i,optionsCompat.toBundle());
            }
        });
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView imageStoryItem;
        TextView storyItemTitle,storyItemAuthor;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            storyItemTitle = itemView.findViewById(R.id.storyItemTitle);
            imageStoryItem = itemView.findViewById(R.id.imageStoryItem);
            storyItemAuthor = itemView.findViewById(R.id.storyItemAuthor);
        }
    }
}


来源: stackexchange

问:
compression level using miniz having no effect
I'm evaluating using the low-level routines in miniz and testing different compression levels with differently sized inputs. Level 0 always gets a little bit larger (as expected) but the other levels all result in the exact same size for the same input. They are getting progressively slower (and level 0 works) so setting a different level has some effect. I can decompress everything back again.</p>
```<code>   tdefl_compressor compressor;
   auto flags = tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY);

   auto status = tdefl_init(&compressor, write, &target, flags);
   assert(status == TDEFL_STATUS_OKAY);
   tdefl_compress_buffer(&compressor, data.data, data.size, TDEFL_FINISH);

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm evaluating using the low-level routines in miniz and testing different compression levels with differently sized inputs. Level 0 always gets a little bit larger (as expected) but the other levels all result in the exact same size for the same input. They are getting progressively slower (and level 0 works) so setting a different level has some effect. I can decompress everything back again.

   tdefl_compressor compressor;
   auto flags = tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY);

   auto status = tdefl_init(&compressor, write, &target, flags);
   assert(status == TDEFL_STATUS_OKAY);
   tdefl_compress_buffer(&compressor, data.data, data.size, TDEFL_FINISH);


问:
Android MockWebServer Dispatch not being called
I'm trying to use MockWebServer in my instrumented tests but its not working. The real API is being called, and not the mock itself.

```<code>com.squareup.okhttp3:mockwebserver:4.10.0
</code>```

I have my base class:

```<code>abstract class BaseInstrumentedTest {

    private var mockWebServer: MockWebServer = MockWebServer()

    init {
        mockWebServer.start(8080)
    }

    @After
    fun after() {
        mockWebServer.shutdown()
    }

    fun setDispatcher(it: Dispatcher){
        mockWebServer.dispatcher = it
    }
}
</code>```

And I'm using this dispatcher just to see how it works.

```<code> fun getDispatcher(): Dispatcher {
        return object : Dispatcher() {
            override fun dispatch(request: RecordedRequest): MockResponse {
                return  MockResponse().setResponseCode(500)
            }
        }
    }
</code>```

So, I could do it like:

```<code> @Test
    fun someTestHere() {
        setDispatcher(getDispatcher())
        launchActivity()
    }
</code>```

But unfortunately its not working.

Any guesses?

Body:
I'm trying to use MockWebServer in my instrumented tests but its not working. The real API is being called, and not the mock itself.

com.squareup.okhttp3:mockwebserver:4.10.0

I have my base class:

abstract class BaseInstrumentedTest {

    private var mockWebServer: MockWebServer = MockWebServer()

    init {
        mockWebServer.start(8080)
    }

    @After
    fun after() {
        mockWebServer.shutdown()
    }

    fun setDispatcher(it: Dispatcher){
        mockWebServer.dispatcher = it
    }
}

And I'm using this dispatcher just to see how it works.

 fun getDispatcher(): Dispatcher {
        return object : Dispatcher() {
            override fun dispatch(request: RecordedRequest): MockResponse {
                return  MockResponse().setResponseCode(500)
            }
        }
    }

So, I could do it like:

 @Test
    fun someTestHere() {
        setDispatcher(getDispatcher())
        launchActivity()
    }

But unfortunately its not working.

Any guesses?


问:
My all flutter apps are not running in my physical device. showing blank screen in my physical device
My app/build.gradle

```<code>def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new FileNotFoundException("\"Flutter SDK not found. Define location with flutter.sdk in the local.properties file.\"")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 31
    ndkVersion flutter.ndkVersion\

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.flt_firebase"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        minSdkVersion 21
        targetSdkVersion 31
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    def multidex_version = "2.0.1"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation platform('com.google.firebase:firebase-bom:31.1.1')
}

</code>```

All flutter app's are not running in my physical device however it's working in virtual device(emulator).When I run my flutter app i see only blank black screen in my physical device.

I tried these thing:-

flutter clean

Device restart

multiple users

uninstall app from device from all users

Body:
My app/build.gradle

def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new FileNotFoundException("\"Flutter SDK not found. Define location with flutter.sdk in the local.properties file.\"")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 31
    ndkVersion flutter.ndkVersion\

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.flt_firebase"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration.
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        minSdkVersion 21
        targetSdkVersion 31
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    def multidex_version = "2.0.1"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation platform('com.google.firebase:firebase-bom:31.1.1')
}

All flutter app's are not running in my physical device however it's working in virtual device(emulator).When I run my flutter app i see only blank black screen in my physical device.

I tried these thing:-

flutter clean

Device restart

multiple users

uninstall app from device from all users


问:
Screen-sharing Pycharm is imperfect
When screen-sharing, the 2nd person can't see everything.
For example, the 2nd person can't see this pop-up (but can see everything else):

Has anyone found a workaround for this?

Title: Screen-sharing Pycharm is imperfect


问:
How to extract monthly Worldclim data for several date-months in R
I know that there are ways of extracting weather data from WorldClim through R, by specifying the coordinates (for example, species presences).

Yet I need to do something a bit more specific.
My data has also several dates from 1980-2018, and the coordinates do not repeat between dates. My idea is to extract precipitation, max T, and min T for each specific month of those dates, preferently in one round.

So, something to identify the month and year from the date, and extract the weather information for the specific coordinate, from the equivalent weather layers (month and year)

Anyone knows how to solve this?


问:
D3 X Domain shifting unexpectedly after panning
I am trying to create a plot that is pannable/zoomable only in the x and is responsive to the page resizes. I am running into an issue where the domain of the x-axis works properly at the original zoomTransform. Code snippet is below. I would suggest opening in a different window to test. Notice that the domain stays the same when the window is resized at the original state. Once the plot is panned any amount (the further you pan the more prominent the issue) the domain will shift on page resize.

I have tested trying to adjust the domain on x_ax to the value of the vd axis but that does not seem to help.

window.addEventListener("resize", redraw);

let parentRect = $("#i3061007142472").parent()[0].getBoundingClientRect();
let pWidth = parentRect.width;
let pHeight = parentRect.height;

var margin = {
    'top': 10,
    'right': 30,
    'bottom': 30,
    'left': 60
  },
  width = pWidth - margin.left - margin.right,
  height = pHeight - margin.top - margin.bottom;

var svg = d3.select("#i3061007142472")
  .attr("width", width)
  .attr("height", height + 20);

var zoom = d3.zoom();
zoom.on("zoom", zoom_handler_dataplot);
d3.select("#i3061007142472").call(zoom);

var x_ax = d3.scaleTime()
  .domain([new Date('0'), new Date('10')])
  .range([60, width]);

x_ax.type = "time";

var svg_gX = svg.append("g")
  .attr("class", "xAxis dataplot")
  .attr("transform", `translate(0, ${height})`)

svg_gX.call(d3.axisBottom(x_ax).ticks(5));

var y_ax = d3.scaleLinear()
  .domain([0, 10])
  .range([height, 0]);
y_ax.type = "linear";

let vd_xaxis_ax = x_ax.copy();
let vd_yaxis_ax = y_ax.copy();

var svg_gY = svg.append("g")
  .attr("class", "yAxis dataplot")
  .style("padding-left", "50px")
  .attr("transform", "translate(" + 60 + ", 0)")
  .call(d3.axisLeft(y_ax).ticks(5));

allow_pan_dir = "x";
domain = x_ax.domain();

function zoom_handler_dataplot() {
  if (allow_pan_dir != "none") {
    if (allow_pan_dir == "x" || allow_pan_dir == "both") {

      vd_xaxis_ax = d3.event.transform.rescaleX(x_ax);
      domain = vd_xaxis_ax.domain()
      svg_gX.call(d3.axisBottom(vd_xaxis_ax));

    } else {
      vd_xaxis_ax = x_ax;
    }
    if (allow_pan_dir == "y" || allow_pan_dir == "both") {
      vd_yaxis_ax = d3.event.transform.rescaleY(y_ax);
      svg_gY.call(d3.axisLeft(vd_yaxis_ax));
    } else {
      vd_yaxis_ax = y_ax;
    }
  }
}

function redraw() {
  console.warn("calling redraw");
  console.warn(allow_pan_dir);
  chartWidth = parseInt(d3.select(".dataplot_i3061007142472").style("width"));
  chartHeight = parseInt(d3.select(".dataplot_i3061007142472").style("height"));
  height = chartHeight - margin.top - margin.bottom + 20;

  x_ax.range([60, chartWidth]);
  y_ax.range([chartHeight - 30 - 10 + 20, 0]);

  if (allow_pan_dir == "x" || allow_pan_dir == "both") {

    vd_xaxis_ax = d3.zoomTransform(d3.select("#i3061007142472").node()).rescaleX(x_ax);

    svg_gX.call(d3.axisBottom(vd_xaxis_ax));

  } else {
    vd_xaxis_ax = x_ax;
  }

  if (allow_pan_dir == "y" || allow_pan_dir == "both") {
    vd_yaxis_ax = d3.zoomTransform(d3.select("#i3061007142472").node()).rescaleY(y_ax);
    svg_gY.call(d3.axisLeft(vd_yaxis_ax));
  } else {
    vd_yaxis_ax = y_ax;
  }

  let currTransform = d3.zoomTransform(d3.select('#i3061007142472').node());
  d3.select("#i3061007142472").call(zoom.transform, currTransform);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./styles.css ">
  <title>Document</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.0.0/d3.min.js" integrity="sha512-il/oXcqETt5LGGmWWbOZLxrDgQQXlr7+ZI37ksA//3e9mxFloAOzlkF8SqtMOlWL6zTCk8hPYUQnreiQvT4elQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
</head>

<body>
  <div id="my_plot" style="display: flex; flex: 1;">
    <svg id="i3061007142472" class="dataplot_i3061007142472 dataplot"></svg>
  </div>

  <script src="./app.js"></script>
</body>

</html></code>```

Body:
I am trying to create a plot that is pannable/zoomable only in the x and is responsive to the page resizes. I am running into an issue where the domain of the x-axis works properly at the original zoomTransform. Code snippet is below. I would suggest opening in a different window to test. Notice that the domain stays the same when the window is resized at the original state. Once the plot is panned any amount (the further you pan the more prominent the issue) the domain will shift on page resize.

I have tested trying to adjust the domain on x_ax to the value of the vd axis but that does not seem to help.

window.addEventListener("resize", redraw);

let parentRect = $("#i3061007142472").parent()[0].getBoundingClientRect();
let pWidth = parentRect.width;
let pHeight = parentRect.height;

var margin = {
    'top': 10,
    'right': 30,
    'bottom': 30,
    'left': 60
  },
  width = pWidth - margin.left - margin.right,
  height = pHeight - margin.top - margin.bottom;

var svg = d3.select("#i3061007142472")
  .attr("width", width)
  .attr("height", height + 20);

var zoom = d3.zoom();
zoom.on("zoom", zoom_handler_dataplot);
d3.select("#i3061007142472").call(zoom);

var x_ax = d3.scaleTime()
  .domain([new Date('0'), new Date('10')])
  .range([60, width]);

x_ax.type = "time";

var svg_gX = svg.append("g")
  .attr("class", "xAxis dataplot")
  .attr("transform", `translate(0, ${height})`)

svg_gX.call(d3.axisBottom(x_ax).ticks(5));

var y_ax = d3.scaleLinear()
  .domain([0, 10])
  .range([height, 0]);
y_ax.type = "linear";

let vd_xaxis_ax = x_ax.copy();
let vd_yaxis_ax = y_ax.copy();

var svg_gY = svg.append("g")
  .attr("class", "yAxis dataplot")
  .style("padding-left", "50px")
  .attr("transform", "translate(" + 60 + ", 0)")
  .call(d3.axisLeft(y_ax).ticks(5));

allow_pan_dir = "x";
domain = x_ax.domain();

function zoom_handler_dataplot() {
  if (allow_pan_dir != "none") {
    if (allow_pan_dir == "x" || allow_pan_dir == "both") {

      vd_xaxis_ax = d3.event.transform.rescaleX(x_ax);
      domain = vd_xaxis_ax.domain()
      svg_gX.call(d3.axisBottom(vd_xaxis_ax));

    } else {
      vd_xaxis_ax = x_ax;
    }
    if (allow_pan_dir == "y" || allow_pan_dir == "both") {
      vd_yaxis_ax = d3.event.transform.rescaleY(y_ax);
      svg_gY.call(d3.axisLeft(vd_yaxis_ax));
    } else {
      vd_yaxis_ax = y_ax;
    }
  }
}

function redraw() {
  console.warn("calling redraw");
  console.warn(allow_pan_dir);
  chartWidth = parseInt(d3.select(".dataplot_i3061007142472").style("width"));
  chartHeight = parseInt(d3.select(".dataplot_i3061007142472").style("height"));
  height = chartHeight - margin.top - margin.bottom + 20;

  x_ax.range([60, chartWidth]);
  y_ax.range([chartHeight - 30 - 10 + 20, 0]);

  if (allow_pan_dir == "x" || allow_pan_dir == "both") {

    vd_xaxis_ax = d3.zoomTransform(d3.select("#i3061007142472").node()).rescaleX(x_ax);

    svg_gX.call(d3.axisBottom(vd_xaxis_ax));

  } else {
    vd_xaxis_ax = x_ax;
  }

  if (allow_pan_dir == "y" || allow_pan_dir == "both") {
    vd_yaxis_ax = d3.zoomTransform(d3.select("#i3061007142472").node()).rescaleY(y_ax);
    svg_gY.call(d3.axisLeft(vd_yaxis_ax));
  } else {
    vd_yaxis_ax = y_ax;
  }

  let currTransform = d3.zoomTransform(d3.select('#i3061007142472').node());
  d3.select("#i3061007142472").call(zoom.transform, currTransform);
}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./styles.css ">
  <title>Document</title>

    <svg id="i3061007142472" class="dataplot_i3061007142472 dataplot"></svg>


问:
How to catch io.netty.handler.timeout.ReadTimeoutException
I am new to WebClient. I would like to handle a io.netty.handler.timeout.ReadTimeoutException thrown from the underlying HTTP client.

This is how I have configured my HttpClient, the one I am passing to WebClient.

```<code>HttpClient httpClient(){
    return HttpClient.create()
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
            .doOnConnected(connection -> {
                connection
                        .addHandlerLast(new WriteTimeoutHandler(30))
                        .addHandlerLast(new ReadTimeoutHandler(30));
            });
</code>```

And here is my WebClient configuration.

```<code>@Bean
WebClient  webClient(){
    return WebClient.builder()
            .clientConnector(new ReactorClientHttpConnector(httpClient))
            .baseUrl("https://jsonplaceholder.typicode.com")
            .build();
}
</code>```

And my code to perform the GET is below:

```<code>public List<Post> getAll() {
    try {
        return webClient
                .get()
                .uri("/posts")
                .retrieve()
                .bodyToFlux(Post.class)
                .collectList()
                .block();
    }  catch (ReadTimeoutException ex) {
        log.error("A ReadTimeoutException occurred: {}", ex.getLocalizedMessage());
        throw new ApiReadTimeOutException(ex.getLocalizedMessage(), ex);
    } catch (WebClientRequestException ex) {
        log.error("A WebClientRequestException occurred: {}", ex.getLocalizedMessage());
        throw new ApiException(ex.getLocalizedMessage(), ex);
    }
}
</code>```

And my code to simulate a timeout. The WebClient for my stub has a timeout of 5 seconds.

```<code>stubFor(get(urlEqualTo("/posts")).willReturn(
        aResponse()
                .withStatus(HttpStatus.OK.value())
                .withBodyFile("all-posts.json")
                .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .withFixedDelay(10000)
));
</code>```

From this a ReadTimeoutException is thrown, however, it's not being captured in the first catch block. I want it to be captured there. It's being captured in the second catch block.

What do I need to do to make ReadTimeoutException be captured in the first catch block?

Body:
I am new to WebClient. I would like to handle a io.netty.handler.timeout.ReadTimeoutException thrown from the underlying HTTP client.

This is how I have configured my HttpClient, the one I am passing to WebClient.

HttpClient httpClient(){
    return HttpClient.create()
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 30000)
            .doOnConnected(connection -> {
                connection
                        .addHandlerLast(new WriteTimeoutHandler(30))
                        .addHandlerLast(new ReadTimeoutHandler(30));
            });

And here is my WebClient configuration.

@Bean
WebClient  webClient(){
    return WebClient.builder()
            .clientConnector(new ReactorClientHttpConnector(httpClient))
            .baseUrl("https://jsonplaceholder.typicode.com")
            .build();
}

And my code to perform the GET is below:

public List<Post> getAll() {
    try {
        return webClient
                .get()
                .uri("/posts")
                .retrieve()
                .bodyToFlux(Post.class)
                .collectList()
                .block();
    }  catch (ReadTimeoutException ex) {
        log.error("A ReadTimeoutException occurred: {}", ex.getLocalizedMessage());
        throw new ApiReadTimeOutException(ex.getLocalizedMessage(), ex);
    } catch (WebClientRequestException ex) {
        log.error("A WebClientRequestException occurred: {}", ex.getLocalizedMessage());
        throw new ApiException(ex.getLocalizedMessage(), ex);
    }
}

And my code to simulate a timeout. The WebClient for my stub has a timeout of 5 seconds.

stubFor(get(urlEqualTo("/posts")).willReturn(
        aResponse()
                .withStatus(HttpStatus.OK.value())
                .withBodyFile("all-posts.json")
                .withHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .withFixedDelay(10000)
));

From this a ReadTimeoutException is thrown, however, it's not being captured in the first catch block. I want it to be captured there. It's being captured in the second catch block.

What do I need to do to make ReadTimeoutException be captured in the first catch block?


问:
Python keeps on showing 'EXPRESSION EXPECTED ' in the elif commands in so many different lines like 46th, 54th, 62nd, and so on
```<code>#Program 9-3
#Menu driven program to do various list operations
myList = [22,4,16,38,13] #myList already has 5 elements
choice = 0
while True:
 print("The list 'myList' has the following elements", myList)
 print("\nL I S T O P E R A T I O N S")
 print(" 1. Append an element")
 print(" 2. Insert an element at the desired position")
 print(" 3. Append a list to the given list")
 print(" 4. Modify an existing element")
 print(" 5. Delete an existing element by its position")
 print(" 6. Delete an existing element by its value")
 print(" 7. Sort the list in ascending order")
 print(" 8. Sort the list in descending order")
 print(" 9. Display the list")
 print(" 10. Exit")
 choice = int(input("ENTER YOUR CHOICE (1-10): "))
 #append element
 if choice == 1:
   element = int(input("Enter the element to be appended: "))
   myList.append(element)
   print("The element has been appended\n")
   #insert an element at desired position
 elif choice == 2:
   element = int(input("Enter the element to be inserted: "))
   pos = int(input("Enter the position:"))
   myList.insert(pos,element)
   print("The element has been inserted\n")
   #append a list to the given list
 elif choice == 3:
   newList = eval(input( "Enter the elements separated by commas"))
   myList.extend(list(newList))
   print("The list has been appended\n")
   #modify an existing element
 elif choice == 4:
   i = int(input("Enter the position of the element to be modified: "))
 if i < len(myList):
   newElement = int(input("Enter the new element: "))
   oldElement = myList[i]
   myList[i] = newElement
   print("The element",oldElement,"has been modified\n")
 else:
   print("Position of the element is more than the length of list")
   #delete an existing element by position
 elif choice == 5:
   i = int(input("Enter the position of the element to be deleted: "))
if i < len(myList):
     element = myList.pop(i)
     print("The element",element,"has been deleted\n")
else:
   print("\nPosition of the element is more than the length of list")
   #delete an existing element by value
 elif choice == 6:
   element = int(input("\nEnter the element to be deleted: "))
   if element in myList:
     myList.remove(element)
     print("\nThe element",element,"has been deleted\n")
   else:
    print("\nElement",element,"is not present in the list")
       #list in sorted order
   elif choice == 7:
     myList.sort()
     print("\nThe list has been sorted")
 #list in reverse sorted order
  elif choice == 8:
    myList.sort(reverse = True)
     print("\nThe list has been sorted in reverse order")
 #display the list
   elif choice == 9:
 print("\nThe list is:", myList)
 #exit from the menu
   elif choice == 10:
     break
   else:
     print("Choice is not valid")
     print("\n\nPress any key to continue..............")
     ch = input()
</code>```

I was trying to write a menu driven program to perform various list operations, such as:

Append an element

Inser an element

Modify an existed element

Delete an existing element from its position

Delete an existing element with a given value

Sort the list in ascending order.

Sort the list in descending order.

Display the list

Body:
#Program 9-3
#Menu driven program to do various list operations
myList = [22,4,16,38,13] #myList already has 5 elements
choice = 0
while True:
 print("The list 'myList' has the following elements", myList)
 print("\nL I S T O P E R A T I O N S")
 print(" 1. Append an element")
 print(" 2. Insert an element at the desired position")
 print(" 3. Append a list to the given list")
 print(" 4. Modify an existing element")
 print(" 5. Delete an existing element by its position")
 print(" 6. Delete an existing element by its value")
 print(" 7. Sort the list in ascending order")
 print(" 8. Sort the list in descending order")
 print(" 9. Display the list")
 print(" 10. Exit")
 choice = int(input("ENTER YOUR CHOICE (1-10): "))
 #append element
 if choice == 1:
   element = int(input("Enter the element to be appended: "))
   myList.append(element)
   print("The element has been appended\n")
   #insert an element at desired position
 elif choice == 2:
   element = int(input("Enter the element to be inserted: "))
   pos = int(input("Enter the position:"))
   myList.insert(pos,element)
   print("The element has been inserted\n")
   #append a list to the given list
 elif choice == 3:
   newList = eval(input( "Enter the elements separated by commas"))
   myList.extend(list(newList))
   print("The list has been appended\n")
   #modify an existing element
 elif choice == 4:
   i = int(input("Enter the position of the element to be modified: "))
 if i < len(myList):
   newElement = int(input("Enter the new element: "))
   oldElement = myList[i]
   myList[i] = newElement
   print("The element",oldElement,"has been modified\n")
 else:
   print("Position of the element is more than the length of list")
   #delete an existing element by position
 elif choice == 5:
   i = int(input("Enter the position of the element to be deleted: "))
if i < len(myList):
     element = myList.pop(i)
     print("The element",element,"has been deleted\n")
else:
   print("\nPosition of the element is more than the length of list")
   #delete an existing element by value
 elif choice == 6:
   element = int(input("\nEnter the element to be deleted: "))
   if element in myList:
     myList.remove(element)
     print("\nThe element",element,"has been deleted\n")
   else:
    print("\nElement",element,"is not present in the list")
       #list in sorted order
   elif choice == 7:
     myList.sort()
     print("\nThe list has been sorted")
 #list in reverse sorted order
  elif choice == 8:
    myList.sort(reverse = True)
     print("\nThe list has been sorted in reverse order")
 #display the list
   elif choice == 9:
 print("\nThe list is:", myList)
 #exit from the menu
   elif choice == 10:
     break
   else:
     print("Choice is not valid")
     print("\n\nPress any key to continue..............")
     ch = input()

I was trying to write a menu driven program to perform various list operations, such as:

Append an element

Inser an element

Modify an existed element

Delete an existing element from its position

Delete an existing element with a given value

Sort the list in ascending order.

Sort the list in descending order.

Display the list


问:
NativeMessaging in Android inside chromebook
I came with a weird question but sadly I don;'t have any code example to base me on.

I'm trying to create an android application that uses native messaging
to communicate with a google chrome extension. That application will be running as android application in the same chromebook as the chrome extension will be running.

Is that even possible? I questioniung because of native messaging uses standard input output to communicate and android also does it for logcat and I think is not actually the same I/O I need because of the VM of android..

So, does anyone know if is that possible? Do you have any other way to do it? I've tried with websockets and it worked but sadly, chrome complains about the ssl certificate because is self signed and the websocket is not running in localhost but in ARC chromebook IP.

Thanks


问:
ngbDropdownToggle doesn't show as active
I'm using ng-Bootstrap, and have a nav as my navbar. Basically I don't know if I am using the correct component (nav for navbar), if so, I have issues for indicating the active tab. I mean, when a link is active, then a dropdown link is clicked, the previous Non-dropdown link is still shown as active. I don't know if I am clear...

as you see here the url is not Home. but the link is still indicated as Active


问:
How to test an action after the HTTP response has been returned in NodeJS Express application
Some actions need to be done after the HTTP response has been sent. Is there a good way of testing this kind of actions?

Jest will often close the test handle too early and thus the later parts are not tested correctly. I have tried to encapsulate the testing inside promises but it seems a bit cumbersome. What would be the recommended way?

Summary: How to test that the Google API call is made?

import express, {Express, NextFunction, Request, Response} from 'express';

export const app: Express = express();

const responseHandler = (req: Request, res: Response, next: NextFunction) => {
  console.log('responseHandler');
  res.send('Hello');
  next();
};

const afterEventHandler = (req: Request, res: Response, next: NextFunction) => {
  fetch('http://www.google.com/').then(response => {
    console.log('status:', response.status);
  });
  next();
};

app.get('/', responseHandler, afterEventHandler);

export default app;
```
<p>Test file:
How to check that the google.com call has been made?</p>
```import nock from "nock";
import app from "./app";
import http from "http";

const apiUrl = 'http://localhost:3001';
const server = http.createServer(app);
const hostname = 'localhost';
const port = 3001;

describe("test", () => {
    beforeAll(() => {
        server.listen(3001,() => {
            console.log(`Server running at http://${hostname}:${port}/`);
        });
    });
    afterAll(() => {
        server.close();
    });

    afterEach(() => {
        if (nock.pendingMocks()) {
            console.log(
                `Not all nock interceptors were used: ${nock.pendingMocks().length} ${JSON.stringify(nock.pendingMocks())}`
            );
        }
        nock.cleanAll();
    })

    test('Request to google is made and the endpoint returns 200', async () => {
        nock('http://www.google.com').get('/').reply(200);

        await new Promise(async (callback) => {
            const response = await fetch(apiUrl);
            const data = await response.text();
            expect(data).toEqual('Hello');
        });

        expect(nock.pendingMocks().length).toEqual(0);
    });
});
```

Body:
Some actions need to be done after the HTTP response has been sent. Is there a good way of testing this kind of actions?

Jest will often close the test handle too early and thus the later parts are not tested correctly. I have tried to encapsulate the testing inside promises but it seems a bit cumbersome. What would be the recommended way?

Summary: How to test that the Google API call is made?

import express, {Express, NextFunction, Request, Response} from 'express';

export const app: Express = express();

const responseHandler = (req: Request, res: Response, next: NextFunction) => {
  console.log('responseHandler');
  res.send('Hello');
  next();
};

const afterEventHandler = (req: Request, res: Response, next: NextFunction) => {
  fetch('http://www.google.com/').then(response => {
    console.log('status:', response.status);
  });
  next();
};

app.get('/', responseHandler, afterEventHandler);

export default app;

Test file:
How to check that the google.com call has been made?

import nock from "nock";
import app from "./app";
import http from "http";

const apiUrl = 'http://localhost:3001';
const server = http.createServer(app);
const hostname = 'localhost';
const port = 3001;

describe("test", () => {
    beforeAll(() => {
        server.listen(3001,() => {
            console.log(`Server running at http://${hostname}:${port}/`);
        });
    });
    afterAll(() => {
        server.close();
    });

    afterEach(() => {
        if (nock.pendingMocks()) {
            console.log(
                `Not all nock interceptors were used: ${nock.pendingMocks().length} ${JSON.stringify(nock.pendingMocks())}`
            );
        }
        nock.cleanAll();
    })

    test('Request to google is made and the endpoint returns 200', async () => {
        nock('http://www.google.com').get('/').reply(200);

        await new Promise(async (callback) => {
            const response = await fetch(apiUrl);
            const data = await response.text();
            expect(data).toEqual('Hello');
        });

        expect(nock.pendingMocks().length).toEqual(0);
    });
});


问:
How to join data with flux (in the sense of SQL)?
I have a measurement with sessions and a measurement with events in my influxdb. Each session has n events. I want to join the streams to group the events by session.AppVersion later. I use the following flux script:

```<code>import "join"
import "array"

bucket = "test03"

// left table
events = from(bucket: bucket)
  |> range(start: -600m)
  |> filter(fn: (r) => r["_measurement"] == "event")
  |> filter(fn: (r) => r._field == "SessionId")

// right table
sessions = from(bucket: bucket)
  |> range(start: -60d)
  |> filter(fn: (r) => r["_measurement"] == "session")

eventsWithSession = join.left(
  left: events,
  right: sessions,
  on: (l, r) => l.SessionIdTag == r.SessionIdTag,
  as: (l, r) => ({l with RSessionIdTag: r.SessionIdTag ,AppVersion: r.AppVersion, App: r.App}),)

eventsWithSession
  |>yield(name: "debug")
</code>```

Unfortunately are the columns r.AppVersion, r.App empty.
If I use join.inner() I get an empty result.
How can I fix that?

If I do the similar with static values/rows it works.

```<code>import "join"
import "array"

eventsTest = array.from(
      rows: [
          {SessionIdTag: "6ApWdNEtIkaoh2ZgkA69yA", Action: "ModA: save"},
      ],
  )

sessionsTest = array.from(
      rows: [
          {SessionIdTag: "6ApWdNEtIkaoh2ZgkA69yA", App: "A", AppVersion: "1.1.1.1"},
      ],
  )

eventsWithSessionTest = join.left(
  left: eventsTest,
  right: sessionsTest,
  on: (l, r) => l.SessionIdTag == r.SessionIdTag,
  as: (l, r) => ({l with RSessionIdTag: r.SessionIdTag ,RAppVersion: r.AppVersion, RApp: r.App}),)

eventsWithSessionTest
  |>yield(name: "debug")
</code>```

Body:
I have a measurement with sessions and a measurement with events in my influxdb. Each session has n events. I want to join the streams to group the events by session.AppVersion later. I use the following flux script:

import "join"
import "array"

bucket = "test03"

// left table
events = from(bucket: bucket)
  |> range(start: -600m)
  |> filter(fn: (r) => r["_measurement"] == "event")
  |> filter(fn: (r) => r._field == "SessionId")

// right table
sessions = from(bucket: bucket)
  |> range(start: -60d)
  |> filter(fn: (r) => r["_measurement"] == "session")

eventsWithSession = join.left(
  left: events,
  right: sessions,
  on: (l, r) => l.SessionIdTag == r.SessionIdTag,
  as: (l, r) => ({l with RSessionIdTag: r.SessionIdTag ,AppVersion: r.AppVersion, App: r.App}),)

eventsWithSession
  |>yield(name: "debug")

Unfortunately are the columns r.AppVersion, r.App empty.
If I use join.inner() I get an empty result.
How can I fix that?

If I do the similar with static values/rows it works.

import "join"
import "array"

eventsTest = array.from(
      rows: [
          {SessionIdTag: "6ApWdNEtIkaoh2ZgkA69yA", Action: "ModA: save"},
      ],
  )

sessionsTest = array.from(
      rows: [
          {SessionIdTag: "6ApWdNEtIkaoh2ZgkA69yA", App: "A", AppVersion: "1.1.1.1"},
      ],
  )

eventsWithSessionTest = join.left(
  left: eventsTest,
  right: sessionsTest,
  on: (l, r) => l.SessionIdTag == r.SessionIdTag,
  as: (l, r) => ({l with RSessionIdTag: r.SessionIdTag ,RAppVersion: r.AppVersion, RApp: r.App}),)

eventsWithSessionTest
  |>yield(name: "debug")


问:
proxy platforms, what technology they use to achieve this
There are many proxy platforms,

I'd like to know what technology they use to achieve this.

hope get the details, i know some python, but do not know how to get the proxy lists


问:
Selenium python unable to get console log messages
I cant get the console messages when i connect to a site. The only message im able to get is the console message written using driver.execute_script("console.log('New message')")
Anyone had similar problems with getting console messages using python selenium?

```<code>async def printConsoleLogs():
  chrome_options = webdriver.ChromeOptions()
  driver = webdriver.Chrome(service=service)
  driver.get("http://localhost:9091")

  async with driver.bidi_connection() as session:
      log = Log(driver, session)
      from selenium.webdriver.common.bidi.console import Console
      async with log.add_listener(Console.ALL) as messages:
         driver.execute_script("console.log('New message')")

      print(messages)

trio.run(printConsoleLogs)
</code>```

Body:
I cant get the console messages when i connect to a site. The only message im able to get is the console message written using driver.execute_script("console.log('New message')")
Anyone had similar problems with getting console messages using python selenium?

async def printConsoleLogs():
  chrome_options = webdriver.ChromeOptions()
  driver = webdriver.Chrome(service=service)
  driver.get("http://localhost:9091")

  async with driver.bidi_connection() as session:
      log = Log(driver, session)
      from selenium.webdriver.common.bidi.console import Console
      async with log.add_listener(Console.ALL) as messages:
         driver.execute_script("console.log('New message')")

      print(messages)

trio.run(printConsoleLogs)


问:
Kubernetes Job should use all available resources
I run a Kubernetes job with thousands of workers following the pattern described in Coarse Parallel Processing Using a Work Queue. I use the Python client for the Kubernetes API to define the job programmatically. The cluster does not scale automatically. The available resources are unknown at the time of programming.

The goal is to use all available resources of the cluster for my job. I have tried to optimise the .spec.parallelism setting. If I set .spec.parallelism and .spec.completions to the same value, all pods for the job are started at the beginning, but most of them could not be scheduled due to resource requirements (e.g. insufficient CPU). When the first pods are finished, the resources are free and more pods are scheduled. But after some time (2.4 hours on my cluster) Kubernetes gives up scheduling the remaining pods and marks them as failed, which eventually causes the whole job to fail.

Is there a pattern for a job on a Kubernetes cluster to use all available resources?


问:
How to embed an XLSX local file into HTML page with Python and Django
For a Python web project (with Django) I developed a tool that generates an XLSX file. For questions of ergonomics and ease for users I would like to integrate this excel on my HTML page.

So I first thought of converting the XLSX to an HTML array, with the xlsx2html python library. It works but since I can’t determine the desired size for my cells or trim the content during conversion, I end up with huge cells and tiny text..

I found an interesting way with the  html tag associated with OneDrive to embed an excel window into a web page, but my file being in my code and not on Excel Online I cannot import it like that. Yet the display is perfect and I don’t need the user to interact with this table.

I have searched a lot for other methods but apart from developing a function to browse my file and generate the script of the html table line by line, I have the feeling that I cannot simply use a method to convert or display it on my web page.
I am not accustomed to this need and wonder if there would not be a cleaner method to display an excel file in html.
Does it make sense to develop a function that builds my html table script in str? Or should I find a library that does it? Maybe there is a specific Django library ?

Thank you for your experience


问:
Color specific cell in an xlsx with python
Hello all (excuse me for my bad English), I want to color cell in an xlsx doc in terms of value.

Here's an example.

I want to color all the "Alexandre".

For that I create this:

```<code>path_to_excel="doc.xlsx"
exemple=openpyxl.load_workbook(path_to_excel)

ws = exemple['Sheet1'] #Name of the working sheet

from openpyxl.styles import PatternFill

#on définie la couleur de coloriage en hexa
Ok_couleur = PatternFill(patternType='solid',
                            fgColor='94e0de')

for column in ws['B']:
        if column.value == "Alexandre":
            ws['B3'].fill = Ok_couleur
</code>```

All i achieved is to color one cell but i want to color all cell with Alexandre.

In this line I trie to replace the B3 with B without success:

```<code>for column in ws['B']:
        if column.value == "Alexandre":
            ws['B'].fill = Ok_couleur`
</code>```

I also trie with B:B or B1:B5 and all i get is  "AttributeError: 'tuple' object has no attribute 'fill'"

Body:
Hello all (excuse me for my bad English), I want to color cell in an xlsx doc in terms of value.

Here's an example.

I want to color all the "Alexandre".

For that I create this:

path_to_excel="doc.xlsx"
exemple=openpyxl.load_workbook(path_to_excel)

ws = exemple['Sheet1'] #Name of the working sheet

from openpyxl.styles import PatternFill

#on définie la couleur de coloriage en hexa
Ok_couleur = PatternFill(patternType='solid',
                            fgColor='94e0de')

for column in ws['B']:
        if column.value == "Alexandre":
            ws['B3'].fill = Ok_couleur

All i achieved is to color one cell but i want to color all cell with Alexandre.

In this line I trie to replace the B3 with B without success:

for column in ws['B']:
        if column.value == "Alexandre":
            ws['B'].fill = Ok_couleur`

I also trie with B:B or B1:B5 and all i get is  "AttributeError: 'tuple' object has no attribute 'fill'"


问:
How to flatten a json nested object that have different names?
Very beginner here.

I have a JSON file with nested objects with different object names: first, second, third.
I'd like to either flatten the nested objected OR remove the object name, OR rename all the object names to the same?
Is it possible to do this using the JSON schema?

```<code>{
        "first": {
          "name": "test",
          "age": 39
        }
      ,

        "second": {
          "name": "test123",
          "age": 39
        }
      ,

        "third": {
          "name": "test456",
          "age": 25,
          "height": 159

      }
}
</code>```

This is the schema where i'd like all objects to be "items" or at least removed

```<code>{
  "type": "object",
  "properties": {
    "items": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "age": {
          "type": "integer"
        },
        "height": {
          "type": "integer"
        }
      }
    }
  }
}
</code>```

And this is what I'd like the output to be:

```<code>
 {
        "items": {
          "name": "test",
          "age": 39
        }
      ,

        "items": {
          "name": "test123",
          "age": 39
        }
      ,

        "items": {
          "name": "test456",
          "age": 25,
          "height": 159

      }
}

</code>```

Or to remove "items" / object name completely?

Body:
Very beginner here.

I have a JSON file with nested objects with different object names: first, second, third.
I'd like to either flatten the nested objected OR remove the object name, OR rename all the object names to the same?
Is it possible to do this using the JSON schema?

{
        "first": {
          "name": "test",
          "age": 39
        }
      ,

        "second": {
          "name": "test123",
          "age": 39
        }
      ,

        "third": {
          "name": "test456",
          "age": 25,
          "height": 159

      }
}

This is the schema where i'd like all objects to be "items" or at least removed

{
  "type": "object",
  "properties": {
    "items": {
      "type": "object",
      "properties": {
        "name": {
          "type": "string"
        },
        "age": {
          "type": "integer"
        },
        "height": {
          "type": "integer"
        }
      }
    }
  }
}

And this is what I'd like the output to be:

 {
        "items": {
          "name": "test",
          "age": 39
        }
      ,

        "items": {
          "name": "test123",
          "age": 39
        }
      ,

        "items": {
          "name": "test456",
          "age": 25,
          "height": 159

      }
}

Or to remove "items" / object name completely?


问:
How to rotate an image of CachedNetworkImage in flutter?
It's flutter app. It's an app with portrait-only mode.

I want to show some images of my product. When user touches the image,
I would like to show it on full screen using CachedNetworkImage.

But the problem is, when width is bigger than height, Boxfit.cover only shows middle part of image (left and right side not shown). If I make it dispaly all picture, then there'll be so much empty space above and below

I would rather to make the image(CachedNetworkImage) rotate 90 degree, so that whole image can fit the full screen.

Any idea?


问:
Odoo.sh Upgrade to v15 : how to migrate obsolete but inherited views?
I am currently following the UPGRADE process in odoo.sh to migrate to Odoo v15.
Because some of the templates have been removed or renamed in v15, I got 100 errors similar to:

```<code>ValueError: External ID not found in the system: website_blog.s_latest_posts
</code>```

Most of these errors are caused by the third party template on version 13.

How to deal with (Theme-) templates which are not existing anymore in the destination (v15) version but used as inherited template in the current version (v13)?

For example:

website_blog.s_latest_posts.xml is existing in the official src/odoo/addons in v13 but not in v15. And I have custumized this template using inherit:

<template id="my_s_latest_post" inherit_id="website_blog.s_latest_posts"><xpath="..."></xpath></template>
```
<p>The "third party theme" module "third_party_theme" inherits from it:</p>
<pre class="lang-xml prettyprint-override"><code><template id="thirdpartytheme_s_latest_post" inherit_id="website_blog.s_latest_posts"><xpath="..."></xpath></template>
</code>```

and other of my custom templates which inherit from third_party_theme 's template:

<template id="my_other_s_latest_post" inherit_id="third_party_theme.thirdpartytheme_s_latest_post"><xpath="..."></xpath></template>
```
<p>or other parts of my custom templates or third party theme CALL the original template:</p>
<pre class="lang-xml prettyprint-override"><code><template><xpath=xxx>
<t t-call=third_party_theme.thirdpartytheme_s_latest_post...
</code>```

And because the website_blog.s_latest_posts.xml is not existing anymore in v15, during the migration process (odoo.sh), such an error occurs: ValueError: External ID not found in the system: website_blog.s_latest_posts

I have heard about pre-migrate scripts to disable views during migration process:
https://www.youtube.com/watch?v=n0jQQlEnUUQ
but i can t figure out how to manage the steps to handle views (see screen shots in attach). Scripts examples (pre-migrate.py, post-migrate.py and end-migrate.py) are welcome :)

I have also tried to figure out what to do with the OpenUpgrade informations: https://github.com/OCA/OpenUpgrade/blob/15.0/openupgrade_scripts/scripts/website_blog/15.0.1.1/upgrade_analysis.txt
For instance:

```<code>---Models in module 'website_blog'---
---Fields in module 'website_blog'---
---XML records in module 'website_blog'---
NEW ir.asset: website_blog.s_blog_posts_000_js
NEW ir.ui.view: website_blog.s_blog_posts
DEL ir.ui.view: website_blog.assets_editor
DEL ir.ui.view: website_blog.assets_frontend
DEL ir.ui.view: website_blog.assets_snippet_s_latest_posts_css_000
DEL ir.ui.view: website_blog.s_latest_posts
DEL ir.ui.view: website_blog.s_latest_posts_big_picture_template
NEW website.snippet.filter: website_blog.dynamic_filter_latest_blog_posts
</code>```

Body:
I am currently following the UPGRADE process in odoo.sh to migrate to Odoo v15.
Because some of the templates have been removed or renamed in v15, I got 100 errors similar to:

ValueError: External ID not found in the system: website_blog.s_latest_posts

Most of these errors are caused by the third party template on version 13.

How to deal with (Theme-) templates which are not existing anymore in the destination (v15) version but used as inherited template in the current version (v13)?

For example:

website_blog.s_latest_posts.xml is existing in the official src/odoo/addons in v13 but not in v15. And I have custumized this template using inherit:

<template id="my_s_latest_post" inherit_id="website_blog.s_latest_posts"><xpath="..."></xpath></template>

The "third party theme" module "third_party_theme" inherits from it:

<template id="thirdpartytheme_s_latest_post" inherit_id="website_blog.s_latest_posts"><xpath="..."></xpath></template>

and other of my custom templates which inherit from third_party_theme 's template:

<template id="my_other_s_latest_post" inherit_id="third_party_theme.thirdpartytheme_s_latest_post"><xpath="..."></xpath></template>

or other parts of my custom templates or third party theme CALL the original template:

<template><xpath=xxx>
<t t-call=third_party_theme.thirdpartytheme_s_latest_post...

And because the website_blog.s_latest_posts.xml is not existing anymore in v15, during the migration process (odoo.sh), such an error occurs: ValueError: External ID not found in the system: website_blog.s_latest_posts

I have heard about pre-migrate scripts to disable views during migration process:
https://www.youtube.com/watch?v=n0jQQlEnUUQ
but i can t figure out how to manage the steps to handle views (see screen shots in attach). Scripts examples (pre-migrate.py, post-migrate.py and end-migrate.py) are welcome :)

I have also tried to figure out what to do with the OpenUpgrade informations: https://github.com/OCA/OpenUpgrade/blob/15.0/openupgrade_scripts/scripts/website_blog/15.0.1.1/upgrade_analysis.txt
For instance:

---Models in module 'website_blog'---
---Fields in module 'website_blog'---
---XML records in module 'website_blog'---
NEW ir.asset: website_blog.s_blog_posts_000_js
NEW ir.ui.view: website_blog.s_blog_posts
DEL ir.ui.view: website_blog.assets_editor
DEL ir.ui.view: website_blog.assets_frontend
DEL ir.ui.view: website_blog.assets_snippet_s_latest_posts_css_000
DEL ir.ui.view: website_blog.s_latest_posts
DEL ir.ui.view: website_blog.s_latest_posts_big_picture_template
NEW website.snippet.filter: website_blog.dynamic_filter_latest_blog_posts


问:
Android Google Map | Two finger scrolling inside tablayout

i have a google maps (fragment) inside a tablayout

With the tablayout i use a FragmentStateAdapter.
This allows me to nicly swipe through my tabs but (you can guess is) this swiping is working against me on the google maps fragment.

My idea was to setup 2 fiinger control for the map while the single finger could still service the tab-swiper.

i found this post and the answer of Andrii Omelchenko did give some real good pointers for a solution

However i do not have a scrollview and i cannot find any on...-methods in my ViewPagers2 and/or the FragmentStateAdapter to intercept the touch-events as is done in the scrollview.

Does anybody have an idea as how to handle the issue?


问:
Handle multiple inputs with React Redux - object spread
Actually I'm looking for more elegant way to handle multiple inputs value with react reduxjs toolkit.
Form state is stored in slice.
I'm handling all the inputs with single handler and dispatching separate action/object for each input.

It works just fine, but I'm sure there is a more elegant way, by using spread operator to update the state. But, to be honest, I'm stuck here

Here is my form

```<code><form id='personalDataStep' onSubmit={handleSubmit}>
          <label>Name:</label>
            <input
              type='text'
              placeholder='Your name'
              required
              name='userName'
              value={personalInfoData.userName}
              onChange={handlePersonalInfo}
            />
            {}
            <label>Email:</label>
            <input
              type='text'
              placeholder='Your email'
              required
              name='userEmail'
              value={personalInfoData.userEmail}
              onChange={handlePersonalInfo}
            />
            <label>Phone number:</label>
            <input
              placeholder='Your phone'
              required
              name='phoneNumber'
              value={personalInfoData.phoneNumber}
              onChange={handlePersonalInfo}
            />
        </form>
</code>```

Here is onChange handler

```<code>const handlePersonalInfo = (e) => {
    dispatch(firstStepData({
      [e.target.name]: e.target.value
    }))
  }
</code>```

And here is the slice

```<code>const formSlice = createSlice({
    name: "form",
    initialState: {
        formData:
            {
                userName: '',
                userEmail: '',
                phoneNumber: '',
                planName: '',
                planDuration: '',
                planPrice: 0,
                priceMultiplier: 10,
                addons: null,
            }
    },
    reducers: {
        firstStepData(state, action) {
            state.formData.userName = action.payload.userName || state.formData.userName
            state.formData.userEmail = action.payload.userEmail || state.formData.userEmail
            state.formData.phoneNumber = action.payload.phoneNumber || state.formData.phoneNumber
        },
</code>```

Body:
Actually I'm looking for more elegant way to handle multiple inputs value with react reduxjs toolkit.
Form state is stored in slice.
I'm handling all the inputs with single handler and dispatching separate action/object for each input.

It works just fine, but I'm sure there is a more elegant way, by using spread operator to update the state. But, to be honest, I'm stuck here

Here is my form

<form id='personalDataStep' onSubmit={handleSubmit}>
          Name:
            <input
              type='text'
              placeholder='Your name'
              required
              name='userName'
              value={personalInfoData.userName}
              onChange={handlePersonalInfo}
            />
            {}
            Email:
            <input
              type='text'
              placeholder='Your email'
              required
              name='userEmail'
              value={personalInfoData.userEmail}
              onChange={handlePersonalInfo}
            />
            Phone number:
            <input
              placeholder='Your phone'
              required
              name='phoneNumber'
              value={personalInfoData.phoneNumber}
              onChange={handlePersonalInfo}
            />
        </form>

Here is onChange handler

const handlePersonalInfo = (e) => {
    dispatch(firstStepData({
      [e.target.name]: e.target.value
    }))
  }

And here is the slice

const formSlice = createSlice({
    name: "form",
    initialState: {
        formData:
            {
                userName: '',
                userEmail: '',
                phoneNumber: '',
                planName: '',
                planDuration: '',
                planPrice: 0,
                priceMultiplier: 10,
                addons: null,
            }
    },
    reducers: {
        firstStepData(state, action) {
            state.formData.userName = action.payload.userName || state.formData.userName
            state.formData.userEmail = action.payload.userEmail || state.formData.userEmail
            state.formData.phoneNumber = action.payload.phoneNumber || state.formData.phoneNumber
        },


问:
Page-break HTML to PDF Xamarin Forms
I have a problem when generating a loop of tables from html to pdf on xamarin, all I print are 33 tables but it is cut at number 14 and it is cut at the end of the page instead of skipping the page in pdf, I have tried various css properties, including if conditions to manually add a div with the class or style of page-break and it still doesn't give me the page break, does anyone know about ?

I am using a html template to replace the html and then generate the pdf.

Html -->

```<code><html lang="en">
<head>
    <title>HOJA DE HORAS</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css">

    <style type="text/css">

        html {
            height: 0;
        }

        body {
            margin-top: 20px;
            color: #484b51;
        }

        .text-secondary-d1 {
            color: #728299 !important;
            text-align: center;
        }

        .page-header {
            margin: 0 0 1rem;
            padding-bottom: 1rem;
            padding-top: .5rem;
            border-bottom: 1px dotted #e2e2e2;
            display: -ms-flexbox;
            display: flex;
            -ms-flex-pack: justify;
            justify-content: space-between;
            -ms-flex-align: center;
            align-items: center;
        }

        .page-title {
            padding: 0;
            margin: 0;
            font-size: 1.75rem;
            font-weight: 300;
        }

        .brc-default-l1 {
            border-color: #dce9f0 !important;
        }

        .ml-n1, .mx-n1 {
            margin-left: -.25rem !important;
        }

        .mr-n1, .mx-n1 {
            margin-right: -.25rem !important;
        }

        .mb-4, .my-4 {
            margin-bottom: 1.5rem !important;
        }

        hr {
            margin-top: 1rem;
            margin-bottom: 1rem;
            border: 0;
            border-top: 1px solid rgba(0,0,0,.1);
        }

        .text-grey-m2 {
            color: #888a8d !important;
        }

        .text-success-m2 {
            color: #86bd68 !important;
        }

        .font-bolder, .text-600 {
            font-weight: 600 !important;
        }

        .text-110 {
            font-size: 110% !important;
        }

        .text-blue {
            color: #478fcc !important;
        }

        .pb-25, .py-25 {
            padding-bottom: .75rem !important;
        }

        .pt-25, .py-25 {
            padding-top: .75rem !important;
        }

        .bgc-default-tp1 {
            background-color: rgba(121,169,197,.92) !important;
        }

        .bgc-default-l4, .bgc-h-default-l4:hover {
            background-color: #f3f8fa !important;
        }

        .page-header .page-tools {
            -ms-flex-item-align: end;
            align-self: flex-end;
        }

        .btn-light {
            color: #757984;
            background-color: #f5f6f9;
            border-color: #dddfe4;
        }

        .w-2 {
            width: 1rem;
        }

        .text-120 {
            font-size: 120% !important;
        }

        .text-primary-m1 {
            color: #4087d4 !important;
        }

        .text-danger-m1 {
            color: #dd4949 !important;
        }

        .text-blue-m2 {
            color: #68a3d5 !important;
        }

        .text-150 {
            font-size: 150% !important;
        }

        .text-60 {
            font-size: 60% !important;
        }

        .text-grey-m1 {
            color: #7b7d81 !important;
        }

        .align-bottom {
            vertical-align: bottom !important;
        }

        .breakpoint {
            border: none;
            page-break-inside:auto;
        }
    </style>
</head>

<body>
    <div class="page-content container">
        <div class="page-header text-blue-d2" style="width: 100%;">
            <h1 class="page-title text-secondary-d1" style="text-align: center; width: 100%;"> HOJA DE HORAS </h1>
        </div>

        <div class="row mt-4">
            <div class="col-12 col-lg-12">
                <!-- #region Header -->
                <div class="row">
                    <div class="col-sm-6">
                        <table>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Refno:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%Refno%}</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Fecha:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%Date%}</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Controlador:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%EmRgCode%} {%EmRgName%}</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Movil:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%DeviceCode%}</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Cod.Seg.:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%SecurityCode%}</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Long./Lat.:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%Longitude%} / {%Latitude%}</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Notes:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%Notes%}</span>
                                </td>
                            </tr>
                        </table>
                    </div>

                    <div class="col-sm-6 align-self-start d-sm-flex justify-content-end">
                        <table>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Proyecto:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%ProjectCode%} {%ProjectDesc%}</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Localización:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%Location%}</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Brigada:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%LbCrewCode%} {%LbCrewName%}</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Empleados:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%WorkForce%}</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Horas Netas:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%NetTime%} | {%NetHours%}</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Supervisor:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%Supervisor%}</span>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <span class="text-secondary-d1 text-105">Estatus:</span>
                                </td>
                                <td>
                                    <span style="margin-left:5px; color: #478fcc">{%Status%} | {%InterfaceStatus%}</span>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
                <!-- #endregion -->
                <!-- #region Content -->
                <div class="breakpoint">
                    {%Body%}
                </div>
                <!-- #endregion -->
                <!-- #region BarCode -->
                <div>
                    <img src="data:image/png;base64, {%Barcode%}" />
                </div>
                <!-- #endregion -->
                <!-- #region Footer -->
                <div style="margin-top:100px;">
                    <div class="row">
                        <div class="col-sm-4">
                            <hr align="left" />
                            <span class="text-secondary-d1 text-105">Firma Controlador</span>
                        </div>

                        <div class="col-sm-4"></div>

                        <div class="col-sm-4">
                            <hr align="right" />
                            <div class="align-self-start d-sm-flex justify-content-start">
                                <span class="text-secondary-d1 text-105">Firma Supervisor</span>
                            </div>
                        </div>

                    </div>
                </div>
                <!-- #endregion -->
            </div>
        </div>
    </div>
</body>
</html>
</code>```

Void

```<code>   private async void PreparePDF(LbRg pdfLbRg)
        {

            try
            {
                LbRgLnService lbRglnService = new LbRgLnService();
                var mLbRgLns = lbRglnService.GetLbRgLnsByLbRgId(pdfLbRg.LbRgId);

                var htmlTemplate = Common.GetFileToString("LaborRegister.html");

 string bodyContent = "";
                int i = 0;
                int linecounter = 0;
                int page = 1;
                // Add Lines
                foreach (var lnRgLn in mLbRgLns.OrderBy(x => x.LbRgLnId))
                {
                    string mainDiv = "<div class='mt-4' >" + Environment.NewLine;
                    string divRow = "<div class='row'>" + Environment.NewLine;
 bodyContent +=  mainDiv + divRow + divMainCol1Close + divMainCol2Close + " </div>" + Environment.NewLine  ;

                    linecounter++;
                    if (page == 1 && linecounter == 7)
                    {
                            bodyContent +="<div class='body' style='page-break-after: always'></div>";
                        linecounter = 0;
                        page++;
                    }
                    else
                    {
                        if (page > 1 && linecounter == 10)
                        {
                            bodyContent +="<div class='body' style='page-break-after: always'></div>";
                            linecounter = 0;
                            page++;
                        }
                    }
                    bodyContent += "</div>";
                    i++;
                }

                htmlTemplate = htmlTemplate.Replace("{%Body%}", bodyContent);

                #endregion

                if (pdfLbRg.Barcode.IsNotNullOrEmpty())
                {
                    var imageBase64 = Xamarin.Forms.DependencyService.Get<IBarcodeService>().ConvertImageStream(pdfLbRg.Barcode);
                    var base64 = Common.ConvertToBase64(imageBase64);
                    htmlTemplate = htmlTemplate.Replace("{%Barcode%}", base64);
                }
                //Ajuste 2022-12-16
                //string fileName = "LbRg_" + pdfLbRg.Refno + "_" + DateTime.Now.Ticks + ".pdf";

                string fileName = "RPMO_" + pdfLbRg.EmRgCode + "_" + pdfLbRg.Refno + "_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf";
                var path = Xamarin.Forms.DependencyService.Get<IHtmlToPDF>().SafeHTMLToPDF(htmlTemplate, fileName);
                if (path.IsNotNullOrEmpty() && path != "Access to the path")
                {
                    Utility.DisplayInfo.ShowLoader();
                    await Task.Delay(5000);
                    Utility.DisplayInfo.HideLoader();

                    await Xamarin.Essentials.Launcher.OpenAsync(new Xamarin.Essentials.OpenFileRequest("PDF", new Xamarin.Essentials.ReadOnlyFile(path)));
                }
                else
                {
                    await DisplayAlert("Error", path, "Ok");
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Exception", ex.Message, "Ok");
            }
        }

</code>```

Part of Service

```<code> if (webpage == null)
                    webpage = new Android.Webkit.WebView(GetApplicationContext());
                int width =  2102;
                int height = 2973;
                webpage.Layout(0, 0, width, height);
                webpage.LoadDataWithBaseURL("", html, "text/html", "UTF-8", null);
                webpage.SetWebViewClient(new WebViewCallBack(file.ToString()));
                System.IO.File.WriteAllText(file.ToString(), html, Encoding.UTF8);
</code>```

Resolve this issue as soon as possible.

Title: Page-break HTML to PDF Xamarin Forms

Body:
I have a problem when generating a loop of tables from html to pdf on xamarin, all I print are 33 tables but it is cut at number 14 and it is cut at the end of the page instead of skipping the page in pdf, I have tried various css properties, including if conditions to manually add a div with the class or style of page-break and it still doesn't give me the page break, does anyone know about ?

I am using a html template to replace the html and then generate the pdf.

Html -->

    <title>HOJA DE HORAS</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.4.1/dist/css/bootstrap.min.css">

 HOJA DE HORAS

                                    Refno:

                                    {%Refno%}

                                    Fecha:

                                    {%Date%}

                                    Controlador:

                                    {%EmRgCode%} {%EmRgName%}

                                    Movil:

                                    {%DeviceCode%}

                                    Cod.Seg.:

                                    {%SecurityCode%}

                                    Long./Lat.:

                                    {%Longitude%} / {%Latitude%}

                                    Notes:

                                    {%Notes%}

                                    Proyecto:

                                    {%ProjectCode%} {%ProjectDesc%}

                                    Localización:

                                    {%Location%}

                                    Brigada:

                                    {%LbCrewCode%} {%LbCrewName%}

                                    Empleados:

                                    {%WorkForce%}

                                    Horas Netas:

                                    {%NetTime%} | {%NetHours%}

                                    Supervisor:

                                    {%Supervisor%}

                                    Estatus:

                                    {%Status%} | {%InterfaceStatus%}

                    {%Body%}

                            Firma Controlador

                                Firma Supervisor

Void

   private async void PreparePDF(LbRg pdfLbRg)
        {

            try
            {
                LbRgLnService lbRglnService = new LbRgLnService();
                var mLbRgLns = lbRglnService.GetLbRgLnsByLbRgId(pdfLbRg.LbRgId);

                var htmlTemplate = Common.GetFileToString("LaborRegister.html");

 string bodyContent = "";
                int i = 0;
                int linecounter = 0;
                int page = 1;
                // Add Lines
                foreach (var lnRgLn in mLbRgLns.OrderBy(x => x.LbRgLnId))
                {
                    string mainDiv = "
" + Environment.NewLine;
                    string divRow = "
" + Environment.NewLine;
 bodyContent +=  mainDiv + divRow + divMainCol1Close + divMainCol2Close + "
" + Environment.NewLine  ;

                    linecounter++;
                    if (page == 1 && linecounter == 7)
                    {
                            bodyContent +="

";
                        linecounter = 0;
                        page++;
                    }
                    else
                    {
                        if (page > 1 && linecounter == 10)
                        {
                            bodyContent +="

";
                            linecounter = 0;
                            page++;
                        }
                    }
                    bodyContent += "
";
                    i++;
                }

                htmlTemplate = htmlTemplate.Replace("{%Body%}", bodyContent);

                #endregion

                if (pdfLbRg.Barcode.IsNotNullOrEmpty())
                {
                    var imageBase64 = Xamarin.Forms.DependencyService.Get<IBarcodeService>().ConvertImageStream(pdfLbRg.Barcode);
                    var base64 = Common.ConvertToBase64(imageBase64);
                    htmlTemplate = htmlTemplate.Replace("{%Barcode%}", base64);
                }
                //Ajuste 2022-12-16
                //string fileName = "LbRg_" + pdfLbRg.Refno + "_" + DateTime.Now.Ticks + ".pdf";

                string fileName = "RPMO_" + pdfLbRg.EmRgCode + "_" + pdfLbRg.Refno + "_" + DateTime.Now.ToString("yyyyMMdd") + ".pdf";
                var path = Xamarin.Forms.DependencyService.Get<IHtmlToPDF>().SafeHTMLToPDF(htmlTemplate, fileName);
                if (path.IsNotNullOrEmpty() && path != "Access to the path")
                {
                    Utility.DisplayInfo.ShowLoader();
                    await Task.Delay(5000);
                    Utility.DisplayInfo.HideLoader();

                    await Xamarin.Essentials.Launcher.OpenAsync(new Xamarin.Essentials.OpenFileRequest("PDF", new Xamarin.Essentials.ReadOnlyFile(path)));
                }
                else
                {
                    await DisplayAlert("Error", path, "Ok");
                }
            }
            catch (Exception ex)
            {
                await DisplayAlert("Exception", ex.Message, "Ok");
            }
        }

Part of Service

 if (webpage == null)
                    webpage = new Android.Webkit.WebView(GetApplicationContext());
                int width =  2102;
                int height = 2973;
                webpage.Layout(0, 0, width, height);
                webpage.LoadDataWithBaseURL("", html, "text/html", "UTF-8", null);
                webpage.SetWebViewClient(new WebViewCallBack(file.ToString()));
                System.IO.File.WriteAllText(file.ToString(), html, Encoding.UTF8);

Resolve this issue as soon as possible.


问:
Add javascript in script tag with React Helmet to HEAD element
I have to add this javascript: var myData = { "myPageType":"foo" } in a
</Helmet>
```


问:
GitHub Actions Continuous Deployment of a Clojure project returning "Source option 5 is no longer supported. Use 6 or later". How to fix it?
I am trying to build a GitHub Actions workflow as a Continuous Deployment procedure on this forked repository of a Clojure project.

The process  goes well until it reaches this point:

Error:  Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project flow: Compilation failure: Compilation failure:
Error:  Source option 5 is no longer supported. Use 6 or later.
Error:  Target option 1.5 is no longer supported. Use 1.6 or later.
Error:  -> [Help 1]
```

Usually, other problems in Stack Overflow related to this error message involve tweaking the pom.xml (see examples: 1, 2, 3, 4, 5, 6).

However, since this is a Clojure project managed by Leiningen, there is not such a file initially. The pom.xml is generated after lein install (and other command) is executed. Clojure is a hosted language on the JVM, after all.

As a side note, I am not sure why this project has :java-source-paths (link) instead of :source-paths. Not sure if this aspect is related to the problem discussed here.

How to fix it?

Body:
I am trying to build a GitHub Actions workflow as a Continuous Deployment procedure on this forked repository of a Clojure project.

The process  goes well until it reaches this point:

Error:  Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project flow: Compilation failure: Compilation failure:
Error:  Source option 5 is no longer supported. Use 6 or later.
Error:  Target option 1.5 is no longer supported. Use 1.6 or later.
Error:  -> [Help 1]

Usually, other problems in Stack Overflow related to this error message involve tweaking the pom.xml (see examples: 1, 2, 3, 4, 5, 6).

However, since this is a Clojure project managed by Leiningen, there is not such a file initially. The pom.xml is generated after lein install (and other command) is executed. Clojure is a hosted language on the JVM, after all.

As a side note, I am not sure why this project has :java-source-paths (link) instead of :source-paths. Not sure if this aspect is related to the problem discussed here.

How to fix it?


问:
Is there a way to run the supplied prisma query as a raw sql query?
I have been stuck with this and similar dilemmas for a while now and can't seem to find an acceptable solution. Prisma currently doesn't allow for upsertMany in it's queries, or in my case a nested upsertMany. I have found some accepted solutions and the most popular one is using $transaction from prisma to write a loop of upserts which doesn't work for me as each query contains up to 200 items to upsert (currently testing 100 items takes roughly 10sec to run so it really isn't an acceptable solution). Prisma offers the ability to use $queryRaw to use a raw SQL query which may offer a more acceptable solution. I've supplied the code to their currently accepted solution as well as the query (that isn't currently possible) that I'm hoping someone could help me turn into a raw sql query or a better solution.

Their accepted solution:

```<code>prisma.$transaction(data.map((d) =>
 prisma.MODEL.upsert({
  where:{
   id: d.id
  },
  update:{
   foo:d.foo,
  },
  create:{
   foo: d.foo,
   bar: d.bar
  },
 }),
 ),
);
</code>```

How I would need to implement it as I would like to create one MODEL with a related array of MODELS and another array of related MODELS:

```<code>let transactionOne = prisma.$transaction(
 arrayOne.map((d)=>
  prisma.MODEL.upsert({
   where:{
    id: d.id,
   },
   update:{
    foo: d.foo,
   },
   create:{
    foo: d.foo,
    bar: d.bar,
   },
  }),
 )
);

let transactionTwo = prisma.$transaction(
 arrayTwo.map((d)=>
  prisma.MODEL.upsert({
   where:{
    id: d.id,
   },
   update:{
    foo: d.foo,
   },
   create:{
    foo: d.foo,
    bar: d.bar,
   },
  }),
 )
);

let data = await prisma.MODEL.create({
 data:{
  foo: foo,
  bar: bar,
  example:{
   connect: transactionOne.map((a)=>({id: a.id})),
  },
  exampleTwo:{
   connect: transactionTwo.map((b)=>({id: b.id})),
  },
},
});
</code>```

My example above like mentioned before takes just over 10 seconds with 100 items and may possibly require 200 items so 20 seconds per call. Is there an easier way to make this faster or like I said a way to create a raw SQL query with the same results?

Thanks for any help!

Body:
I have been stuck with this and similar dilemmas for a while now and can't seem to find an acceptable solution. Prisma currently doesn't allow for upsertMany in it's queries, or in my case a nested upsertMany. I have found some accepted solutions and the most popular one is using $transaction from prisma to write a loop of upserts which doesn't work for me as each query contains up to 200 items to upsert (currently testing 100 items takes roughly 10sec to run so it really isn't an acceptable solution). Prisma offers the ability to use $queryRaw to use a raw SQL query which may offer a more acceptable solution. I've supplied the code to their currently accepted solution as well as the query (that isn't currently possible) that I'm hoping someone could help me turn into a raw sql query or a better solution.

Their accepted solution:

prisma.$transaction(data.map((d) =>
 prisma.MODEL.upsert({
  where:{
   id: d.id
  },
  update:{
   foo:d.foo,
  },
  create:{
   foo: d.foo,
   bar: d.bar
  },
 }),
 ),
);

How I would need to implement it as I would like to create one MODEL with a related array of MODELS and another array of related MODELS:

let transactionOne = prisma.$transaction(
 arrayOne.map((d)=>
  prisma.MODEL.upsert({
   where:{
    id: d.id,
   },
   update:{
    foo: d.foo,
   },
   create:{
    foo: d.foo,
    bar: d.bar,
   },
  }),
 )
);

let transactionTwo = prisma.$transaction(
 arrayTwo.map((d)=>
  prisma.MODEL.upsert({
   where:{
    id: d.id,
   },
   update:{
    foo: d.foo,
   },
   create:{
    foo: d.foo,
    bar: d.bar,
   },
  }),
 )
);

let data = await prisma.MODEL.create({
 data:{
  foo: foo,
  bar: bar,
  example:{
   connect: transactionOne.map((a)=>({id: a.id})),
  },
  exampleTwo:{
   connect: transactionTwo.map((b)=>({id: b.id})),
  },
},
});

My example above like mentioned before takes just over 10 seconds with 100 items and may possibly require 200 items so 20 seconds per call. Is there an easier way to make this faster or like I said a way to create a raw SQL query with the same results?

Thanks for any help!