鉴于
class Foo {
x = 1;
y = 2;
}
class Bar extends Foo {
override x = 11;
z = 3;
}
是否可以自动推导出Foo
给定值Bar
?比如Superclass<Bar> === Foo
?
鉴于
class Foo {
x = 1;
y = 2;
}
class Bar extends Foo {
override x = 11;
z = 3;
}
是否可以自动推导出Foo
给定值Bar
?比如Superclass<Bar> === Foo
?
我目前正在创建一个应用程序,其中我编写了一个函数以便能够从具有特定扩展名的 Web 获取图像,但这里有一个错误,我不知道如何解决帮帮我
文字错误
/C:/Users/sina%20saffar/AppData/Local/Pub/Cache/hosted/pub.dev/flutter_dropzone_web-3.0.13/lib/flutter_dropzone_plugin.dart:64:25: Error: The return type of the method 'FlutterDropzonePlugin.pickFiles' is 'Future<List<dynamic>>', which does not match the return type, 'Future<List<DropzoneFileInterface>>', of the overridden method, 'FlutterDropzonePlatform.pickFiles'.
- 'Future' is from 'dart:async'.
- 'List' is from 'dart:core'.
- 'DropzoneFileInterface' is from 'package:flutter_dropzone_platform_interface/dropzone_file_interface.dart' ('/C:/Users/sina%20saffar/AppData/Local/Pub/Cache/hosted/pub.dev/flutter_dropzone_platform_interface-2.2.0/lib/dropzone_file_interface.dart').
Change to a subtype of 'Future<List<DropzoneFileInterface>>'.
Future<List<dynamic>> pickFiles(bool multiple,
^
/C:/Users/sina%20saffar/AppData/Local/Pub/Cache/hosted/pub.dev/flutter_dropzone_platform_interface-2.2.0/lib/flutter_dropzone_platform_interface.dart:97:39: Context: This is the overridden method ('pickFiles').
Future<List<DropzoneFileInterface>> pickFiles(bool multiple,
选择本地图像功能:
Future<void> selectLocalImages() async {
final files = await dropzoneViewController.pickFiles(
multiple: true,
mime: ['image/jpeg', 'image/png'],
);
if (files.isNotEmpty) {
for (var file in files) {
if (file is html.File) {
final bytes = await dropzoneViewController.getFileData(file);
final image = ImageModel(
url: '',
file: file,
folder: '',
filename: file.name,
localImageToDisplay: Uint8List.fromList(bytes),
);
selectedImagesToUpload.add(image);
}
}
}
}
我在 Flutter iOS 应用中尝试使用 Firebase Messaging 获取令牌时遇到错误。错误消息如下:
FLTFirebaseMessaging: An error occurred while calling method Messaging#getToken, errorOrNil => { NSLocalizedFailureReason = "Invalid fetch response, expected 'token' or 'Error' key";}
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: [firebase_messaging/unknown] An unknown error has occurred.
#0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:651:7)
#1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:334:18)
<asynchronous suspension>
#2 MethodChannel.invokeMapMethod (package:flutter/src/services/platform_channel.dart:534:43)
<asynchronous suspension>
#3 MethodChannelFirebaseMessaging.getToken (package:firebase_messaging_platform_interface/src/method_channel/method_channel_messaging.dart:248:11)
<asynchronous suspension>
#4 FCMToken.getFcm (package:instahire/firebase/fcm_token.dart:5:21)
<asynchronous suspension>
#5 SplashController.getToken (package:instahire/controllers/splash_controller.dart:42:23)
<asynchronous suspension>
直到昨天它还运行正常,突然出现此错误。如何解决?
我正在我的项目中设置 Stripe 用于付款,但在管理客户方面遇到了一些问题。
我试图做的是创建一个新客户,并在用户创建结帐会话时将条纹客户 ID 存储在我的数据库中。问题是,在用户完成付款后,正在创建另一个客户。
@app.post('/create-checkout-session')
async def create_checkout_session(request: Request):
data = await request.json()
price_id = data['price_id']
user_id = data['user_id']
base_url = data['base_url']
stripe_customer_id = data.get('stripe_customer_id')
try:
if stripe_customer_id is not None:
stripe_customer = stripe.Customer.retrieve(stripe_customer_id)
if stripe_customer:
print('stripe_customer', stripe_customer)
return
else:
print('request', request)
stripe_customer = stripe.Customer.create(metadata={"user_id": user_id})
customer_id = stripe_customer.id
await update_user_with_stripe_customer_id(user_id, customer_id)
checkout_session = stripe.checkout.Session.create(
customer=stripe_customer_id,
line_items=[
{
'price': price_id,
'quantity': 1,
},
],
mode='subscription',
success_url=base_url + '/payment-success',
cancel_url=base_url + '?canceled=true',
client_reference_id=user_id,
)
logger.info(f"Checkout session created successfully: {checkout_session.id}")
return JSONResponse(content={"url": checkout_session.url}, status_code=200)
except stripe.error.StripeError as e:
logger.error(f"Stripe error: {str(e)}")
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Error creating checkout session: {str(e)}")
raise HTTPException(status_code=500, detail=str(e))
async def update_user_with_stripe_customer_id(user_id: str, stripe_customer_id: str):
db = firestore.client()
user_ref = db.collection('customers').where(filter=FieldFilter("user_id", "==", user_id))
user_docs = user_ref.get()
if user_docs:
user_doc = user_docs[0]
user_doc.reference.update({
'stripe_customer_id': stripe_customer_id
})
print(f"Updated user {user_id} with Stripe customer ID {stripe_customer_id}")
else:
logger.error(f"User {user_id} not found in database")
raise HTTPException(status_code=404, detail="User not found")
结账会话完成且付款成功后,我想更新数据库以向用户提供分配的信用额度。但是我收到 404 未找到用户错误。
@app.post('/webhook')
async def webhook_received(request: Request):
print("Webhook received!")
payload = await request.body()
sig_header = request.headers.get('stripe-signature')
logger.info(f"Stripe signature: {sig_header}")
try:
event = stripe.Webhook.construct_event(
payload, sig_header, STRIPE_WEBHOOK_SECRET
)
print(f"Event constructed: {event['type']}")
except ValueError as e:
logger.info(f"Invalid payload: {str(e)}")
raise HTTPException(status_code=400, detail='Invalid payload')
except stripe.error.SignatureVerificationError as e:
logger.info(f"Invalid signature: {str(e)}")
raise HTTPException(status_code=400, detail='Invalid signature')
if event['type'] == 'checkout.session.completed':
logger.info("Checkout session completed event received")
return
session = event['data']['object']
try:
result = await handle_checkout_session_completed(session)
return JSONResponse(content={"status": "success", "result": result}, status_code=200)
except Exception as e:
logger.error(f"Error handling checkout session: {str(e)}")
return JSONResponse(content={"status": "error", "message": str(e)}, status_code=500)
elif event['type'] =='invoice.paid':
logger.info("Invoice paid event received")
session = event['data']['object']
try:
result = await handle_invoice_paid(session)
return JSONResponse(content={"status": "success", "result": result}, status_code=200)
except Exception as e:
logger.error(f"Error handling invoice paid: {str(e)}")
return JSONResponse(content={"status": "error", "message": str(e)}, status_code=500)
else:
logger.info(f"Unhandled event type: {event['type']}")
async def handle_invoice_paid(session):
print('session', session)
credits = session.get('lines').data[0].plan.metadata.credits
tier = session.get('lines').data[0].plan.metadata.tier
stripe_customer_id = session.get('customer')
print('credits', credits, tier, stripe_customer_id)
if credits:
db = firestore.client()
user_ref = db.collection('customers').where(filter=FieldFilter("stripe_customer_id", "==", stripe_customer_id))
user_docs = user_ref.get()
if user_docs:
user_doc = user_docs[0]
user_doc.reference.update({
'credits': credits,
'current_subscription_tier': tier,
'stripe_customer_id': stripe_customer_id
})
updated_user_doc = user_doc.reference.get()
updated_user_data = updated_user_doc.to_dict()
return JSONResponse(content={"updated_user": updated_user_data}, status_code=200)
else:
print(f"User document not found for user_id: {stripe_customer_id}")
raise HTTPException(status_code=404, detail="User not found")
else:
print(f"credits: {credits} not found")
我尝试过不同的方法来创建客户。最终我需要用客户 ID 来更新数据库,但我的问题是,由于要创建多个用户,因此有多个客户 ID。
为什么相同的查询在 Windows MySQL 实例上有效,但在 Ubuntu MySQL 实例上无效?
实例版本非常接近:
Windows:@@sql_mode:STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION
Ubuntu:@@sql_mode:ONLY_FULL_GROUP_BY、STRICT_TRANS_TABLES、NO_ZERO_IN_DATE、NO_ZERO_DATE、ERROR_FOR_DIVISION_BY_ZERO、NO_ENGINE_SUBSTITUTION
Ubuntu 上的错误:
错误 3065 (HY000):ORDER BY 子句的表达式 #1 不在 SELECT 列表中,引用的列“p.priority”不在 SELECT 列表中;这与 DISTINCT 不兼容
查询:
SELECT DISTINCT
`id`, `date_created`, `date_last_update`, `text_id_map`, `address_search_aid`, `lat`, `lng`,
`street_line1`, `street_line2`, `zip`, `company_status`, `compassion_level`, `emails`,
`phones`, `social_media`, `urls`, `description`, `importance`, `name`, `object_status`,
`search_aid`, `short_name`, `created_by_id`, `last_update_by_id`, `alternate_country_id`,
`city_id`, `parent_id`, `city_region_id`, `autocomplete`, `sitemap_xml`
FROM (
SELECT p.*, 0 AS `priority`, CASE WHEN `parent_id` IS NULL THEN 1 ELSE 0 END AS `is_parent`
FROM `provider` p
CROSS JOIN JSON_TABLE( JSON_KEYS(`name`), '$[*]' COLUMNS (locale VARCHAR(10) PATH '$') ) AS l
CROSS JOIN JSON_TABLE( JSON_EXTRACT(`name`, CONCAT('$.', l.locale)), '$' COLUMNS (`jsonval` VARCHAR(2048) PATH '$') ) AS j
WHERE
INSTR( CONCAT(' ', REPLACE(j.jsonval, '-', ' '), ' '), CONCAT(' ', 'web', ' ') ) > 0
AND
INSTR( CONCAT(' ', REPLACE(j.jsonval, '-', ' '), ' '), CONCAT(' ', 'kon', ' ') ) > 0
UNION
SELECT *,
CASE
WHEN
INSTR( CONCAT(' ', `autocomplete`, ' '), CONCAT(' ', 'web', ' ') ) > 0
AND
INSTR( CONCAT(' ', `autocomplete`, ' '), CONCAT(' ', 'kon', ' ') ) > 0
THEN 1
WHEN INSTR( `autocomplete`, 'web' ) > 0 AND INSTR( `autocomplete`, 'kon' ) > 0 THEN 2
ELSE 3
END `priority`,
CASE
WHEN parent_id IS NULL THEN 1
ELSE 0
END AS `is_parent`
FROM `provider`
) p
WHERE `priority` < 3
ORDER BY `priority`, `is_parent` DESC
LIMIT 10;
表是这样创建的:
CREATE TABLE `provider` (
`id` int NOT NULL,
`date_created` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`date_last_update` varchar(80) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`text_id_map` text COLLATE utf8mb4_unicode_ci,
`address_search_aid` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`lat` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`lng` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`street_line1` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`street_line2` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`zip` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`company_status` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`compassion_level` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`emails` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`phones` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`social_media` text COLLATE utf8mb4_unicode_ci,
`urls` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`description` text COLLATE utf8mb4_unicode_ci,
`importance` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`name` text COLLATE utf8mb4_unicode_ci,
`object_status` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`search_aid` text COLLATE utf8mb4_unicode_ci,
`short_name` text COLLATE utf8mb4_unicode_ci,
`created_by_id` int DEFAULT NULL,
`last_update_by_id` int DEFAULT NULL,
`alternate_country_id` int DEFAULT NULL,
`city_id` int DEFAULT NULL,
`parent_id` int DEFAULT NULL,
`city_region_id` int DEFAULT NULL,
`autocomplete` text COLLATE utf8mb4_unicode_ci,
`sitemap_xml` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci,
PRIMARY KEY (`id`),
KEY `FKotfd80u3xayhxxjrvtpclqwe6` (`created_by_id`),
KEY `FK7gqnbcylk4ghwciki0779g32u` (`last_update_by_id`),
KEY `FKk6jlj4kwu3hi5kl4a4qqso7j3` (`alternate_country_id`),
KEY `FKrlh8uhcluf8si4vfbgdw3w6p1` (`city_id`),
KEY `FK6psluxn6a0b64bcxggfuum2l0` (`parent_id`),
KEY `FKegsn16mm766i6j5du01dlvn6` (`city_region_id`),
CONSTRAINT `FK6psluxn6a0b64bcxggfuum2l0` FOREIGN KEY (`parent_id`) REFERENCES `provider` (`id`),
CONSTRAINT `FK7gqnbcylk4ghwciki0779g32u` FOREIGN KEY (`last_update_by_id`) REFERENCES `veg_user` (`id`),
CONSTRAINT `FKegsn16mm766i6j5du01dlvn6` FOREIGN KEY (`city_region_id`) REFERENCES `city_region` (`id`),
CONSTRAINT `FKk6jlj4kwu3hi5kl4a4qqso7j3` FOREIGN KEY (`alternate_country_id`) REFERENCES `country` (`id`),
CONSTRAINT `FKotfd80u3xayhxxjrvtpclqwe6` FOREIGN KEY (`created_by_id`) REFERENCES `veg_user` (`id`),
CONSTRAINT `FKrlh8uhcluf8si4vfbgdw3w6p1` FOREIGN KEY (`city_id`) REFERENCES `city` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
来自 Windows 上的 Heidi 的屏幕截图;查询从这个 SO 问题复制而来:
这个想法是创建一个查询,它将用作自动完成,但它会将具有精确关键字的结果移动到顶部。
查询的第一部分 p1 搜索精确匹配,而最后一部分 p2 搜索任何子字符串的出现。这意味着在第一部分中将选择名称中包含“ One ”的提供商,而在第二部分中将选择名称中包含“ Done ”的提供商。
问题是第二部分也从第一部分中选择了项目。
因此,我尝试为 union 的每个部分添加别名,并尝试为 union 的最后一部分添加附加条件:AND p2.id != p1.id
这对于 MySQL 不起作用:
SQL 错误(1054):‘where 子句’中未知列‘p1.id’。
也尝试过HAVING
,但根本没有运气。
SELECT * FROM (
(SELECT DISTINCT
p1.*,
1 AS priority,
CASE WHEN parent_id IS NULL THEN 1 ELSE 2 END AS is_parent
FROM provider p1
WHERE CONCAT(' ', name, ' ') LIKE '% one %'
LIMIT 100)
UNION
(SELECT DISTINCT
p2.*,
2 AS priority,
CASE WHEN parent_id IS NULL THEN 1 ELSE 2 END AS is_parent
FROM provider p2
WHERE name LIKE '%one%' AND p2.id != p1.id
LIMIT 100)
ORDER BY priority, is_parent
) AS t LIMIT 100;
样本数据:
ID | Parent ID | Name
---------------------------
1 | <NULL> | One dove
2 | 1 | One play
3 | <NULL> | Monitor
4 | 1 | Day one
5 | <NULL> | Drone
6 | <NULL> | Screen
7 | <NULL> | Done with you
8 | <NULL> | Not done
9 | <NULL> | All as one
预期结果:
ID | Parent ID | Name | Priority | Is parent
------------------------------------------------------
1 | <NULL> | One dove | 1 | 1
9 | <NULL> | All as one | 1 | 1
2 | 1 | One play | 1 | 2
4 | 1 | Day one | 1 | 2
5 | <NULL> | Drone | 2 | 1
7 | <NULL> | Done with you | 2 | 1
8 | <NULL> | Not done | 2 | 1
当TooltipBox
打开时,单击屏幕上的任何 Composable 都不会产生任何效果,除了关闭 Popup。它是如何做到的,以及在打开时无论当前 Composable 在 Composition 树中的什么位置,实现它的有效方法是什么,Popup
这样其他 Composable 都不会Popup
接收任何手势。
@Preview
@Composable
fun TooltipBoxSample() {
Column(
modifier = Modifier.fillMaxSize().border(2.dp, Color.Blue)
) {
Button(
onClick = {}
){
Text("Some button")
}
val state = rememberTooltipState(
isPersistent = true
)
val coroutineScope = rememberCoroutineScope()
Spacer(modifier = Modifier.height(120.dp))
Row(
modifier = Modifier.weight(1f)
) {
Spacer(modifier = Modifier.width(100.dp))
TooltipBox(
positionProvider = rememberPlainTooltipPositionProvider(
spacingBetweenTooltipAndAnchor = 16.dp
),
state = state,
tooltip = {
PlainTooltip(
caretProperties = CaretProperties(
caretWidth = 16.dp,
caretHeight = 16.dp
),
shape = RoundedCornerShape(16.dp),
containerColor = Color.Red
) {
Text(
text = "Tooltip Content for testing...",
modifier = Modifier.padding(16.dp)
)
}
},
content = {
Icon(
modifier = Modifier
.size(60.dp)
.clickable {
coroutineScope.launch {
state.show()
}
},
imageVector = Icons.Default.Info,
contentDescription = null
)
}
)
}
}
}
如果你使用Popup
Composables 触摸屏幕上的任意位置,则会收到点击事件
@Preview
@Composable
fun PopupOpenCloseTest() {
var showPopup by remember {
mutableStateOf(false)
}
Column(
modifier = Modifier.fillMaxSize()
) {
Button(
onClick = {}
) {
Text("Some button")
}
Box {
Icon(
modifier = Modifier
.border(2.dp, Color.Blue)
.size(60.dp)
.clickable {
if (showPopup.not()) {
showPopup = true
}
println("CLICKED showPopup: $showPopup")
},
imageVector = Icons.Default.Info,
contentDescription = null
)
if (showPopup) {
Popup(
offset = IntOffset(300, 300),
onDismissRequest = {
if (showPopup) {
showPopup = false
}
}
) {
Box(
modifier = Modifier.background(Color.White).padding(16.dp)
) {
Text("Popup Content")
}
}
}
}
}
}
我检查了Tooltip和BasicTooltip的源代码,但没有地方创建取消手势的窗口或视图,或者使用任何手势。
我有一台 mac m2,我正在尝试使用一些钛模块运行苹果模拟器,但出现以下错误:
[ERROR] Error: The app is using native modules that do not support arm64 simulators and you are on an arm64 device:
- de.marcelpociot.imagefromgif
- ti.safaridialog
- com.movento.splitwindow
- net.iamyellow.tiws
at iOSBuilder.invokeXcodeBuild (/Users/programador1/Library/Application Support/Titanium/mobilesdk/osx/12.2.1.GA/iphone/cli/commands/_build.js:7096:17)
Process exited with 1
请帮我。
之前的模块没有 m2 的更新,或者至少我没有找到最近的更新。
目前,要重新初始化 的模型AutoModelForSequenceClassification
,我们可以这样做:
from transformers import AutoModel, AutoConfig, AutoModelForSequenceClassification
m = "moussaKam/frugalscore_tiny_bert-base_bert-score"
config = AutoConfig.from_pretrained(m)
model_from_scratch = AutoModel(config)
model_from_scratch.save_pretrained("frugalscore_tiny_bert-from_scratch")
model = AutoModelForSequenceClassification(
"frugalscore_tiny_bert-from_scratch", local_files_only=True
)
AutoConfig
?model = AutoModelForSequenceClassification(
"moussaKam/frugalscore_tiny_bert-base_bert-score",
local_files_only=True
reinitialize_weights=True
)
或类似的东西:
model = AutoModelForSequenceClassification(
"moussaKam/frugalscore_tiny_bert-base_bert-score",
local_files_only=True
)
model.reinitialize_parameters()
在比较 2 个表之间的数据的查询中,我经常使用 和 的组合COALESCE
来FULL OUTER JOIN
显示仅在其中 1 个表中可用的记录。
这可以用更少的语法糖来完成吗?(我的意思并不是替换COALESCE
为之NVL
类的。)
WITH Dataset1 AS (
SELECT
id,
SUM(amount) AS amount
FROM
table1
GROUP BY
id
),
Dataset2 AS (
SELECT
id,
SUM(amount) AS amount
FROM
table2
GROUP BY
id
)
SELECT
COALESCE(d1.id, d2.id) AS ID,
COALESCE(d1.amount, 0) AS D1_AMOUNT,
COALESCE(d2.amount, 0) AS D2_AMOUNT,
COALESCE(d1.amount, 0) - COALESCE(d2.amount, 0) AS DELTA
FROM
Dataset1 d1
FULL OUTER JOIN
Dataset2 d2 c ON
d2.id = d1.id
WHERE
ABS(COALESCE(d1.amount, 0) - COALESCE(d2.amount, 0)) >= 5
ORDER BY
ID
我目前有一个包含多个对象的数组。for 循环使用模型的 for 循环基于数组对象执行查询集。
search_post = ["1990", "2023"]
for query in search_post:
vehicle_result = Vehicle.objects.filter(
Q(title__icontains=query) |
Q(details__icontains=query) |
Q(year__icontains=query) |
Q(notes__icontains=query)
)
print('vehicle_result: %s' % vehicle_result)
我遇到的问题是,当数组有多个项目时,它会为每个对象执行 for 循环,并输出每个对象的结果。如果我在代码中的其他地方调用此变量,则仅保留最后一个对象结果。
示例输出:
vehicle_result: <QuerySet [<Vehicle: BMW>]>
vehicle_result: <QuerySet [<Vehicle: Toyota>, <Vehicle: Mercedes>, <Vehicle: Honda>]>
我想将它们全部存储/合并到一个变量中 - 防止丢失所有结果(我猜现在只保留最后一个结果,因为变量被覆盖了)
我怎样才能实现?