instruction
stringlengths
0
30k
null
You might want to communicate with your employer about this. The interpersonal stack exchange might be helpful for that: https://interpersonal.stackexchange.com/ I don't know much about it but it seems worth a try. I'd be curious to know if your fellow Chinese citizens also share your frustration. Otherwise, how could China be doing so well in terms of productivity? (At least that's how it seems) Also, I'm assuming from the tag to this post that you work as a programmer, am I right?
I want to access the MS Graph API from inside my script task. I didn't get the SDK to work (in SSIS at least) so I thought I would write my own class using the System.Net.Http HttpClient. Outside of SSIS I did not have any problem getting that to work. When I'm trying to run HttpClient.SendAsync() in SSIS however I'm getting an Error. ``` public void Main() { var HttpClient = new HttpClient(); var req_msg = new HttpRequestMessage(HttpMethod.Get, "http://ip.jsontest.com/"); HttpResponseMessage t = System.Threading.Tasks.Task.Run(async () => await HttpClient.SendAsync(req_msg)).Result; MessageBox.Show(t.StatusCode.ToString()); // -> OK var req_msg2 = new HttpRequestMessage(HttpMethod.Get, $"https://graph.microsoft.com/v1.0/users/{test_name}"); HttpResponseMessage t2 = System.Threading.Tasks.Task.Run(async () => await HttpClient.SendAsync(req_msg2)).Result; // -> Error MessageBox.Show(t2.StatusCode.ToString()); Dts.TaskResult = (int)ScriptResults.Success; } ``` This is the Error: ``` bei System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) bei System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) bei System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) bei System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) bei Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript() ``` It might have something to do with Https, that's my theory at least. Then again in regular c# projects that was not a problem. Also it's the same way with getAsync(), postAsync(), ...
Error resolving templates: template might not exists or might not accessible by any of the configured Template Resolver in Thymeleaf
|thymeleaf|spring5|
null
You can customize your WebClient WebClient.builder() .clientConnector(new ReactorClientHttpConnector(httpClient.create() .secure(contextSpec -> contextSpec.sslContext(sslContext) .handlerConfigurator(handler -> { SSLEngine engine = handler.engine(); SSLParameters params = engine.getSSLParameters (); params.setServerNames(List.of(new SNIHostName(<hostname-to-match-certificate-CN>))); engine.setSSLParameters(params); }); ))) .build(); providing the hostname in such a way will cause it to be verified with what we have in the certificate and then the url we are hitting can contain, for example, a clean IP in the host section
Recently we released the first release candidate of a [high-performance JSON masker library in Java with no runtime dependencies](https://github.com/Breus/JSON-masker) which you might want to use to do this. It works on any JSON value type, has an extensive and configurable API, and adds minimal computation overhead both in terms of CPU time and memory allocations. Additionally, it has limited JsonPath support.
{"Voters":[{"Id":20143744,"DisplayName":"Atmo"},{"Id":1625187,"DisplayName":"Evg"},{"Id":8877,"DisplayName":"Ðаn"}],"SiteSpecificCloseReasonIds":[13]}
I have to get data from a server in my electron app I am using "net" module of the node js. As "net" is main process moduel I can't directly access it from renderer file. I had to use 'net' module in main.js file. I followed two way IPC from [tutorial](https://www.electronjs.org/docs/latest/tutorial/ipc#pattern-2-renderer-to-main-two-way). With this approach I managed to fetch the data from server in main.js file as I can print in console log. But when I try to return this data to renderer it is not working. On renderer getting below messages ``` Promise {<pending>} [[Prototype]]: Promise [[PromiseState]]: "fulfilled" [[PromiseResult]]: undefined ``` ### main.js ```js const { app, BrowserWindow, ipcMain, net } = require('electron'); const path = require("path"); const remoteMain = require('@electron/remote/main'); remoteMain.initialize(); let text; let win; function handleData() { const request = net.request({ method: 'GET', protocol: 'http:', hostname: 'some IP address', port: some port, path: '/some path', redirect: 'follow' }); request.on('response', (response) => { console.log(`STATUS: ${response.statusCode}`) console.log(`HEADERS: ${JSON.stringify(response.headers)}`) response.on('data', (chunk) => { // console.log(`${chunk}`) text = `${chunk}`; console.log(text); // this prints the json data on console. / tried return text; but same error. }) response.on('end', () => { console.log('No more data in response.') console.log(text); // this prints the json data on console. return text; }) }) request.end() }; const createWindow = () => { win = new BrowserWindow({ width: 800, height: 600, webPreferences: { preload: path.join(__dirname, 'preload.js'), }, }) remoteMain.enable(win.webContents) } function openIndex() { win.loadFile('HTML/index.html'); win.webContents.openDevTools(); } ipcMain.handle("request:get", handleData); app.whenReady().then(() => { createWindow(); openIndex(); app.on("activate", function() { if (BrowserWindow.getAllWindows().length === 0) createWindow(); }); }); app.on("window-all-closed", function() { if (process.platform !== "darwin") app.quit(); }); ``` ### preload.js ```js const { contextBridge, ipcRenderer } = require("electron"); contextBridge.exposeInMainWorld("electronAPI", { getData: () => ipcRenderer.invoke("request:get", message), }); ``` ### renderer.js (index.js) ```js const btnclick = document.getElementById("PFLIoT"); btnclick.addEventListener("click", () => { console.log("Hello from Machine List IOT"); const response = window.electronAPI.getData(); console.log(response); // Also tried this code // window.electronAPI.getData().then((data) => { // console.log(data);}) }); ``` ### rendere HTML(index.html) ```html <html> <head> <link rel="stylesheet" href="../css/layout.css" > </head> <body> <div class="area"></div> <nav class="main-menu"> <ul> <li> <a href="#"> <i class="fa fa-home fa-2x"></i> <span class="nav-text"> Dashboard </span> </a> </li> <li class="has-subnav"> <a href="#home"> <i class="fa fa-laptop fa-2x"></i> <span class="nav-text"> </span> </a> </li> </nav> </body> <script src="../js/layout.js"> </script> </html> ```
Is there a lightweight GUI protocol like X11 that works well over ssh?
|ssh|x11|xorg|x11-forwarding|
You could **extend** the column definition type to suit your needs. Use the `ColumnDef` type of `tanstack/react-table` and add your style object. ```js import type { ColumnDef } from '@tanstack/react-table'; // New custom column def type export type ColumnDefType<T> = ColumnDef<T> & { style?: Record<string, string> }; ``` You could use that type when typing your columns. So the style object is available when you create your rows for example. The style object can be extracted from `column.columnDef` and applied where necessary. ```js import type { ColumnDefType } from '<custom-type-file-location>'; const columns = useMemo<ColumnDefType<YourRowType>[]>( () => [ { header: 'Name', accessorKey: 'name', style: ... } ] ) ``` This example uses `@tanstack/react-table v8`
The best place to do validation would be at the setters function,doing validation at `def __init__()` can be by passed using dot notation
nestjs/swagger not documenting the query params so you have to use @ApiQuery() annotation , [source][1] <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> @Get('search') @ApiOperation({ summary: 'Get Products by search ' }) @ApiQuery({ name:'searchString', required: true, type:'string' }) @ApiQuery({ name: 'take', required: false, type: 'number' }) @ApiQuery({ name: 'page', required: false, type: 'number' }) getPaginatedBySearchString( @Query('searchString') searchString: string, @Query('take') take = 10, @Query('page') page = 0, ) { take = take > 20 ? 20 : take; return this.productsService.findPoductsBySearchString( take, page, searchString, ); } <!-- end snippet --> [1]: https://github.com/nestjs/swagger/issues/291
I use Apache2 to intervene between my site and the User with an Authentication Login dialogue. I've added a hashed password to the Apache2 .htaccess file. The Site has a registered subdomain, and the web server has a set of SSL certs and keys. However, when a User tries to access the site and they are presented with the Username & Password box, the username and password are not accepted. I would appreciate some help. I create a Username and Password for the site authentication using: sudo htpasswd -c /etc/apache2/.htpasswd I can see a hashed version of the password in that file. Then, these are my Apache2 server configuration files: **/etc/apache2/sites-available/my-site.conf** <IfModule mod_ssl.c> <VirtualHost *:443> ServerName my-site.com ServerAlias subdomain.my-site.com DocumentRoot /var/www/my-site/public_html <Directory /var/www/my-site/public_html> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> <Location "/"> AuthType Digest AuthName "Restricted Area" AuthDigestDomain / AuthDigestProvider file AuthUserFile /etc/apache2/.htpasswd Require valid-user </Location> SSLCertificateFile /etc/letsencrypt/live/subdomain.my-site.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/subdomain.my-site.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> </IfModule> And the main apache config file **/etc/apache2/apache.conf** DefaultRuntimeDir ${APACHE_RUN_DIR} PidFile ${APACHE_PID_FILE} Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 5 User ${APACHE_RUN_USER} Group ${APACHE_RUN_GROUP} HostnameLookups Off ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn IncludeOptional mods-enabled/*.load IncludeOptional mods-enabled/*.conf Include ports.conf <Directory /> Options FollowSymLinks AllowOverride None Require all denied </Directory> <Directory /usr/share> AllowOverride None Require all granted </Directory> <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> <Directory /usr/share> AllowOverride None Require all granted </Directory> <Directory /var/www/> Options Indexes FollowSymLinks AllowOverride None Require all granted </Directory> AccessFileName .htaccess <FilesMatch "^\.ht"> Require all denied </FilesMatch> LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent IncludeOptional conf-enabled/*.conf IncludeOptional sites-enabled/*.conf Include /etc/apache2/httpd.conf My **/etc/apache/httpd.conf** file is empty. I've cleared the cache, used private browsers, and I've asked others to try, but ultimately the password and username I set don't work. Please tell me if I'm missing data for you to help. I'm happy to edit the question. Thanks
Issue with HttpClient.SendAsync("...") in SSIS Script Task
|ssis|dotnet-httpclient|script-task|
You can try something like this: ret, frame = cam.read() lower = np.array([0, 50, 50]) high = np.array([5, 255, 255]) lower2 = np.array([170, 50, 50]) high2 = np.array([180, 255, 255]) first = cv.inRange(hsv, lower, high) second = cv.inRange(hsv, lower2, high2) both = mask + mask2 img = cv.bitwise_and(frame, frame, mask=both) the `both` mask will contain the mask for both the colors.
I have an Enum that I already use for multiple other purposes, however in those cases I use the Enum like a public variable of the class meaning I can access it like `EntityManager.FAll`. However, in the new use case I have for it I want to use the Enum in that class as a function parameter of another class's function like `CEntityManager::EBroadcastTypes`. But no matter what I try, when I try to compile the code this always fails telling me that either when using the scope operator I need to be using a Class or Namespace even though this is a class (error code: C2653), or that `EBroadcastTypes` isnt a known identifier (error code: 2061). Just to further 'visualize' this, as an example. I want to use this Enum for 'filtering channels' when Ray Casting, so that I can either only check for specific Wanted Entities. ``` EntityManager.h class CEntityManager { public: enum EBroadcastTypes { FAll, FVehicle, FProjectile, FDynamic, // Any Entity that can movement on update (ie. Vehicle and Shells) FStatic, // Any Entity that never moves (ie. Scenery) }; struct BroadcastFilter { EBroadcastTypes type; vector<string> channels; }; vector<BroadcastFilter> m_BroadcastFilters; vector<string> GetChannelsOfFilter(EBroadcastTypes Type) { for (const auto& BroadcastFilter : m_BroadcastFilters) { if (BroadcastFilter.type == Type) { return BroadcastFilter.channels; } } } } ``` ``` Main.h // Primary Update(tick) function Update() { if()// On Some condition { TFloat32 range = 400.0f HitResult Hit = RayCast(ray, EntityManager::FAll, range); // Do something with Hit ... } } ``` RayCast file doesn't contain a class, simply functions that fall under the same category that would be used across multiple points/classes throughout the code. ``` CRayCast.h #include "EntityManager.h" struct CRay { CVector3 m_Origin; CVector3 m_Direction; }; HitResult RayCast(CRay ray, CEntityManager::EBroadcastType Type, TFloat32 Range); ``` ``` CRayCast.cpp #include "CRayCast.cpp" // Actually using EntityManager here, other than for getting the Enum. extern CEntityManager EntityManager; HitResult RayCast(CRay ray, CEntityManager::EBroadcastTypes Type, TFloat32 Range) { // Do the raycasting here // ... } ``` So is there any way to actually use the Enum like this? Tried including the header as well as forward declaring both the class and enum (the compiler then told me it didn't know what those forwards are).
Due to the changes in Flutter 3.19 regarding the [Deprecated imperative apply of Flutter's Gradle plugins](https://docs.flutter.dev/release/breaking-changes/flutter-gradle-plugin-apply), I had to migrate my files in order to work with the new version. However, after following the guide, I keep running into this issue: ``` FAILURE: Build failed with an exception. * Where: Build file 'D:\Android Studio Projects\Traux\TeamNews-App\android\app\build.gradle' line: 2 * What went wrong: An exception occurred applying plugin request [id: 'com.android.application'] > Failed to apply plugin 'com.android.internal.application'. > Could not create an instance of type com.android.build.gradle.internal.plugins.AppPlugin$ApplicationAndroidComponentsExtensionImplCompat. > Could not generate a decorated class for type AppPlugin.ApplicationAndroidComponentsExtensionImplCompat. > Cannot have abstract method AndroidComponentsExtension.registerSourceType(). ``` This is my `settings.gradle`: ``` pluginManagement { def flutterSdkPath = { def properties = new Properties() file("local.properties").withInputStream { properties.load(it) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" return flutterSdkPath }() includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") repositories { google() mavenCentral() gradlePluginPortal() } } plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" id "com.android.application" version "7.1.2" apply false id "org.jetbrains.kotlin.android" version "1.8.22" apply false id "com.google.gms.google-services" version "4.4.0" apply false } include ":app" ``` My `android/build.grade`: ``` allprojects { repositories { google() mavenCentral() } } rootProject.buildDir = '../build' subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(':app') } tasks.register("clean", Delete) { delete rootProject.buildDir } ``` And my `app/build.gradle`: ``` plugins { id "com.android.application" id "org.jetbrains.kotlin.android" id "dev.flutter.flutter-gradle-plugin" id "com.google.gms.google-services" } def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { localPropertiesFile.withReader('UTF-8') { reader -> localProperties.load(reader) } } def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' } def flutterVersionName = localProperties.getProperty('flutter.versionName') if (flutterVersionName == null) { flutterVersionName = '1.0' } def keystoreProperties = new Properties() def keystorePropertiesFile = rootProject.file('key.properties') if (keystorePropertiesFile.exists()) { keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } android { compileSdkVersion 33 ndkVersion flutter.ndkVersion compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' } sourceSets { main.java.srcDirs += 'src/main/kotlin' } defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.ingressosa.santa_cruz_news" // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration. minSdkVersion 21 targetSdkVersion 33 versionCode flutterVersionCode.toInteger() versionName flutterVersionName multiDexEnabled true } signingConfigs { release { keyAlias keystoreProperties['keyAlias'] keyPassword keystoreProperties['keyPassword'] storeFile keystoreProperties['storeFile'] ? file(keystoreProperties['storeFile']) : null storePassword keystoreProperties['storePassword'] } } buildTypes { release { signingConfig signingConfigs.release } } } flutter { source '../..' } dependencies {} ``` What can I do here? I've tried deleting my **pubspec.lock** file and running: `flutter clean` `flutter pub get` `flutter pub cache repair`
Issue when migrating Android build files to declarative form
|android|flutter|gradle|
Prometheus: Changing unit on Y axis
|prometheus|grafana|k6|
try this instead `npm install --save @types/dom-speech-recognition` worked for me
Have you tried using something like this in your Dockerfile: RUN apt-get update && apt-get install -y git If you want to use 'yum' you should use [centos][1] or [radhat][2] base image. [1]: https://hub.docker.com/_/centos [2]: https://hub.docker.com/r/redhat/ubi8
I need to perform a merge between two databases but, due to numerous typing errors, I would like to make the criteria for this merge more flexible so that in cases where the keys differ by just one character and there is a single correspondence between the keys 1 and 2, the merge is still performed. For example, in the following dataframes, I would expect the keys **A**A_DLA_25051946 and **B**A_DLA_25051946 to still result in a merge between the dataframes. ``` Chave1<-c("AA_DLA_25051946","BAJ_FRR_10091975","CBR_ARM_30111961") Chave2<-c("BA_DLA_25051946","AB_FB_31101952","ABR_ARM_30111961") ``` I created a comparison function that seems to work, but I can't apply it to the merge: ``` comparar_strings <- function(coluna1, coluna2) { # Inicializa um vetor de resultados resultados <- logical(length = length(coluna1)) # Loop pelos elementos das colunas for (i in seq_along(coluna1)) { str1 <- coluna1[i] str2 <- coluna2[i] # Comparar se as strings são idênticas ou diferem por apenas um caractere resultados[i] <- sum(strsplit(str1, "")[[1]] != strsplit(str2, "")[[1]]) <= 1 } # Retorna vetor de resultados return(resultados) } ```
Create a flexible key for merge in R
|r|primary-key|stringr|
null
I have a healthy, 2/2 Ready Pod that has been running without restarts for over half an hour, on Kubernetes 1.27 through EKS. When I try to run `kubectl logs -n $MY_NS pod/$MY_POD -c $MY_CONTAINER` on my Apple M1 Max with a `kubectl version` of 1.25, I get no logs. When I exec into a Pod mounting the Node FS, I can see, in `/var/log/pods/$MY_NS-$MY_POD/$MY_CONTAINER`, logs (including rotations). I copied them with `kubectl cp` to my laptop, and they and the contents look roughly as I'd expect: ``` $ ls -la total 16M drwxr-xr-x 7 jrichards 224 Mar 12 15:45 ./ drwxr-xr-x 7 jrichards 224 Mar 12 15:45 ../ -rw-r--r-- 1 jrichards 0 Mar 12 15:45 0.log -rw-r--r-- 1 jrichards 920K Mar 12 15:45 0.log.20240312-212825.gz -rw-r--r-- 1 jrichards 922K Mar 12 15:45 0.log.20240312-212835.gz -rw-r--r-- 1 jrichards 908K Mar 12 15:45 0.log.20240312-212845.gz -rw-r--r-- 1 jrichards 13M Mar 12 15:45 0.log.20240312-212856 ``` As you can probably tell from the filenames, the container in question was spamming a crazy number of log lines (the most recent gzip file was rotated after only ~10s, after recording >2k msg/s for ~10s, with an uncompressed file size of 76MiB). Even so, this is very confusing to me. Why does `kubectl logs` not return the any logged output from this container? I tried the command multiple times. I was able to find [a kubernetes bugfix](https://github.com/kubernetes/kubernetes/pull/115702) that's targeted for 1.29 relating to `kubectl logs -f`, but I'm not using `-f`. I also found [a 2015 kubernetes issue](https://github.com/kubernetes/kubernetes/issues/11046) that mentions that ['"kubectl logs" may give empty output'](https://github.com/kubernetes/kubernetes/issues/11046#issuecomment-120281807) and ['I think we should advise that `kubectl logs` is just a "cache" of some of the logs for a pod'](https://github.com/kubernetes/kubernetes/issues/11046#issuecomment-120505698). Is this still true? I have read [the kuberenetes logging guide](https://kubernetes.io/docs/concepts/cluster-administration/logging/) as well as [the `kubectl logs` man page](https://kubernetes.io/docs/reference/kubectl/generated/kubectl_logs/) and found nothing that mentions any limitations on `kubectl logs`. My questions: 1. Where can I find details on the limitations of `kubectl logs`? 2. Where can I find details of how Kubernetes handles log rotation? 3. How I should expect files to be formatted and used in `/var/log/containers/$MY_NS-$MY_POD/$MY_CONTAINER`?
In your code you need to initialise the LCD and also turn on the backlight. Also you need to check that you have the correct I2C address for your LCD. For the unit that you appear to be using this is usually either 0x27 or 0x3f. If this is wrong you will see nothing. In the code below I am using an Arduino Uno with and I2C LCD with address 0x3f, and I am displaying the value read from A0, so if you have no connection on A0 you should see a continuously changing value (I am getting around 270 - 285). #include <LiquidCrystal_I2C.h> LiquidCrystal_I2C lcd(0x3f, 16, 2); // Set the LCD I2C address - ususally 0x27 or 0x3F void setup() { lcd.init(); lcd.backlight(); lcd.clear(); lcd.print("Hello world"); } void loop() { int sensorValue = analogRead(A0); lcd.setCursor(0, 1); // Display analogue reading on line 2 lcd.print(String(sensorValue) + " "); delay(500); } If you see nothing on the LCD you may have your I2C connections wrong. You should have SDA on A4 and SCL on A5.
I have two list components or card stacks. 5 Decks and several cards in each deck. I am listing the 5 decks and passing it's content to a child component when I click on it with a (selectedItem) state. Then I'm picking that up in its child component and mapping another flatlist with the cards inside. My problem is, when I click to an index that is beyond the limit of a smaller deck. FOr example, Deck1 = 23 cards Deck2 = 15 cards When I index+1 on Deck1 to anywhere past 15, and I try to click on Deck2, it says it's out of range (obviously lol), I'd like it to reset to index(0) when I change decks. I can't just add more cards and make them all the same amount because I am setting a new feature later where the user can build his own deck and it can be any number of cards Here's my Decks Component const Decks = () => { const {theme} = useContext(ThemeContext) let activeColors = colors[theme.mode] const allbelts = [yellowbelt, orangebelt, greenbelt, brownbeltthree, brownbelttwo, brownbeltone] const ref = useRef(null); const [selectedItem, setSelectedItem] = useState(null); const [deckIndex, setDeckIndex] = useState(0); const handleItemPress = (item) => { setSelectedItem(item); console.log("deckIndex:", deckIndex); }; return ( <View style={{flex:1}}> <View style={{flex:1, marginTop: 40}}> <Text style={[{color:activeColors.primary}, styles.sectionheading]}> Testing Card Decks </Text> <Animated.FlatList ref={ref} data={allbelts} horizontal keyExtractor={(item, index) => index.toString()} showsHorizontalScrollIndicator={false} snapToInterval={ITEM_SIZE} decelerationRate={0} bounces={false} scrollEventThrottle={16} renderItem={({item, deckIndex}) => ( <View style={{}}> <TouchableOpacity key={deckIndex} onPress={() => { handleItemPress(item) }}> <Animated.View style={[{ backgroundColor: item.color, shadowColor: item.color, borderColor: activeColors.bgalt}, styles.card]}> <Text numberOfLines={2} style={[{color: item.color === "#F5D143" ? activeColors.black : activeColors.white}, styles.cardtitle]}> {item.rank_japanese} </Text> <Text numberOfLines={2} style={[{color: item.color === "#F5D143" ? activeColors.black : activeColors.white}, styles.cardtitle]}> {item.rank_english} </Text> </Animated.View> </TouchableOpacity> </View> )} /> <TestingCards selectedItem={selectedItem} deckIndex={deckIndex} /> </View> </View> ) } export default Decks and here is the Cards component const Card = ({info}) => { const {theme} = useContext(ThemeContext) let activeColors = colors[theme.mode] const rotate = useSharedValue(0); const frontAnimatedStyle = useAnimatedStyle(() => { const rotateValue = interpolate( rotate.value, [0, 1], [0, 180] ); return { transform: [ {rotateY: withTiming(`${rotateValue}deg`, {duration: 500})} ] } }) const backAnimatedStyle = useAnimatedStyle(() => { const rotateValue = interpolate( rotate.value, [0, 1], [180, 360] ); return { transform: [ {rotateY: withTiming(`${rotateValue}deg`, {duration: 500})} ] } }) return ( <View style={[styles.cardcontainer]}> <View style={styles.iconcnt}> <Pressable onPress={() => { rotate.value = rotate.value ? 0 : 1; }} style={styles.icon}> <Icon name="swap-horizontal" size={24} color={activeColors.textcolor} /> </Pressable> </View> <View style={styles.cardContent}> <Animated.View style={[ {backgroundColor: activeColors.bgalt, position:"absolute"}, styles.card, frontAnimatedStyle]}> <View> <Text style={[{color: activeColors.textcolor}, styles.cardtext]}> {info.q} </Text> </View> </Animated.View> <Animated.View style={[ {backgroundColor: activeColors.primary}, styles.card, backAnimatedStyle]}> <View> <Text style={[{color: activeColors.textcolor}, styles.cardtext]}> {info.a} </Text> </View> </Animated.View> </View> </View> ) } const FlashCards = ({selectedItem, deckIndex}) => { const {theme} = useContext(ThemeContext) let activeColors = colors[theme.mode] const [index, setIndex] = useState(0); const [lastIndex, setLastIndex] = useState(null); const [viewPosition, setViewPosition] = useState(0.5); const flatlistRef = useRef(null) useEffect(() => { setLastIndex(selectedItem?.questions?.length - 1); // console.log("selectedItem:", selectedItem); console.log("lastIndex at TestingCards:", lastIndex); flatlistRef.current?.scrollToIndex({ index: index, animated: true, viewPosition, }) } , [index, viewPosition, lastIndex, selectedItem]) if (!selectedItem) { return null; } return ( <View style={[styles.container]}> <Animated.FlatList data={selectedItem.questions} ref={flatlistRef} index={deckIndex} keyExtractor={(item, index) => index.toString()} initialScrollIndex={0} horizontal showsHorizontalScrollIndicator={false} snapToInterval="ITEM_SIZE" decelerationRate={0} bounces={false} scrollEventThrottle={16} initialNumToRender={10} onScrollToIndexFailed={index => { setIndex(0) const wait = new Promise(resolve => setTimeout(resolve, 0)); wait.then(() => { flatlistRef.current?.scrollToIndex({ index: index, animated: true }); }); }} renderItem={({item, index}) => <Card info={item} index={index} totalLength={lastIndex} seefront={true} />} /> <View style={styles.btnGroup}> <TouchableOpacity onPress={()=>{ setIndex(0); setViewPosition(0.5); }}> <LinearGradient colors={['rgba(1,102,175,1)', 'rgba(155,24,213,1)']} start={{ x: 0, y: 1 }} end={{ x: 1, y: 1 }} style={styles.btnPrimary}> <Icon name="chevron-double-left" size={24} color={activeColors.white} /> </LinearGradient> </TouchableOpacity> <TouchableOpacity onPress={()=>{ if (index === 0) { return; } setIndex(index - 1); setViewPosition(0.5); }}> <LinearGradient colors={['rgba(1,102,175,1)', 'rgba(155,24,213,1)']} start={{ x: 0, y: 1 }} end={{ x: 1, y: 1 }} style={styles.btnPrimary}> <Icon name="chevron-left" size={24} color={activeColors.white} /> </LinearGradient> </TouchableOpacity> <TouchableOpacity onPress={()=>{ if (index === lastIndex) { return; } setIndex(index + 1); setViewPosition(0.5); }}> <LinearGradient colors={['rgba(1,102,175,1)', 'rgba(155,24,213,1)']} start={{ x: 0, y: 1 }} end={{ x: 1, y: 1 }} style={styles.btnPrimary}> <Icon name="chevron-right" size={24} color={activeColors.white} /> </LinearGradient> </TouchableOpacity> <TouchableOpacity onPress={()=>{ if (index === lastIndex) { return; } setIndex(lastIndex - 1); setViewPosition(0.5); }}> <LinearGradient colors={['rgba(1,102,175,1)', 'rgba(155,24,213,1)']} start={{ x: 0, y: 1 }} end={{ x: 1, y: 1 }} style={styles.btnPrimary}> <Icon name="chevron-double-right" size={24} color={activeColors.white} /> </LinearGradient> </TouchableOpacity> </View> </View> ) } export default FlashCards
How can I limit my data.length with invariant data sizes so I don't ever get past the lastindex? React Native
|javascript|reactjs|react-native|
Code: @slackbot.command('hi') def idk(): user = slackbot.slack_client.api_call( "users.info", user=command.user, ) print(user) When the user types of command in slack as "!hi", that users information is taken into the command. This is what I have so far, but how do I now extract purely the users first name? `print(user)` at the moment prints everything I need to see, including the `'first_name:"name"`, but how do I now single this out? Please help!
|python|slack|
From CSL's perspective you're looking for the solution in the wrong place: If you look at the screenshot below, CSL (via Zotero in this case) inserts a tab and a line feed in Word. The exact width of the line feed is not a question of the citation style but of typography/design (just like, say, font) so this is something you'd handle in your word processor. In your case, specifically, you can modify the `bibliography` style in Word (in this case by increasing the width of the hanging indentation). [![IEEE Bibliography in Word created by Zotero][1]][1] [1]: https://i.stack.imgur.com/Ei3L2.png
How can I resolve signature of method decorator when called as an expression?
<!-- language-all: sh --> The registry key of origin and the comparison operand imply that you're dealing with _version numbers_. **To meaningfully compare version numbers based on their _string representations_, cast them to `[version]`**: ``` [version] $soft.DisplayVersion -lt [version] '124.0' ``` Note: * For brevity, you could omit the RHS `[version]` cast, because the LHS cast would implicitly coerce the RHS to `[version]` too. However, using it on both sides can help conceptual clarity. * For a [`[version]`](https://learn.microsoft.com/en-US/dotnet/api/System.Version) cast to succeed, the input string must have _at least 2_ components (e.g. `[version] '124.0'` and _at most 4_ (e.g, `[version] '124.0.1.2'`), and each component must be a positive decimal integer (including `0`). * `[version]` is _not_ capable of parsing [_semantic_ version numbers](https://semver.org/), however, which are limited to _3 components_ and may contain non-numeric suffixes (e.g., `7.5.0-preview.2`). * Use **[`[semver]`](https://learn.microsoft.com/en-US/dotnet/api/System.Management.Automation.SemanticVersion) to parse *semantic versions***; however, that type is available in [_PowerShell (Core) 7_](https://github.com/PowerShell/PowerShell/blob/master/README.md) only. * Unlike with `[version]`, a _single_ component is sufficient in the input string of a `[semver]` cast; e.g., `[semver] '124'` works to create version `124.0.0`. --- As for **what you tried**: * `$soft.DisplayVersion -lt "124.0"` and `$soft.DisplayVersion -lt 124.0` are _equivalent_, and neither works as intended: * Because the _LHS_ operand is a _string_, `-lt` coerces the RHS operand to a string too, and then performs _lexical_ comparison, which is not what you want: `'95.0' -lt '124.0'` `'95.0' -lt 124.0` are both _false_, because the _character_ `'9'` is _greater than_ the character `'1'`. * `[decimal]$soft.DisplayVersion -lt 124.0` (from [your own answer](https://stackoverflow.com/a/78231854/45375)) works only for version-number strings _up to two components_; e.g. `[decimal] '95.0.1'` would break.
null
my task is to create drag and drop interface, where user drags an element, which changes its appearance during that short amount of time - till it is dropped in its destination. I would like to do it with native Web API. I have found the event called "dragstart" in [MDN Documentation][1]. And prepared this [fiddle][2] to demonstrate the behaviour. ``` <head> <style> body { /* Prevent the user from selecting text in the example */ user-select: none; } #container { width: 400px; height: 20px; background: blueviolet; padding: 10px; } #draggable { text-align: center; background: white; } .dragging { width: 422px; color: red; font-weight: 700; } </style> </head> <body> <div id="container"> <div id="draggable" draggable="true">Drag me</div> </div> <div class="dropzone"></div> <script> const source = document.getElementById("draggable"); source.addEventListener("dragstart", (event) => { event.target.classList.add("dragging"); }); source.addEventListener("dragend", (event) => { event.target.classList.remove("dragging"); }); </script> </body> ``` However the result is not sufficient. In my task I need the default element to persist its appearance and change only the dragged minimised version of it - ideally it should be narrower and show a little different content than the default element. If you knew any source, where this task is resolved (anyhow), I'd be glad for your reply. [1]: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dragstart_event [2]: https://jsfiddle.net/xL2wy0uv/2/
Change the appearance of dragged element
|javascript|drag|webapi|
Friends, I have implemented the extension of WP_list_table PHP class that I use to render my table in the Wordpress site admin plugin. In one of the columns of the WP_list_table I use textarea field for user notes. function column_notes($item){ return sprintf( '<span><textarea id="%s" ></textarea>', $item['ID'] ); } When the user adds some text in the text area, I save it with javascript and jquery to a WP database table column 'notes'. If I read from the mysql the contents of the 'notes' column with PHP how can I display them on the textarea? In the WP_list_table I use function prepare_items to prepare data for the table. For each item that I want to display in table row I define data array: $data[] =array( 'ID' => $order->id, 'date_created' => wc_format_datetime($order->get_date_created()), 'total'=> wc_price($order->total), 'notes'=> htmlspecialchars($wpdb->get_var("SELECT notes FROM orders WHERE id = '$order->id'")) ); Although the query returns the contents of the notes field from DB, its not displayed on the text area. Is it possible to do that with php, or do I need javascript/jquery here again?
WP_list_table display text on column with textarea
|javascript|php|html|jquery|wordpress|
I'm using React, and in the file structure, I've defined a global CSS where I apply a reset and basic body styles, and within the root, I define some variables. I apply this CSS in the `main.jsx` file, which serves as the parent component for the entire project. I'm having issues using autocomplete to get the names of these variables in other CSS files in the project. For example, I have the `Header.jsx` component within the components folder and its style file `Header.module.css`. In this file, I can't use autocomplete with the variable names from the globals.css file. I've tried using the HTML CSS Support extension by ecmel, and it didn't work.
in website shop2game.com I want to make request to add redeem code this website protected by datadome protection system when I want to send request need x-datadome-client session I want to just login with player_id from garena and get session and after that I want to insert redeem code and my customer and buy with redeem code please help me how I can send request when datadome is active and I use 2captcha for bypass captcha system anybody can to analyses this website and show me a way to get login name session after that insert redeem code to garena server for active my user request thank you for help I will make up for it I have used python selenium for getting session data with this code ``` async def spoof_webdriver(): driver = None try: options = uc.ChromeOptions() options.add_argument("--headless") user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36" options.add_argument(f'user-agent={user_agent}') #options.add_argument('user-data-dir=C:/Users/mahdi/AppData/Local/Google/Chrome/User Data/Default') driver = uc.Chrome(options=options) #driver.delete_all_cookies() driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined});") driver.get('https://shop2game.com/?language=en&app=100067') #wait = WebDriverWait(driver, 30) print("website is opnening .... ") time.sleep(20) print("website is opne") driver.save_screenshot('screenshot.png') cookies = driver.get_cookies() return cookies finally: if driver: try: driver.quit() except Exception as e: print(f"Error closing browser: {e}") print("Browser closed") # اجرای حلقه asyncio cookies = asyncio.run(spoof_webdriver()) # URL ارسال فرم لاگین login_url = 'https://shop2game.com/api/auth/player_id_login' # داده‌های فرم لاگین data = {"app_id":100067,"login_id":"34234324234","app_server_id":0} # ارسال یک درخواست اولیه # ارسال درخواست POST به سرور برای لاگین cookies_dict = {cookie['name']: cookie['value'] for cookie in cookies} print(cookies_dict) session_key = cookies_dict.get('session_key') print("sessiont key :" + str(session_key)) datadom = cookies_dict['datadome'] response = requests.post(login_url, json=data,cookies=cookies_dict) response.close() print(str(response)) pay_url = 'https://shop2game.com/api/shop/pay/init?language=en®ion=ME' data = { "service": "pc", "app_id": 100067, "packed_role_id": 0, "channel_id": 299999, "channel_data": { "card_password": "123123123123", "card_no": "123123123123", "friend_username": None }, "experiment": {}, "revamp_experiment": { "session_id": session_key, # اینجا session_key را استفاده می‌کنیم. "group": "control2" } } response = requests.post(login_url, json=data,cookies=cookies_dict) print ("response2 = "+ str(response)) ``` but response is datadome code error
make automation with selenium in python datadom bypass
|python|api|selenium-webdriver|
null
New to salesforce and Apex, i got a home task which im asked to create 20000 caseComments on a Case after insert. caseComments and Case are different objects but they are associated. i thought its going to be simple but the problems starts when reaching the DML limits of 10k per transaction. I Tried to change the Inner and outer loops in my batch but nothing works, I'm able to create 9800 new CaseComments and if i cannot increase the Loop values even by 1 cause it will pass the limit. The Trigger: ```java trigger CommentsOnCaseInsert on Case (after insert) { System.debug('Triggered'); if (Trigger.isAfter && Trigger.isInsert && Trigger.new.size() == 1) { CreateCaseCommentsBatch batch = new CreateCaseCommentsBatch(Trigger.new[0].Id); Database.executeBatch(batch); } } ``` The Batch job : ```java public class CreateCaseCommentsBatch implements Database.Batchable<SObject> { private Id caseId; public CreateCaseCommentsBatch(Id caseId) { this.caseId = caseId; } public Database.QueryLocator start(Database.BatchableContext context) { return Database.getQueryLocator([SELECT Id FROM Case WHERE Id = :caseId]); } // Execute method to create case comments public void execute(Database.BatchableContext context, List<Case> scope) { List<CaseComment> caseCommentsToInsert = new List<CaseComment>(); for (Integer i = 0; i < 150; i++) { for (Integer j = 0; j < 66; j++) { Integer commentNumber = i * 66 + j + 1; CaseComment caseComment = new CaseComment( ParentId = caseId, CommentBody = 'Dummy Comment ' + commentNumber + ' - Of Case: ' + caseId ); caseCommentsToInsert.add(caseComment); } insert caseCommentsToInsert; caseCommentsToInsert.clear(); } } // Finish method `your text` public void finish(Database.BatchableContext context) { } } ```
int arr[] = {10,20,30,40}; arr | 10 | 20 | 30 | 40 index | 0 | 1 | 2 | 3 pointer | @+0 | @+1 | @+2 | @+3 int *p1 = arr; int *p2 = &arr[2]; this mean, p1 points to the first address of the arr which is @ and p2 points to the third element of arr which is @+2 printf("%d",p2-p1); p2-p1 => @+2 - @ = 2 so output is 2
The problem is that the original image is not saved correctly as png. When you see the chessboard pattern it's likely that you have downloaded it wrongly. try to import the image in something like Figma and see if it actually has a transparent background.
**Follow the steps given below** **STEP 1 : Replace your foreach loop with the following foreach loop** <?php foreach($users_list as $users) { $emp_full_name = $users['first_name'] . ' ' . $users['middle_name'] . ' ' . $users['last_name']; ?> <tr> <td><?php echo $users['id']; ?></td> <td><?php echo $users['first_name'] . ' ' . $users['middle_name'] . ' ' . $users['last_name']; ?></td> <td><a class="ptoModal" href="javascript:void(0)" data-toggle="modal" onclick="showModal('<?php echo $emp_full_name ?>','<?php echo $users['id']?>')"><i class="fa fa-plus" title="Add PTO"></i> Set up PTO</a> </td> <?php }?> **STEP 2 : Using the following script to call the modal** function showModal(emp_full_name,userID){ document.getElementById("ModalLabel").innerText = 'Set up PTO for '+emp_full_name; document.getElementById("user_id").value = userID; $('#ptoModal').modal('show'); } **STEP 3 : In your modal, replace the title line with the line given below.** <h5 class="modal-title" id="ModalLabel"></h5> **STEP 4 : In your modal, replace the user_id hidden input field line with the line given below.** <input type="hidden" name="user_id" id="user_id" class="user_id"> **Notes** : **I assumed you are using Jquery and Bootstrap version < 5**
I did everything I could, searched all the topics on stackoverflow, but no matter what I did, it didn't work. Please help me :) I'm running my .net 8 project on docker with Jenkins When I looked at the status of the container with portainer, I saw that it had entered the exit state and when I looked at its logs, I got the following error. Error [enter image description here][1] Jenkins file: pipeline { agent any environment { DISABLE_AUTH = 'true' DB_ENGINE = 'sqlite' DOTNET_CLI_HOME = "/tmp/DOTNET_CLI_HOME" } stages { stage("verify tooling") { steps { sh ''' docker version docker info docker-compose version ''' } } stage('Prune Docker data') { steps { sh 'docker system prune -a --volumes -f' } } stage('Start container') { steps { sh 'docker-compose down' sh 'docker-compose build' sh 'docker-compose up -d' sh 'docker-compose ps' } } } } docker-compose file version: "3.8" services: blazorwebuitest: image: blazorwebuitest_ui build: context: . dockerfile: BlazorWebUI/Dockerfile volumes: blazorwebdb_volume: docker-compose.override.yml version: '3.8' services: blazorwebuitest: container_name: blazorwebuitest_ui environment: - ASPNETCORE_ENVIRONMENT=Development - ASPNETCORE_URLS=https://+:443;http://+:80 - ASPNETCORE_Kestrel__Certificates__Default__Password=TestL.31235 - ASPNETCORE_Kestrel__Certificates__Default__Path=/https/aspnetapp1.pfx - DatabaseSettings:ConnectionString=mongodb://blazorwebdb:27020 ports: - "5040:80" - "5042:443" depends_on: - blazorwebdb volumes: - ./https/aspnetapp1.pfx:/https/aspnetapp1.pfx:ro blazorwebdb: container_name: blazorwebdb restart: always ports: - "27020:27017" volumes: - blazorwebdb_volume:/data/db Dockerfile FROM mcr.microsoft.com/dotnet/aspnet:8.0-jammy AS base USER root WORKDIR /app RUN chmod 777 -R /app EXPOSE 80 EXPOSE 443 FROM mcr.microsoft.com/dotnet/sdk:8.0-jammy AS build RUN dotnet dev-certs https --clean RUN dotnet dev-certs https ARG BUILD_CONFIGURATION=Release WORKDIR /src COPY ["BlazorWebUI/BlazorWebUI.csproj", "BlazorWebUI/"] RUN dotnet restore "./BlazorWebUI/BlazorWebUI.csproj" COPY . . WORKDIR "/src/BlazorWebUI" RUN dotnet build "./BlazorWebUI.csproj" -c $BUILD_CONFIGURATION -o /app/build FROM build AS publish ARG BUILD_CONFIGURATION=Release RUN dotnet publish "./BlazorWebUI.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "BlazorWebUI.dll"] [1]: https://i.stack.imgur.com/tmEKB.png
null
The error "Property 'css' does not exist on type 'DetailedHTMLProps'" typically occurs when you're trying to use the css prop in a TypeScript project without properly setting up the types for your styling library. Here are some steps you can take to resolve this issue: Update Your TypeScript Configuration If you're using a library like Emotion or Styled Components, you need to include their types in your TypeScript configuration. For example, if you're using Emotion, you can add "@emotion/react" to the types array in your > tsconfig.json file: { "compilerOptions": { "types": ["@emotion/react"] } } Declare CSS Prop in a Type Declaration File You can declare the css prop in a type declaration file > (.d.ts) . This tells TypeScript that the css prop exists on all HTML elements. Here's an example of how to do this: import { CSSProp } from 'styled-components' declare module 'react' { interface HTMLAttributes<T> extends DOMAttributes<T> { css?: CSSProp; } } In this code, CSSProp is imported from styled-components, and the css prop is added to the HTMLAttributes interface from react. Reinstall Dependencies If you're still encountering the issue after updating your TypeScript configuration and declaring the css prop, you might need to reinstall your dependencies. You can do this by deleting your node_modules folder and running npm install or yarn install again. **Update Your TypeScript Version** If you're using the new JSX transform introduced in React 17, you might need to update your TypeScript version to 4.1 or later. This version of TypeScript includes support for the new JSX transform. By following these steps, you should be able to resolve the "Property 'css' does not exist on type 'DetailedHTMLProps'" error in your TypeScript project. If you continue to experience issues, please provide more details about your code and the context in which you're using the css prop, and I'll be happy to provide further assistance.
I want to use the FastText.NetWrapper library in my project. I imported the library and wrote the sample code, but after running it, I get the following error: ``` Unhandled exception. System.DllNotFoundException: Unable to load shared library 'fasttext' or one of its dependencies. In order to help diagnose loading problems, consider setting the DYLD_PRINT_LIBRARIES environment variable: dlopen(/Users/a/Desktop/Spell Corrector/MyMLNetProject/bin/Debug/net7.0/runtimes/osx-arm64/native/fasttext.dylib, 0x0001): tried: '/Users/a/Desktop/Spell Corrector/MyMLNetProject/bin/Debug/net7.0/runtimes/osx-arm64/native/fasttext.dylib' (no such file), '/System/Volumes/Preboot/Cryptexes/OS/Users/a/Desktop/Spell Corrector/MyMLNetProject/bin/Debug/net7.0/runtimes/osx-arm64/native/fasttext.dylib' (no such file), '/Users/a/Desktop/Spell Corrector/MyMLNetProject/bin/Debug/net7.0/runtimes/osx-arm64/native/fasttext.dylib' (no such file) ``` I'm sure I installed the library correctly.I'm posting a code for an example. ```cs using FastText.NetWrapper; using System; class Program { static void Main(string[] args) { using (var classifier = new FastTextWrapper()) { classifier.Supervised("train.txt", "model"); string testText = "Bu bir test metnidir."; var result = classifier.PredictSingle(testText); Console.WriteLine($"Tahmin edilen sınıf: {result.Label}"); Console.WriteLine($"Tahmin edilen olasılık: {result.Probability}"); } } } ``` Can someone help about this? I tried to train a model , it didn't work.
null
I'm using docker compose to create resources in aws and using `x-aws-cloudformation` extension to change somethings but I had to create a aws codepipeline with blue/green (to avoid down time) but looks like that `x-aws-cloudformation` extension haven't support to blue/green ... Tried to set the `DeploymentControler` to `CODE_DEPLOY` in ecs service but it fails. Well someone knows if is possible to set it in docker compose? I wouldn't like to do it manually or use CloudFormation. Thanks in advanced. I'm expecting to found a solution.
Is possible to force docker compose to create aws ecs service as blue/green?
|amazon-web-services|docker|docker-compose|amazon-ecs|blue-green-deployment|
null
Something like this(but this is not a generic one) type State = { one?: string; two?: { three?: { four?: string; five?: string; six: number }, seven: string } } type FourRequiredState = { two: { three: { four: string } } } & State //Now we can't skip four const fourRequiredState: FourRequiredState = { two: { three: { four: '4', six: 0 }, seven: '7' } }
There does not appear to be any way around the issue until Google fixes it. As you can see from Google's Issue Tracker in the link shared by darrelltw (Updated link as the issues have now been consolidated: https://issuetracker.google.com/issues/326802543), it has been impacting users in many places around the world. In the interest of adding some more information (as many people are trying to get answers), I am including the following link providing Google's confirmation of the issue here: https://support.cloud.google.com/portal/system-status?product=WORKSPACE. Screenshot from the above site: [![Screenshot][1]][1] **Update:** Here in my region of the USA, my Apps Script projects are now currently accessible for the first time this morning. I have not tested them yet. [1]: https://i.stack.imgur.com/C1Fnc.png
{"OriginalQuestionIds":[45651029],"Voters":[{"Id":12046409,"DisplayName":"JohanC","BindingReason":{"GoldTagBadge":"python"}}]}
I'm using docker compose to create resources in aws and using `x-aws-cloudformation` extension to change somethings but I had to create a aws codepipeline with blue/green (to avoid down time) but looks like that `x-aws-cloudformation` extension haven't support to blue/green ... Tried to set the `DeploymentControler` to `CODE_DEPLOY` in ecs service but it fails. Well someone knows if is possible to set it in docker compose? I wouldn't like to do it manually or use CloudFormation. Thanks in advanced.
I have an issue with regard to sympy and jupyter notebooks. Whenever i display any fraction it automatically formats the fraction into a decimal an image of an example is attached to the post ![example of issue](https://i.stack.imgur.com/ao99X.png) is there a way to make sympy display the fraction instead of the decimal?
I have a working code use CGI qw(:standard); print header( -type => "text/html; charset='utf-8'"); print start_html( -title => 'Простой пример', -bgcolor => "#cccccc", -encoding => "utf-8" );
As per the title, you need to set up a secret containing the username and access tokens for accessing images in certain repos but the documentation never specifies the specific key names that need to be set in the AWS secrets manager secret. So I've guessed at username and I've tried access token, access-token, access_token and token. None seem to have worked so far so I'm looking for an answer to what the key names are for both ghcr.io and dockerhub (if they are different). I'm implementating via Terraform but that makes no difference here, and the highly suspect docs are [here](https://docs.aws.amazon.com/AmazonECR/latest/userguide/pull-through-cache-creating-rule.html). I do have public repos like the k8s one working already. Also, the required permissions for the access token are never specified and I'm suspecting that accessing a public ghcr.io image, like those published by keda are maybe not supported by the pull through cache (if anyone has got this set up I'd be interested as to how). Tried a lucky dip of potential key names. Endless Google searches and searches across YouTube videos without luck so far.
Configuring secret for ECR pull through cache for dockerhub or github cr docs don't specify the valid key names
|amazon-ecr|
null
The `instance` attribute of `ModelForm` is instantiated in `get_form_kwargs()` defined in `ModelFormMixin` For detailed explanation see below : The `UpdateView` view inherits `SingleObjectTemplateResponseMixin, BaseUpdateView` `BaseUpdateView` further inherits `ModelFormMixin` and `ProcessFormView` It also defines the `get` and `post` methods that are called via dispatch These `get` and `post` methods sets the `object` attribute as the current model object. Below is the code snippet from django docs : class BaseUpdateView(ModelFormMixin, ProcessFormView): """ Base view for updating an existing object. Using this base class requires subclassing to provide a response mixin. """ def get(self, request, *args, **kwargs): self.object = self.get_object() return super(BaseUpdateView, self).get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = self.get_object() return super(BaseUpdateView, self).post(request, *args, **kwargs) The get and post methods also call the parent's get and post method i.e. get and post defined in `ProcessFormView` **During GET request** The `get` method defined in `ProcessFormView` calls the `get_context_data()` overridden under `FormMixin` which further invokes `get_form()` to return an instance of the form to be used in the view. def get_context_data(self, **kwargs): """ Insert the form into the context dict. """ if 'form' not in kwargs: kwargs['form'] = self.get_form() return super(FormMixin, self).get_context_data(**kwargs) `get_form()` calls `get_form_kwargs()` which lies in `ModelFormMixin` as well as `FormMixin` but since the `ModelFormMixin` inherits from `FormMixin`, the method defined in `ModelFormMixin` overrides the one defined in `FormMixin`. This `get_form_kwargs()` method first calls the super/parent's method and then sets the `instance` attribute of the form to the current model object i.e `self.object` (or simply `object`). Code snippet from the docs below : def get_form_kwargs(self): #defined in ModelFormMixin class """ Returns the keyword arguments for instantiating the form. """ kwargs = super(ModelFormMixin, self).get_form_kwargs() if hasattr(self, 'object'): kwargs.update({'instance': self.object}) return kwargs The form is then rendered using the model object's attributes **During POST request :** As mentioned earlier (see first code snippet), just like `get()`, `post()` method also sets the `object` attribute to the current model object i.e. `self.object=self.get_object()`. ( get_object() is inherited from `SingleObjectMixin` class ) It then calls `post` method of `ProcessFormView`i.e. parent class which creates the instance of `form` using `get_form()` method. (Just like get_context_method was doing in case of `get` request) `get_form()` calls the `get_form_kwargs` which further sets the `instance` attribute of the form to the `self.object` instantiated in first `post` method call. Code snippet below : class ProcessFormView(View): """ A mixin that renders a form on GET and processes it on POST. """ def get(self, request, *args, **kwargs): """ Handles GET requests and instantiates a blank version of the form. """ return self.render_to_response(self.get_context_data()) def post(self, request, *args, **kwargs): """ Handles POST requests, instantiating a form instance with the passed POST variables and then checked for validity. """ form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) # PUT is a valid HTTP verb for creating (with a known URL) or editing an # object, note that browsers only support POST for now. def put(self, *args, **kwargs): return self.post(*args, **kwargs) Next, the form is validated against basic constraints and this is done by calling `form.is_valid()` method which is inherited from `BaseForm` class. This is a very important step because at this point, the `instance` object's attributes are updated to the data POSTed in the form. This all is achieved via following stack of calls : `form.is_valid()` calls -> `errors` property -> which calls `full_clean()` -> `_clean_fields()` -> `_clean_form()` -> `_post_clean()` `_post_clean()` constructs the `instance` from `POST` data by calling `construct_instance_method` To understand these functions better read the `BaseForm` class for `is_valid()` [here](https://github.com/django/django/blob/stable/1.11.x/django/forms/forms.py#L65) and `BaseModelForm` class for `_post_clean()` [here](https://github.com/django/django/blob/stable/1.11.x/django/forms/models.py#L289)
I am trying to figure out the best way to loop multiple array values together. Sample arrays: ``` a = (1 2 3 4) b = ('A' 'B' 'C') c = ('x' 'y') ``` Now I want to create a combination of commands like following. ``` command A x 1 command A y 1 command A x 2 command A y 2 command A X 3 .... command C x 3 command C y 3 command C x 4 command C y 4 ``` Please help. I was trying with the following, but not sure if that works. Please note, I am a beginner in coding/bash, facing similar requirement at work. ``` #!/bin/bash a = (1 2 3 4) b = ('A' 'B' 'C') c = ('x' 'y') for aa in a; do for bb in b; do for cc in c; do command $(aa[@]) $(bb[@]) $(cc[@]) done done done ```
Hello i have a problem using lower_bound to find element in array by 2 parameters. I have a ``` struct person{ public: person(const std::string CITY, const std::string ADDRESS, const std::string REGION, const unsigned ID, std::string PARENT = ""): m_city(CITY), m_addr(ADDRESS), m_region(REGION), m_id(ID), m_parent(PARENT) {} std::string m_city; std::string m_addr; std::string m_region; unsigned m_id; std::string m_parent; }; ``` from this structs there is a `std::vector<person>` how can i find exact person using lower_bound in vector which is already sorted by Region? my approach works the worst way. Most of the time it doesn't find anything. ``` auto iteratorRegion = findPerson(m_sortedByRegion, candidatePerson); std::vector<person>::iterator findPerson(std::vector<Person>& ARRAY, const person& candidatePerson) const { auto iterator = std::lower_bound(ARRAY.begin(), ARRAY.end(), candidatePerson, cityAdressComparator); if (iterator != ARRAY.end() && iterator->m_city == candidatePerson.m_city && iterator->m_addr == candidatePerson.m_addr) { return iterator; } auto iterator2 = std::lower_bound(ARRAY.begin(), ARRAY.end(), candidatePerson, regionIDComparator); if (iterator2 != ARRAY.end() && iterator2->m_region == candidatePerson.m_region && iterator2->m_id == candidatePerson.m_id) { return iterator2; } return ARRAY.end(); } ``` all comparators looks like this inside ``` if (!(realEstateL.m_city == realEstateR.m_city)) { return realEstateL.m_city < realEstateR.m_city; } return realEstateL.m_addr < realEstateR.m_addr; ```
.NET 8-Linux Docker Permission denied
|.net|docker|jenkins|
Most likely the problem is that the original image is not saved correctly as png. When you see the chessboard pattern it's likely that you have downloaded it wrongly. Try to import the image in something like Figma and see if it actually has a transparent background.
I'm trying to use a custom API provided by a client, its a login authentication api and when I test the url on tools it works fine but when I call it in my code I receive this error: >Access to XMLHttpRequest at 'api url' from origin 'http://localhost:5174' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource "A cross-origin resource sharing (CORS) request was blocked because of invalid or missing response headers of the request or the associated preflight request ." I have tried using chrome extensions but its the same issue, I've never worked with a custom apis before so I'm not sure if its an issue from the server side, API provider or my code. How to check?
null
|api|cors|postman|
The way to do this is actually easy, but requires some manual steps. Here are the steps for Linux: 1. You create a network: ``` $ docker network create docker_airgap_network bb7645298697d420dab8eaf1fd4738fccceb8230c783aa93ebe76abec6c40f41 ``` 2. Fetch the created bridge interface name: ``` $ export IFACE=br-$(docker network inspect docker_airgap_network | jq -r '.[0].Id | .[:12]') The above will output something like: br-bb7645298697 ``` 3. Verify this interface is actually there: ``` $ ip -br l | grep -i "$IFACE" br-bb7645298697 DOWN 01:43:e3:a2:5f:9d <BROADCAST,MULTICAST,DOWN,LOWER_UP> ``` 4. Add an `iptables` rule to drop traffic outside the docker subnet (this would allow communication between all containers; you might want to adjust this just to the `docker_airgap_network` subnet if you need to be more precise) ``` $ iptables -I DOCKER-USER -i $IFACE ! -d 172.0.0.0/8 -j DROP $ iptables -nvL DOCKER-USER Chain DOCKER-USER (1 references) pkts bytes target prot opt in out source destination 48 4032 DROP 0 -- br-bb7645298697 * 0.0.0.0/0 !172.0.0.0/8 406 34104 0 -- * * 0.0.0.0/0 0.0.0.0/0 430 36120 RETURN 0 -- * * 0.0.0.0/0 0.0.0.0/0 ``` 5. Bring up your `docker-compose.yml` file to life with `docker-compose up`: ``` version: '3' services: service1: image: alpine command: /bin/sh tty: true networks: - docker_airgap_network service2: image: alpine command: /bin/sh tty: true networks: - docker_airgap_network networks: docker_airgap_network: external: true ``` 6. Test ``` $ docker-compose exec -it service1 ping -c 1 -W 1 google.com PING google.com (142.250.184.142): 56 data bytes --- google.com ping statistics --- 1 packets transmitted, 0 packets received, 100% packet loss $ docker-compose exec -it service1 ping -c 1 -W 1 service2 PING service2 (172.26.0.2): 56 data bytes 64 bytes from 172.26.0.2: seq=0 ttl=64 time=0.077 ms --- service2 ping statistics --- 1 packets transmitted, 1 packets received, 0% packet loss round-trip min/avg/max = 0.077/0.077/0.077 ms $ docker-compose exec -it service2 ping -c 1 -W 1 google.com PING google.com (142.250.184.142): 56 data bytes --- google.com ping statistics --- 1 packets transmitted, 0 packets received, 100% packet loss $ docker-compose exec -it service2 ping -c 1 -W 1 service1 PING service1 (172.26.0.3): 56 data bytes 64 bytes from 172.26.0.3: seq=0 ttl=64 time=0.054 ms --- service1 ping statistics --- 1 packets transmitted, 1 packets received, 0% packet loss round-trip min/avg/max = 0.054/0.054/0.054 ms ```
I have created a form in visual studio C# and am trying to assign a unique random category to each label (numbered from 1 to 9), but it seems that there are repeat values every time that I click the randomize button. I took the code from the Fisher-Yates shuffle, which should work as intended, what part am I missing that gives my labels non-unique values? See code below: public void button2_Click(object sender, EventArgs e) { List<String> unshuffledCategories = new List<String> { "History", "Geography", "Music", "Animals", "Logos", "Flags", "Food", "games", "Sports" }; List<String> shuffledCategories = new List<string>(); Random r = new Random(); var labels = new List<Label> { lblField1, lblField2, lblField3, lblField4, lblField5, lblField6, lblField7, lblField8, lblField9 }; for (int n = unshuffledCategories.Count; n > 0; --n) { int k = r.Next(n); String temp = unshuffledCategories[k]; shuffledCategories.Add(temp); } for (int i = 0; i < labels.Count; i++) { labels[i].Text = shuffledCategories[i]; } } Hope someone can help me out, much appreciated <3! I tried to create a form which pulls unique random elements from a string list I have created in C#, I was expecting it to provide random unique values, but values are nearly always repeated when I click the button to execute the code.
random unique list - not providing unique values in C#
|c#|random|unique|
null
ubuntu 22.04: ```bash sudo apt install gcc-12 ```
The Sockets Connector for Mule 4 provides a [Listener source][1]. That means that it can read messages from a socket to trigger the execution of a flow. Example: ``` lang-xml <sockets:listener-config name="Sockets_Listener_config"> <sockets:tcp-listener-connection host="localhost" port="8082" /> </sockets:listener-config> <flow name="SocketsFlow" > <sockets:listener config-ref="Sockets_Listener_config"/> <logger message="Message received from socket" level="INFO"/> </flow> ``` It does not provide a 'read' operation to use inside a flow. [1]: https://docs.mulesoft.com/sockets-connector/latest/sockets-documentation#listener
This is a **generic** version with **wrapSelectorWheel** and **onValueChange** parameters, that works with **all types of list**. [![Previews][1]][1] ListPicker: package com.inidamleader.ovtracker.util.compose import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.gestures.snapping.rememberSnapFlingBehavior import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.LocalTextStyle import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.rememberTextMeasurer import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.inidamleader.ovtracker.layer.ui.theme.OvTrackerTheme import com.inidamleader.ovtracker.util.compose.geometry.toDp import kotlinx.coroutines.flow.collectLatest import java.time.LocalDate import java.time.format.DateTimeFormatter import java.time.format.FormatStyle import java.util.Locale @OptIn(ExperimentalFoundationApi::class) @Composable fun <E> ListPicker( initialValue: E, list: ImmutableWrapper<List<E>>, modifier: Modifier = Modifier, wrapSelectorWheel: Boolean = false, format: E.() -> String = { this.toString() }, onValueChange: (E) -> Unit, outOfBoundsPageCount: Int = 1, textStyle: TextStyle = LocalTextStyle.current, verticalPadding: Dp = 16.dp, dividerColor: Color = MaterialTheme.colorScheme.outline, dividerThickness: Dp = 1.dp ) { val listSize = list.value.size val coercedOutOfBoundsPageCount = outOfBoundsPageCount.coerceIn(0..listSize / 2) val indexOfInitialValue = remember(key1 = list) { list.value.indexOf(initialValue).takeIf { it != -1 } ?: 0 } val visibleItemsCount = 1 + coercedOutOfBoundsPageCount * 2 val iteration = if (wrapSelectorWheel) remember(key1 = coercedOutOfBoundsPageCount, key2 = listSize) { (Int.MAX_VALUE - 2 * coercedOutOfBoundsPageCount) / listSize } else 1 val intervals = remember(key1 = coercedOutOfBoundsPageCount, key2 = iteration, key3 = listSize) { listOf( 0, coercedOutOfBoundsPageCount, coercedOutOfBoundsPageCount + iteration * listSize, coercedOutOfBoundsPageCount + iteration * listSize + coercedOutOfBoundsPageCount, ) } val initialFirstVisibleItemIndex = remember( key1 = indexOfInitialValue, key2 = listSize, key3 = iteration, ) { indexOfInitialValue + (listSize * (iteration / 2)) } val lazyListState = rememberLazyListState(initialFirstVisibleItemIndex = initialFirstVisibleItemIndex) LaunchedEffect(key1 = Unit) { snapshotFlow { lazyListState.firstVisibleItemIndex } .collectLatest { onValueChange(list.value[it % listSize]) } } val density = LocalDensity.current val itemHeight = run { val textMeasurer = rememberTextMeasurer() remember(textStyle, textMeasurer, verticalPadding, density) { density.toDp( textMeasurer.measure( text = "", style = textStyle, ).size.height ) + verticalPadding * 2 } } Box(modifier = modifier) { LazyColumn( state = lazyListState, flingBehavior = rememberSnapFlingBehavior(lazyListState = lazyListState), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .fillMaxWidth() .height(itemHeight * visibleItemsCount) .fadingEdge( brush = remember { Brush.verticalGradient( 0F to Color.Transparent, 0.5F to Color.Black, 1F to Color.Transparent ) }, ), ) { items( count = intervals.last(), key = { it }, ) { index -> when (index) { in intervals[0]..<intervals[1] -> Text( text = if (wrapSelectorWheel) list.value[(index - coercedOutOfBoundsPageCount + listSize) % listSize].format() else "", maxLines = 1, overflow = TextOverflow.Ellipsis, style = textStyle, modifier = Modifier.padding(vertical = verticalPadding) ) in intervals[1]..<intervals[2] -> Text( text = list.value[(index - coercedOutOfBoundsPageCount) % listSize].format(), maxLines = 1, overflow = TextOverflow.Ellipsis, style = textStyle, modifier = Modifier.padding(vertical = verticalPadding) ) in intervals[2]..<intervals[3] -> Text( text = if (wrapSelectorWheel) list.value[(index - coercedOutOfBoundsPageCount) % listSize].format() else "", maxLines = 1, overflow = TextOverflow.Ellipsis, style = textStyle, modifier = Modifier.padding(vertical = verticalPadding), ) } } } HorizontalDivider( modifier = Modifier.offset(y = itemHeight * coercedOutOfBoundsPageCount - dividerThickness / 2), thickness = dividerThickness, color = dividerColor, ) HorizontalDivider( modifier = Modifier.offset(y = itemHeight * (coercedOutOfBoundsPageCount + 1) - dividerThickness / 2), thickness = dividerThickness, color = dividerColor, ) } } @Preview(widthDp = 100) @Composable fun PreviewListPicker1() { OvTrackerTheme { Surface { var value by remember { mutableStateOf("5") } val values = remember { (1..10).map { it.toString() } } ListPicker( initialValue = value, list = values.toImmutableWrapper(), modifier = Modifier, onValueChange = { value = it }, textStyle = TextStyle(fontSize = 32.sp), verticalPadding = 8.dp, ) } } } @Preview(widthDp = 300) @Composable fun PreviewListPicker2() { OvTrackerTheme { Surface(color = MaterialTheme.colorScheme.primary) { var value by remember { mutableStateOf(LocalDate.now()) } val list = remember { buildList { repeat(10) { add(LocalDate.now().minusDays((it - 5).toLong())) } } } ListPicker( initialValue = value, list = list.toImmutableWrapper(), modifier = Modifier, format = { format( DateTimeFormatter .ofLocalizedDate(FormatStyle.MEDIUM) .withLocale(Locale.getDefault()), ) }, wrapSelectorWheel = true, onValueChange = { value = it }, textStyle = TextStyle(fontSize = 32.sp), verticalPadding = 8.dp, ) } } } @Preview(widthDp = 100) @Composable fun PreviewListPicker3() { OvTrackerTheme { Surface(color = MaterialTheme.colorScheme.tertiary) { var value by remember { mutableStateOf("5") } val list = remember { (1..10).map { it.toString() } } ListPicker( initialValue = value, list = list.toImmutableWrapper(), modifier = Modifier, onValueChange = { value = it }, outOfBoundsPageCount = 2, textStyle = TextStyle(fontSize = 32.sp), verticalPadding = 8.dp, ) } } } DensityExt.kt: package com.inidamleader.ovtracker.util.compose.geometry import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.geometry.isSpecified import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.isSpecified // DP fun Density.toSp(dp: Dp): TextUnit = dp.toSp() fun Density.toPx(dp: Dp): Float = dp.toPx() fun Density.roundToPx(dp: Dp): Int = dp.roundToPx() // TEXT UNIT fun Density.toDp(sp: TextUnit): Dp = sp.toDp() fun Density.toPx(sp: TextUnit): Float = sp.toPx() fun Density.roundToPx(sp: TextUnit): Int = sp.roundToPx() // FLOAT fun Density.toDp(px: Float): Dp = px.toDp() fun Density.toSp(px: Float): TextUnit = px.toSp() // INT fun Density.toDp(px: Int): Dp = px.toDp() fun Density.toSp(px: Int): TextUnit = px.toSp() // SIZE fun Density.toIntSize(dpSize: DpSize): IntSize = IntSize(dpSize.width.roundToPx(), dpSize.height.roundToPx()) fun Density.toSize(dpSize: DpSize): Size = if (dpSize.isSpecified) Size(dpSize.width.toPx(), dpSize.height.toPx()) else Size.Unspecified fun Density.toDpSize(size: Size): DpSize = if (size.isSpecified) DpSize(size.width.toDp(), size.height.toDp()) else DpSize.Unspecified fun Density.toDpSize(intSize: IntSize): DpSize = DpSize(intSize.width.toDp(), intSize.height.toDp()) // OFFSET fun Density.toIntOffset(dpOffset: DpOffset): IntOffset = IntOffset(dpOffset.x.roundToPx(), dpOffset.y.roundToPx()) fun Density.toOffset(dpOffset: DpOffset): Offset = if (dpOffset.isSpecified) Offset(dpOffset.x.toPx(), dpOffset.y.toPx()) else Offset.Unspecified fun Density.toDpOffset(offset: Offset): DpOffset = if (offset.isSpecified) DpOffset(offset.x.toDp(), offset.y.toDp()) else DpOffset.Unspecified fun Density.toDpOffset(intOffset: IntOffset): DpOffset = DpOffset(intOffset.x.toDp(), intOffset.y.toDp()) ImmutableWrapper.kt: package com.inidamleader.ovtracker.util.compose import androidx.compose.runtime.Immutable import kotlin.reflect.KProperty @Immutable data class ImmutableWrapper<T>(val value: T) fun <T> T.toImmutableWrapper() = ImmutableWrapper(this) operator fun <T> ImmutableWrapper<T>.getValue(thisRef: Any?, property: KProperty<*>) = value ModifierExt: @Stable fun Modifier.fadingEdge(brush: Brush) = this .graphicsLayer(compositingStrategy = CompositingStrategy.Offscreen) .drawWithContent { drawContent() drawRect(brush = brush, blendMode = BlendMode.DstIn) } [1]: https://i.stack.imgur.com/K9eNH.png
For new versions of vscode: Open *Settings* (<kbd>Ctrl</kbd>+<kbd>,</kbd> or <kbd>Ctrl</kbd>+<kbd>⌘</kbd>), search for "autoClosingBrackets" and select "never" from the dropdown. Or, for users who prefer to configure the settings via text editor, [open the settings file][1], `settings.json` and add: "editor.autoClosingBrackets": "never" You can also do this in a language-specific way by "[javascript]": { "editor.autoClosingBrackets": "never" } `"always"`, `"languageDefined"`, and `"beforeWhitespace"` are the new additional options. [![vscode curly braces settings][2]][2] ----------------- **[Previous, now inaccurate, setting.]** > // Controls if the editor should automatically close brackets after opening them "editor.autoClosingBrackets": false, [1]: https://stackoverflow.com/a/65909052/332936 [2]: https://i.stack.imgur.com/lhyO2.png
c++ using std::lower_bound to find element in array by 2 parameters
|c++|arrays|sorting|comparator|lower-bound|
null
You can try something like this: ret, frame = cam.read() lower = np.array([0, 50, 50]) high = np.array([5, 255, 255]) lower2 = np.array([170, 50, 50]) high2 = np.array([180, 255, 255]) first = cv.inRange(hsv, lower, high) second = cv.inRange(hsv, lower2, high2) both = first + second img = cv.bitwise_and(frame, frame, mask=both) the `both` mask will contain the mask for both the colors.
I am trying to get hold of a tab item that is selected using pywinauto. I am not able to get the correct property which is best to identify that element. here's a sample code i am using to get to the list of tab items. here's a list of ``` app = Application(backend = "uia").start(app_path, timeout=10) dlg = app.WindowTitle tabs = dlg.child_window(title = "somet_title", control_type = "Tab").children() for tab in tabs: print(i.is_enabled()) app.kill() ``` i don't think is_enabled() is correct because it results in true for all tabs. but only of them is selected. Please tell me how i should proceed here? Also let me know what else do i need to share?
Locate a tab item from list of tabs that is selected using pywinauto