instruction stringlengths 0 30k ⌀ |
|---|
According to [An Introduction to R](https://cran.r-project.org/doc/manuals/R-intro.html#R-commands_003b-case-sensitivity-etc):
> Command lines entered at the console are limited[4] to about 4095 bytes (not characters).
The [4] is a footnote which says:
> some of the consoles will not allow you to enter more, and amongst those which do some will silently discard the excess and some will use it as the start of the next line.
Although that document says _This manual is for R, version 4.3.3 (2024-02-29)_, I'm not sure it still applies. I just created a line of >50k characters and was able to parse it in VS Code. But I found a 2018 Posit forum [thread](https://forum.posit.co/t/does-console-impose-an-upper-limit-on-the-length-of-strings/12872/2) where a user reports hitting the limit in RStudio.
There is also a maximum length for a vector which depends on whether you're using 32/64 bit R, the R version and the type of vector. It's probably 2^52-1 elements for an integer or numeric vector with a reasonably modern R version on a computer that isn't very old. See [Long vectors](https://cran.r-project.org/doc/manuals/r-release/R-ints.html#Long-vectors) in R Internals. |
try to use
if not pd_temp.empty and pd_temp.notnull().any().any() and len(pd_temp) >= 1:
instead of
if not pd_temp.empty and pd_temp.notnull and len(pd_temp) >= 1:
|
vscode port-forward rule is auto-generate or edit by user via vscode-GUI,
[enter image description here](https://i.stack.imgur.com/iEits.png)
how to manually set a port forward rule by config-file or code? (we try to write a config file to determine the port forward rule) |
how to manually set a port forward rule? |
|portforwarding|vscode-remote| |
null |
|java|sql|spring|oracle-database| |
{"OriginalQuestionIds":[49956367],"Voters":[{"Id":4108803,"DisplayName":"blackgreen"}]} |
You are not using the && in the right place. If &J=1 and want the value of YY1 then you should do:
%let year_x = &&yy&j;
The first pass will convert && into & and &J into 1 resulting in &yy1. Which the second pass will convert to the value of YY1.
|
Added the AspNetCore.Mvc.Razor.RuntimeCompilation package for live updating of .cshtml pages. But when writing builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation(); an error occurs in the Program.cs file An error occurred during the compilation of a resource required to process this request. Please review the following specific error details and modify your source code appropriately. When compiled with the usual builder.Services.AddControllersWithViews(), everything works correctly.
The package version is correct and no other errors occur. Please tell me what could be the problem? |
Razor.RuntimeCompilation creates an error |
|asp.net|asp.net-mvc|razor|runtime|razor-pages| |
null |
I'm trying to initialize an array of hashes of a specific length in a short way.
$array=@(@{"status"=1})*3
This does not work as I expect it to, when I change a value in the hash for one element in the array, all elements are updated
$a1=@(@{"status"=1},@{"status"=1},@{"status"=1})
$a2=@(@{"status"=1})*3
$a3=@(1)*3
$a1[1]["status"]=2
$a2[1]["status"]=2
$a3[1]=2
Write-Host "`nArray a1:"
$a1
Write-Host "`nArray a2:"
$a2
Write-Host "`nArray a3:"
$a3
I expect that only the second element in the array is affected by the update in all three scenarios. But this is what I get
```
Array a1:
Name Value
---- -----
status 1
status 2
status 1
Array a2:
status 2
status 2
status 2
Array a3:
1
2
1
``` |
|reactjs|mongodb|express|web|mern| |
null |
Need to calculate Matrix exponential with Tailor series with MPI matrix is small 3 x 3 for example
Meanwhile
```
vector<vector<double>> matrixExp(const vector<vector<double>>& A) {
int n = A.size();
vector<vector<double>> E(n, vector<double>(n, 0));
vector<vector<double>> T(n, vector<double>(n, 0));
vector<vector<double>> localE(n, vector<double>(n, 0));
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
for (int i = 0; i < n; i++)
E[i][i] = 1;
for (int i = 0; i < n; i++)
localE[i][i] = 0;
T = E;
for (int j = 1; j <= rank; j++)
{
T = matrixMult(T, A);
T = matrixDiv(T, j);
}
localE = T;
for (int i = rank + 1; i <= N; i += size) {
for (int j = i; j < i + size; j++) {
T = matrixMult(T, A);
T = matrixDiv(T, j);
}
localE = matrixSum(localE, T);
}
MPI_Reduce(localE[0].data(), E[0].data(), n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(localE[1].data(), E[1].data(), n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(localE[2].data(), E[2].data(), n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
return E;
}
```
But i dont know how to optimize this
```
for (int j = i; j < i + size; j++) {
T = matrixMult(T, A);
T = matrixDiv(T, j);
}
```
Maybe it's impossible with this implementation
[enter image description here][1]
[1]: https://i.stack.imgur.com/fIjye.png |
One counter example to your solution is
```
[8, 7, 5, 4, 4, 1]
```
Adding as you have done would give the subsets
```
[8, 4, 4], [7, 5, 1]: difference of sums = 3
```
while the optimal solution is
```
[8, 5, 4], [7, 4, 1]: difference of sums = 1
```
Thus, to solve this problem, you need to brute force generate all combinations of (n choose floor(n/2)) and find the one with the smallest difference. Here is a sample code:
```python
comb = []
def getcomb(l, ind, k):
if len(comb) == k:
return [comb[:]]
if ind == len(l):
return []
ret = getcomb(l, ind+1, k)
comb.append(l[ind])
ret += getcomb(l, ind+1, k)
comb.pop()
return ret
def get_best_split(l):
lsm = sum(l)
best = lsm
for i in getcomb(l, 0, len(l)//2):
sm = sum(i)
best = min(best, abs(sm - (lsm - sm)))
return best
print(get_best_split([8, 7, 5, 4, 4, 1])) # outputs 1
``` |
I am making `MultiVector` class for Entity Component System. It is used for storing objects of different types for iterating over them efficiently.
I use vectors of bytes as raw storage and `reinterpret_cast` it to whichever type I need. Basic functionality (`push_back` by const reference and `pop_back`) seems to work.
However, when I try to implement move semantics for `push_back` (commented lines), clang gives me incomprehensible 186 lines error message, something about 'allocate is declared as pointer to a reference type'. As I understand, vector tries to `push_back` reference to `T`, which it cannot do because it must own contained objects.
How am I supposed to do it?
```
#include <iostream>
#include <vector>
using namespace std;
int g_class_id { 0 };
template <class T>
const int get_class_id()
{
static const int id { g_class_id++ };
return id;
}
class MultiVector {
public:
MultiVector() : m_vectors(g_class_id + 1) {}
template <typename T>
vector<T>& vector_ref() {
const int T_id { get_class_id<T>() };
if (T_id >= m_vectors.size()) {
m_vectors.resize(T_id + 1);
}
vector<T>& vector_T { *reinterpret_cast<vector<T>*>(&m_vectors[T_id]) };
return vector_T;
}
template<typename T>
void push_back(const T& value) {
vector_ref<T>().push_back(value);
}
// Move semantics, take rvalue reference
template<typename T>
void push_back(T&& value) {
vector_ref<T>().push_back(std::move(value));
}
template <typename T>
void pop_back() {
vector_ref<T>().pop_back();
}
private:
vector<vector<byte>> m_vectors;
};
template<typename T>
void show(const vector<T>& vct)
{
for (const auto& item : vct) cout << item << ' ';
cout << '\n';
}
int main(int argc, const char *argv[])
{
string hello = "hello";
string world = "world";
MultiVector mv;
mv.push_back(10);
mv.push_back(20);
mv.push_back(2.7);
mv.push_back(3.14);
mv.push_back(hello);
mv.push_back(world);
show(mv.vector_ref<int>());
show(mv.vector_ref<double>());
show(mv.vector_ref<string>());
mv.vector_ref<int>().pop_back();
show(mv.vector_ref<int>());
return 0;
}
```
Tried to replace rvalue reference `T&&` to just value `T`, does not compile too because call to `push_back` becomes ambiguous. |
Get list of matching keywords for each post |
|r|ggplot2|background-image|spider-chart| |
I'm having trouble with Git. I'm trying to push the master but I apparently have a problem with the new ssh key.
```bash
willy@DESKTOP-MH62RJV MINGW64 ~/OneDrive/Desktop/booki (master)
$ git push --force ssh master
```
```log
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
```
Do you've an idea ??
I also tried to clone it but the same:
```bash
willy@DESKTOP-MH62RJV MINGW64 ~/OneDrive/Desktop/booki (master)
$ git clone git@github.com:RodolpheACHY/booki.git
```
```log
Cloning into 'booki'...
git@github.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
```
willy@DESKTOP-MH62RJV MINGW64 ~/OneDrive/Desktop/booki (master) |
|scala|tuples|scala-3|hlist| |
{"OriginalQuestionIds":[2610497],"Voters":[{"Id":523612,"DisplayName":"Karl Knechtel"},{"Id":-1,"DisplayName":"Community","BindingReason":{"DuplicateApprovedByAsker":""}}]} |
I had a similar problem and found if I set the row height in the grid containing the CollectionView from "Auto" to "*", it fixed the problem. |
Player class with boolean settings which I want to get in another class and change
```
public Dictionary<string, bool>? Settings
{
get
{
Dictionary<string, bool> settings = null!;
foreach (var property in GetType().GetProperties().Where(p => p.PropertyType == typeof(bool)))
{
settings?.Add(property.Name, (bool) property.GetValue(this, null)!);
}
return settings;
}
}
```
p.s. f i add log to foreach then I will see the variable and its state
if this is important, then I use the latest version of the counterstrikesharp API, but the problem here is most likely not in the API
```
private void CreateMenu(CCSPlayerController? player)
{
if (player == null) return;
if (!_players.TryGetValue(player.SteamID.ToString(), out var user)) return;
var title = "RES";
user!.Menu = Config.UseCenterHtmlMenu ? new CenterHtmlMenu(title) : new ChatMenu(title);
if (user.Menu == null)
{
Console.WriteLine("user.Menu == null");
return;
}
_logUtils.Log(user.Settings?.Count.ToString()); // empty log
foreach (var (feature, state) in user.Settings!) // user.Settings empty too
{
_logUtils.Log("TEST 6");
var featureState = state switch
{
true => "[ВКЛ]",
false => "[ВЫКЛ]"
};
user.Menu.AddMenuOption(
feature + ($"[{featureState}]"),
(controller, _) =>
{
var returnState = featureState;
player.PrintToChat($"{feature}: {(returnState == featureState ? "[ВКЛ]" : "[ВЫКЛ]")}");
if (Config.ReOpenMenuAfterItemClick)
CreateMenu(controller);
});
}
if (Config.UseCenterHtmlMenu)
MenuManager.OpenCenterHtmlMenu(this, player, (CenterHtmlMenu)user.Menu);
else
MenuManager.OpenChatMenu(player, (ChatMenu)user.Menu);
}
```
I marked problem areas with comments
I logged and debugged, but I can’t understand what the problem is
|
installing algolia plugin in medusajs backend store, gives an error |
|plugins|algolia|medusajs| |
null |
I am beginner with Spring Boot. I found no static folder to place html files.
While executing the project, it was displaying the following errors:
```
[ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:3.2.3:run (default-cli) on project hello-spring: Process terminated with exit code: 1 -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
```
Moreover, I am still getting the white label error when I have placed the `index.html` file in resource directory. |
null |
I'm encountering an issue while debugging a specific Node.js application, despite having identical configurations across multiple apps. Here's the configuration I'm using:
```json
// nodemon.json
{
"restartable": "rs",
"ignore": [".git", "node_modules/", "dist/", "coverage/"],
"watch": ["lib/", ".env", "@types/"],
"execMap": {
"ts": "node -r ts-node/register"
},
"env": {
"NODE_ENV": "development"
},
"ext": "js,json,ts"
}
```
script used to execute
```json
"start:dev": "nodemon --config nodemon.json lib/server.ts | bunyan"
```
server.ts
```ts
// Disable eslint on this file to prevent imports from being re-orderd. dotenv config needs to be first.
/* eslint-disable */
import * as dotenv from 'dotenv';
dotenv.config();
import app from './app';
import { startWorkers } from './services/workers';
import { emitEvent } from 'services/events';
import { AddressInfo } from 'net';
const logger = require('/services/logger');
process.on('uncaughtException', async (err) => {
logger.error({ err }, 'An unhandled exception was thrown, and will cause the application to restart');
const logCtx = {};
const payload = {};
try {
await emitEvent('error.unhandled', { err, logCtx, payload });
} catch (ex) {
logger.error({ err: ex }, 'Failed to emit the unhandled exception');
}
process.exit(1);
});
startWorkers();
if (process.env.WORKER_MODE !== 'ON') {
const PORT = process.env.PORT || 8080;
const server = app.listen(PORT, () => {
const port = (server.address() as AddressInfo).port;
logger.info(`Express server listening on port ${port}`);
});
}
```
Despite seeing the message "Express server listening on port 8083," indicating that the server is running fine, I'm unable to debug the application. Breakpoints don't seem to be working regardless of their placement.
I've attempted several troubleshooting steps, including reinstalling node_modules, restarting both the IDE and my laptop, and updating Visual Studio Code, but the issue persists. Notably, I've observed that the call stack of the debugger isn't connected to the code being executed.
What could potentially be causing this peculiar issue where debugging works in all applications except for this particular one?
|
I'm developing a ToDo app using Flutter and encountered a `RenderFlex overflowed` error that I'm struggling to resolve. The debug console provided the following output, indicating that the contents of a `RenderFlex` widget are too big to fit within the available space:
> The overflowing RenderFlex has an orientation of Axis.vertical.
> The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and
> black striped pattern. This is usually caused by the contents being too big for the RenderFlex.
> Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the
> RenderFlex to fit within the available space instead of being sized to their natural size.
> This is considered an error condition because it indicates that there is content that cannot be
> seen. If the content is legitimately bigger than the available space, consider clipping it with a
> ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex,
> like a ListView.
> The specific RenderFlex in question is: RenderFlex#33d4b relayoutBoundary=up2 OVERFLOWING:
> needs compositing
> creator: Column ← MediaQuery ← Padding ← SafeArea ← Stack ← LayoutBuilder ← SizedBox ← Center ←
> KeyedSubtree-[GlobalKey#bf933] ← _BodyBuilder ← MediaQuery ← LayoutId-[<_ScaffoldSlot.body>] ← ⋯
> parentData: offset=Offset(0.0, 0.0) (can use size)
> constraints: BoxConstraints(0.0<=w<=500.0, 0.0<=h<=237.0)
> size: Size(500.0, 237.0)
> direction: vertical
I've isolated the issue to my `ToDoPage` widget, where a `Column` widget containing several child widgets, including text and images, seems to be the source of the problem. Below is the relevant portion of my code:
```dart
class ToDoPage extends StatefulWidget {
const ToDoPage({Key? key}) : super(key: key);
@override
State<ToDoPage> createState() => _ToDoPageState();
}
class _ToDoPageState extends State<ToDoPage> {
bool isActive = false;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xffFAFAFA),
body: Center(
child: SizedBox(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: LayoutBuilder(
builder: (context, constraints) => Stack(
children: [
SizedBox(
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Image.asset(
"assets/mountain.jpg",
fit: BoxFit.cover,
),
),
SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(
height: 20.0,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
child: Padding(
padding: EdgeInsets.fromLTRB(23, 8, 23, 8),
child: Align(
alignment: Alignment.topLeft,
child: Text(
'My success list',
style: GoogleFonts.nunito(
color: Colors.white,
fontSize: 30.0,
fontWeight: FontWeight.w500,
),
),
),
),
),
Padding(
padding: EdgeInsets.fromLTRB(23, 8, 23, 8),
child: Tooltip(
message: 'List options menu',
child: Semantics(
label: 'My success list options menu',
enabled: true,
readOnly: true,
child: IconButton(
icon: const Icon(
Icons.more_vert_outlined,
color: Colors.white,
size: 25,
semanticLabel:
'Pomodoro timer list options menu',
),
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Text('list options menu')),
);
},
),
),
),
),
],
),
Padding(
padding: EdgeInsets.fromLTRB(23, 8, 23, 8),
child: Align(
alignment: Alignment.topLeft,
child: Text(
'Thusrday, December 29, 2022',
style: GoogleFonts.nunito(
color: Colors.white,
fontSize: 20.0,
fontWeight: FontWeight.w500,
),
),
),
),
Padding(
padding: EdgeInsets.fromLTRB(23, 8, 23, 8),
child: Align(
alignment: Alignment.center,
child: Glassmorphism(
blur: 5,
opacity: 0.2,
radius: 15,
child: Container(
height: 100,
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment:
MainAxisAlignment.spaceAround,
children: [
Row(
mainAxisAlignment:
MainAxisAlignment.spaceBetween,
children: [
Text(
'task 1',
style: GoogleFonts.nunito(
color: Colors.white,
fontSize: 24.0,
fontWeight: FontWeight.bold,
),
),
SmileFaceCheckbox(
isActive: isActive,
onPress: () {
setState(() {
isActive = !isActive;
});
}),
],
),
Align(
alignment: Alignment.topLeft,
child: Text(
'Explain note',
textAlign: TextAlign.center,
style: GoogleFonts.nunito(
color: Colors.white.withOpacity(0.8),
fontSize: 16.0,
),
),
),
],
),
),
),
),
),
//hiint
Expanded(
child: Align(
alignment: FractionalOffset.bottomCenter,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Padding(
padding: const EdgeInsets.symmetric(
vertical: 10.0, horizontal: 15.0),
child: Glassmorphism(
blur: 20,
opacity: 0.1,
radius: 15.0,
child: TextButton(
onPressed: () {
// handle push to HomeScreen
},
child: Container(
padding: const EdgeInsets.symmetric(
vertical: 10.0,
horizontal: 15.0,
),
child: Text(
'+ Add successful task',
style: GoogleFonts.nunito(
color: Colors.white,
fontSize: 20.0,
),
),
),
),
),
),
],
),
),
),
),
],
),
),
],
),
),
),
),
);
}
}
```
In an attempt to fix the issue, I've tried wrapping the problematic `Column` widget in a `SingleChildScrollView` and using `Expanded` widgets around my text widgets, but the overflow error persists.
Here's a snippet of the attempted fix:
```
SafeArea(
child: Expanded(
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const SizedBox(height: 20.0),
],
),
),
),
)
```
And for the text widgets:
```
child: Flexible(
child: Text(
'My success list',
style: GoogleFonts.nunito(
color: Colors.white,
fontSize: 30.0,
fontWeight: FontWeight.w500,
),
),
)
```
I've also included custom widgets `Glassmorphism` and `SmileFaceCheckbox` in my UI. Could these be affecting layout calculations?
Update:
Glassmorphism.dart
import 'dart:ui';
import 'package:flutter/material.dart';
class Glassmorphism extends StatelessWidget {
final double blur;
final double opacity;
final double radius;
final Widget child;
const Glassmorphism({
Key? key,
required this.blur,
required this.opacity,
required this.radius,
required this.child,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return ClipRRect(
borderRadius: BorderRadius.circular(radius),
child: BackdropFilter(
filter: ImageFilter.blur(sigmaX: blur, sigmaY: blur),
child: Container(
decoration: BoxDecoration(
color: Colors.white.withOpacity(opacity),
borderRadius: BorderRadius.all(Radius.circular(radius)),
border: Border.all(
width: 1.5,
color: Colors.white.withOpacity(0.2),
),
),
child: child,
),
),
);
}
}
Smileyface.dart
import 'package:flutter/material.dart';
class SmileFaceCheckbox extends StatefulWidget {
final double height;
final bool isActive;
final VoidCallback onPress;
final Color activeColor;
final Color deactiveColor;
const SmileFaceCheckbox({
Key? key,
this.height = 24.0,
required this.isActive,
required this.onPress,
}) : activeColor = const Color.fromARGB(255, 116, 217, 48),
deactiveColor = const Color(0xffD94530),
super(key: key);
@override
State<SmileFaceCheckbox> createState() => _SmileFaceCheckboxState();
}
class _SmileFaceCheckboxState extends State<SmileFaceCheckbox>
with SingleTickerProviderStateMixin {
late AnimationController _animationController;
late Animation<double> _animationValue;
void setupAnimation() {
_animationController = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 300),
);
_animationValue = CurvedAnimation(
parent: _animationController,
curve: const Interval(0.0, 1.0),
);
}
@override
void initState() {
setupAnimation();
super.initState();
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final height = widget.height;
final width = height * 2;
final largeRadius = (height * 0.9) / 2;
final smallRadius = (height * 0.2) / 2;
return GestureDetector(
onTap: widget.onPress,
child: AnimatedBuilder(
animation: _animationController,
builder: (context, _) {
if (widget.isActive) {
_animationController.forward();
} else {
_animationController.reverse();
}
return Container(
height: height,
width: width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(80.0),
color:
widget.isActive ? widget.activeColor : widget.deactiveColor,
),
child: Stack(
alignment: Alignment.center,
children: [
Transform.translate(
offset: Offset(
-largeRadius + largeRadius * 2 * _animationValue.value,
0), // add animation move from -largeRadius to largeRadius
child: Container(
width: largeRadius * 2,
height: largeRadius * 2,
decoration: const BoxDecoration(
color: Colors.white,
shape: BoxShape.circle,
),
child: Stack(
alignment: Alignment.center,
children: [
Transform.translate(
offset: Offset(0, -smallRadius),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
Container(
width: smallRadius * 2,
height: smallRadius * 2,
decoration: BoxDecoration(
color: widget.isActive
? widget.activeColor
: widget.deactiveColor,
shape: BoxShape.circle,
),
),
Container(
width: smallRadius * 2,
height: smallRadius * 2,
decoration: BoxDecoration(
color: widget.isActive
? widget.activeColor
: widget.deactiveColor,
shape: BoxShape.circle,
),
),
],
),
),
Transform.translate(
offset: Offset(0, smallRadius * 2),
child: Container(
width: smallRadius * 4,
height:
widget.isActive ? smallRadius * 2 : smallRadius,
decoration: BoxDecoration(
color: widget.isActive
? widget.activeColor
: widget.deactiveColor,
borderRadius: !widget.isActive
? BorderRadius.circular(22.0)
: const BorderRadius.only(
bottomLeft: Radius.circular(40.0),
bottomRight: Radius.circular(40.0),
),
),
),
),
],
),
),
),
],
),
);
},
),
);
}
}
How can I resolve the `RenderFlex overflowed` error in my Flutter app, ensuring all content fits within the available space without overflow?
Any insights or solutions would be greatly appreciated. Thank you!
|
Fixing RenderFlex Overflow Error in Flutter ToDo App |
|flutter|dart|layout|overflow|flutter-renderflex-error| |
I'm deleting your post because this seems like a programming-specific question, rather than a conversation starter. With more detail added, this may be better as a Question rather than a Discussions post. Please see [this page](https://stackoverflow.com/help/how-to-ask) for help on asking a question on Stack Overflow. If you are interested in starting a more general conversation about how to approach a technical issue or concept, feel free to make another Discussion post. |
null |
I need a regex that allows me to use all characters except `|`. I need this for a text input in a flutter app. Here I want to make sure that this character is not present in the text. The widget in which I use this looks like this.
```
TextField(
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp(>>regex here<<)),
],
maxLength: 20,
controller: titleEditingController,
decoration: const InputDecoration(
hintText: 'Title',
label: Text("Title"),
),
),
``` |
how do I filter individual characters with regex |
|regex|flutter|dart| |
You should definitely not use REDIS this way as performances will be terrible.
But, you are looking for `KEYS` command :
KEYS customer|*|task|*
Not sure if the pipe has to be escaped or not. I believe it doesn't.
You probably rather take a look at that then : https://redis.io/docs/interact/search-and-query/indexing/ and index your objects properly for way better performances. |
Hi I am trying to follow the instructions from ms learns module "Create a build pipeline with Azure Pipelines". I am following the "Github Codespaces development environment using a self-hosted agent" version. I have forked the repo from the microsoft site. But when I create a codespace the process fails and i get a "Running in recovery mode due to container error" message.
Error code: 1302 (UnifiedContainersErrorFatalCreatingContainer)
after 372 log lines I get the following error:
#17 3.695 /usr/bin/apt
2024-03-05 22:22:18.797Z: #17 3.791
#17 3.791 WARNING: apt2024-03-05 22:22:18.941Z: does not have a stable CLI interface. Use with caution in scripts.2024-03-05 22:22:18.946Z:
2024-03-05 22:22:18.966Z: #17 3.791
and later
68 Reading state information...
6.087 E: Unable to locate package liblttng-ust0
6.107 'apt' failed with exit code '0'
6.107 Can't install dotnet core dependencies.
6.107 Please make sure that required repositories are connected for relevant package installer.
6.107 For issues with dependencies installation (like 'dependency was not found in repository' or 'problem retrieving the repository index file') - you can reach out to distribution owner for futher support.
6.107 You can manually install all required dependencies based on following documentation2024-03-05 22:22:23.185Z:
As I am new to codespaces I wonder if anyone kbows what is going on here (and how to fix it).
Also curiuos if anyone else tried this module and had the problems.
Cheers
FROM mcr.microsoft.com/devcontainers/dotnet:6.0
# Install NodeJS
# [Choice] Node.js version: none, lts/*, 18, 16, 14
ARG NODE_VERSION="16"
RUN if [ "${NODE_VERSION}" != "none" ]; then su vscode -c "umask
0002 && . /usr/local/share/nvm/nvm.sh && nvm install ${NODE_VERSION}
2>&1"; fi
# Install Gulp
RUN npm install --global gulp-cli
RUN curl -sL https://aka.ms/InstallAzureCLIDeb | bash
# [Optional] Install zsh
ARG INSTALL_ZSH="true"
# [Optional] Upgrade OS packages to their latest versions
ARG UPGRADE_PACKAGES="false"
# Install needed packages and setup non-root user. Use a separate
RUN statement to add your own dependencies.
ARG USERNAME=vscode
ARG USER_UID=1000
ARG USER_GID=$USER_UID
COPY library-scripts/*.sh /tmp/library-scripts/
RUN bash /tmp/library-scripts/common-debian.sh "${INSTALL_ZSH}"
"${USERNAME}" "${USER_UID}" "${USER_GID}" "${UPGRADE_PACKAGES}"
"true" "true"
# cd into the user directory, download and unzip the Azure DevOps
agent
RUN cd /home/vscode && mkdir azure-pipelines && cd azure-pipelines
# input Azure DevOps agent arguments
ARG ARCH="x64"
ARG AGENT_VERSION="2.206.1"
#RUN cd /home/vscode/azure-pipelines \
&& curl -O -L
https://vstsagentpackage.azureedge.net/agent/${AGENT_VERSION}/vsts-
agent-linux-${ARCH}-${AGENT_VERSION}.tar.gz \
&& tar xzf /home/vscode/azure-pipelines/vsts-agent-
linux-${ARCH}-${AGENT_VERSION}.tar.gz \
&& /home/vscode/azure-pipelines/bin/installdependencies.sh
# copy over the start.sh script
COPY library-scripts/start.sh /home/vscode/azure-pipelines/start.sh
# Apply ownership of home folder
RUN chown -R vscode ~vscode
# make the script executable
RUN chmod +x /home/vscode/azure-pipelines/start.sh
# Clean up
RUN rm -rf /var/lib/apt/lists/* /tmp/library-scripts |
C# unable to get bool settings from class |
|c#| |
null |
Endianness is really a question of interfaces. For a 32 bit register load one interface is asking for a 32 bit value, and the memory interface provides an array of bytes. Something has to resolve that interface. If it resolves the byte array as the low order bytes going into the most significant bits of the returned value, then it is big endian. If it resolves it with the low order bytes going into the least significant bits of the returned value it is little endian.
So, really your question is who resolves those interfaces. Technically, it matters how the processor requests data from the memory. If it requests it by saying "I want a 32 bit value" then the memory, which has an array of bytes, must resolve it. If it requests it by saying "I want 4 bytes", then the processor has to resolve it before storing it into the registers.
By convention, the processor resolves this interface. This allows the memory to work with both big and little endian processors because it can present the same interface (a byte array) to both types of processors and just let the processor resolve it anyway it wants it. At the risk of being to simplistic: the processor resolves it in the load/store unit and memory interface unit. The registers never have to think about it because by the time it reaches them, it is an 32 bit value, having already been resolved by the memory interface unit from the byte array it requested from memory. |
null |
|r|latex|r-markdown|font-awesome-5|tinytex| |
Trying to develop my fist web aplication, i just downloaded the 9v open layers files to build it. As suggested by ssome tutorials that were using openlayers 6v, instructor were connecting ol.js from the folder downloaded on open layers page to index.html that was being created. Open layers folder are not with the 4 main archives, the folder is coming with a bunch of files. Anyone can help?
Which folder or archive should imention on index.html file |
Where's the ol.js (full build of library) from open layers 6v documentation on 9v? |
|openlayers|openlayers-6|index.html| |
null |
{"Voters":[{"Id":14732669,"DisplayName":"ray"},{"Id":3700524,"DisplayName":"Mohsen_Fatemi"},{"Id":269970,"DisplayName":"esqew"}]} |
### Simple regex without index support
Without index support (only sensible for trivial cardinalities!) this is fastest in Postgres, while doing **exactly** what you ask for:
~~~pgsql
SELECT post_id, COALESCE(string_agg(topic_id::text, ',' ), 'Vague!') AS topic
FROM (
SELECT p.post_id, k.topic_id
FROM post p
LEFT JOIN keyword k ON p.content ~* ('\m' || k.keyword || '\M')
ORDER BY p.post_id, k.topic_id
) sub
GROUP BY post_id
ORDER BY post_id;
~~~
`~*` is the case-insensitive regular-expression match operator. See:
- https://stackoverflow.com/questions/20336665/lower-like-vs-ilike/20337500#20337500
Concerning my regex, I cite [the manual:][1]
`\m` ... matches only at the beginning of a word
`\M` ... matches only at the end of a word
This covers the start (`^`) and end (`$`) of the string implicitly. `\W` (as suggested in another answer) matches any non-word character, and is wrong for the task.)
Note how I apply `ORDER BY` once in a subquery instead of per-aggregate. See:
- [How to combine ORDER BY and LIMIT with an aggregate function?][2]
I this constellation, a simple `COALESCE` catches the case of no matches.
### FTS index for strict matching
The simple (naive) approach above scales with O(N*M), i.e. terribly with a non-trivial number of rows in each table. Typically, you want index support.
While strictly matching keywords, the best index should be a **[Full Text Search index][3] with the `'simple'` dictionary**, and a query that can actually use that index:
~~~pgsql
CREATE INDEX post_content_fts_simple_idx ON post USING gin (to_tsvector('simple', content));
SELECT post_id, COALESCE(topics, 'Vague!') AS topics
FROM (
SELECT post_id, string_agg(topic_id::text, ',') AS topics
FROM (
SELECT p.post_id, k.topic_id
FROM keyword k
JOIN post p ON to_tsvector('simple', p.content) @@ to_tsquery('simple', k.keyword)
ORDER BY p.post_id, k.topic_id
) sub
GROUP BY post_id
) sub1
RIGHT JOIN post p USING (post_id)
ORDER BY post_id;
~~~
### FTS index for matching English words
To match natural language words with built-in stemming, use a matching **dictionary, `'english'`** in the example:
~~~pgsql
CREATE INDEX post_content_fts_en_idx ON post USING gin (to_tsvector('english', content));
SELECT post_id, COALESCE(topics, 'Vague!') AS topics
FROM (
SELECT post_id, string_agg(topic_id::text, ',') AS topics
FROM (
SELECT p.post_id, k.topic_id
FROM keyword k
JOIN post p ON to_tsvector('english', p.content) @@ to_tsquery('english', k.keyword)
ORDER BY p.post_id, k.topic_id
) sub
GROUP BY post_id
) sub1
RIGHT JOIN post p USING (post_id)
ORDER BY post_id;
~~~
[fiddle](https://dbfiddle.uk/5YQwykLS)
For fuzzy matching consider a trigram index. See:
- https://stackoverflow.com/questions/1566717/postgresql-like-query-performance-variations/13452528#13452528
- https://stackoverflow.com/questions/7730027/how-to-create-simple-fuzzy-search-with-postgresql-only/7747765#7747765
Related:
- [Pattern matching with LIKE, SIMILAR TO or regular expressions][4]
- [Get partial match from GIN indexed TSVECTOR column][5]
[1]: https://www.postgresql.org/docs/current/functions-matching.html#POSIX-CONSTRAINT-ESCAPES-TABLE
[2]: https://dba.stackexchange.com/a/213724/3684
[3]: https://www.postgresql.org/docs/current/textsearch-tables.html#TEXTSEARCH-TABLES-INDEX
[4]: https://dba.stackexchange.com/a/10696/3684
[5]: https://dba.stackexchange.com/a/157982/3684 |
Is there any way to tell Notepad please do this...
FROM THIS
15.63387,46.42795,1,130,1,210,Sele pri Polskavi
TO THIS
15.63387,46.42795,1,130,1,210
I would like to remove everything after the last , (after number 210)
So that in the end it looks like
15.63387,46.42795,1,130,1,210
Thing is when I try it using Notepad++ with the command
FIND = [[:alpha:]] or [\u\l]
REPLACE = (leave it empty)
It removed all alphabetical characters but it leaves , signs at the end, which I can remove with `.{1}$` but for some reason some lines have empty spaces after , sign.
Some lines have one or more and this command `.{1}$` does not work since notepad++ sees empty space as a character and therefore does not remove all the , signs at the end of each line. |
- `\d` detects any digit
- `0` will detect 0
- `[0]` will also detect 0
- `\d[0]` you are asking to detect any digit followed by 0
in SAS you might be better served with `val_n = INPUT(val,??best.)` |
Need to calculate Matrix exponential with Tailor series with MPI matrix is small 3 x 3 for example
Meanwhile
```
vector<vector<double>> matrixExp(const vector<vector<double>>& A) {
int n = A.size();
vector<vector<double>> E(n, vector<double>(n, 0));
vector<vector<double>> T(n, vector<double>(n, 0));
vector<vector<double>> localE(n, vector<double>(n, 0));
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
for (int i = 0; i < n; i++)
E[i][i] = 1;
for (int i = 0; i < n; i++)
localE[i][i] = 0;
T = E;
for (int j = 1; j <= rank; j++)
{
T = matrixMult(T, A);
T = matrixDiv(T, j);
}
localE = T;
for (int i = rank + 1; i <= N; i += size) {
for (int j = i; j < i + size; j++) {
T = matrixMult(T, A);
T = matrixDiv(T, j);
}
localE = matrixSum(localE, T);
}
MPI_Reduce(localE[0].data(), E[0].data(), n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(localE[1].data(), E[1].data(), n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(localE[2].data(), E[2].data(), n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
return E;
}
```
But i dont know how to optimize this
```
for (int j = i; j < i + size; j++) {
T = matrixMult(T, A);
T = matrixDiv(T, j);
}
```
Maybe it's impossible with this implementation
[1]
[1]: https://i.stack.imgur.com/fY1Zq.png |
Since the below given advice works only for a specific class
```java
@Before("staticinitialization(org.mazouz.aop.Main1)")
```
I tried to make the advice generic such that it can work for any package
```java
@Before("staticinitialization(*.*.*(..))")
```
Im getting the below error
```log
Syntax error on token "staticinitialization(*.*.*(..))", ")" expected
```
|
Have you ever tried [json-server][1]? Usually I mock compatible data and I work with this for mvps
[1]: https://www.npmjs.com/package/json-server |
Need to calculate Matrix exponential with Tailor series with MPI matrix is small 3 x 3 for example
Meanwhile
```
vector<vector<double>> matrixExp(const vector<vector<double>>& A) {
int n = A.size();
vector<vector<double>> E(n, vector<double>(n, 0));
vector<vector<double>> T(n, vector<double>(n, 0));
vector<vector<double>> localE(n, vector<double>(n, 0));
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
for (int i = 0; i < n; i++)
E[i][i] = 1;
for (int i = 0; i < n; i++)
localE[i][i] = 0;
T = E;
for (int j = 1; j <= rank; j++)
{
T = matrixMult(T, A);
T = matrixDiv(T, j);
}
localE = T;
for (int i = rank + 1; i <= N; i += size) {
for (int j = i; j < i + size; j++) {
T = matrixMult(T, A);
T = matrixDiv(T, j);
}
localE = matrixSum(localE, T);
}
MPI_Reduce(localE[0].data(), E[0].data(), n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(localE[1].data(), E[1].data(), n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
MPI_Reduce(localE[2].data(), E[2].data(), n, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
return E;
}
```
But i dont know how to optimize this
```
for (int j = i; j < i + size; j++) {
T = matrixMult(T, A);
T = matrixDiv(T, j);
}
```
Maybe it's impossible with this implementation
https://i.stack.imgur.com/fY1Zq.png |
Unable to debug a nodejs express app in vs code |
|node.js|visual-studio-code|debugging|vscode-debugger| |
I am currently doing a scatter map of Colombia with some points that need to be differentiated according to a categorical variable. The color changes fine but it suddenly stops showing on the map when I try to change its symbol. Oddly enough, it still comes up in the legend.
This is my code:
```python
import plotly.express as px
fig = px.scatter_mapbox(datos, lat="latitud", lon="longitud", hover_name="id_direccion",
zoom=1, center=dict(lat=7, lon=-74.2973328),
mapbox_style="open-street-map",
hover_data=["Origen"],
color = "Origen"
)
fig.update_layout(title="Coordinadora")
fig.update_layout(mapbox_bounds={"west": -83, "east": -65, "south": -5, "north": 16})
fig.update_layout(width=800, height=700)
fig.show()
```
![Output map without changing marker symbols][1]
I tried to use this line of code but that's when the issue arises:
`fig.update_traces(marker={"symbol": "circle-open", }, selector={"name": "here"})`
![Output map changing marker symbols][2]
It is worth noting that I have a DataFrame called datos with four columns: `latitud`, `longitud`, `id_direccion`, and `Origen`. Origen is categorical and it can take values such as `here` or `GPS`, etc.
[1]: https://i.stack.imgur.com/WxLvL.png
[2]: https://i.stack.imgur.com/djuWh.png |
null |
Ctrl + Alt + Up / Down Arrow on windows
|
You could try below possible way to achieve dynamic controller requirement.
For that first you have to create `GenericController<T>`:
public class GenericController<T> : ControllerBase where T : class
{
// Implement your controller actions
}
Define a middleware:
public class EntityRoutingMiddleware
{
private readonly RequestDelegate _next;
public EntityRoutingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context, IEnumerable<EntitySetConfiguration> entitySets)
{
var path = context.Request.Path.Value.Trim('/');
var routeValuesFeature = context.Features.Get<IRouteValuesFeature>();
if (routeValuesFeature == null)
{
routeValuesFeature = new RouteValuesFeature();
context.Features.Set<IRouteValuesFeature>(routeValuesFeature);
}
var routeValues = routeValuesFeature.RouteValues;
foreach (var set in entitySets)
{
if (path.Equals(set.Name, StringComparison.OrdinalIgnoreCase))
{
var entityType = set.ClrType;
var controllerName = $"Generic{entityType.Name}";
routeValues["controller"] = controllerName;
routeValues["action"] = "YourActionMethod"; // Adjust this to your actual action method
break;
}
}
await _next(context);
}
}
Register the middleware in `Startup.Configure`:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
....
// Add your custom middleware before UseRouting()
app.UseMiddleware<EntityRoutingMiddleware>(/* pass your EntitySetConfiguration collection here */);
app.UseRouting();
......
.......
}
Register the generic controller type in your `Startup.ConfigureServices`:
public void ConfigureServices(IServiceCollection services)
{
// Add application services.
services.AddControllers().AddControllersAsServices()
.PartManager.FeatureProviders.Add(new GenericControllerFeatureProvider());
}
public class GenericControllerFeatureProvider : IApplicationFeatureProvider<ControllerFeature>
{
public void PopulateFeature(IEnumerable<ApplicationPart> parts, ControllerFeature feature)
{
foreach (var entityType in entityTypes)
{
var controllerType = typeof(GenericController<>).MakeGenericType(entityType).GetTypeInfo();
feature.Controllers.Add(controllerType);
}
}
}
|
I'm currently confused about windows and states. Suppose I have a program that counts user access data every minute and needs to do sum statistics in each window. Assume that at this time, I configure checkpoint for the fault tolerance of the program. The checkpoint configuration is to trigger every 30 seconds. Then when the time is 01:00, the program hangs. In theory, it can only be restored to the state data at 00:30, but there is no trigger window at 00:30. After calculation, we get the kafka offset data at 00:30 and the window data at 00:00. Is there any problem with my understanding?
here is my program:
[flink graph][1]
build stream:
SingleOutputStreamOperator<BaseResult> wordCountSampleStream = subStream.assignTimestampsAndWatermarks(
WatermarkStrategy.<MetricEvent>forBoundedOutOfOrderness(config.getDelayMaxDuration())
.withTimestampAssigner(new MetricEventTimestampAssigner())
.withIdleness(config.getWindowIdlenessTime())
).setParallelism(CommonJobConfig.getParallelismOfSubJob("WORD_COUNT_SAMPLE_TEST"))
.flatMap(new WordCountToResultFlatMapFunction(config)).setParallelism(CommonJobConfig.getParallelismOfSubJob("WORD_COUNT_SAMPLE_TEST"))
.keyBy(new BaseResultKeySelector())
.window(TumblingEventTimeWindows.of(Time.milliseconds(config.getAggregateWindowMillisecond())))
.apply(new WordCountWindowFunction(config)).setParallelism(CommonJobConfig.getParallelismOfSubJob("WORD_COUNT_SAMPLE_TEST"));
wordCountSampleStream.addSink(sink).setParallelism(CommonJobConfig.getParallelismOfSubJob("WORD_COUNT_SAMPLE_TEST"));
window apply function:
public class WordCountWindowFunction extends RichWindowFunction<BaseResult, BaseResult, String, TimeWindow> {
private StreamingConfig config;
private Logger logger = LoggerFactory.getLogger(WordCountWindowFunction.class);
public WordCountWindowFunction(StreamingConfig config) {
this.config = config;
}
@Override
public void close() throws Exception {
super.close();
}
@Override
public void apply(String s, TimeWindow window, Iterable<BaseResult> input, Collector<BaseResult> out) throws Exception {
WordCountEventPortrait result = new WordCountEventPortrait();
long curWindowTimestamp = window.getStart() / config.getAggregateWindowMillisecond() * config.getAggregateWindowMillisecond();
result.setDatasource("word_count_test");
result.setTimeSlot(curWindowTimestamp);
for (BaseResult sub : input) {
logger.info("in window cur sub is {} ", sub);
WordCountEventPortrait curInvoke = (WordCountEventPortrait) sub;
result.setTotalCount(result.getTotalCount() + curInvoke.getTotalCount());
result.setWord(curInvoke.getWord());
}
logger.info("out window result is {} ", result);
out.collect(result);
}
}
sink function:
public class ClickHouseRichSinkFunction extends RichSinkFunction<BaseResult> implements CheckpointedFunction {
private ConcurrentHashMap<String, SinkBatchInsertHelper<BaseResult>> tempResult = new ConcurrentHashMap<>();
private ClickHouseDataSource dataSource;
private Logger logger = LoggerFactory.getLogger(ClickHouseRichSinkFunction.class);
@Override
public void snapshotState(FunctionSnapshotContext context) throws Exception {
logger.info("start insert all temp data with snapshot");
long count =0;
for (Map.Entry<String, SinkBatchInsertHelper<BaseResult>> helper : tempResult.entrySet()) {
count = count + helper.getValue().insertAllTempData();
}
logger.info("insert all temp data with snapshot end,insert count is {}",count);
}
@Override
public void initializeState(FunctionInitializationContext context) throws Exception {
}
@Override
public void open(Configuration parameters) throws Exception {
Properties properties = new Properties();
properties.setProperty("user", CommonJobConfig.CLICKHOUSE_USER);
properties.setProperty("password", CommonJobConfig.CLICKHOUSE_PASSWORD);
dataSource = new ClickHouseDataSource(CommonJobConfig.CLICKHOUSE_JDBC_URL, properties);
}
@Override
public void close() {
log.info("准备处理未插入至Clickhouse的数据");
AtomicInteger totalCount = new AtomicInteger();
tempResult.values().forEach(it -> {
totalCount.addAndGet(it.getTempList().size());
batchSaveBaseResult(it.getTempList());
it.getTempList().clear();
});
log.info("处理完毕,共插入{}条数据", totalCount.get());
}
@Override
public void invoke(BaseResult value, Context context) {
tempResult.compute(value.getDatasource(), (datasource, baseResults) -> {
if (baseResults == null) {
baseResults = new SinkBatchInsertHelper<>(CommonJobConfig.COMMON_BATCH_INSERT_COUNT,
needToInsert -> batchSaveBaseResult(needToInsert),
CommonJobConfig.BATCH_INSERT_INTERVAL_MS);
}
baseResults.tempInsertSingle(value);
return baseResults;
});
}
private void batchSaveBaseResult(List<BaseResult> list) {
if (list.isEmpty()) {
return;
}
String sql = list.get(0).getPreparedSQL();
try {
try (PreparedStatement ps = dataSource.getConnection().prepareStatement(sql)) {
for (BaseResult curResult : list) {
curResult.addParamsToPreparedStatement(ps);
ps.addBatch();
}
ps.executeBatch();
}
} catch (SQLException error) {
log.error("has exception during batch insert,datasource is {} ", list.get(0).getDatasource(), error);
}
}
}
batch insert helper:
public class SinkBatchInsertHelper<T> {
private List<T> waitToInsert;
private ReentrantLock lock;
private int bulkActions;
private AtomicInteger tempActions;
private Consumer<List<T>> consumer;
private AtomicLong lastSendTimestamp;
private long sendInterval;
private Logger logger = LoggerFactory.getLogger(SinkBatchInsertHelper.class);
public SinkBatchInsertHelper(int bulkActions, Consumer<List<T>> consumer, long sendInterval) {
this.waitToInsert = new ArrayList<>();
this.lock = new ReentrantLock();
this.bulkActions = bulkActions;
this.tempActions = new AtomicInteger(0);
this.consumer = consumer;
this.sendInterval = sendInterval;
this.lastSendTimestamp = new AtomicLong(0);
}
public void tempInsertSingle(T data) {
lock.lock();
try {
waitToInsert.add(data);
if (tempActions.incrementAndGet() >= bulkActions || ((System.currentTimeMillis() - lastSendTimestamp.get()) >= sendInterval)) {
//批量插入
batchInsert();
}
} finally {
lastSendTimestamp.set(System.currentTimeMillis());
lock.unlock();
}
}
public long insertAllTempData() {
lock.lock();
try {
long result = tempActions.get();
if (tempActions.get() > 0) {
batchInsert();
}
return result;
} finally {
lock.unlock();
}
}
private void batchInsert() {
for(T t: waitToInsert){
logger.info("batch insert data:{}", t);
}
consumer.accept(waitToInsert);
waitToInsert.clear();
tempActions.set(0);
}
public int getTempActions() {
return tempActions.get();
}
public List<T> getTempList() {
lock.lock();
try {
return waitToInsert;
} finally {
lock.unlock();
}
}
}
The resulting phenomenon is:
Suppose I cancel the task at 00:31:30, then when I restart the task, the statistics at 00:31:00 will be less than expected. I found out by printing records that it was because when the sink wrote the data at 00:30:00, the kafka consumer had actually consumed the data after 00:31:00, but this part of the data was not written to ck. , it was not replayed in the window when restarting, so this part of the data was lost. The statistics will not return to normal until 00:32:00.
[1]: https://i.stack.imgur.com/03630.png |
I'm relatively new to using neo4j. I've connected to a database with the py2neo library and populated the database with the faker library to create nodes for Person and Address each with attributes attached to them. I'm interested in creating indexes and testing the performance of different indexes. These were the two indexes I had created
```
`# Step 3: Create Indexes for Persons and Addresses
graph.run(" CREATE INDEX IF NOT EXISTS FOR (p:Person) ON (p.name, p.dob, p.email, p.gender)")
graph.run("CREATE INDEX IF NOT EXISTS FOR (a:Address) ON (a.address, a.postcode, a.country)")'
```
Before I get to that point, I created some indexes and used the command
```
`graph.run("SHOW INDEXES;")`
```
[Output][1]
I was expecting 2 indexes to show but 3 indexes returned. The final one was a Look up type and had some null properties. That attached image shows the output, Why is this index showing up? Thanks.
I was expecting only 2 to return, so I'm thinking maybe this is some lack of understanding on my part? I've started reading through the Neo4j documentation on indexes but I'm still unsure. Any help would be appreciated. Thanks!
[1]: https://i.stack.imgur.com/6Hw4J.png |
{"Voters":[{"Id":-1,"DisplayName":"Community"}]} |
1. Add a click event to detect which element was clicked (`svgElem.onclick`)
2. Create a panel (`div`)
3. For each attribute ([attributes](https://developer.mozilla.org/en-US/docs/Web/API/Element/attributes) can get all current attributes), add an `input` field in the panel
4. Add an `input.onchange` event handler to update the element's attribute: `input.onchange = () => {element.setAttribute(attr.name, input.value)}`
### simple version
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-html -->
<style>
.selected {stroke: red;}
body {display: flex;}
</style>
<svg width="500" height="500" xmlns="http://www.w3.org/2000/svg">
<rect width="30" height="60" x="80" y="10" style="transform: rotate(30deg)"/>
<line x1="143" y1="100" x2="358" y2="55" fill="#000000" stroke="#000000" stroke-width="4" stroke-dasharray="8,8"
opacity="1"></line>
<circle cx="50" cy="50" r="10" fill="green"/>
</svg>
<div id="info-panel"></div>
<script>
const svgElement = document.querySelector('svg')
svgElement.addEventListener('click', (event) => {
document.querySelector(`[class~='selected']`)?.classList.remove("selected")
const targetElement = event.target
targetElement.classList.add("selected")
displayAttrsPanel(targetElement)
})
function displayAttrsPanel(element) {
const infoPanel = document.getElementById('info-panel')
infoPanel.innerHTML = ''
const attributes = element.attributes
for (let i = 0; i < attributes.length; i++) {
const attr = attributes[i]
const frag = createInputFragment(attr.name, attr.value)
const input = frag.querySelector('input')
input.onchange = () => {
element.setAttribute(attr.name, input.value)
}
infoPanel.append(frag)
}
}
function createInputFragment(name, value) {
return document.createRange()
.createContextualFragment(
`<div><label>${name}<input value="${value}"></div>`
)
}
</script>
<!-- end snippet -->
## Full code
The above example is a relatively concise version. The following example provides more settings, such as:
- [**type**](https://www.w3schools.com/tags/tag_input.asp): input can perform simple judgments to distinguish whether it is `input.type={color, number, text}`, etc.
- **Delete Button**: add the button on each properties for delete.
- **New Attribute Button**: The ability to add new attributes through the panel
- [**dialog**](https://www.w3schools.com/tags/tag_dialog.asp): For more complex attributes like {class, style, [d](https://www.w3schools.com/graphics/svg_path.asp), [points](https://www.w3schools.com/graphics/svg_polyline.asp)}, pupup an individual dialog can be used to set each value separately
<!-- begin snippet: js hide: false console: false babel: false -->
<!-- language: lang-html -->
<style>
.selected {stroke: red;}
body {display: flex;}
</style>
<svg width="500" height="500" xmlns="http://www.w3.org/2000/svg">
<rect width="30" height="60" x="80" y="10" style="transform: rotate(30deg);opacity: 0.8;"/>
<line x1="143" y1="100" x2="358" y2="55" fill="#000000" stroke="#000000" stroke-width="4" stroke-dasharray="8,8"
opacity="1"></line>
<circle class="cute big" cx="50" cy="50" r="10" fill="green"/>
<polygon points="225,124 114,195 168,288 293,251.123456"></polygon>
<polyline points="50,150 100,75 150,50 200,140 250,140" fill="yellow"></polyline>
<path d="M150 300 L75 200 L225 200 Z" fill="purple"></path>
</svg>
<div id="info-panel"></div>
<script>
const svgElement = document.querySelector('svg')
svgElement.addEventListener('click', (event) => {
document.querySelector(`[class~='selected']`)?.classList.remove("selected")
const targetElement = event.target
targetElement.classList.add("selected")
displayAttrsPanel(targetElement)
})
function displayAttrsPanel(element) {
const infoPanel = document.getElementById('info-panel')
infoPanel.innerHTML = ''
// Sorting is an optional feature designed to ensure the presentation order remains as fixed as possible.
const attributes = [...element.attributes].sort((a, b)=>{
return a.name < b.name ? -1 :
a.name > b.name ? 1 : 0
})
for (let i = 0; i < attributes.length; i++) {
const attr = attributes[i]
const frag = createInputFragment(attr.name, attr.value)
// add event
const input = frag.querySelector('input')
const deleteBtn = frag.querySelector('button')
input.onchange = () => {
element.setAttribute(attr.name, input.value)
}
// allow delete attribute
deleteBtn.onclick = () => {
element.removeAttribute(attr.name)
displayAttrsPanel(element) // refresh
}
// For special case, when clicking the label, sub-items can be displayed separately, making it convenient for editing.
const label = frag.querySelector("label")
if (["class", "style", "points", "d"].includes(attr.name)) {
label.style.backgroundColor = "#d8f9d8" // for the user know it can click
label.style.cursor = "pointer"
let splitFunc
const cbOptions = []
switch (attr.name) {
case "points": // https://www.w3schools.com/graphics/svg_polygon.asp
case "class":
splitFunc=value=>value.split(" ")
cbOptions.push((newValues)=>element.setAttribute(attr.name, newValues.join(" ")))
break
case "style":
splitFunc=value=>value.split(";")
cbOptions.push((newValues)=>element.setAttribute(attr.name, newValues.join(";")))
break
case "d": // https://www.w3schools.com/graphics/svg_path.asp
const regex = /([MLHVCSQTAZ])([^MLHVCSQTAZ]*)/g;
splitFunc=value=>value.match(regex)
cbOptions.push((newValues)=>element.setAttribute(attr.name, newValues.join("")))
}
label.addEventListener("click", () => {
openEditDialog(attr.name, attr.value,
splitFunc,
(newValues) => {
for (option of cbOptions) {
option(newValues)
}
displayAttrsPanel(element) // refresh
})
})
}
infoPanel.append(frag)
}
// Add New Attribute Button
const frag = document.createRange()
.createContextualFragment(
`<div><label>+<input placeholder="attribute"><input placeholder="value"></label><button>Add</button></div>`
)
const [inputAttr, inputVal] = frag.querySelectorAll("input")
frag.querySelector("button").onclick = () => {
const name = inputAttr.value.trim()
const value = inputVal.value.trim()
if (name && value) {
element.setAttribute(name, value)
inputAttr.value = ''
inputVal.value = ''
displayAttrsPanel(element) // refresh
}
}
infoPanel.appendChild(frag)
}
function createInputFragment(name, value) {
const frag = document.createRange()
.createContextualFragment(
`<div><label>${name}</label><input value="${value}"><button>-</button></div>`
)
const input = frag.querySelector("input")
switch (name) {
case "stroke":
case "fill":
input.type = "color"
break
case "opacity":
input.type = "range"
input.step = "0.05"
input.max = "1"
input.min = "0"
break
case "cx":
case "cy":
case "r":
case "rx":
case "ry":
case "x":
case "y":
case "x1":
case "x2":
case "y1":
case "y2":
case "stroke-width":
input.type = "number"
break
default:
input.type = "text"
}
return frag
}
function openEditDialog(name, valueStr, splitFunc, callback) {
const frag = document.createRange()
.createContextualFragment(
`<dialog open>
<div style="display: flex;flex-direction: column;"></div>
<button id="add">Add</button>
<button id="save">Save</button></dialog>`
)
const dialog = frag.querySelector("dialog")
const divValueContainer = frag.querySelector('div')
const addBtn = frag.querySelector("button#add")
const saveBtn = frag.querySelector("button#save")
const values = splitFunc(valueStr)
for (const val of values) {
const input = document.createElement("input")
input.value = val
divValueContainer.append(input)
}
// Add
addBtn.onclick = () => {
const input = document.createElement("input")
divValueContainer.append(input)
}
// Save
saveBtn.onclick = () => {
const newValues = []
dialog.querySelectorAll("input").forEach(e=>{
if (e.value !== "") {
newValues.push(e.value)
}
})
callback(newValues)
dialog.close()
}
document.body.append(dialog)
}
</script>
<!-- end snippet -->
|
Your logic and exact data are unclear.
One sure thing, you might need to double check [De Morgan's law](https://en.wikipedia.org/wiki/De_Morgan%27s_laws).
Your current code:
```
mask = (df['datetime'].dt.hour <= 6) & (df['datetime'].dt.hour >= 11)
```
Is equivalent to:
```
mask = ~(df['datetime'].dt.hour <= 6) | ~(df['datetime'].dt.hour >= 11)
```
(since not (A and B) = (not A) or (not B))
Also equivalent to:
```
mask = (df['datetime'].dt.hour > 6) | (df['datetime'].dt.hour < 11)
```
Since `NOT >=` it `<` / `NOT <=` it `>`.
Thus, if you want to include `11` in the final selection, you must **exclude** if from your original (inverted) mask:
```
mask = (df['datetime'].dt.hour <= 6) & (df['datetime'].dt.hour > 11)
concat_df = concat_df[~mask]
```
The logic is the same if you want to include `6`
#### now back to your original issue
"*I want to find all rows from my data frame that fall between 7am and 11am inclusive*"
Then `(df['datetime'].dt.hour <= 6) & (df['datetime'].dt.hour >= 11)` wouldn't work anyway since the hour is necessarily **EITHER** <=6 or >=11 (It can't be both) and your condition would always be False (irrespective of the >/>=).
What you probably want is:
```
mask = (df['datetime'].dt.hour >= 7) & (df['datetime'].dt.hour <= 11)
concat_df = concat_df[mask]
```
Or:
```
mask = df['datetime'].dt.hour.between(7, 11, inclusive='both')
concat_df = concat_df[mask]
```
|
I am working on a project where i have to use python to make a form functional so that once you fill the form and submit it, it sends that info to a mail
But it is not working even though it was working before and that is where i got this error from "Error connecting to SMTP server: (421, b'Service not available')"
I have tried everything, i linked my python to a css and html file as the anchors for the frontend, when i submit it is supposed to lead you to a particular page, but it doesn't it just gives me that error |
|r|ggplot2|jupyter-notebook| |
I had a similar problem where I wasn't seeing a Vertical scollbar. I
found if I set the row height in the grid containing the CollectionView from "Auto" to "*", it fixed the problem. |
I generate a code for graphviz. This network plan always contains 2 arrows for there and back directions. Unfortunately, 2 separate arrows are displayed in the example - but I don't want that...
[![network plan][1]][1]
Would anyone have an idea how to avoid the red double arrow? Are there perhaps other options that need to be considered?
```
digraph {
node [shape=box, style=filled, fillcolor=white, color=grey, margin=0];
graph [bgcolor=floralwhite];
edge[arrowhead="normal", color="darkblue", arrowsize=1];
rankdir=LR;
concentrate=true;
AAA [label=<
<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="2" color="black">
<TR><TD><B>10.182.2.1</B></TD></TR>
<TR><TD>AAA</TD></TR>
<TR><TD>Switch1</TD></TR>
<TR><TD PORT="111">1/1/1</TD></TR>
<TR><TD PORT="121">1/2/1</TD></TR>
<TR><TD PORT="161">1/6/1</TD></TR>
</TABLE>
>];
BBB [label=<
<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="2" color="black">
<TR><TD><B>10.182.2.2</B></TD></TR>
<TR><TD>BBB</TD></TR>
<TR><TD>Switch2</TD></TR>
<TR><TD PORT="141">1/4/1</TD></TR>
<TR><TD PORT="151">1/5/1</TD></TR>
</TABLE>
>];
CCC [label=<
<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="2" color="black">
<TR><TD><B>10.182.2.3</B></TD></TR>
<TR><TD>CCC</TD></TR>
<TR><TD>Switch3</TD></TR>
<TR><TD PORT="111">1/1/1</TD></TR>
<TR><TD PORT="161">1/6/1</TD></TR>
</TABLE>
>];
DDD [label=<
<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="2" color="black">
<TR><TD><B>10.182.2.4</B></TD></TR>
<TR><TD>DDD</TD></TR>
<TR><TD>Switch4</TD></TR>
<TR><TD PORT="141">1/4/1</TD></TR>
<TR><TD PORT="151">1/5/1</TD></TR>
</TABLE>
>];
EEE [label=<
<TABLE BORDER="0" CELLBORDER="1" CELLSPACING="0" CELLPADDING="2" color="black">
<TR><TD><B>10.182.2.5</B></TD></TR>
<TR><TD>EEE</TD></TR>
<TR><TD>Switch5</TD></TR>
<TR><TD PORT="111">1/1/1</TD></TR>
<TR><TD PORT="121">1/2/1</TD></TR>
<TR><TD PORT="161">1/6/1</TD></TR>
</TABLE>
>];
BBB:141 -> CCC:161
BBB:151 -> AAA:121
AAA:111 -> EEE:161
AAA:121 -> BBB:151
AAA:161 -> DDD:141
CCC:111 -> DDD:151
CCC:161 -> BBB:141
DDD:141 -> AAA:161
DDD:151 -> CCC:111
EEE:161 -> AAA:111
}
```
[1]: https://i.stack.imgur.com/SUk9h.jpg |
null |
I'm having a huge problem.
I have a struct
```c++
struct Particle {
int x = -1;
int y = -1;
int type = -1;
int number = -1;
bool operator==(Particle p) {
if (this->x == p.x && this->y == p.y && this->type == p.type
&& this->number == p.number) { return true; }
else { return false; }
}
};
```
and an array of vectors of them `std::vector<Particle> energies[5];` on which I call the method `std::erase(energies[neighbor.type], neighbor);`
The problem I have is that compiling using `g++ crystal.cpp -std=g++23 -o crystal $(root-config --cflags --glibs)` (the latter part is for the CERN ROOT library which I need in my program) gives me the compiler error
```
$: g++ crystal.cpp -std=c++23 -o crystal `root-config --cflags --glibs`
crystal.cpp: In lambda function:
crystal.cpp:94:22: error: ‘erase’ is not a member of ‘std’
std::erase(energies[neighbor.type], neighbor);
```
and I have no clue why that is.
Running `g++ --version` says I have 13.2.1 and that function should have been added in version 9 according to this table https://en.cppreference.com/w/Template:cpp/compiler_support/20. The error I get is the same if I substitute g++ with clang++.
Running the mock code
```c++
#include <vector>
#include <iostream>
struct Particle {
int x = -1;
int y = -1;
bool operator==(Particle p) {
if (this->x == p.x && this->y == p.y) { return true; }
else { return false; }
}
};
int main() {
std::vector<Particle> v = {{1, 0}, {0, 1}, {1, 1}};
Particle to_erase = {1, 0};
std::erase(v, to_erase);
for (auto &entry : v) {
std::cout << entry.x << ' ' << entry.y << std::endl;
}
std::cout << std::endl;
}
```
in an online compiler https://www.onlinegdb.com/ compiles and works as expected.
I have absolutely no idea why this case of "doesn't work on my machine" has struck me, but I couldn't find any issues akin to mine online.
Please help, I'm desperate. |
I'm currently in the process of testing custom logging for an Azure Function (function trigger) within a .NET 8 isolated environment. While I can see the logs being printed on the debug terminal, regrettably, they're not showing up in the Azure Portal's Application Insights. I've taken care to confirm that the instrumentation key is accurately configured in the local.settings.json file. Additionally, I've attempted solutions such as adding log levels in the host.json file, but the issue persists.
using Microsoft.ApplicationInsights.Channel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
namespace Company.Function
public class TestFunctionPOC
{
private readonly ILogger<TestFunctionPOC> _logger;
public TestFunctionPOC(ILogger<TestFunctionPOC> logger)
{
_logger = logger;
}
[Function("TestFunctionPOC")]
public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req)
{
_logger.LogInformation("C# HTTP trigger function processed a request.");
_logger.LogWarning("## this is a sample warning ##");
_logger.LogTrace("## This is a sample Trace #$#");
return new OkObjectResult("Welcome to Azure Functions!");
}
}
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/B8Sao.png |
Azure Application Insights Not Displaying Custom Logs for Azure Functions with .NET 8 |
|c#|asp.net|.net|azure|azure-functions| |
I have discovered the solution. By default, Application Insights only prints logs that are more severe, such as warnings. Therefore, we need to modify the default rule to include other log levels.
[![enter image description here][1]][1]
[See microsoft docs for above here][2]
[![enter image description here][3]][3]
And this solved my issue for azure functions in .net 8 isolated
[1]: https://i.stack.imgur.com/dlYM9.png
[2]: https://learn.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide?tabs=windows#application-insights
[3]: https://i.stack.imgur.com/UzKv2.png |
I suggest to follow the steps described in the official documentation when creating/using areas: [Areas in ASP.NET Core][1]
When following the documentation and adding an area you see the following `ScaffoldingReadMe.txt`:
```
Scaffolding has generated all the files and added the required dependencies.
However the Application's Startup code may require additional changes for things to work end to end.
Add the following code to the Configure method in your Application's Startup class if not already done:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name : "areas",
pattern : "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
});
```
This is exactly what intended to make the routing process work correctly. In your case use the following code:
``` c#
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
```
The pattern `areas` described above is generic and will be used for another areas too.
Don't forget to use correct [Area folder structure][2] too.
<hr>
*By the way, you code is working good for me. Therefore, I suppose your problem is caused by incorrect folders structure: use `Add > Area...` menu command from the `Area` folder. The Visual Studio template will help you to avoid mistakes.*
[1]: https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/areas?view=aspnetcore-8.0
[2]: https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/areas?view=aspnetcore-8.0#area-folder-structure |
I manually created 'test' directory in my Downloads folder and add your structure.
import shutil
shutil.make_archive(
base_name = '13_03_2024',
format = 'zip',
root_dir = 'test/',
base_dir = '.'
)
After running this code I extracted it successfully - no parent folder
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/5diUe.png |
To update plots dynamically, Mayavi uses either generators via `mlab.animate()` as in [this example from the docs](https://mayavi.readthedocs.io/en/latest/auto/example_mlab_visual.html#example-mlab-visual) or via rather complicated `traits` as in [this other example from the docs](https://mayavi.readthedocs.io/en/latest/auto/example_mlab_interactive_dialog.html#example-mlab-interactive-dialog).
The solution provided by `mlab.animate()` is simple and neat, but it steals control from the user: updates occurs at regular time intervals. I would like to retain control of the workflow by calling an 'update plot' method within my own loop or after a certain condition of my own is met (without embedding these loops or if conditions within the function called by animate...)
Is there a simple solution that avoids defining classes deriving from `HasTraits` etc.?
There was a similar question [here](https://stackoverflow.com/questions/39840638/update-mayavi-plot-in-loop) but the accepted answer no longer works with new versions of mayavi.
|
How to update a mayavi plot at arbitrary times |
|mayavi.mlab| |
null |
[cmd error image here](https://i.stack.imgur.com/oTlwW.png)
```
Network resources
X A cryptographic error occurred while checking "https://cocoapods.org/": Handshake error in client
You may be experiencing a man-in-the-middle attack, your network may be compromised, or you may have malware
installed on your computer.
```
Flutter install, env have set
PUB_HOSTED_URL https://pub.flutter-io.cn
FLUTTER_STORAGE_BASE_URL https://storage.flutter-io.cn
My Operate System is Windows 11
I've try 'flutter channel master' not working at all..
How could i fix that? But cocoapods goes error... |
Flutter doctor network resources error about cocoapods |
|flutter|dart|cocoapods| |
null |
This is my ansible playbook,
```yaml
---
- name: Check timeout error
hosts: all
ignore_errors: yes
gather_facts: false
tasks:
- name: test if server is connecting within n seconds
become: True
shell: id
register: id_result
async: 60
poll: 20
- name: display id result
debug: var=id_result
```
Question:
I need to exit shell task, if it runs beyond n seconds (remote host). In above case it is 10 seconds.
Expected Outcome:
```json
{"msg": "Timeout (62s) waiting for privilege escalation prompt: "}
```
Actual Outcome:
I get the shell command output, but it takes more than 4 minutes to get the output, since ssh itself to remote host is quite slow.
Doubt:
I know async works for localhost command, but is there any similar way check timeout for shell module that runs command on remote host? |
File refuses to compile std::erase() even if using -std=g++23 |
|c++|gcc|compiler-errors|g++|clang++| |
null |
{"Voters":[{"Id":3157076,"DisplayName":"francescalus"},{"Id":1280439,"DisplayName":"Ian Bush"},{"Id":721644,"DisplayName":"Vladimir F Героям слава"}]} |
Problem resolved:
```
s.get(f'http://ip', timeout = 10, verify = False, auth = HTTPDigestAuth('admin', ''))
``` |
null |
**_Originally asked on Swift Forums: https://forums.swift.org/t/using-bindable-with-a-observable-type/70993_**
I'm using SwiftUI environments in my app to hold a preferences object which is an @Observable object
But I want to be able to inject different instances of the preferences object for previews vs the production code so I've abstracted my production object in to a `Preferences` protocol and updated my Environment key's type to:
```swift
protocol Preferences { }
@Observable
final class MyPreferencesObject: Preferences { }
@Observable
final class MyPreviewsObject: Preferences { }
// Environment key
private struct PreferencesKey: EnvironmentKey {
static let defaultValue : Preferences & Observable = MyPreferencesObject()
}
extension EnvironmentValues {
var preferences: Preferences & Observable {
get { self[PreferencesKey.self] }
set { self[PreferencesKey.self] = newValue }
}
}
```
The compiler is happy with this until I go to use `@Bindable` in my code where the compiler explodes with a generic error,
eg:
```swift
@Environment(\.preferences) private var preferences
// ... code
@Bindable var preferences = preferences
```
If I change the environment object back to a conforming type eg:
```swift
@Observable
final class MyPreferencesObject() { }
private struct PreferencesKey: EnvironmentKey {
static let defaultValue : MyPreferencesObject = MyPreferencesObject()
}
extension EnvironmentValues {
var preferences: MyPreferencesObject {
get { self[PreferencesKey.self] }
set { self[PreferencesKey.self] = newValue }
}
}
```
Then `@Bindable` is happy again and things compile.
Specifically the compiler errors with:
> Failed to produce diagnostic for expression; please submit a bug report (Swift.org - Contributing)
On the parent function the @Bindable is inside of
and with a
> Command SwiftCompile failed with a nonzero exit code
In the app target.
Is this a known issue/limitation? Or am I missing something here?
Example project: https://github.com/adammcarter/observable-example/
https://github.com/adammcarter/observable-example/blob/main/observabletest/ContentView.swift |