甜是你

文章 评论 浏览 31

甜是你 2025-02-11 06:09:40

通常,您会使用优先队列,堆或类似的时间来使用单个计时器来管理定时回调。您检查接下来需要调用哪些回调,这是您设置的计时器唤醒您的时间。

但是,如果所有回调都使用常数30s重复,则可以使用队列。新的回调将作为一对回调添加到末尾,并且(绝对)时间戳,下一个要回电的回调将始终在前面。每次调用回调时,都会增加30秒的时间戳。

Normally you would use a priority queue, a heap or similar to manage your timed callbacks using a single timer. You check what callback needs to be called next and that is the time you set for the timer to wake you up.

But if all callbacks use a constant 30s repeat then you can just use a queue. New callbacks are added to the end as a pair of callback and (absolute) timestamp and the next callback to call will always be at the front. Every time you call a callback you add it back to the queue with a timestamp 30s increased.

调度程序设计?从不同时间开始的同一时间轴上的多个事件

甜是你 2025-02-11 02:45:59

您的数据框架非常复杂。
我建议您切换到numpy,以处理数据:

temp = np.concatenate(([elem for elem in TST['data', 'stageA'].to_numpy()]))
np.histogram(temp, bins = 2)

Your dataframe is extremely complex.
I suggest you switch to numpy to handle the data with something like:

temp = np.concatenate(([elem for elem in TST['data', 'stageA'].to_numpy()]))
np.histogram(temp, bins = 2)

如何与熊猫数据框架内的numpy阵列一起工作

甜是你 2025-02-10 17:21:54
 let newArray = [];
items.forEach(i=>{
    if(i.selected){
    newArray.push(i.id)
    }
    if(i.subItems){
    i.subItems.forEach(j=>{
        if(j.selected){
        newArray.push(j.id)
        }
    })
}
});

所以这有点冗长。使用2个地图循环

 let newArray = [];
items.forEach(i=>{
    if(i.selected){
    newArray.push(i.id)
    }
    if(i.subItems){
    i.subItems.forEach(j=>{
        if(j.selected){
        newArray.push(j.id)
        }
    })
}
});

so this is bit lengthy. with 2 map loops

获取对象值的数组和对象值的嵌套数组

甜是你 2025-02-10 09:04:40

根据该方法的在此处输入链接描述解决方案2,我首先从P2中提取“ NP.Where”真正重要的行。

通过这样做,由于P2剩下的行要少得多,因此合并步骤将加速。

def split_2_pieces(img_coors: List[List[float]], P2, img_h, img_w, file_name):
    # Step1
    for (x, y) in img_coors:
        # Step2
        X, Y = np.meshgrid(x, y) # x is a list, y is a list
        P1 = {"X": X.flatten(), "Y": Y.flatten()}
        P1 = pd.DataFrame(data=P1)
        
        # New step 
        x_min, x_max = x.min(), x.max()
        y_min, y_max = y.min(), y.max()
        df_X, df_Y = P2.X.values, P2.Y.values

        row_idx = np.where((df_X >= x_min) & (df_X <= x_max) & df_Y >= y_min) & (df_Y <= y_max))
        P2_extracted = P2.iloc[row_idx]
        
        # Step3 (Modified)
        P_merge = P1.merge(P2_extracted [["X", "Y", "value1", ...]], how="left", on=["X","Y"]).fillna(0)
    
        # Step4
        P_merge_npy = np.array(P_merge).reshape(img_h, img_w, 13)
        np.save(Path(path, str(idx) + file_name), P_merge_npy)

原始运行时间从 18.7秒 1.13秒

According to the method by enter link description here Solution 2, I first extract the rows from P2 that really matters by "np.where".

By doing this, the merge step will be speeded up since P2 have left much less rows.

def split_2_pieces(img_coors: List[List[float]], P2, img_h, img_w, file_name):
    # Step1
    for (x, y) in img_coors:
        # Step2
        X, Y = np.meshgrid(x, y) # x is a list, y is a list
        P1 = {"X": X.flatten(), "Y": Y.flatten()}
        P1 = pd.DataFrame(data=P1)
        
        # New step 
        x_min, x_max = x.min(), x.max()
        y_min, y_max = y.min(), y.max()
        df_X, df_Y = P2.X.values, P2.Y.values

        row_idx = np.where((df_X >= x_min) & (df_X <= x_max) & df_Y >= y_min) & (df_Y <= y_max))
        P2_extracted = P2.iloc[row_idx]
        
        # Step3 (Modified)
        P_merge = P1.merge(P2_extracted [["X", "Y", "value1", ...]], how="left", on=["X","Y"]).fillna(0)
    
        # Step4
        P_merge_npy = np.array(P_merge).reshape(img_h, img_w, 13)
        np.save(Path(path, str(idx) + file_name), P_merge_npy)

The original run time reduces from 18.7 seconds to 1.13 seconds!

加快熊猫合并并进行循环python

甜是你 2025-02-10 06:42:36

这是解决问题的问题,我正在使用AWS依赖性 -

<dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.11.931</version>
        </dependency>

我不需要所有依赖性,我只需要S3和Lambda。因此,请删除此依赖性。它减少了我的罐子文件。 255 MB至50 MB。

This is issue is resolved, I am using AWS Dependency -

<dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.11.931</version>
        </dependency>

I don't need all the dependency, I need only S3 and Lambda. So Have remove this dependency. It decrease my Jar file. 255 MB to 50 MB.

如何减少当前255 MB的Maven Jar文件大小?

甜是你 2025-02-10 05:13:52

正如Chiappar提到的那样,这是一个数学问题,而不是代码问题。
但是他的解决方案是错误的。

要解决此问题,您可以从&gt; = 中删除相等的符号,但是您还必须更新值,因此它们将如下:

  1. if(randnumber&gt; 59)
  2. 如果(randnumber&gt; 19)
  3. if(randnumber&gt; 4)
  4. else

As chiappar mentioned it is a math problem, not a code problem.
But his solution is wrong.

To solve this you could remove the equal sign from >=, but then you also have to update the values, so they will be as follows:

  1. if (randNumber > 59)
  2. if (randNumber >19)
  3. if (randNumber >4)
  4. else

基于0到99之间的随机值,用预定概率执行不同的动作

甜是你 2025-02-10 04:46:06

Python字典项目以键:值对表示,可以使用密钥名称来提及。

如果允许您修改Origin JSON对象。

只是这样做:


def sort_submissions_of_items(json_list):
    for item in json_list:
        subs = item.get("submissions", [])
        if isinstance(subs, list):
            subs.sort(key=lambda x: x.get("score", 0), reverse=True)

sort_submissions_of_items(inputData)

Python Dictionary items are presented in key:value pairs, and can be referred to by using the key name.

If you are allowed to modify the origin JSON Object.

Just do like this:


def sort_submissions_of_items(json_list):
    for item in json_list:
        subs = item.get("submissions", [])
        if isinstance(subs, list):
            subs.sort(key=lambda x: x.get("score", 0), reverse=True)

sort_submissions_of_items(inputData)

如何对Python中的数组的JSON对象进行排序?

甜是你 2025-02-09 18:43:53

我认为解决上述问题的解决方案将是CQRS设计模式的使用。

这个想法将是一项单一的服务,它会在Twitter Analytics和Instagram Analytics中听这些事件,并将这些详细信息保存在数据库中。存储数据后,我们可以点击此服务以获取所需的数据。

最终,我们正在介绍中间服务,该服务将在这些分析服务中聆听事件并将其保存到数据库中。现在,我们可以通过对此特定服务进行单个API调用来避免多个API调用,这将为您提供所需的详细信息。

我认为这可能会有所帮助!!

参考: https://microservices.io/patterns/data/data/cqrs.html#:~: text = xtt = xtt = xt = how%20to; %20回路%20DATA,已发布%20by%20 the%维修%20that%20 own%20 the%20Data

I think the solution to the above problem will be the usage of CQRS design pattern.

The idea will be a single service that listens to the events in Twitter analytics and Instagram analytics and save those details in a database. Once the data is stored we can hit this service to get the required data.

Eventually we are introducing an intermediatory service which will listen to the events in those analytics services and save them to a database. Now we can avoid multiple api calls by making a single api call to this particular service which will give you the required details.

I think this might be of some help !!.

References : https://microservices.io/patterns/data/cqrs.html#:~:text=How%20to%20implement%20a%20query%20that%20retrieves%20data,published%20by%20the%20service%20that%20own%20the%20data.
https://medium.com/design-microservices-architecture-with-patterns/cqrs-design-pattern-in-microservices-architectures-5d41e359768c

从多个微服务查询数据

甜是你 2025-02-09 16:46:50

rect()将“ top”和“底部”视为顶部边框,作为参考,与 inset()不同,因为对于后一个“底部”将考虑底部边界作为参考。 “左”和“右”的逻辑相同,

您需要执行以下操作以获得相同的结果

<img src="https://i.ibb.co/0qG5Bzp/stone-wall.jpg" style="position: absolute; height: 554px; top: 0px; left: 0px; width: 2216px; clip: rect(0px, 50px, 100px, 25px); border: 1px solid red;">

<img src="https://i.ibb.co/0qG5Bzp/stone-wall.jpg" style="position: absolute; height: 554px; top: 125px; left: 0px; width: 2216px; clip-path: inset(0px calc(100% - 50px) calc(100% - 100px) 25px);  border: 1px solid red;">

clip: rect(top, right, bottom, left);
clip-path: inset(top calc(100% - right) calc(100% - bottom) left)

"top" and "bottom" for rect() consider the top border as a reference which is different with inset() because for the latter "bottom" will consider the bottom border as a reference. Same logic for "left" and "right"

You need to do the following to get the same result

<img src="https://i.ibb.co/0qG5Bzp/stone-wall.jpg" style="position: absolute; height: 554px; top: 0px; left: 0px; width: 2216px; clip: rect(0px, 50px, 100px, 25px); border: 1px solid red;">

<img src="https://i.ibb.co/0qG5Bzp/stone-wall.jpg" style="position: absolute; height: 554px; top: 125px; left: 0px; width: 2216px; clip-path: inset(0px calc(100% - 50px) calc(100% - 100px) 25px);  border: 1px solid red;">

clip: rect(top, right, bottom, left);
clip-path: inset(top calc(100% - right) calc(100% - bottom) left)

如何将CSS clip Rect()转换为clippath?

甜是你 2025-02-08 23:11:26

有关可见项目的所有信息均在 state.layoutinfo 中获得。要检查项目是否可见,您需要根据视口尺寸比较第一个和最后一个项目位置(肯定会可见的所有其他项目)。

要仅针对已更改的单元格进行重新组件,您可以在 Item> Item 中再次使用 deDivedStateof 将索引转换为特定的布尔状态。

val state = rememberLazyListState()
val fullyVisibleIndices: List<Int> by remember {
    derivedStateOf {
        val layoutInfo = state.layoutInfo
        val visibleItemsInfo = layoutInfo.visibleItemsInfo
        if (visibleItemsInfo.isEmpty()) {
            emptyList()
        } else {
            val fullyVisibleItemsInfo = visibleItemsInfo.toMutableList()

            val lastItem = fullyVisibleItemsInfo.last()

            val viewportHeight = layoutInfo.viewportEndOffset + layoutInfo.viewportStartOffset

            if (lastItem.offset + lastItem.size > viewportHeight) {
                fullyVisibleItemsInfo.removeLast()
            }

            val firstItemIfLeft = fullyVisibleItemsInfo.firstOrNull()
            if (firstItemIfLeft != null && firstItemIfLeft.offset < layoutInfo.viewportStartOffset) {
                fullyVisibleItemsInfo.removeFirst()
            }

            fullyVisibleItemsInfo.map { it.index }
        }
    }
}
LazyColumn(
    state = state,
    contentPadding = PaddingValues(30.dp)
) {
    items(100) { index -> 
        val isVisible by remember(index) {
            derivedStateOf {
                fullyVisibleIndices.contains(index)
            }
        }
        Text(
            index.toString(),
            modifier = Modifier
                .background(if (isVisible) Color.Green else Color.Transparent)
                .padding(30.dp)
        )
    }
}

All info about visible items is available in state.layoutInfo. To check wether the item is visible you need to compare first and last item positions(all other items for sure are gonna be visible) according to viewport size.

To initiate recomposition only for changed cells, you can again use derivedStateOf within item to convert the indexes to a specific boolean state.

val state = rememberLazyListState()
val fullyVisibleIndices: List<Int> by remember {
    derivedStateOf {
        val layoutInfo = state.layoutInfo
        val visibleItemsInfo = layoutInfo.visibleItemsInfo
        if (visibleItemsInfo.isEmpty()) {
            emptyList()
        } else {
            val fullyVisibleItemsInfo = visibleItemsInfo.toMutableList()

            val lastItem = fullyVisibleItemsInfo.last()

            val viewportHeight = layoutInfo.viewportEndOffset + layoutInfo.viewportStartOffset

            if (lastItem.offset + lastItem.size > viewportHeight) {
                fullyVisibleItemsInfo.removeLast()
            }

            val firstItemIfLeft = fullyVisibleItemsInfo.firstOrNull()
            if (firstItemIfLeft != null && firstItemIfLeft.offset < layoutInfo.viewportStartOffset) {
                fullyVisibleItemsInfo.removeFirst()
            }

            fullyVisibleItemsInfo.map { it.index }
        }
    }
}
LazyColumn(
    state = state,
    contentPadding = PaddingValues(30.dp)
) {
    items(100) { index -> 
        val isVisible by remember(index) {
            derivedStateOf {
                fullyVisibleIndices.contains(index)
            }
        }
        Text(
            index.toString(),
            modifier = Modifier
                .background(if (isVisible) Color.Green else Color.Transparent)
                .padding(30.dp)
        )
    }
}

如何知道JetPack组成的懒惰行的视图端口中完全可见的项目?

甜是你 2025-02-08 05:48:33

当尝试使用Nodemon在纱线工作区内运行节点服务器时,我只是遇到了这个问题。从工作区子文件夹中运行nodemon,但无法从工作区根文件夹本身。

worspace子文件夹中的脚本看起来像这样

"dev": "nodemon"

,从根文件夹中,

"dev:my-service": "yarn workspace my-service dev"

我通过专门将ts节点作为dev依赖关系求解了“ my-service”工作区

I just ran into this problem when trying to run a node server inside a yarn workspace with nodemon. Running nodemon from the workspace sub folder worked, but not from workspace root folder itself.

Script in worspace sub folder looks like this

"dev": "nodemon"

and from root folder

"dev:my-service": "yarn workspace my-service dev"

I solved it by specifically adding ts-node as a dev dependency to the "my-service" workspace

使用TS-Node-dev运行一个简单的Express应用并获得错误:false表达式:非弦乐值传递给`ts.resolvetyperecredendedircordertive“

甜是你 2025-02-08 00:46:52
let sample_data = [{
    user_song: {
      user_id: 2,
      username: 'tommy.g',
    },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: {
      user_id: 1,
      username: 'billy.m',
    },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: {
      user_id: 2,
      username: 'tommy.g',
    },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: {
      user_id: 3,
      username: 'sally.e',
    },
    user_time: null,
    user_scene: null,
  }];

let result = sample_data.map ( function (x) {
    x.user_song_count = sample_data.filter ( y => y.user_song.user_id == x.user_song.user_id ).length;
    return x;
});

console.log (result);

let sample_data = [{
    user_song: {
      user_id: 2,
      username: 'tommy.g',
    },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: {
      user_id: 1,
      username: 'billy.m',
    },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: {
      user_id: 2,
      username: 'tommy.g',
    },
    user_time: null,
    user_scene: null,
  },
  {
    user_song: {
      user_id: 3,
      username: 'sally.e',
    },
    user_time: null,
    user_scene: null,
  }];

let result = sample_data.map ( function (x) {
    x.user_song_count = sample_data.filter ( y => y.user_song.user_id == x.user_song.user_id ).length;
    return x;
});

console.log (result);

映射JavaScript数组,以计算不同的值

甜是你 2025-02-07 22:35:52

尝试完美地实现其他依赖库,例如

NPM安装 @react-navigation/本机
NPM安装反应式屏幕
npm安装反应新的安全区域封闭式
NPM install @react-navigation/native-stac

之后,您可以检查下面的代码。

import React from 'react';
import type { Node } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native- stack';
import {
   SafeAreaView,
   ScrollView,
   StatusBar,
   StyleSheet,
   Text,
   useColorScheme,
   View,
 } from 'react-native';
 const Stack = createNativeStackNavigator();
 function HomeScreen() {
   return (
       <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
     </View>
  );
}
const App: () => Node = () => {
  return (
    <>
     <NavigationContainer>
       <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
       </Stack.Navigator>
     </NavigationContainer>
    </>
   );
  };
 const styles = StyleSheet.create({
    sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
   }, 
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
  },
  highlight: {
    fontWeight: '700',
  },
 });
 export default App;

Try to implement other dependency library perfectly like below

npm install @react-navigation/native
npm install react-native-screens
npm install react-native-safe-area-context
npm install @react-navigation/native-stac

After that you can check the code below how it’s done.

import React from 'react';
import type { Node } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native- stack';
import {
   SafeAreaView,
   ScrollView,
   StatusBar,
   StyleSheet,
   Text,
   useColorScheme,
   View,
 } from 'react-native';
 const Stack = createNativeStackNavigator();
 function HomeScreen() {
   return (
       <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
     </View>
  );
}
const App: () => Node = () => {
  return (
    <>
     <NavigationContainer>
       <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} />
       </Stack.Navigator>
     </NavigationContainer>
    </>
   );
  };
 const styles = StyleSheet.create({
    sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
   }, 
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
  },
  highlight: {
    fontWeight: '700',
  },
 });
 export default App;

为什么我会遇到这样的错误,“不确定不是对象路由。

甜是你 2025-02-07 21:46:33

您说的是Django贯穿所有URL模式并停止直到找到匹配的URL。因此,这里发生的事情是,当您使用Localhost键入AURL时:8000/Backend/abc/它在将404返回客户端之前通过所有URL运行。因此,它停止在URL上支持任何字符串,在您的情况下在URL下方的情况下。

path('<slug:category_slug>/<slug:slug_subcategory>/', butik_views.cat_or_article),

通过在URL中添加静态单词来获得404。

path('shop/<slug:category_slug>/<slug:slug_subcategory>/', butik_views.cat_or_article),

或者

path('backend/', include('backend.urls')),
path('shop/', include('shop.urls')),

You you said Django run through all of the URL patterns and stops till it finds its matching URL. SO, what has happen here is that when you type a URL with localhost:8000/backend/abc/ it runs through all the URLS before returning 404 to the client. So, it stops at the URL that support any string with 2 parameters in your case below URL.

path('<slug:category_slug>/<slug:slug_subcategory>/', butik_views.cat_or_article),

To get a 404 by adding a static word in you URL.

path('shop/<slug:category_slug>/<slug:slug_subcategory>/', butik_views.cat_or_article),

or

path('backend/', include('backend.urls')),
path('shop/', include('shop.urls')),

Django:未发现的URL路径跳入下一个应用程序

甜是你 2025-02-07 19:08:29

有很多方法可以做到这一点,让我们使用对象。Keys和单个循环进行操作

const keys = Object.keys(users);
for(let i=0; i<keys.length; i++){
  let user = keys[i]; //Alex or Asab
  let skills = users[user].skills;
  let skill_count = skills.length;
  console.log(`${user} has ${skill_count} skills.`)
}

There is a lots of way to do it and let's use Object.keys and a single for loop to do it

const keys = Object.keys(users);
for(let i=0; i<keys.length; i++){
  let user = keys[i]; //Alex or Asab
  let skills = users[user].skills;
  let skill_count = skills.length;
  console.log(`${user} has ${skill_count} skills.`)
}

如何搜索两个对象属性

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文