row_id int64 0 48.4k | init_message stringlengths 1 342k | conversation_hash stringlengths 32 32 | scores dict |
|---|---|---|---|
18,387 | import pyodbc
import numpy
import pandas as pd
import matplotlib.pyplot as plt
import xlwings as xw
def brinson(portfolioID, beginDate, endDate, analyst=None, industry=None):
try:
# 建立与Excel的互动
wb = xw.Book.caller()
sht = wb.sheets['sheet1']
sht2 = wb.sheets['sheet2']
# 设置连接字符串和数据库连接
conn_str = r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\LIQI\Documents\portfolio.accdb"
conn = pyodbc.connect(conn_str)
portfolio_benchmark_mapping = {
'300Active': 'CSI300',
'300Standard': 'CSI300',
'500Active': 'CSI500',
'500Standard': 'CSI500'}
# 获取给定portfolioID的对应benchID
if portfolioID not in portfolio_benchmark_mapping:
print(f"未找到投资组合ID的基准: {portfolioID}")
else:
benchID = portfolio_benchmark_mapping[portfolioID]
# 查询数据库
portfolio_query = "SELECT * FROM Mockportfolio WHERE ID = ? AND TRADEDATE >= ? AND tradedate <= ?"
portfolio_data = pd.read_sql(portfolio_query, conn, params=[portfolioID, beginDate, endDate])
# 修改 benchmark_query,使用参数化查询
benchmark_query = "SELECT * FROM Benchmark WHERE BenchID = ? AND TRADEDATE >= ? AND tradedate <= ?"
benchmark_data = pd.read_sql(benchmark_query, conn, params=[benchID, beginDate, endDate])
portfolio_data['RETURN'] = portfolio_data['RETURN'].astype(float)
benchmark_data['Weight'] = benchmark_data['Weight'].astype(float)
benchmark_data['Return'] = benchmark_data['Return'].astype(float)
portfolio_data['CONTRIBUTION'] = portfolio_data['WEIGHT'] * portfolio_data['RETURN']
benchmark_data['CONTRIBUTION'] = benchmark_data['Weight'] * benchmark_data['Return']
if analyst is not None:
# 为指定的分析师过滤投资组合数据
portfolio_data = portfolio_data[portfolio_data['Analyst'] == analyst]
benchmark_data = benchmark_data[benchmark_data['Analyst'] == analyst]
benchmark_data_grouped = benchmark_data.groupby(['TradeDate', 'Industry I'])[['Weight', 'Return', 'CONTRIBUTION']].sum().reset_index()
portfolio_data_grouped = portfolio_data.groupby(['TRADEDATE', 'Industry I'])[['WEIGHT', 'RETURN', 'CONTRIBUTION']].sum().reset_index()
benchmark_data_grouped['Return'] = benchmark_data_grouped['CONTRIBUTION'] / benchmark_data_grouped['Weight']
portfolio_data_grouped['RETURN'] = portfolio_data_grouped['CONTRIBUTION'] / portfolio_data_grouped['WEIGHT']
#portfolio_data_grouped['RETURN'] = portfolio_data_grouped['RETURN'].fillna(0)
benchmark_data_grouped.rename(columns={'TradeDate': 'TRADEDATE','Weight': 'WEIGHT','Return': 'RETURN'}, inplace=True)
portfolio_df = pd.merge(portfolio_data_grouped, benchmark_data_grouped, on=['TRADEDATE', 'Industry I'], suffixes=('_P', '_B'))
portfolio_df['Q1_daily'] = portfolio_df['WEIGHT_B'] * portfolio_df['RETURN_B']
portfolio_df['Q2_daily'] = portfolio_df['WEIGHT_P'] * portfolio_df['RETURN_B']
portfolio_df['Q3_daily'] = portfolio_df['WEIGHT_B'] * portfolio_df['RETURN_P']
portfolio_df['Q4_daily'] = portfolio_df['WEIGHT_P'] * portfolio_df['RETURN_P']
portfolio_df['excess_return_daily'] = portfolio_df['Q4_daily'] - portfolio_df['Q1_daily']
portfolio_df['allocation_effect_daily'] = portfolio_df['Q2_daily'] - portfolio_df['Q1_daily']
portfolio_df['selection_effect_daily'] = portfolio_df['Q3_daily'] - portfolio_df['Q1_daily']
portfolio_df['interaction_effect_daily'] = portfolio_df['Q4_daily'] - portfolio_df['Q3_daily'] - portfolio_df['Q2_daily'] + portfolio_df['Q1_daily']
# 计算各行业的累积超额收益,每日收益率累乘-1
portfolio_df['RETURN_P_compound']=(1 + portfolio_df['RETURN_P']).groupby([portfolio_df.iloc[:, 1]]).cumprod()-1
portfolio_df['RETURN_B_compound']=(1 + portfolio_df['RETURN_B']).groupby([portfolio_df.iloc[:, 1]]).cumprod()-1
portfolio_df['Q1_compound']=(1 + portfolio_df['Q1_daily']).groupby([portfolio_df.iloc[:, 1]]).cumprod()-1
portfolio_df['Q2_compound']=(1 + portfolio_df['Q2_daily']).groupby([portfolio_df.iloc[:, 1]]).cumprod()-1
portfolio_df['Q3_compound']=(1 + portfolio_df['Q3_daily']).groupby([portfolio_df.iloc[:, 1]]).cumprod()-1
portfolio_df['Q4_compound']=(1 + portfolio_df['Q4_daily']).groupby([portfolio_df.iloc[:, 1]]).cumprod()-1
#四种效应的累计收益
portfolio_df['excess_return_compound'] = portfolio_df['Q4_compound'] - portfolio_df['Q1_compound']
portfolio_df['allocation_effect_compound'] = portfolio_df['Q2_compound'] - portfolio_df['Q1_compound']
portfolio_df['selection_effect_compound'] = portfolio_df['Q3_compound'] - portfolio_df['Q1_compound']
portfolio_df['interaction_effect_compound'] = portfolio_df['Q4_compound'] - portfolio_df['Q3_compound'] - portfolio_df['Q2_compound'] + portfolio_df['Q1_compound']
#对 portfolio_df 数据框进行了索引重置,以确保索引重新从零开始,以便于后续处理和分析。
portfolio_df=portfolio_df.reset_index()
# 计算整个投资组合的累积超额收益
#四种效应下的累计收益按交易日期分组求和然后索引重置
#excess_return_compound = portfolio_df.groupby('TRADEDATE')['excess_return_compound'].sum().reset_index()
#allocation_effect_compound = portfolio_df.groupby('TRADEDATE')['allocation_effect_compound'].sum().reset_index()
#selection_effect_compound = portfolio_df.groupby('TRADEDATE')['selection_effect_compound'].sum().reset_index()
#interaction_effect_compound = portfolio_df.groupby('TRADEDATE')['interaction_effect_compound'].sum().reset_index()
# 为特定行业绘制图表
if industry is not None:
industry_data = portfolio_df[portfolio_df['Industry I'] == industry]
x_data = industry_data['TRADEDATE'].to_numpy()
y1_data = industry_data['excess_return_compound'].to_numpy()
y2_data = industry_data['allocation_effect_compound'].to_numpy()
y3_data = industry_data['selection_effect_compound'].to_numpy()
y4_data = industry_data['interaction_effect_compound'].to_numpy()
# 创建一个图形和坐标轴
plt.figure(figsize=(12, 9))
fig, ax = plt.subplots()
# 绘制折线图
ax.plot(x_data, y1_data, color='blue', marker='o', label='excess_return_compound')
ax.plot(x_data, y2_data, color='red', marker='o', label='allocation_effect_compound')
ax.plot(x_data, y3_data, color='black', marker='o', label='selection_effect_compoundt')
ax.plot(x_data, y4_data, color='purple', marker='o', label='interaction_effect_compound')
plt.xticks(rotation=45)
plt.title(f"Excess Return in {industry}")
plt.xlabel('TRADEDATE')
plt.ylabel('excess_return_compound')
plt.legend()
# Show the plot
left = sht2.range('G3').left
top = sht2.range('G3').top
sht2.pictures.add(fig, name='Industry', update=True, left=left, top=top)
#生成单行业时间序列
industry_data = industry_data[['TRADEDATE','excess_return_compound','allocation_effect_compound','selection_effect_compound','interaction_effect_compound']]
industry_data.rename(columns={'TRADEDATE':'交易日'}, inplace=True)
industry_data.rename(columns={'excess_return_compound': '超额收益','allocation_effect_compound': '配置效应'}, inplace=True)
industry_data.rename(columns={'selection_effect_compound': '选股效应','interaction_effect_compound': '交叉效应'}, inplace=True)
# 将后四列的数据格式化为 #.###### 格式
decimal_format = lambda x: f'{x:.6f}'
columns_to_format = ['超额收益', '配置效应', '选股效应', '交叉效应']
#写入excel
sht2.range('A2').options(index=False, header=True, numbers=str).value = industry_data
# 为特定组合绘制图表
excess_return_compound = portfolio_df.groupby('TRADEDATE')['excess_return_compound'].sum().reset_index()
allocation_effect_compound = portfolio_df.groupby('TRADEDATE')['allocation_effect_compound'].sum().reset_index()
selection_effect_compound = portfolio_df.groupby('TRADEDATE')['selection_effect_compound'].sum().reset_index()
interaction_effect_compound = portfolio_df.groupby('TRADEDATE')['interaction_effect_compound'].sum().reset_index()
x21_data = excess_return_compound['TRADEDATE'].to_numpy()
y21_data = excess_return_compound['excess_return_compound'].to_numpy()
y22_data = allocation_effect_compound['allocation_effect_compound'].to_numpy()
y23_data = selection_effect_compound['selection_effect_compound'].to_numpy()
y24_data = interaction_effect_compound['interaction_effect_compound'].to_numpy()
# 创建一个图形和坐标轴
plt.figure(figsize=(12, 9))
fig, ax = plt.subplots()
ax.plot(x21_data, y21_data, color='blue', marker='o', label='excess_return_compound')
ax.plot(x21_data, y22_data, color='red', marker='o', label='allocation_effect_compound')
ax.plot(x21_data, y23_data, color='black', marker='o', label='selection_effect_compoundt')
ax.plot(x21_data, y24_data, color='purple', marker='o', label='interaction_effect_compound')
plt.title('Entire Portfolio Compound Excess Return')
plt.xlabel('Trade Date')
plt.ylabel('Excess Return')
# 添加图例
ax.legend()
plt.xticks(rotation=45)
# 插入第二个图表到 sheet1
left = sht.range('J3').left
top = sht.range('J3').top
sht.pictures.add(fig, name='PortfolioChart2', update=True, left=left, top=top)
#生成投资组合快照
portfolio_snap = portfolio_df[portfolio_df['TRADEDATE'] == endDate]
portfolio_snap = portfolio_snap[['Industry I','WEIGHT_P','WEIGHT_B','RETURN_P_compound','RETURN_B_compound','excess_return_compound','allocation_effect_compound','selection_effect_compound','interaction_effect_compound']]
portfolio_snap = portfolio_snap.sort_values('selection_effect_compound', ascending=False)
portfolio_snap.rename(columns={'Industry I':'行业','WEIGHT_P':'组合权重','WEIGHT_B':'指数权重','RETURN_P_compound': '组合回报','RETURN_B_compound': '指数回报'}, inplace=True)
portfolio_snap.rename(columns={'excess_return_compound': '超额收益','allocation_effect_compound': '配置效应'}, inplace=True)
portfolio_snap.rename(columns={'selection_effect_compound': '选股效应','interaction_effect_compound': '交叉效应'}, inplace=True)
# 将后四列的数据格式化为 #.###### 格式
decimal_format = lambda x: f'{x:.6f}'
columns_to_format = ['组合权重','指数权重','组合回报','超额收益', '配置效应', '选股效应', '交叉效应']
#写入excel
sht.range('A2').options(index=False, header=True, numbers=str).value = portfolio_snap
except Exception as e:
print(f"Error: {e}")
finally:
conn.close()
def generate():
# 建立与Excel的互动
wb = xw.Book.caller()
sht = wb.sheets['sheet1']
portfolioID = sht.range('b1').value#300Active,300Standard……
beginDate = sht.range('j1').value
endDate = sht.range('l1').value
analyst = sht.range('h1').value
industry = sht.range('e1').value#一级行业
brinson(portfolioID, beginDate, endDate, analyst, industry)
if __name__ == "__main__":
generate() 我写了一个brinson归因分析的脚本,现在遇到一个问题。如果从参数beginDate到endDate,某个analyst在某个industry的weight_p上一直>0,那么 在#生成投资组合快照这一段会出现有关该industry的数据,但一旦endDate那天,该industry的weight_p=0,数据就不显示了。问题出在哪里呢?因为即便在endDate,不再持有该industry的股票,在期间还是会有累积超额收益数据啊 | 248a97dd3858f027bb2b42348960fad7 | {
"intermediate": 0.45285964012145996,
"beginner": 0.38861554861068726,
"expert": 0.15852487087249756
} |
18,388 | <template>
<q-page class="flex flex-center">
<q-card>
<div style="width: 600px; height: 300px;">
<p class="text-h6 q-ma-md flex flex-center" style="color: grey; font-weight: 520;">登录</p>
<q-input class="q-ma-md" filled v-model="username" label="用户名:" />
<q-input class="q-ma-md" v-model="password" filled label="密码:" :type="isPwd ? 'password' : 'text'">
<template v-slot:append>
<q-icon :name="isPwd ? 'visibility_off' : 'visibility'" class="cursor-pointer" @click="isPwd = !isPwd" />
</template>
</q-input>
<q-btn style="width:300px;display: flex;position: flex; margin-left: 130px;" class="q-ma-md" color="primary"
label="登录" @click="submit" />
</div>
</q-card>
</q-page>
</template>
<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { useQuasar } from 'quasar';
import { useRouter } from 'vue-router'
const $q = useQuasar();
const router = useRouter();
const username = ref('');
const password = ref('');
const isPwd = ref(true);
const submit = async () => {
axios.get("http://localhost:8080/select1").then(res => {
if (res) {
for (let i = 0; i < res.data.length; i++) {
if (username.value == res.data[i].name && password.value == res.data[i].password) {
router.push("/loginSuccess");
break;
} else if (i == parseInt(res.data.length) - 1) {
$q.notify({
message: '登录失败,账号或密码错误',
color: 'red',
position: 'top'
})
}
}
}
})
}
</script>
这个登录页面我想一个登录拦截 | 35b1c9820ace84217db822a17189522f | {
"intermediate": 0.3290341794490814,
"beginner": 0.4115867614746094,
"expert": 0.2593790590763092
} |
18,389 | In Hibernate, if I have an interface (not partially abstract class or concrete class) Animal and concrete classes Cat and Dog, do I need to put @Entity for Animal too or just Cat and Dog? | bb11ded57cc1869d919d9bc402c51500 | {
"intermediate": 0.6964426636695862,
"beginner": 0.17622065544128418,
"expert": 0.1273367702960968
} |
18,390 | If Animal is an interface and not a partially-abstract or concrete class (this is an important assumption) and there are concrete classes Cat and Dog that inherit from Animal, there is apparently no need to persist the Animal interface, but which Hibernate strategies are viable? Of those, which should be used? | ed26870b91ee7d041ccc0e1b47e2fdc1 | {
"intermediate": 0.39692598581314087,
"beginner": 0.1743623912334442,
"expert": 0.4287116229534149
} |
18,391 | I have a table with columns StartDate, EndDate, Customer, SKU, Month, Share. Month is used in slicer (option between). I need the DAX for calculated measure to calculate the SUM of differences between EndDate and StartDate for uinique combination of Customer and SKU. If uinique combination of Customer and SKU has several rows with the same Share, sum it only once. If StartDate is less than starting date of selected month in slicer, sum the diffirenece between EndDate and starting date of month in slicer. If EndDate is more than ending date of selected month in slicer, sum the diffirenece between ending date of month in slicer and StartDate. | 89bcef69b384aa6566b34c63451c8f5f | {
"intermediate": 0.46931973099708557,
"beginner": 0.26274368166923523,
"expert": 0.2679365575313568
} |
18,392 | For older versions of Minecraft mod making with Forge, mods could use the interface "IConnectionHandler" to know when players joined a server. This was removed in Minecraft 1.7 at the same time as when a new packet handler was introduced: the SimpleNetworkWrapper. When this change was made, what became the new way to monitor when a player joined the world? | fece5f00a65888573e26b6afa18ceabf | {
"intermediate": 0.5893265604972839,
"beginner": 0.1781713217496872,
"expert": 0.23250213265419006
} |
18,393 | how to sleep in windows batch script file | 34dbf3133c1bb499f72ee2e33d127d30 | {
"intermediate": 0.3393170237541199,
"beginner": 0.3139561414718628,
"expert": 0.34672683477401733
} |
18,394 | I know very little about Hibernate and am completely clueless about Spring and Spring Boot.
Knowing this, explain to me in a very-easy-to-understand way, what is @Autowired and how is it used?
Be as concise as possible. | 524643ff1430df7524a17b8aabf3bb00 | {
"intermediate": 0.7225978970527649,
"beginner": 0.131107360124588,
"expert": 0.1462947428226471
} |
18,395 | If I have a column with Year and column with Month. How to determine the starting day of Month and Year using DAX? | d0ac64af1fee301c3d65084918c39b25 | {
"intermediate": 0.36158487200737,
"beginner": 0.21952223777770996,
"expert": 0.4188929498195648
} |
18,396 | running arch linux any simple android emulators that can play azur lane | f28dbf769ecf864b1148aedc57f3042d | {
"intermediate": 0.36312335729599,
"beginner": 0.3648419678211212,
"expert": 0.2720346748828888
} |
18,397 | Subset of a previous ChatGPT session:
To explicitly use UUID version 4 as the identifier for the Cat and Dog classes, you can modify the code as follows:
@Entity
@Table(name = “cats”) // table name for Cat class
public class Cat implements Animal {
@Id
@GeneratedValue(generator = “uuid4”)
@GenericGenerator(name = “uuid4”, strategy = “org.hibernate.id.UUIDGenerator”)
@Column(name = “id”, columnDefinition = “BINARY(16)”)
private UUID id;
// Other Cat-specific fields and methods
}
@Entity
@Table(name = “dogs”) // table name for Dog class
public class Dog implements Animal {
@Id
@GeneratedValue(generator = “uuid4”)
@GenericGenerator(name = “uuid4”, strategy = “org.hibernate.id.UUIDGenerator”)
@Column(name = “id”, columnDefinition = “BINARY(16)”)
private UUID id;
// Other Dog-specific fields and methods
}
In this modified version, the @GeneratedValue annotation is used along with a custom generator named “uuid4”. The @GenericGenerator annotation is used to define this custom generator and specify the strategy as org.hibernate.id.UUIDGenerator.
The @Column annotation is used to define the column properties for the UUID field. In this example, it specifies the column name as “id” and the column type as “BINARY(16)” to store the UUID values.
Make sure to import the correct UUID class and GenericGenerator class from the appropriate package.
Why BINARY(16), specifically?
The column definition of “BINARY(16)” refers to a fixed-length binary data type with a length of 16 bytes. In the context of UUIDs, UUID version 4 is a 128-bit value (16 bytes) represented as a hexadecimal string.
Using the “BINARY(16)” column type ensures that the UUID is stored in its binary representation, which can optimize storage space and potentially improve performance compared to storing it as a string. Storing UUIDs as binary data can be especially beneficial when dealing with large volumes of data or when performing operations involving UUIDs, such as indexing or querying.
However, the choice of column type ultimately depends on your specific database system and requirements. Different database systems may have different data types for representing UUIDs. For example, some databases may use the “UUID” or “GUID” data type instead. You should consult the documentation or guidelines of your database system to determine the appropriate column type for storing UUIDs.
New message:
Concisely explain what the UUID situations are MariaDB, PostgreSQL and SQLite. | 42842f0ffa496291493836205e69e99e | {
"intermediate": 0.5262699127197266,
"beginner": 0.21910417079925537,
"expert": 0.2546258866786957
} |
18,398 | I have a table with columns Start Date, End Date, Customer, SKU, Month, Share in Power BI. Each row is transaction. The same rows can be for unique combination of Customer, SKU, and Share in different months. Month is used in slicer (option between). I need the DAX for calculated measure to determine the SUM of time differences between EndDate and StartDate for uinique combination of Customer, SKU, and Share. Ignore the repeated values of Shares in the selected interval of month.
If StartDate is less than starting date of selected month in slicer, the difference is calculated as EndDate minus starting date of month in slicer.
If EndDate is more than ending date of selected month in slicer, the difference is calculated as ending date of month in slicer minus StartDate.
Provide DAX expression | d3826bd21ffd702a6c836c5ba454bf5a | {
"intermediate": 0.36033928394317627,
"beginner": 0.25855058431625366,
"expert": 0.38111016154289246
} |
18,399 | Select
acc.Id as accId,
sub.Id as subId,
sub.Version as subVersion,
sub.Status as subStatus,
cp.previousAction__c as PolicyPreviousAction,
cp.Action__c as PolicyCurrentAction,
cp.balanceDaysOverdue__c as PolicyDays,
cp.SubActionRequired__c as IsUpdateSubscription,
csp.Action__c as ServiceCurrentAction,
csp.PolicyServiceType__c as ServiceType,
date(date_add('day', cast(cp.NextActionDays__c as bigint), (current_timestamp AT TIME ZONE 'Australia/Sydney'))) as newNextActionDueDate
From
Account acc
Join Subscription sub on sub.accountid = acc.id
Join default__CollectionPolicy cp on acc.CollectPolicyCode__c = cp.policyCode__c
Join default__CollectionServicePolicy csp on cp.policyCode__c = csp.Policy__c
Where
acc.inCollections__c='True' AND
acc.Status='Active' AND
acc.Balance>0 AND
(acc.nextActionDueDate__c=cast('2999-12-31' as date) OR cast(acc.nextActionDueDate__c as date) <= current_date) AND
cp.Active__c=true AND
csp.Active__c=true AND
acc.collectStage__c=cp.previousAction__c AND
(sub.Status = 'Active' OR (sub.Status = 'Cancelled' AND date_diff('day',sub.CancelledDate,current_date) <= 30)) AND
sub.collectStage__c=csp.previousAction__c
Order by cp.balanceDaysOverdue__c | 2aff12e12e967c72636f2b395a052467 | {
"intermediate": 0.3538156747817993,
"beginner": 0.348924458026886,
"expert": 0.29725974798202515
} |
18,400 | If I have columns Start Date, Ending Date, Customer, SKU. How to create table with Customer, SKU, Date, where Date are all dates between Start Date and Ending Date for each Customer and SKU. Use DAX | 722cfd3945a5b3544864568d60311be0 | {
"intermediate": 0.439133882522583,
"beginner": 0.2642008662223816,
"expert": 0.2966652512550354
} |
18,401 | Is it possible from a workstation to list the SCCM servers by using cmd or powershell? | 4d6430e04c5e5126f930241b7f18abcc | {
"intermediate": 0.5060716271400452,
"beginner": 0.20684322714805603,
"expert": 0.2870851457118988
} |
18,402 | hey chat gpt what's the diffrence between saying the variable is public and UPROPERTY in unreal engine 5 C++ | 5f6c352fcf1a81b5a810a3e4d085cc4b | {
"intermediate": 0.2900495231151581,
"beginner": 0.4326706826686859,
"expert": 0.277279794216156
} |
18,403 | Write a script in ironpython for revit 2022 mirror only mirrored windows around their axis | 71548b9205a408936045dc309e1629e5 | {
"intermediate": 0.32178977131843567,
"beginner": 0.21120552718639374,
"expert": 0.4670047163963318
} |
18,404 | while 1 do
local result, tp, data = sys.waitUntil(topic, 30000)
log.info("event", result, tp, data) 解释此代码 | 964039f424030d25f3d7c7c13eda5401 | {
"intermediate": 0.33668747544288635,
"beginner": 0.42514199018478394,
"expert": 0.2381705790758133
} |
18,405 | Как поставить фоновый цывет <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".main_Fragments.BlankHomeFragment">
<androidx.cardview.widget.CardView
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="300dp"
app:cardCornerRadius="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="@+id/blankImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop" />
</androidx.cardview.widget.CardView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/cardView" />
</androidx.constraintlayout.widget.ConstraintLayout> | 9a2359320edff1a6f666753802740fa4 | {
"intermediate": 0.46714213490486145,
"beginner": 0.26358744502067566,
"expert": 0.2692703604698181
} |
18,406 | @CrossOrigin
@PostMapping("/insert")
public String insert(@RequestBody user req_user){
req_user.setCreatetime(LocalDateTime.now());
return userMapper.insert(req_user)>0?"success":"false";
}这个后端会插入一个name的字段,为唯一约束。当name不存在的时候它会给前端返回success,但当name存在的时候为什么它不会给前端返回fasle。 | 4aa9ad9978d5ec1847c9673513b308b8 | {
"intermediate": 0.38392016291618347,
"beginner": 0.3419407606124878,
"expert": 0.2741391062736511
} |
18,407 | how to pass a pointer to interface object to dynamically loaded library in c++ | 2b930f81f3aca1132fed6e0860dbd4ed | {
"intermediate": 0.7715689539909363,
"beginner": 0.12601131200790405,
"expert": 0.10241977125406265
} |
18,408 | In this VBA event, I want it to detect if Word is open.
If a word document is open the warn with message "A word document is open and needs to be closed to use the Job Request"
When the word document is closed the VBA should then proceed
Private Sub Worksheet_Activate()
Call Module11.EnableManualMainEvents
Application.Wait (Now + TimeValue("0:00:01"))
'Call Module5.ListUniqueValuesCount
Range("G2:I2").Calculate
Range("D9:D14").Value = ""
Range("D8").Calculate
Range("D16:D20").Value = ""
Range("D15").Calculate
Range("A21:I21").Calculate
Range("A2").Select
Dim message As String
Dim response As VbMsgBoxResult
If WorksheetFunction.CountA(Range("A2:F2")) > 0 Then
message = "Do you want to delete the Request Entry?"
response = MsgBox(message, vbYesNo + vbQuestion, "Delete contents?")
If response = vbYes Then
ThisWorkbook.Sheets("Job Request").Range("A2:F2").ClearContents
ThisWorkbook.Sheets("Job Request").Range("D9:D14").ClearContents
ThisWorkbook.Sheets("Job Request").Range("D16:D20").ClearContents
ThisWorkbook.Sheets("Job Request").Range("E7:E20").ClearContents
Range("G2:I2").Calculate
Range("F3:I3").Calculate
Range("E6").Calculate
Else
Exit Sub
End If
End If
End Sub | 5ebaaef7bfa096ff7c4d1bfd2eb02674 | {
"intermediate": 0.45217835903167725,
"beginner": 0.32340723276138306,
"expert": 0.2244144082069397
} |
18,409 | Сделай так чтобы под Title появились квадратики с округлыми краями и надпись , важно чтобы эти квадратики появлялись квадратик появлялись после вызова метода , и эти квадратико должно быть рнесколь ко , кажды последующий появляется слева , есил места недостаточно то пояляется сниуз <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/bg"
tools:context=".main_Fragments.BlankHomeFragment">
<androidx.cardview.widget.CardView
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="300dp"
app:cardCornerRadius="40dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="@+id/blankImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop" />
</androidx.cardview.widget.CardView>
<TextView
android:id="@+id/Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="28dp"
android:text="Enkanto"
android:textColor="@color/white"
android:textSize="32dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/cardView" />
<TextView
android:id="@+id/Runtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="268dp"
android:text="Runtime"
android:textColor="@color/white"
android:textSize="16dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/cardView" />
<TextView
android:id="@+id/Runtime_Timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="268dp"
android:text="1h 22m"
android:textColor="@color/silver"
android:textSize="16dp"
android:textStyle="bold"
app:layout_constraintStart_toEndOf="@+id/Runtime"
app:layout_constraintTop_toBottomOf="@+id/cardView" />
<TextView
android:id="@+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="232dp"
android:layout_marginTop="268dp"
android:text="description"
android:textColor="@color/white"
android:textSize="16dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/cardView" />
</androidx.constraintlayout.widget.ConstraintLayout> | 7e3ac3ad1b8c09594def8821c479317b | {
"intermediate": 0.2343795746564865,
"beginner": 0.5787366032600403,
"expert": 0.1868838369846344
} |
18,410 | Перепиши на язык Kotlin , а так же добавь параметр в NewInstance , чтобы мы могли передать название и этого было бы достаточно , чтобы смоздать квадратик
Чтобы добавить квадратики с округлыми краями после заголовка и чтобы они появлялись последовательно слева, можно использовать горизонтальный LinearLayout внутри ConstraintLayout. После вызова метода можно программно добавлять новые квадратики в LinearLayout.
Вот измененный код с добавлением квадратиков после заголовка: | 8663beee85f1b98b0d6df9f2c9f8b149 | {
"intermediate": 0.3345617353916168,
"beginner": 0.3031047582626343,
"expert": 0.3623335063457489
} |
18,411 | Please help me write a visual novel on kirikiri. I need 3 splash screens to appear at the very beginning before the main menu of the novel. Please write an example of the implementation of the smooth appearance and disappearance of these splash screens. | f9f5fd23de3050d9f3f2a06982f18370 | {
"intermediate": 0.4118707478046417,
"beginner": 0.2713280916213989,
"expert": 0.31680116057395935
} |
18,412 | @Prop({ default: buttonText }) btnText: string
get buttonText () {
if (!this.btnText) {
return this.$t('btns.addOne')
}
return ''
}
как написать дефолтное значение | 652457f59cec8cf4776f5cb0f2250afc | {
"intermediate": 0.3791557252407074,
"beginner": 0.3163885772228241,
"expert": 0.3044556677341461
} |
18,413 | How to directly access ChatGPT in China | ef4f271e51515266b347d8ee06d111b5 | {
"intermediate": 0.46089690923690796,
"beginner": 0.17274266481399536,
"expert": 0.3663604259490967
} |
18,414 | how do i clone table's child in roblox lua | f37d9500ee11fce96f8c06b997d41903 | {
"intermediate": 0.5035492181777954,
"beginner": 0.16970019042491913,
"expert": 0.32675057649612427
} |
18,415 | When using Hibernate, do custom objects in an object marked as an entity need to also be marked as entities? | ea3b5df1534a33e3344c9e64e40e7079 | {
"intermediate": 0.6549292206764221,
"beginner": 0.12277932465076447,
"expert": 0.2222914695739746
} |
18,416 | Hello so i wrote a code to search for player's backpack if the specific gear is in player's backpack its gonna put it in the startergear but i forgot to search for player bacpack could you fix it?local gearStorage = game:GetService("ServerStorage")
local Players = game:GetService("Players")
print("debug")
local specificGearNames = {
"KnightSword",
"GrimAxe"
}
print("debug2")
local function onGearObtained(player, gear)
for i, v in ipairs(specificGearNames) do
print(i, v)
-- Accessing StarterGear from Server Script
local function onPlayerAdded(player)
-- Wait for the StarterGear to be added
local starterGear = player:WaitForChild("StarterGear")
-- Add a Tool to the StarterGear
local gears = gearStorage.SpecificGears.GrimAxe:Clone()
gears.Parent = starterGear
end
Players.PlayerAdded:Connect(onPlayerAdded)
end
end
onGearObtained() | 4be2d12c7673b4cdc950f3cffb30b873 | {
"intermediate": 0.4256621301174164,
"beginner": 0.4197278618812561,
"expert": 0.15460997819900513
} |
18,417 | disk_data = {
'C:': [{'type': 'folder',
'name': '笔记',
'children': [{'type': 'file', 'name': 'Cobalt Strike工具(免杀).md', 'size': '300KB',
'modified_time': '2021-01-01 11:00:00'},
{'type': 'folder', 'name': 'hh', 'children': [], 'modified_time': '2021-01-01 10:00:00'},
{'type': 'file', 'name': 'Java笔记.md', 'size': '300KB',
'modified_time': '2021-01-01 11:00:00'},
{'type': 'file', 'name': 'PHP笔记.md', 'size': '300KB',
'modified_time': '2021-01-01 11:00:00'},
{'type': 'file', 'name': 'Python.md', 'size': '300KB',
'modified_time': '2021-01-01 11:00:00'},
{'type': 'file', 'name': 'vulfocus复现 (自学).md', 'size': '300KB',
'modified_time': '2021-01-01 11:00:00'},
{'type': 'file', 'name': '丁香鱼路线.md', 'size': '300KB',
'modified_time': '2021-01-01 11:00:00'},
{'type': 'file', 'name': '域渗透:Kerberos 安全.md', 'size': '300KB',
'modified_time': '2021-01-01 11:00:00'},
{'type': 'file', 'name': '安全笔记.md', 'size': '300KB',
'modified_time': '2021-01-01 11:00:00'},
{'type': 'file', 'name': '攻防世界(练习).md', 'size': '300KB',
'modified_time': '2021-01-01 11:00:00'},
{'type': 'file', 'name': '数据库.md', 'size': '300KB',
'modified_time': '2021-01-01 11:00:00'},
{'type': 'file', 'name': '问答.md', 'size': '300KB',
'modified_time': '2021-01-01 11:00:00'}]},
{'type': 'folder', 'name': 'hh', 'children': [{'type': 'file', 'name': 'Cobalt Strike工具(免杀).md', 'size': '300KB',
'modified_time': '2021-01-01 11:00:00'}], 'modified_time': '2021-01-01 10:00:00'}
]
}服务端接收以上数据,遍历然后用tkinter实现文件夹的树形结构(只需要插入文件夹,不插入文件),type为folder的是文件夹,type为file是文件,children里面的是文件夹里面的文件夹或者文件 | 7303ab0689bee789e7e0801d6d1074e6 | {
"intermediate": 0.2466491460800171,
"beginner": 0.5639458298683167,
"expert": 0.18940499424934387
} |
18,418 | I used your code:
balance_info = client.balance()
usdt_balance = None
for balance in balance_info:
if balance['asset'] == 'USDT':
usdt_balance = balance['balance']
def get_quantity(symbol, usdt_balance):
try:
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
token_price = mark_price
margin = 50
quantity = round(float(usdt_balance) * margin / token_price, 2)
return quantity
except BinanceAPIException as e:
print("Error executing long order:")
return 0
print(get_quantity(symbol, usdt_balance))
while True:
lookback = 10080
interval = '1m'
df = get_klines(symbol, interval, lookback)
if df is not None:
signals = signal_generator(df)
order_quantity = get_quantity(symbol, usdt_balance)
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Price: [{mark_price}] - Signals: {signals}")
if signals == ['buy']:
try:
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=order_quantity)
print("Long order executed!")
except BinanceAPIException as e:
print(f"Error executing long order: {e}")
elif signals == ['sell']:
try:
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=order_quantity)
print("Short order executed!")
except BinanceAPIException as e:
print(f"Error executing short order: {e}")
time.sleep(1)
But I getting ERROR: The signal time is: 2023-08-23 12:41:43 Price: [187.45] - Signals: ['buy']
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 210, in <module>
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=order_quantity)
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\um_futures\account.py", line 113, in new_order
return self.sign_request("POST", url_path, params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\api.py", line 83, in sign_request
return self.send_request(http_method, url_path, payload, special)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\api.py", line 118, in send_request
self._handle_exception(response)
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\api.py", line 172, in _handle_exception
raise ClientError(status_code, err["code"], err["msg"], response.headers)
binance.error.ClientError: (400, -2019, 'Margin is insufficient.', {'Date': 'Wed, 23 Aug 2023 09:41:44 GMT', 'Content-Type': 'application/json', 'Content-Length': '46', 'Connection': 'keep-alive', 'Server': 'Tengine', 'x-mbx-used-weight-1m': '-1', 'x-mbx-order-count-10s': '1', 'x-mbx-order-count-1m': '2', 'x-response-time': '5ms', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS'})
Give me code which will execute my buy or sell orders and wich will doesn't give me ERROR | 1c73b307693a67daa6d192c109135f30 | {
"intermediate": 0.34261542558670044,
"beginner": 0.4637002646923065,
"expert": 0.19368432462215424
} |
18,419 | python如何把D:\code\RK3568\hal\TinyLib\gcov\../../build/libgcov/obj/gcov_gcc.gcda这个路径,转换成windows格式 | 152d928ade2b0ed6d7b83d3bce8c5e0a | {
"intermediate": 0.44145891070365906,
"beginner": 0.295248419046402,
"expert": 0.26329267024993896
} |
18,420 | In this VBA code, The loop does not exit when I close Word: ' Check to see if Word is open
Dim wdApp As Object
Dim wdRunning As Boolean
Dim wdLoop As Boolean
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number = 0 Then
wdRunning = True
Else
wdRunning = False
End If
If wdRunning Then
MsgBox "A WORD DOCUMENT IS OPEN" & vbCrLf & vbCrLf & _
"First Close Word then click OK here to continue ", vbCritical
wdLoop = True
Else
wdLoop = False
End If
Do While wdLoop
wdApp.WaitUntilIdle
wdRunning = wdApp.IsRunning
If Not wdRunning Then
wdLoop = False
Else
MsgBox "WORD IS STILL OPEN" & vbCrLf & vbCrLf & _
"Please close it and click OK here to continue.", vbCritical
End If
Loop
' VBA continues when Word is finaly closed | 5228bd610158bce4f292a6230cd8bc49 | {
"intermediate": 0.24670182168483734,
"beginner": 0.6340131759643555,
"expert": 0.11928495764732361
} |
18,421 | can i use replicated storage as a table? | 0a2ac8ed69d78eb83a38166d7f62196f | {
"intermediate": 0.35240063071250916,
"beginner": 0.2731388509273529,
"expert": 0.37446051836013794
} |
18,422 | how to pass pointer to interface to plugin library in c++ | 84091b5fb8a37900c6cb77fc92a413e1 | {
"intermediate": 0.777513325214386,
"beginner": 0.10596049576997757,
"expert": 0.11652620881795883
} |
18,423 | When I run this code, If Word is open I get the first message "A WORD DOCUMENT IS OPEN".
If I do not close the Word document, I get the second message "WORD IS STILL OPEN"
If I close Word after the second message, the VBA exits the loop and continues with the rest of my other code.
Which is what is expected.
However, If Word is open and I get the first message "A WORD DOCUMENT IS OPEN".
If I close Word at this point, I still get the second message "A WORD DOCUMENT IS OPEN" and the VBA exits the loop and continues with the rest of my other code.
I would expect that after the first message, if I close Word, I should not get the second message "A WORD DOCUMENT IS OPEN".
Can you help me fix this.
’ Check to see if Word is open
Dim wdApp As Object
Dim wdRunning As Boolean
Dim wdTimeout As Date
On Error Resume Next
Set wdApp = GetObject(, “Word.Application”)
If Err.Number = 0 Then
wdRunning = True
wdTimeout = Now + TimeValue(“00:00:10”) ’ Set timeout duration here (10 seconds in this example)
Else
wdRunning = False
End If
If wdRunning Then
MsgBox “A WORD DOCUMENT IS OPEN” & vbCrLf & vbCrLf & _
"First close Word then click OK here to continue ", vbCritical
Do While Now < wdTimeout
wdRunning = Not wdApp Is Nothing
If Not wdRunning Then Exit Do
wdApp.WaitUntilIdle
DoEvents ’ Allow VBA to respond to events
Loop
If wdRunning Then
MsgBox “WORD IS STILL OPEN” & vbCrLf & vbCrLf & _
“Please close it and click OK here to continue.”, vbCritical
End If
End If
’ VBA continues when Word is finally closed | 5259287065ae35ad94913eb2fa71f91d | {
"intermediate": 0.3627886176109314,
"beginner": 0.4363785684108734,
"expert": 0.20083284378051758
} |
18,424 | Working with TCP/IP components in Delphi. All the details and answers and code for the same ? | e4800662170f6ce766dcafd9b15ca5b6 | {
"intermediate": 0.4852921664714813,
"beginner": 0.3155840039253235,
"expert": 0.19912385940551758
} |
18,425 | UserWarning: `meta` is not specified, inferred from partial data. Please provide `meta` if the result is unexpected.
Before: .apply(func)
After: .apply(func, meta={'x': 'f8', 'y': 'f8'}) for dataframe result
or: .apply(func, meta=('x', 'f8')) for series result
df = df.groupby('host').apply(IsolationForest_detect, column=['A_0', 'A_1'], contamination=0.01) | 42dd9647a18ca836057fc8cc89426e11 | {
"intermediate": 0.44902104139328003,
"beginner": 0.32755565643310547,
"expert": 0.22342339158058167
} |
18,426 | I sued your code : balance_info = client.balance()
usdt_balance = None
for balance in balance_info:
if balance['asset'] == 'USDT':
usdt_balance = balance['balance']
def get_quantity(symbol, usdt_balance):
try:
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
token_price = mark_price
margin = 50
quantity = round(float(usdt_balance) * margin / token_price, 2)
return quantity
except BinanceAPIException as e:
print("Error executing long order:")
return 0
print(get_quantity(symbol, usdt_balance))
while True:
lookback = 10080
interval = '1m'
df = get_klines(symbol, interval, lookback)
if df is not None:
signals = signal_generator(df)
order_quantity = get_quantity(symbol, usdt_balance)
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Price: [{mark_price}] - Signals: {signals}")
try:
if signals == ['buy']:
try:
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=order_quantity)
print("Long order executed!")
except BinanceAPIException as e:
print("Error executing long order:")
time.sleep(1)
if signals == ['sell']:
try:
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=order_quantity)
print("Short order executed!")
except BinanceAPIException as e:
print("Error executing short order:")
time.sleep(1)
except BinanceAPIException as e:
print("Error, position already open!")
time.sleep(1)
time.sleep(1)
But I getting ERROR: -2019 MARGIN_NOT_SUFFICIEN | 5c2f409fab757b8e845424d3d0df10a0 | {
"intermediate": 0.2745192050933838,
"beginner": 0.41764673590660095,
"expert": 0.30783408880233765
} |
18,427 | I used this code : balance_info = client.balance()
usdt_balance = None
for balance in balance_info:
if balance['asset'] == 'USDT':
usdt_balance = round(float(balance['balance']), 2)
def get_quantity(symbol, usdt_balance):
try:
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
token_price = mark_price
margin = 50
quantity = round(float(usdt_balance) * margin / token_price, 2)
return quantity
except BinanceAPIException as e:
print("Error executing long order:")
return 0
print(get_quantity(symbol, usdt_balance))
while True:
lookback = 10080
interval = '1m'
df = get_klines(symbol, interval, lookback)
if df is not None:
signals = signal_generator(df)
order_quantity = get_quantity(symbol, usdt_balance)
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Price: [{mark_price}] - Signals: {signals}")
try:
if signals == ['buy']:
try:
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=order_quantity)
print("Long order executed!")
except BinanceAPIException as e:
print("Error executing long order:")
time.sleep(1)
if signals == ['sell']:
try:
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=order_quantity)
print("Short order executed!")
except BinanceAPIException as e:
print("Error executing short order:")
time.sleep(1)
except BinanceAPIException as e:
print("Error, position already open!")
time.sleep(1)
time.sleep(1)
But I getting ERROR: The signal time is: 2023-08-23 14:36:03 Price: [188.24] - Signals: ['sell']
Traceback (most recent call last):
File "c:\Users\Alan\.vscode\jew_bot\jew_bot\jew_bot.py", line 219, in <module>
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=order_quantity)
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\um_futures\account.py", line 113, in new_order
return self.sign_request("POST", url_path, params)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\api.py", line 83, in sign_request
return self.send_request(http_method, url_path, payload, special)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\api.py", line 118, in send_request
self._handle_exception(response)
File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\api.py", line 172, in _handle_exception
raise ClientError(status_code, err["code"], err["msg"], response.headers)
binance.error.ClientError: (400, -2019, 'Margin is insufficient.', {'Date': 'Wed, 23 Aug 2023 11:36:04 GMT', 'Content-Type': 'application/json', 'Content-Length': '46', 'Connection': 'keep-alive', 'Server': 'Tengine', 'x-mbx-used-weight-1m': '-1', 'x-mbx-order-count-10s': '1', 'x-mbx-order-count-1m': '1', 'x-response-time': '8ms', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS'}) | c3b4f9dca49317e2d1b9257e4abce7b0 | {
"intermediate": 0.3249623477458954,
"beginner": 0.46256983280181885,
"expert": 0.21246790885925293
} |
18,428 | I used your code: balance_info = client.balance()
usdt_balance = None
for balance in balance_info:
if balance['asset'] == 'USDT':
usdt_balance = round(float(balance['balance']), 2)
def get_quantity(symbol, usdt_balance):
try:
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
token_price = mark_price
margin = 50
quantity = round(float(usdt_balance) * margin / token_price, 2)
return quantity
except BinanceAPIException as e:
print("Error executing long order:")
return 0
print(get_quantity(symbol, usdt_balance))
while True:
try:
lookback = 10080
interval = '1m'
df = get_klines(symbol, interval, lookback)
if df is not None:
signals = signal_generator(df)
order_quantity = get_quantity(symbol, usdt_balance)
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Price: [{mark_price}] - Signals: {signals}")
if signals == ['buy']:
try:
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=order_quantity)
print("Long order executed!")
except BinanceAPIException as e:
print("Error executing long order:")
time.sleep(1)
if signals == ['sell']:
try:
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=order_quantity)
print("Short order executed!")
except BinanceAPIException as e:
print("Error executing short order:")
time.sleep(1)
except BinanceAPIException as e:
print("Error executing short order:")
time.sleep(1)
But it doesn't executing buy order, please solve this problem | cb0b34bec6d2035e6d6447bdcf57ac31 | {
"intermediate": 0.3200433850288391,
"beginner": 0.46215909719467163,
"expert": 0.21779751777648926
} |
18,429 | How does one make Hibernate use SQLite? | 5d5269120e112cc2eb7424afd4bbb4c4 | {
"intermediate": 0.6315212845802307,
"beginner": 0.15207724273204803,
"expert": 0.21640142798423767
} |
18,430 | def process(self):
"""
Process of recognition faces in video by frames.
Writes id as uuid4.
Returns:
tuple: with list of faces and list of names
"""
name = uuid.uuid4()
while True:
ret, frame = self.video.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = self.face_cascade.detectMultiScale(
gray, scaleFactor=1.1, minNeighbors=5, minSize=(100, 100))
for (x, y, w, h) in faces:
cur_face = gray[y:y + h, x:x + w]
rec = cv2.face.LBPHFaceRecognizer.create()
rec.train([cur_face], np.array(0))
f = True
for face in self.faces_list:
_, confidence = rec.predict(face)
if confidence < self.threshold:
f = False
if f:
label = name
name = uuid.uuid4()
self.faces_list.append(cur_face)
self.names_list.append(label)
self._close()
return self.faces_list, self.names_list
Разбей здесь обработку каждого кадра в 8 потоков | 4a0255a8d940a824895781a5e98a9c86 | {
"intermediate": 0.39861416816711426,
"beginner": 0.38759157061576843,
"expert": 0.21379421651363373
} |
18,431 | i want to add data to an empty column of a table from csv using load data local infile statement but the data is being added to the end of the existing data in table i want it to be added from the first row into the empty column. | 05357ddab487b8019c4908cb6d3aeb58 | {
"intermediate": 0.5019537806510925,
"beginner": 0.19963037967681885,
"expert": 0.2984159290790558
} |
18,432 | Create a python script that can take in any string with the following format, "url:login:password" and split it into separate parts | ee86df81b10b6751b206e762918939f6 | {
"intermediate": 0.3860742747783661,
"beginner": 0.2218591570854187,
"expert": 0.3920665681362152
} |
18,433 | In this VBA event below,
If a word document is open it triggers a first message "A WORD DOCUMENT IS OPEN".
When the word document is closed the VBA should then exit the loop and proceed without any other message.
If the word document is not closed after the first message the vba should remain in the loop and it should trigger a second message "WORD IS STILL OPEN".
When the word document is eventually closed the VBA should then exit the loop and proceed without any other message.
The VBA should not exit the loop until the word document is closed.
The issue I am having with this VBA event is;
When I get the first message "A WORD DOCUMENT IS OPEN" and I then close the word document, I still get the second message "WORD IS STILL OPEN" before the VBA exits the loop.
Can you fix this issue.
' Check to see if Word is open
Dim wdApp As Object
Dim wdRunning As Boolean
Dim wdTimeout As Date
Application.EnableEvents = False
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number = 0 Then
wdRunning = True
wdTimeout = Now + TimeValue("00:00:05") ' Set timeout duration here (5 seconds in this example)
Else
wdRunning = False
End If
If wdRunning Then
MsgBox "A WORD DOCUMENT IS OPEN" & vbCrLf & vbCrLf & _
"First Save/Close Word then click OK here to continue ", vbCritical
Do While Now < wdTimeout
Set wdApp = GetObject(, "Word.Application") ' Recheck if Word is still running
wdRunning = Not wdApp Is Nothing
If Not wdRunning Then Exit Do
wdApp.WaitUntilIdle
DoEvents ' Allow VBA to respond to events
Loop
If wdRunning Then
MsgBox "WORD IS STILL OPEN" & vbCrLf & vbCrLf & _
"Please Save/Close Word and click OK here to continue.", vbCritical
Set wdApp = Nothing ' Release the reference again before continuing
End If
End If
Application.EnableEvents = True
' VBA continues when Word is finally closed | 0f8f8cbdaf40668fd3c3bf04c9a62146 | {
"intermediate": 0.43645915389060974,
"beginner": 0.3665902018547058,
"expert": 0.19695061445236206
} |
18,434 | I used your code: while True:
try:
lookback = 10080
interval = '1m'
df = get_klines(symbol, interval, lookback)
if df is not None:
signals = signal_generator(df)
order_quantity = get_quantity(symbol, usdt_balance)
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} Price: [{mark_price}] - Signals: {signals}")
if signals == ['buy']:
order_quantity = get_quantity(symbol, usdt_balance)
try:
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=order_quantity)
print("Long order executed!")
except BinanceAPIException as e:
print("Error executing long order:")
if signals == ['sell']:
order_quantity = get_quantity(symbol, usdt_balance)
try:
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=order_quantity)
print("Short order executed!")
except BinanceAPIException as e:
print("Error executing short order:")
except BinanceAPIException as e:
print("Error executing order:")
time.sleep(1)
But it doesn't execute buy orders | d47489d3b02a530622041afc53b66317 | {
"intermediate": 0.3908531963825226,
"beginner": 0.36911067366600037,
"expert": 0.24003611505031586
} |
18,435 | Сделай так чтобы элементы могли выстраиватьтся в 2 строки , + расскажи что такое 1f и как это работает : @SuppressLint("ResourceAsColor")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val imageView = view.findViewById<ImageView>(R.id.blankImage)
imageView.setImageResource(imageResId)
val squaresLayout: LinearLayout = view.findViewById(R.id.squaresLayout)
createSquare(squaresLayout, "Sample Text", resources.getColor(R.color.silver), 15f)
createSquare(squaresLayout, "Another Text", resources.getColor(R.color.silver), 10f)
createSquare(squaresLayout, "Another Text", resources.getColor(R.color.silver), 10f)
createSquare(squaresLayout, "Another Text", resources.getColor(R.color.silver), 10f)
}
private fun createSquare(parentLayout: LinearLayout, text: String, textColor: Int, cornerRadius: Float) {
val square = LinearLayout(requireContext())
val layoutParams = LinearLayout.LayoutParams(400, 250)
layoutParams.weight = 1f
square.layoutParams = layoutParams
val drawable = GradientDrawable()
drawable.cornerRadius = cornerRadius
drawable.setColor(textColor) // Set color with the given textColor parameter
square.background = drawable
val textView = TextView(requireContext())
textView.text = text
textView.setTextColor(Color.WHITE) // Set text color to white
textView.gravity = Gravity.CENTER
square.gravity = Gravity.CENTER
textView.setPadding(20, 20, 20, 20) // Set padding within the text
square.addView(textView)
parentLayout.addView(square)
// Add margin to the square
val margins = layoutParams as ViewGroup.MarginLayoutParams
margins.setMargins(0, 0, 20, 0) // Set bottom margin to 20 pixels
} | 5344ace607460cdab43f439c55eebc16 | {
"intermediate": 0.531499445438385,
"beginner": 0.26590222120285034,
"expert": 0.20259836316108704
} |
18,436 | import pandas as pd
import openpyxl
import pyodbc
from datetime import datetime,timedelta
#建立连接
excel_file=r"C:\Users\LIQI\Documents\民生证券\投资管理\浪淘沙1号\Portfoliolog.xlsx"
workbook = openpyxl.load_workbook(excel_file)
#读取工作表
sheet1 = workbook['Sheet1']
log=pd.read_excel(excel_file,sheet_name='Sheet1')
# 连接到Access数据库
access_db_file = r"C:\Users\LIQI\Documents\portfolio1.accdb"
conn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
f'DBQ={access_db_file};'
)
conn = pyodbc.connect(conn_str)
#获取日期
today = datetime.now().date()
current_weekday = today.weekday()
if current_weekday == 0:
delta = timedelta(days=3)
lastday = today - delta
elif 1 <= current_weekday <= 4:
delta = timedelta(days=1)
lastday = today - delta
else current_weekday == 5 or current_weekday == 6:
exit()
lastday =lastday.strftime("%Y-%m-%d")
log_new=log[log["TRADEDATE"]==lastday]
try:
cursor = conn.cursor()
for index, row in log_new.iterrows():
ID = row[0]
TradeDate = row[1]
Ticker = row[2]
Weight = round(float(row[3]), 6)
Industry1 = row[4]
Industry2 = row[5]
rtn = round(float(row[6]), 6)
Analyst = row[7]
# 插入数据到表(不指定主键列)
query = (
"INSERT INTO Mockportfolio (ID, TRADEDATE, TICKER,WEIGHT,[Industry I], [Industry II], [RETURN], Analyst) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
)
values = (ID, TradeDate, Ticker, Weight, Industry1, Industry2,rtn,Analyst)
cursor.execute(query, values)
# 提交更改并关闭连接
conn.commit()
except Exception as e:
print("发生错误:", e)
conn.rollback()
finally:
conn.close()
print("数据成功传输到Access数据库的Mockportfolio表中。")
File "C:\Users\LIQI\AppData\Local\Temp/ipykernel_11868/106618414.py", line 31
else current_weekday == 5 or current_weekday == 6:
^
SyntaxError: invalid syntax
怎么改呢? | 0eb9a407ad30004d714e97191ec9d575 | {
"intermediate": 0.34421294927597046,
"beginner": 0.48226678371429443,
"expert": 0.1735202521085739
} |
18,437 | Can you write an arduino script which simulates fire with WS2811, 22 LED, I do not want the color white in it | 9c9f155bf804c8fd7ddae883a65cf679 | {
"intermediate": 0.4593222141265869,
"beginner": 0.22689764201641083,
"expert": 0.31378012895584106
} |
18,438 | pynvml.nvmlSystemGetDriverVersion().decode()
AttributeError: 'str' object has no attribute 'decode' | 8117dc277b55e05b6958519066c49ea0 | {
"intermediate": 0.5342792868614197,
"beginner": 0.2360083907842636,
"expert": 0.2297123223543167
} |
18,439 | I have an angular project where I run some react code. In this react code, I now want to run some angular code. How can I do this ? | 3c4437d27dfd50a97350afb90cb439ea | {
"intermediate": 0.6008036136627197,
"beginner": 0.22933945059776306,
"expert": 0.1698569655418396
} |
18,440 | hello | 988e11197a9dfc1a8f05dd7fb8cae720 | {
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
} |
18,441 | Invalid object name 'job_history'. | 5185f98759baff77d45a7d2af41288f3 | {
"intermediate": 0.40211963653564453,
"beginner": 0.3749212920665741,
"expert": 0.2229590117931366
} |
18,442 | Переработай дизайн с нуля. Сделай так, чтобы outcomes without point располагались следующим образом: команда 1 ничья команда 2. Индексы outcomes: команда 1 - index 0, ничья index 2, команда 2 индекс 1. Названия команд должны быть расположены горизонтально друг к другу, как на сайте букмекера fon.bet. Сделай дизайн похожим на fon.bet
вот код:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<title>Event Details</title>
</head>
<body>
<div class="container mt-5">
<hr>
<div class="row">
<h3 class="col-md-12">Bookmakers:</h3>
<% event.bookmakers.forEach(bookmaker => { %>
<div class="card col-md-6 my-3 p-4 bg-light border-primary">
<h4><%= bookmaker.title %></h4>
<p>Last Update: <%= bookmaker.last_update %></p>
<% bookmaker.markets.forEach(market => { %>
<div class="my-3">
<h5><%= market.key %>:</h5>
<% market.outcomes.forEach(outcome => { %>
<!-- Check if outcome has a point -->
<% if (outcome.point) { %>
<!-- Outcome card with point -->
<div class='card p-3 mb-2'>
<div class="row">
<div class="col-md-6">
<%= outcome.name %>
</div>
<div class="col-md-6">
<%= outcome.price %>
</div>
</div>
<div class="row">
<div class="col-md-12">
<%= outcome.point %>
</div>
</div>
</div>
<% } else { %>
<!-- Outcome card without point -->
<div class='card p-3 mb-2'>
<div class="row">
<div class="col-md-6">
<%= outcome.name %>
</div>
<div class="col-md-6">
<%= outcome.price %>
</div>
</div>
</div>
<% } %>
<% }) %>
</div>
<% }) %>
</diV>
<% }) %>
</dIV>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.4/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html> | f500a672689e45616e0f14655b2fbb43 | {
"intermediate": 0.34549573063850403,
"beginner": 0.48507875204086304,
"expert": 0.16942550241947174
} |
18,443 | var allSections = solrSectionResults.SelectMany(x => x.ParentHeadingIDs != null).ToList(); chequear que ParentHeadingIDs sea distinto de null | 4614d071087a1f99751f6a71a88fb9c2 | {
"intermediate": 0.42714065313339233,
"beginner": 0.21972471475601196,
"expert": 0.3531346619129181
} |
18,444 | I used this code: client = futures.HTTP(api_key=API_KEY_BINANCE, api_secret=API_SECRET_BINANCE)
symbol = 'BCHUSDT'
depth_data = client.get_depth(symbol=symbol)
print(depth_data)
start_row = 5 # Starting row index (inclusive)
end_row = 61 # Ending row index (exclusive)
print("Depth:")
balance_info = client.asset()
usdt_balance = None
for balance in balance_info:
if balance['asset'] == 'USDT':
usdt_balance = round(float(balance['balance']), 2)
if usdt_balance is not None:
print("USDT Balance:", usdt_balance)
else:
print("USDT balance not found.")
url = 'https://api.binance.com/api/v3/account' # Replace with the appropriate Binance API endpoint
headers = {
'X-MBX-APIKEY': API_KEY_BINANCE
}
timestamp = int(dt.datetime.now().timestamp() * 1000) # Generate the current timestamp in milliseconds
# Create signature
params = urlencode({'timestamp': timestamp})
signature = hmac.new(API_SECRET_BINANCE.encode('utf-8'), params.encode('utf-8'), hashlib.sha256).hexdigest()
# Add signature and API key to request parameters
params += f'&signature={signature}'
# Make API request to check connection
response = requests.get(url, headers=headers, params=params)
# Check API response
if response.status_code == 200:
print('Connected to the Binance API.')
else:
print('Failed to connect to the Binance API.')
print('Response:', response.text)
def get_klines(symbol, interval, lookback):
API_KEY_BINANCE = 'your-api-key' # Replace with your Binance API key
symbol = symbol.replace("/", "") # remove slash from symbol
url = "https://api.binance.com/api/v3/klines"
end_time = int(dt.datetime.now().timestamp() * 1000) # end time is now
start_time = end_time - (lookback * 60 * 1000) # start time is lookback minutes ago
params = {
'symbol': symbol,
'interval': interval,
'startTime': start_time,
'endTime': end_time
}
headers = {
'X-MBX-APIKEY': API_KEY_BINANCE,
}
response = requests.get(url, params=params, headers=headers)
response.raise_for_status()
data = response.json()
if not data: # if data is empty, return None
print('No data found for the given timeframe and symbol')
return None
ohlcv = []
for d in data:
timestamp = dt.datetime.fromtimestamp(d[0] / 1000).strftime('%Y-%m-%d %H:%M:%S')
ohlcv.append({
'Open time': timestamp,
'Open': float(d[1]),
'High': float(d[2]),
'Low': float(d[3]),
'Close': float(d[4]),
'Volume': float(d[5])
})
df = pd.DataFrame(ohlcv)
df.set_index('Open time', inplace=True)
return df
interval = '1m'
lookback = 10080
df = get_klines(symbol, interval, lookback)
# Import the necessary libraries
def signal_generator(df):
if df is None or len(df) < 2:
return ''
signal = []
# Retrieve depth data
threshold = 0.35
depth_data = client.get_depth(symbol=symbol)
bid_depth = depth_data['bids']
ask_depth = depth_data['asks']
buy_price = float(bid_depth[0][0]) if bid_depth else 0.0
sell_price = float(ask_depth[0][0]) if ask_depth else 0.0
mark_price_data = client.ticker(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0
sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0
if (sell_qty > (1 + threshold)) > buy_qty:
signal.append('sell')
elif (buy_qty > (1 + threshold)) > sell_qty:
signal.append('buy')
else:
signal.append('')
return signal
end_time = int(time.time() * 1000)
start_time = end_time - lookback * 60 * 1000
secret_key = API_KEY_BINANCE
access_key = API_SECRET_BINANCE
import binance
import decimal
balance_info = client.asset('USDT')
usdt_balance = None
for balance in balance_info:
if balance['asset'] == 'USDT':
usdt_balance = round(float(balance['balance']), 2)
def get_quantity(symbol, usdt_balance):
try:
mark_price_data = client.ticker(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
token_price = mark_price
margin = 50
quantity = round(float(usdt_balance) * margin / token_price, 2)
return quantity
except BinanceAPIException as e:
print("Error executing long order:")
return 0
print(get_quantity(symbol, usdt_balance))
while True:
lookback = 10080
df = get_klines(symbol, interval, lookback)
if df is not None:
signals = signal_generator(df)
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Signals: {signals}")
mark_price = client.ticker(symbol=symbol)
if signals == ['buy']:
try:
quantity = get_quantity(symbol, usdt_balance)
client.order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity)
print("Long order executed!")
except binance.error.ClientError as e:
print(f"Error executing long order: {e}")
time.sleep(1)
if signals == ['sell']:
try:
quantity = get_quantity(symbol, usdt_balance)
client.order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity)
print("Short order executed!")
except binance.error.ClientError as e:
print(f"Error executing short order: {e}")
time.sleep(1)
time.sleep(1)
Can you set them for `pymexc` please | 0434a72599452178a913e11629be3459 | {
"intermediate": 0.25635501742362976,
"beginner": 0.5505427122116089,
"expert": 0.19310224056243896
} |
18,445 | write a matlab code for adding two numbers | dbf6622fd171b3ad3329b72bb8c726e3 | {
"intermediate": 0.30794304609298706,
"beginner": 0.18927812576293945,
"expert": 0.5027787685394287
} |
18,446 | using System;
using System.Data;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace HorseRacing
{
public partial class HorsesForm : Form
{
private MySqlConnection conn;
private Form1 parentForm;
private int selectedOwnerID;
public HorsesForm(Form1 parentForm)
{
InitializeComponent();
this.parentForm = parentForm;
string connString = parentForm.GetDBConnectionString();
conn = new MySqlConnection(connString);
//this.selectedOwnerID = selectedOwnerID;
}
//private void HorseForm_Load(object sender, EventArgs e)
//{
// // Perform any additional initialization or data binding if needed
//}
private void BtnSave_Click(object sender, EventArgs e)
{
// Retrieve the selected OwnerID from the ComboBox
int ownerID = Convert.ToInt32(cmbOwners.SelectedValue);
string horseName = txtHorseName.Text;
int age = Convert.ToInt32(txtAge.Text);
string gender = cmbGender.SelectedItem.ToString();
string breed = txtBreed.Text;
string query = "INSERT INTO Horses (HorseName, Age, Gender, Breed, OwnerID) " +
"VALUES('" + horseName + "', " + age + ", '" +gender + "', '" + breed + "', '" + ownerID + "')";
try
{
MySqlCommand cmd = new MySqlCommand(query, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Horse data saved successfully.");
this.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error saving horse data: " + ex.Message);
}
}
//private void cmbOwners_SelectedIndexChanged(object sender, EventArgs e)
//{
//
//}
private void HorseForm_Load(object sender, EventArgs e)
{
// Populate ComboBox with Owner names
string query = "SELECT OwnerID, OwnerName FROM Owners";
MySqlCommand cmd = new MySqlCommand(query, conn);
MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);
cmbOwners.DisplayMember = "OwnerName";
cmbOwners.ValueMember = "OwnerID";
cmbOwners.DataSource = dt;
// Select the owner based on selectedOwnerID
cmbOwners.SelectedValue = cmbOwners;
}
}
}
How to get all Owners and their OwnerID in cmbOwners | bdb1bd50baca455dcd531489be6a6bc4 | {
"intermediate": 0.3765214681625366,
"beginner": 0.5138130784034729,
"expert": 0.1096653938293457
} |
18,447 | write decompressor in this compress code:
void compressByPacking0(uint8_t *out, uint8_t *in, uint32_t length) {
static uint8_t lookup[4096];
static const uint8_t lookup5[8] = { 0, 1, 2, 0, 3, 0, 0, 0 };
if (lookup[0] == 0) {
/* initialize lookup table */
for (int i = 0; i < 4096; i++) {
lookup[i] = (lookup5[(i >> 0) & 7] << 0) +
(lookup5[(i >> 3) & 7] << 2) +
(lookup5[(i >> 6) & 7] << 4) +
(lookup5[(i >> 9) & 7] << 6);
}
}
for (; length >= 4; length -= 4, in += 4, out++) {
*out = lookup[(in[0] << 9) + (in[1] << 6) + (in[2] << 3) + (in[3] << 0)];
}
uint8_t last = 0;
switch (length) {
case 3:
last |= lookup5[in[2]] << 4;
/* fall through */
case 2:
last |= lookup5[in[1]] << 2;
/* fall through */
case 1:
last |= lookup5[in[0]] << 0;
*out = last;
break;
}
} | 823f833aed4a4108ddd7755117e6d1c8 | {
"intermediate": 0.3810840845108032,
"beginner": 0.2915205657482147,
"expert": 0.32739531993865967
} |
18,448 | write a python script that opens the steam application | 2e997a505d9bf0a18be503ae1460c323 | {
"intermediate": 0.36656537652015686,
"beginner": 0.20938752591609955,
"expert": 0.4240470826625824
} |
18,449 | Compressing and decompressing a 'char' array using bit packing in C++ | 6693189d9b186b309d82706d0c60d80f | {
"intermediate": 0.3457218408584595,
"beginner": 0.20173421502113342,
"expert": 0.4525439441204071
} |
18,450 | Compressing and decompressing a ‘char’ array using bit packing in C++ | d148f9ed4f7f3abc24d72425127672a4 | {
"intermediate": 0.34799259901046753,
"beginner": 0.1990160495042801,
"expert": 0.4529912769794464
} |
18,451 | что делает данный код? N = 3 # количество углов в многоугольнике
x <- runif(N, -5, 10)
y <- runif(N, -5, 10)
x <-round(x)
y <-round(y)
table <- data.frame(x,y)
table <- table[order(x),]
k <- 0
x <- table$x
y <- table$y
for(i in 1:N)
{
k[i] <- (y[i] - y[1]) / (x[i] - x[1])
}
k[1] <- -Inf
table <- cbind(table,k)
table <- table[order(table$k),]
x <- table$x
y <- table$y
S = 0
first <-c(x[N], y[N])
second <-c(x[1], y[1])
S <- det(as.matrix(rbind(first,second)))
for(i in 2:N)
{
first <-c(x[i-1],y[i-1])
second <-c(x[i] ,y[i] )
A <- as.matrix(rbind(first,second))
print(A)
print(det(A))
S = S+ det(A)
}
#S/2
#Square[j] <- S/2
min_x <- min(table$x)-1
max_x <- max(table$x)+1
min_y <- min(table$y)-1
max_y <- max(table$y)+1
#minimum <- min(min(table$x),min(table$y))
#maximum <- max(max(table$x),max(table$y))
#jpeg(paste(as.character(j),"png",sep = "."), width = 1000, height = 1000*(max_y-min_y+2)/(max_x-min_x+2))
#plot(x = -3:10, y = -3:10, col = "white",xaxt='n', yaxt='n',ann=FALSE) # Draw empty plot
plot(x , y , xlim=c(min_x,max_x), ylim=c(min_y,max_y), col = "white",xaxt='n', yaxt='n',ann=FALSE) # Draw empty plot
polygon(x = x, # X-Coordinates of polygon
y = y, # Y-Coordinates of polygon
col = "#1b98e0") # Color of polygon
#abline(h = -3:10, v = -3:10, col = "black", lty = 1)
abline(h = (min_y-3):(max_y+7), v = (min_x-3):(max_x+7), col = "black", lty = 1)
text(max_x-1,min_y+1,"kuzovkin.info",cex=3) | ed54d033a5384e5982f20bcf1efb011e | {
"intermediate": 0.31841474771499634,
"beginner": 0.46643078327178955,
"expert": 0.21515443921089172
} |
18,452 | maximum likelihood calculator using python for a time_series_data | 03230c18866f97c467aaa311c4516b57 | {
"intermediate": 0.34005075693130493,
"beginner": 0.23671972751617432,
"expert": 0.4232296049594879
} |
18,453 | for esp32 microcontroller, read i2c data from #define PIN_SDA 21 //BLUE
#define PIN_SCL 22 //Yellow using #include <ESP32SPISlave.h> and send this data on i2c using #include <Adafruit_SSD1306.h> | 7f226d2c95b6f0898f85f1731a73db85 | {
"intermediate": 0.6478983163833618,
"beginner": 0.17242512106895447,
"expert": 0.17967651784420013
} |
18,454 | # Set the desired embedding dimension and time delay
EmbDim = 3
Tau = 1
# Perform the delay-embed reconstruction
reconstructed_data = pyEDM.EmbedDimension(dataFrame=tseries, maxE=EmbDim, tau=Tau, columns=['time', 'data'])
# Apply the Grassberger-Procaccia algorithm to estimate the correlation dimension
corr_dim = pyEDM.CorrelationDimension(reconstructed_data)
# Print the correlation dimension
print("Correlation Dimension:", corr_dim)
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
Cell In[75], line 6
3 Tau = 1
5 # Perform the delay-embed reconstruction
----> 6 reconstructed_data = pyEDM.EmbedDimension(dataFrame=tseries, maxE=EmbDim, tau=Tau, columns=['time', 'data'])
8 # Apply the Grassberger-Procaccia algorithm to estimate the correlation dimension
9 corr_dim = pyEDM.CorrelationDimension(reconstructed_data)
File ~\anaconda3\Lib\site-packages\pyEDM\CoreEDM.py:488, in EmbedDimension(pathIn, dataFile, dataFrame, pathOut, predictFile, lib, pred, maxE, Tp, tau, exclusionRadius, columns, target, embedded, verbose, validLib, numThreads, showPlot)
485 columns = ' '.join( map( str, columns ) )
487 # D is a Python dict from pybind11 < cppEDM CCM
--> 488 D = pyBindEDM.EmbedDimension( pathIn,
489 dataFile,
490 DF,
491 pathOut,
492 predictFile,
493 lib,
494 pred,
495 maxE,
496 Tp,
497 tau,
498 exclusionRadius,
499 columns,
500 target,
501 embedded,
502 verbose,
503 validLib,
504 numThreads )
506 df = DataFrame( D ) # Convert to pandas DataFrame
508 if showPlot :
RuntimeError: Parameters::Validate(): library indices not found. | dfd7ded5b7f02703dd40ef216085f552 | {
"intermediate": 0.42535004019737244,
"beginner": 0.29982519149780273,
"expert": 0.2748247981071472
} |
18,456 | сам код не меняй , но мне нужно прокуручивание вниз , с помощью scrollView или аналога : <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/bg"
tools:context=".main_Fragments.BlankHomeFragment">
<androidx.cardview.widget.CardView
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="300dp"
app:cardCornerRadius="40dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="@+id/blankImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="centerCrop" />
</androidx.cardview.widget.CardView>
<TextView
android:id="@+id/Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="28dp"
android:text="Enkanto"
android:textColor="@color/white"
android:textSize="32dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/cardView" />
<LinearLayout
android:id="@+id/squaresLayout"
android:layout_width="394dp"
android:layout_height="47dp"
android:layout_marginTop="24dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.515"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/Title" />
<TextView
android:id="@+id/Runtime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="172dp"
android:text="Runtime"
android:textColor="@color/white"
android:textSize="16dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/cardView" />
<TextView
android:id="@+id/Runtime_Timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="4dp"
android:layout_marginTop="172dp"
android:text="1h 22m"
android:textColor="@color/silver"
android:textSize="16dp"
android:textStyle="bold"
app:layout_constraintStart_toEndOf="@+id/Runtime"
app:layout_constraintTop_toBottomOf="@+id/cardView" />
<TextView
android:id="@+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="216dp"
android:text="description"
android:textColor="@color/silver_text"
android:textSize="13dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/cardView" />
<VideoView
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="@+id/description"
tools:layout_editor_absoluteX="0dp" />
</androidx.constraintlayout.widget.ConstraintLayout> | b0434babcc17da33acd47730f0d72f1b | {
"intermediate": 0.2386045753955841,
"beginner": 0.5513719320297241,
"expert": 0.2100234478712082
} |
18,457 | Сделай прокрутку сверху вниз : <?xml version=“1.0” encoding=“utf-8”?>
<ScrollView xmlns:android=“http://schemas.android.com/apk/res/android”
xmlns:tools=“http://schemas.android.com/tools”
android:layout_width=“match_parent”
android:layout_height=“match_parent”>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:background=“@color/bg”
tools:context=“.main_Fragments.BlankHomeFragment”>
<androidx.cardview.widget.CardView
android:id=“@+id/cardView”
android:layout_width=“match_parent”
android:layout_height=“300dp”
app:cardCornerRadius=“40dp”
app:layout_constraintEnd_toEndOf=“parent”
app:layout_constraintStart_toStartOf=“parent”
app:layout_constraintTop_toTopOf=“parent”>
<ImageView
android:id=“@+id/blankImage”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:adjustViewBounds=“true”
android:scaleType=“centerCrop” />
</androidx.cardview.widget.CardView>
<TextView
android:id=“@+id/Title”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginStart=“16dp”
android:layout_marginTop=“28dp”
android:text=“Enkanto”
android:textColor=“@color/white”
android:textSize=“32dp”
android:textStyle=“bold”
app:layout_constraintStart_toStartOf=“parent”
app:layout_constraintTop_toBottomOf=“@+id/cardView” />
<LinearLayout
android:id=“@+id/squaresLayout”
android:layout_width=“394dp”
android:layout_height=“47dp”
android:layout_marginTop=“24dp”
android:orientation=“horizontal”
app:layout_constraintEnd_toEndOf=“parent”
app:layout_constraintHorizontal_bias=“0.515”
app:layout_constraintStart_toStartOf=“parent”
app:layout_constraintTop_toBottomOf=“@+id/Title” />
<TextView
android:id=“@+id/Runtime”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginStart=“16dp”
android:layout_marginTop=“172dp”
android:text=“Runtime”
android:textColor=“@color/white”
android:textSize=“16dp”
android:textStyle=“bold”
app:layout_constraintStart_toStartOf=“parent”
app:layout_constraintTop_toBottomOf=“@+id/cardView” />
<TextView
android:id=“@+id/Runtime_Timer”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginStart=“4dp”
android:layout_marginTop=“172dp”
android:text=“1h 22m”
android:textColor=“@color/silver”
android:textSize=“16dp”
android:textStyle=“bold”
app:layout_constraintStart_toEndOf=“@+id/Runtime”
app:layout_constraintTop_toBottomOf=“@+id/cardView” />
<TextView
android:id=“@+id/description”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:layout_marginStart=“16dp”
android:layout_marginTop=“216dp”
android:text=“description”
android:textColor=“@color/silver_text”
android:textSize=“13dp”
android:textStyle=“bold”
app:layout_constraintStart_toStartOf=“parent”
app:layout_constraintTop_toBottomOf=“@+id/cardView” />
<VideoView
android:layout_width=“match_parent”
android:layout_height=“200dp”
android:layout_marginTop=“8dp”
app:layout_constraintTop_toBottomOf=“@+id/description”
tools:layout_editor_absoluteX=“0dp” />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView> | 5518c388106165444ccac67dde5b8b58 | {
"intermediate": 0.3052326440811157,
"beginner": 0.491346538066864,
"expert": 0.20342081785202026
} |
18,458 | pi 3b how to flip screen on boot | e928ffa72ca309f84fef7a3722823692 | {
"intermediate": 0.35761168599128723,
"beginner": 0.2946107089519501,
"expert": 0.3477776050567627
} |
18,459 | Please provide an example for Minecraft Forge for 1.7 of registering PlayerLoggedInEvent to the correct event bus. | f8c40f25c1b90ae292fb2c14c10105c3 | {
"intermediate": 0.5970233082771301,
"beginner": 0.20583489537239075,
"expert": 0.19714178144931793
} |
18,460 | I used this code: client = futures.HTTP(api_key=API_KEY_BINANCE, api_secret=API_SECRET_BINANCE)
symbol = "BCH_USDT"
depth_data = client.get_depth(symbol=symbol)
print(depth_data)
bids = depth_data['bids']
asks = depth_data['asks']
start_row = 5 # Starting row index (inclusive)
end_row = 61 # Ending row index (exclusive)
print("Depth:")
for i in range(start_row, end_row):
bid = bids[i]
ask = asks[i]
print("Bid:", bid, "Ask:", ask)
But it doesn't return me depth with rows and columns | 9d24ec972873072ada1b8c2507ae3a71 | {
"intermediate": 0.4076616168022156,
"beginner": 0.35155418515205383,
"expert": 0.24078422784805298
} |
18,461 | 1. Project setup:
a. Create a new Spring Boot project using your preferred IDE.
b. Add the necessary dependencies for Spring Boot, Hibernate, Couchbase, Elasticsearch, Kibana, Redis, and unit testing frameworks.
2. Design the database structure and product entity:
a. Determine the attributes necessary for the product catalog, such as name, description, price, availability, etc.
b. Use Hibernate to map the product entity to the product table in the Couchbase database.
3. Implement CRUD operations for product management:
a. Design API endpoints for creating, reading, updating, and deleting products.
b. Implement the necessary logic to perform CRUD operations on product records in the Couchbase database using Hibernate. I am at 3. Implement CRUD operations for product management: please elaborate it | 0fa4a87d6ada432868d0a969cc8437e5 | {
"intermediate": 0.7884276509284973,
"beginner": 0.11900285631418228,
"expert": 0.09256943315267563
} |
18,462 | How can I use python packages to calculate field of study similarity score | 13dd902c3643397e39510d37d82e313a | {
"intermediate": 0.5138992071151733,
"beginner": 0.10405084490776062,
"expert": 0.3820500075817108
} |
18,463 | I sued this code: client = futures.HTTP(api_key=API_KEY_BINANCE, api_secret=API_SECRET_BINANCE)
symbol = "BCH_USDT"
depth_data = client.get_depth(symbol=symbol)
print(depth_data)
bids = depth_data['bids']
asks = depth_data['asks']
start_row = 5 # Starting row index (inclusive)
end_row = 61 # Ending row index (exclusive)
print("Depth:")
for i in range(start_row, end_row):
bid = bids[i]
ask = asks[i]
print("Bid:", bid, "Ask:", ask)
But it doesn't print me bids and asks as rows and columns | d2cbf3e1d563084871de83a771717ac2 | {
"intermediate": 0.3861008882522583,
"beginner": 0.42111510038375854,
"expert": 0.19278395175933838
} |
18,464 | in a c++ project, how to remove a line with an specific string from a file? | c36e3f079c85dc1eef7342577b803db0 | {
"intermediate": 0.44152823090553284,
"beginner": 0.28013932704925537,
"expert": 0.27833250164985657
} |
18,465 | How I can get balance through pymexc ? | 46da7ae5762613c1a0bf5e3cb6e8db46 | {
"intermediate": 0.360578328371048,
"beginner": 0.11809238791465759,
"expert": 0.5213293433189392
} |
18,466 | When I click on a cell, I get a pop up message which I have to click OK to close. How can I use VBA to remember the cell I clicked on before the message so that I can use it as a Target value | 9210e58c9d7880ab2569ad5683423fce | {
"intermediate": 0.5030449628829956,
"beginner": 0.17058448493480682,
"expert": 0.32637056708335876
} |
18,467 | write html/css code for a wild pig themed website | dbfca1f4edfef4e49f4753274e65e757 | {
"intermediate": 0.3731186091899872,
"beginner": 0.3052048981189728,
"expert": 0.3216764032840729
} |
18,468 | # Load the required library
library(tseriesChaos)
# Read the CSV file
x <- read.csv("C:/Users/whoami/Machine Learning/Training/eu-west-1.csv")
# Convert date_hour column to POSIXct format
x$date_hour <- as.POSIXct(x$date_hour, format = "%Y-%m-%d %H:%M:%S")
# Calculate the neighbourhood diameter
eps <- sd(x$price) / 10
# Create a new dataframe with only the price column
price_data <- x$price
# Take the first 2000 elements of the price data
price_data_subset <- price_data[1:2000]
# Define parameters
m_max <- 10 # Maximum embedding dimension to explore
d <- 18 # Tentative time delay
tw <- 100 # Theiler window
rt <- 10 # Escape factor
# Calculate false nearest neighbors for the price subset
fn <- false.nearest(price_data_subset, m_max, d, tw, rt, eps)
# Print the result
print(fn)
# Plot the result
plot(fn)
library(scatterplot3d)
# Calculate the AMI
# Calculate average mutual information for time delay selection
lm <- 120 # Largest lag
ami_result <- mutual(price_data_subset, lag.max = lm)
# Print the AMI result
print(ami_result)
# Find the first minimum of the AMI
estimated_d <- which.min(ami_result)
# Print the estimated time delay
cat("Estimated Time Delay (d):", estimated_d, "\n")
# Choose embedding dimension (m) and time delay (d)
m <- 3 # Embedding dimension
d <- estimated_d # Choose the estimated time delay
# Embed the 'observed' series
xyz <- embedd(price_data_subset, m, d)
# Create a scatterplot in 3D
windows()
scatterplot3d(xyz, type = "l")
# Load the required libraries
library(tseriesChaos)
library(gplots)
library(scatterplot3d)
# Set parameters for the Lorenz system
a <- 10
b <- 28
c <- -8/3
x0 <- 1
y0 <- 1
z0 <- 1
t_init <- 0
t_fin <- 1000
step.int <- 0.01
# Simulate the Lorenz system
lorenz.syst <- function(t, x, parms) {
dx <- a * (x[2] - x[1])
dy <- x[1] * (c - x[3]) - x[2]
dz <- x[1] * x[2] - b * x[3]
return(list(c(dx, dy, dz)))
}
times <- seq(t_init, t_fin, by = step.int)
xyz <- sim.cont(lorenz.syst, start = t_init, end = t_fin, dt = step.int,
start.x = c(x0, y0, z0), parms = c(a, b, c)) # Adjust these values as needed
# Create a scatterplot in 3D
scatterplot3d(xyz[, 1], xyz[, 2], xyz[, 3], type = "l", xlim = c(-30, 30),
cex.lab = 1.4, cex.axis = 1.2)
# Assuming you have processed price_data and have a two-dimensional matrix price_matrix
# Calculate the two-dimensional histogram for price_data
h2d <- hist2d(price_matrix, show = FALSE, same.scale = FALSE, nbins = 100)
h2d$counts <- h2d$counts / max(h2d$counts) # normalization
# Plot the invariant density
par(mai = c(1.02, 1., 0.82, 0.42) + 0.1, cex.axis = 1.2, cex.lab = 1.6)
filled.contour(h2d$x, h2d$y, h2d$counts, col = gray.colors(10, start = 0, end = 1), nlevels = 10,
xlab = "Price", ylab = "Density", main = "", xlim = c(min(price_data), max(price_data)),
ylim = c(0, 1), las = 0, key.axes = axis(4, las = 1))
+ }
> times <- seq(t_init, t_fin, by = step.int)
> xyz <- sim.cont(lorenz.syst, start = t_init, end = t_fin, dt = step.int,
+ start.x = c(x0, y0, z0), parms = c(a, b, c)) # Adjust these values as needed
DLSODA- At T (=R1), too much accuracy requested
for precision of machine.. See TOLSF (=R2)
In above message, R1 = 126.892, R2 = nan
Warning messages:
1: In lsoda(start.x, times, func = syst, parms = parms) :
Excessive precision requested. scale up `rtol' and `atol' e.g by the factor 10
2: In lsoda(start.x, times, func = syst, parms = parms) :
Returning early. Results are accurate, as far as they go
> # Create a scatterplot in 3D
> scatterplot3d(xyz[, 1], xyz[, 2], xyz[, 3], type = "l", xlim = c(-30, 30),
+ cex.lab = 1.4, cex.axis = 1.2)
Error in `[.default`(xyz, , 1) : incorrect number of dimensions | 9f520f4cf1d017e48c19dee62b26c6d2 | {
"intermediate": 0.328508198261261,
"beginner": 0.39472103118896484,
"expert": 0.27677077054977417
} |
18,469 | what for is the static word used for in C | 6cf30b13b5f2377c1f5d7b7b7603ba3a | {
"intermediate": 0.31443676352500916,
"beginner": 0.43765801191329956,
"expert": 0.24790526926517487
} |
18,470 | run | 23267b6beaf73b2742b4737c4e7361d6 | {
"intermediate": 0.2813085913658142,
"beginner": 0.3596680164337158,
"expert": 0.35902339220046997
} |
18,471 | how CString allocate / release memory? | 62ba10134cec29bc4b5dce61bd3a3a9e | {
"intermediate": 0.38223886489868164,
"beginner": 0.1860409677028656,
"expert": 0.43172019720077515
} |
18,472 | create table name(name varchar(30))
insert into name values ('Hamidulla')
insert into name values ('Ibragimovich')
select * from name
cut name from first 'i' till end | e18a9fd2bea169e3c1acd3d14dfa1b63 | {
"intermediate": 0.40142303705215454,
"beginner": 0.21959993243217468,
"expert": 0.3789770007133484
} |
18,473 | detect memory leak of a function in MFC application | 5466039977e9e3c7e661141332bf95d5 | {
"intermediate": 0.3535977005958557,
"beginner": 0.14146018028259277,
"expert": 0.5049420595169067
} |
18,474 | import uuid
import cv2
import numpy as np
from libs.face_recognition import ALG
class FaceRecognition:
"""Service for using face recognition."""
def __init__(self, video_path, threshold=80):
"""
Sets model's parameters.
Args:
video_path (str): path to video
threshold (int): model's threshold
"""
self.face_cascade_path = cv2.data.haarcascades + ALG
self.face_cascade = cv2.CascadeClassifier(self.face_cascade_path)
self.faces_list = []
self.names_list = []
self.threshold = 80
self.video = cv2.VideoCapture(video_path)
def process(self):
"""
Process of recognition faces in video by frames.
Writes id as uuid4.
Returns:
tuple: with list of faces and list of names
"""
name = uuid.uuid4()
while True:
ret, frame = self.video.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = self.face_cascade.detectMultiScale(
gray, scaleFactor=1.1, minNeighbors=5, minSize=(100, 100))
for (x, y, w, h) in faces:
cur_face = gray[y:y + h, x:x + w]
rec = cv2.face.LBPHFaceRecognizer.create()
rec.train([cur_face], np.array(0))
f = True
for face in self.faces_list:
_, confidence = rec.predict(face)
if confidence < self.threshold:
f = False
if f:
label = name
name = uuid.uuid4()
self.faces_list.append(cur_face)
self.names_list.append(label)
self._close()
return self.faces_list, self.names_list
def _close(self):
"""
Closes video and destroys all windows.
Returns:
None:
"""
self.video.release()
cv2.destroyAllWindows()
Разбей обработку каждого кадра по 8 потокам | ea65e45571841bfb39b6eea408de0ddd | {
"intermediate": 0.44757723808288574,
"beginner": 0.4124830961227417,
"expert": 0.13993971049785614
} |
18,475 | If I have Spring, Spring Boot and Hibernate, and I want to use SQLite with them, do I only need to configure it with Hibernate or more? | f1f431b217255b11537cdaf24747316f | {
"intermediate": 0.8002038598060608,
"beginner": 0.09487603604793549,
"expert": 0.10492009669542313
} |
18,476 | Please indicate the rsi value under the chart candle with the Pinescript V5. Please show up every ten candles. | 81149147d74fcd0dc6cee63679f679f8 | {
"intermediate": 0.35941600799560547,
"beginner": 0.2380625605583191,
"expert": 0.40252140164375305
} |
18,477 | in vba how can i write a module variable to record last Target | bbdacf1f6a715072756170efd2c23ba5 | {
"intermediate": 0.4992961883544922,
"beginner": 0.33835092186927795,
"expert": 0.16235288977622986
} |
18,478 | generate a sonic pi code for a piano chords as a melody | afd726ab9e4e640af25655a2af71173a | {
"intermediate": 0.2570846974849701,
"beginner": 0.16438168287277222,
"expert": 0.5785335898399353
} |
18,479 | как переделать функцию ниже, чтобы она возвращала объект json, в котором будут: guid, proxy_guid, user, created_at.
CREATE OR REPLACE FUNCTION api.idom_bind_proxy(bind jsonb)
RETURNS void
LANGUAGE plpgsql
AS $function$
BEGIN
UPDATE idom.proxy_bindings
SET deleted_at = now()
WHERE "user" = bind ->> 'user' and deleted_at is null;
INSERT INTO idom.proxy_bindings (guid, proxy_guid, "user", created_at)
SELECT
COALESCE((bind->>'guid')::uuid, uuid_generate_v4()),
(bind->>'proxy_guid')::uuid,
(bind->>'user')::text,
now();
END;
$function$
; | 962a92f16eb1af9accdafbf8b3fa6989 | {
"intermediate": 0.3825226426124573,
"beginner": 0.4092913269996643,
"expert": 0.20818597078323364
} |
18,480 | Переведет ли такая кнопка по ссылке?
<a href="#" type="submit" class="btn btn-danger" style="padding: 10px 15px" data-action="lock-card/lock_form">
<i class="fa fa-lock "> Блокировать</i> | efe11b2e529e326e54126b9afc386895 | {
"intermediate": 0.3299041986465454,
"beginner": 0.42223092913627625,
"expert": 0.24786488711833954
} |
18,481 | Can you help me provide interview questions and answers based on below Job Description requirement ? | 40468d5da9a469148855d54831f5d34d | {
"intermediate": 0.4141034483909607,
"beginner": 0.24398399889469147,
"expert": 0.34191256761550903
} |
18,482 | can you give me examples for MAC OS devices hunting queries on Microsoft 365 defender | b99fb6dd03b0aef80ce69b708091bc9b | {
"intermediate": 0.5307356715202332,
"beginner": 0.24935898184776306,
"expert": 0.2199053317308426
} |
18,483 | Generate a flowchart using valid mermaid.js syntax that shows the process for making a cup of tea. Then explain the process. | 3af174c5301e2b98fc226c92b7282148 | {
"intermediate": 0.44809848070144653,
"beginner": 0.2911929488182068,
"expert": 0.26070860028266907
} |
18,484 | Hi, I need you, an expert XML and XSLT developer, to help with with making an XSLT. I have the following existing XML:
<?xml version="1.0" encoding="UTF-8"?><root>
<testelem1>111</testelem1>
<foo>
<testelem2>teststring</testelem2>
<bar>
<testelem3>test33</testelem3>
</bar>
</foo>
<foo>
<bar>
<testelem3>test332</testelem3>
</bar>
</foo>
</root>
And I need your expert help to use XSLT version 1.0 to change the XML into the following structure:
<?xml version="1.0" encoding="UTF-8"?><root>
<testelem1>111</testelem1>
<foo>
<newElem>
<testelem2>teststring</testelem2>
<bar>
<testelem3>test33</testelem3>
</bar>
</newElem>
<newElem>
<testelem2>teststring2</testelem2>
<bar>
<testelem3>test332</testelem3>
</bar>
</newElem>
</foo>
</root> | cf9c91060b17b81b8d28ccb1d1fc55d2 | {
"intermediate": 0.3286636173725128,
"beginner": 0.3903871178627014,
"expert": 0.28094929456710815
} |
18,485 | import {SseProviderProps} from "./SseProvider.props";
import {createContext, useContext} from "react";
import {useSSE} from "../../hooks/sse";
interface SseProviderContext {}
const defaultContextValue: SseProviderContext = {};
const Context = createContext(defaultContextValue);
export function useSseProvider() {
return useContext(Context);
}
const SseProvider = ({children}: SseProviderProps) => {
const {} = useSSE();
return <Context.Provider value={{}}>
{children}
</Context.Provider>;
};
export default SseProvider;
как мне испоьзовать SseProvider в своем реакт приложении? | a766f41d453b5cbe0e0026be6f03897c | {
"intermediate": 0.38593196868896484,
"beginner": 0.3666183352470398,
"expert": 0.24744972586631775
} |
18,486 | ExpressionEvaluationFailed. The execution of template action 'Apply_to_each' failed: the result of the evaluation of 'foreach' expression '@{triggerBody()['key-button-date']}@{triggerBody()['boolean']}@{triggerBody()['boolean_1']}' is of type 'String'. The result must be a valid array. | e6d277742aa968c03b6b7b623a615c1b | {
"intermediate": 0.44639480113983154,
"beginner": 0.3035176694393158,
"expert": 0.25008755922317505
} |
18,487 | In JIRA, I want a JQL request that shows every "test" tickets from a test execution | 71e10a3fd496eb71455f280c4c19416c | {
"intermediate": 0.5411022901535034,
"beginner": 0.1907709538936615,
"expert": 0.26812678575515747
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.