instruction
stringlengths
0
30k
null
I have installed firebase version 8.6.5 using `npm install firebase` . But I wish to downgrade firebase to version 7.16.1 due to some code compatibility.
How can I downgrade firebase version?
I had been made a custom auth server wiht `org.springframework.security:spring-security-oauth2-authorization-server:1.2.2` and `spring boot 3.x`. And I tried to make a server like documents. but there was a problem. ``` @Configuration @EnableWebSecurity public class SecurityCon { @Bean @Order(1) public SecurityFilterChain authorizationServerSecurityFilterChain( HttpSecurity http) throws Exception { OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http); http.getConfigurer( OAuth2AuthorizationServerConfigurer.class) .oidc( oidc -> oidc .providerConfigurationEndpoint( provider -> provider .providerConfigurationCustomizer( config->config .issuer( "http://localhost:8000" ) .userInfoEndpoint( "/user" ) .authorizationEndpoint( "/login/oauth2/oidc-client" ) ) ) .userInfoEndpoint( userinfo -> userinfo.authenticationProvider( new AuthenticationProvider() { @Override public Authentication authenticate( Authentication authentication ) throws AuthenticationException { return null; } @Override public boolean supports( Class< ? > authentication ) { return false; } } ) )); // Enable OpenID Connect 1.0 return http.build(); } @Bean @Order(2) public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests((authorize) -> authorize .anyRequest().permitAll() ) .csrf( httpSecurityCsrfConfigurer -> httpSecurityCsrfConfigurer.disable()); // Form login handles the redirect to the login page from the // authorization server filter chain // .formLogin(Customizer.withDefaults()); return http.build(); } @Bean public UserDetailsService userDetailsService() { UserDetails userDetails = User.withDefaultPasswordEncoder() .username("user") .password("user") .roles("USER") .build(); return new InMemoryUserDetailsManager(userDetails); } @Bean public RegisteredClientRepository registeredClientRepository() { RegisteredClient oidcClient = RegisteredClient.withId( UUID.randomUUID().toString()) .clientId("oidc-client") .clientSecret("{noop}secret") .scope( OidcScopes.OPENID ) // .clientAuthenticationMethod( ClientAuthenticationMethod.CLIENT_SECRET_BASIC) .authorizationGrantType( AuthorizationGrantType.AUTHORIZATION_CODE) .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN) .redirectUri("http://127.0.0.1:8000/login/oauth2/code/oidc-client") .postLogoutRedirectUri("http://127.0.0.1:8000/") .clientSettings( ClientSettings.builder().requireAuthorizationConsent(true).build()) .build(); return new InMemoryRegisteredClientRepository(oidcClient); } @Bean public JWKSource< SecurityContext > jwkSource() { KeyPair keyPair = generateRsaKey(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); RSAKey rsaKey = new RSAKey.Builder(publicKey) .privateKey(privateKey) .keyID(UUID.randomUUID().toString()) .build(); JWKSet jwkSet = new JWKSet(rsaKey); return new ImmutableJWKSet<>(jwkSet); } private static KeyPair generateRsaKey() { KeyPair keyPair; try { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(2048); keyPair = keyPairGenerator.generateKeyPair(); } catch (Exception ex) { throw new IllegalStateException(ex); } return keyPair; } @Bean public JwtDecoder jwtDecoder( JWKSource< SecurityContext > jwkSource) { return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource); } @Bean public AuthorizationServerSettings authorizationServerSettings() { return AuthorizationServerSettings.builder().build(); } } ``` I made a configuration. And I called `http://localhost:8000/oauth2/authorize?response_type=code&client_id=oidc-client&scope=openid&redirect_uri=http://127.0.0.1:8000/login/oauth2/code/oidc-client` url with GET Method. but Spring occurred error and this is my debug log. ``` 2024-03-13T14:50:18.625+09:00 DEBUG 77476 --- [nio-8000-exec-1] o.s.security.web.FilterChainProxy : Securing GET /oauth2/authorize?response_type=code&client_id=oidc-client&scope=openid&redirect_uri=http://127.0.0.1:8000/login/oauth2/code/oidc-client 2024-03-13T14:50:18.626+09:00 DEBUG 77476 --- [nio-8000-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Set SecurityContextHolder to anonymous SecurityContext 2024-03-13T14:50:18.629+09:00 DEBUG 77476 --- [nio-8000-exec-1] o.s.s.w.s.HttpSessionRequestCache : Saved request http://localhost:8000/oauth2/authorize?response_type=code&client_id=oidc-client&scope=openid&redirect_uri=http://127.0.0.1:8000/login/oauth2/code/oidc-client&continue to session 2024-03-13T14:50:18.629+09:00 DEBUG 77476 --- [nio-8000-exec-1] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using Or [Ant [pattern='/oauth2/token', POST], Ant [pattern='/oauth2/introspect', POST], Ant [pattern='/oauth2/revoke', POST], Ant [pattern='/oauth2/device_authorization', POST]] 2024-03-13T14:50:18.629+09:00 DEBUG 77476 --- [nio-8000-exec-1] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using Or [org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer$BearerTokenRequestMatcher@74a820bf, RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest], And [Not [MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@2dafae61, matchingMediaTypes=[text/html], useEquals=false, ignoredMediaTypes=[]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@2dafae61, matchingMediaTypes=[application/atom+xml, application/x-www-form-urlencoded, application/json, application/octet-stream, application/xml, multipart/form-data, text/xml], useEquals=false, ignoredMediaTypes=[*/*]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@2dafae61, matchingMediaTypes=[*/*], useEquals=true, ignoredMediaTypes=[]]] 2024-03-13T14:50:18.631+09:00 DEBUG 77476 --- [nio-8000-exec-1] s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using default entry point org.springframework.security.web.authentication.HttpStatusEntryPoint@1060c298 ``` so I tested one more things. did Oidc auth endpoint work well. I called http://localhost:8000/login/oauth2/oidc-client. but spring give me a 404 error. why didn't accept oidc custom config?? i apparently set custom config like this. ``` http.getConfigurer( OAuth2AuthorizationServerConfigurer.class) .oidc( oidc -> oidc .providerConfigurationEndpoint( provider -> provider .providerConfigurationCustomizer( config->config .issuer( "http://localhost:8000" ) .userInfoEndpoint( "/user" ) .authorizationEndpoint( "/login/oauth2/oidc-client" ) ) ) .userInfoEndpoint( userinfo -> userinfo.authenticationProvider( new AuthenticationProvider() { @Override public Authentication authenticate( Authentication authentication ) throws AuthenticationException { return null; } @Override public boolean supports( Class< ? > authentication ) { return false; } } ) )); // Enable OpenID Connect 1.0 return http.build(); ```
how to accept custom oauth2 and oidc authentication server?
|spring|spring-boot|spring-security|oauth-2.0|openid-connect|
``` T = TypeVar("T", bound=str) def foo(a: T, b: T) -> T: return a + b print(foo("1", "2")) ``` mypy: `error: Incompatible return value type (got "str", expected "T") [return-value]` I dont understand how to fix this problem(using bound).
mypy Incompatible return value type with TypeVar(bound=str)
|mypy|typing|
null
I am trying to perform a network meta-analysis. The network contains 3 subnetworks. Therefore I decided to use netmeta::discomb to perform an additive analysis. This worked without error in another project, but not with the new studies. My current dataset contains 9 studies over a total of 10 treatments (all two-armed, continuous outcome) . The data was transformed from the arm-based to the contrast-based design using netmeta::pairwise. When calling the method netmeta::discomb, the error appears that the dimensions of the edge-vertex incidence matrices B and C are non-conformable. I guess, the warning about the missing separator will later become a problem. The help says: *By default, the matrix C is calculated internally from treatment names.* Passing a C-matrix myself was also unsuccessful. I would like to be able to create a reasonable overview at the end, i.e. with `summary(m1.netmeta)`, `netgraph(m1.netmeta)` and `forest(m1.netmeta,...)`. If required, I can also provide the data and script from the previous project. Maybe it will help. The minimal code used is below. This is session info: R version 4.3.2 (2023-10-31 ucrt) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows 10 x64 (build 19045) Matrix products: default I appreciate any help and will be happy to answer any questions. ``` library(netmeta) df <- data.frame(study= c('study 1', 'study 1', 'study 2', 'study 2', 'study 3', 'study 3', 'study 4', 'study 4', 'study 5', 'study 5', 'study 6', 'study 6', 'study 7', 'study 7', 'study 8', 'study 8', 'study 9', 'study 9'), stud_ind= c(1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2), comparators= c(1, 2, 3, 2, 1, 2, 4, 2, 5, 0, 6, 2, 7, 2, 6, 2, 8, 9), n_probands= c(14, 14, 15, 15, 9, 9, 19, 19, 21, 21, 27, 27, 15, 15, 18, 19, 14, 11), mean= c(3.13, 3.47, 2.36, 3.61, 2.89, 2.78, 2.36, 2.36, 2.64, 5.00, 3.24, 3.28, 1.53, 1.53, 3.07, 2.89, 3.00, 3.30), sd= c(2.06, 1.74, 1.99, 1.95, 1.97, 1.29, 1.32, 1.32, 1.68, 2.75, 1.21, 1.17, 1.20, 1.20, 2.23, 2.56, 1.53, 1.52)) # long to wide + contrast based df_wide = df %>% pivot_wider(names_from=c(stud_ind), values_from=c(comparators, n_probands, mean, sd)) p1 <- pairwise(list(comparators_1, comparators_2), TE = list(mean_1, mean_2), seTE = list(sd_1, sd_2), data = df_wide, sm = "MD", reference.group = "2") # look at network nc1 <- netconnection( data=p1, sep.trts = ":", nchar.trts = 500, title = "", warn = FALSE, ) print(nc1) ################################# m1.netmeta <- discomb(TE = TE, seTE = seTE, treat1= treat1, treat2= treat2, studlab = study, data = p1, sm = "MD", fixed = FALSE, random = TRUE, reference.group = "2", details.chkmultiarm = FALSE, sep.trts = " vs. ") # results in error: # Error in B.matrix %*% C.matrix : non-conformable arguments # In addition: Warning message: # No treatment contains the component separator '+'. ################################# # try with 'own' C.matrix C <- rbind(c(1, 0, 0, 0, 0, 0, 0, 0, 0), # 0 c(0, 1, 0, 0, 0, 0, 0, 0, 0), # 1 c(0, 0, 1, 0, 0, 0, 0, 0, 0), # 2 c(0, 0, 0, 1, 0, 0, 0, 0, 0), # 3 c(0, 0, 0, 0, 1, 0, 0, 0, 0), # 4 c(0, 0, 0, 0, 0, 1, 0, 0, 0), # 5 c(0, 0, 0, 0, 0, 0, 1, 0, 0), # 6 c(0, 0, 0, 0, 0, 0, 0, 1, 0), # 8 c(0, 0, 0, 0, 0, 0, 0, 0, 1)) # 9 colnames(C)<-c("0","1","2","3","4","5","6","8","9") rownames(C)<-c("0","1","2","3","4","5","6","8","9") m2.netmeta <- discomb(TE = TE, seTE = seTE, treat1= treat1, treat2= treat2, studlab = study, data = p1, sm = "MD", fixed = FALSE, random = TRUE, reference.group = "2", details.chkmultiarm = FALSE, sep.trts = " vs. ", C.matrix = C) # results in error: # Error in B.matrix %*% C.matrix : non-conformable arguments # In addition: Warning message: # No treatment contains the component separator '+'. ```
I'm fairly new to .NET Core and I'm working on a mini project, an apartment booking website. I've already made my data models and data tables for the site. When I scaffold a new controller with Razor views, the create form just doesn't work when there is a foreign key in the table. The basic create for simple tables works. I tried everything, I gave ChatGPT all of my code and it still does not work. What am I doing wrong? There are 2 data tables `Apartments` and `Bookings`. Here are the 2 data classes which are needed in the form (they inherit their `ID` from `BaseEntity`): ``` using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; namespace Vendeghazak.Data { public class Booking : BaseEntity { public int GuestID { get; set; } public DateTime CheckInDate { get; set; } public DateTime CheckOutDate { get; set; } public string? Comment { get; set; } public string? Status { get; set; } public bool Cancelled { get; set; } [ForeignKey("ApartmentId")] public int ApartmentId { get; set; } public Apartment Apartment { get; set; } public int NumberOfPersons { get; set; } public int PersonsUnder18 { get; set; } public string BillingAddress { get; set; } public string BillingEmail { get; set;} } public class Apartment : BaseEntity { public string Name { get; set; } public int Capacity { get; set; } } public partial class BaseEntity { public int Id { get; set; } public DateTime DateCreated { get; set; } public DateTime DateModified { get; set; } } } ``` I tried removing the `Id` from the foreign key annotation, but it didn't help. When I submit the form, the `Apartments` subkey always be null and the `ModelState` is invalid because of that. There is a dropdown list for the apartments and I tried different methods to populate it correctly, without success. I also tried hard coding the ID value of the apartment into the view then manually assign it in the controller, but the `Apartments` subkey is always null after submission. What am I doing wrong?
Visual Studio scaffolded Create form does not work in ASP.NET Core 8 MVC
|asp.net-core-mvc|foreign-keys|visual-studio-2022|modelstate|asp.net-mvc-scaffolding|
As already noted - use `localStorage`. Gave you a working example, but it won't work on stackoverflow.com because of `allow-same-origin`: <!-- begin snippet: js hide: false console: true babel: false --> <!-- language: lang-js --> const langEls = document.querySelectorAll('.lang'); const textEl = document.querySelector('.text'); const chosenLanguage = localStorage.getItem('lang') || 'nl'; document.querySelector(`.language [data-lang="${chosenLanguage}"]`).classList.add('active') const i18n = { nl: { text: 'nl' }, en: { text: 'en' }, es: { text: 'es' }, id: { text: 'id' } }; textEl.textContent = i18n[chosenLanguage].text; langEls.forEach(el => { el.addEventListener('click', () => { const lang = el.dataset.lang; langEls.forEach(langEl => langEl.classList.remove('active')); el.classList.add('active'); textEl.textContent = i18n[lang].text; localStorage.setItem('lang', lang); }); }); <!-- language: lang-css --> :root { --secondary-color: #4978ff; } .language { background: #141414; text-align: center; padding: 60px 0 50px; } .language a { margin: 0; text-transform: uppercase; color: #fff; text-decoration: none; padding: 0 15px; font-weight: bold; background: #555656; font-size: 18px; } .language a.active { background: var(--secondary-color); } <!-- language: lang-html --> <p class="text"></p> <div class="language"> <div class="langWrap"> <a href="#" data-lang="nl" class="lang">NL</a> <a href="#" data-lang="en" class="lang">EN</a> <a href="#" data-lang="es" class="lang">ES</a> <a href="#" data-lang="id" class="lang">ID</a> </div> </div> <!-- end snippet -->
[pathlib][1] is perfect for this. [1]: https://docs.python.org/3/library/pathlib.html Code: from pathlib import Path files = [x.name for x in Path.cwd().glob("*.xls*")] Edit: In the off chance a file is named abc.xls.txt you can add a check. files = [x.name for x in Path.cwd().glob("*.xls*") if x.suffix in [".xlsx", ".xlsm", ".xlsb", ".xls"]]
Cannot resolve method 'requestLocationUpdates(String, int, int, LocationListener)' try { locationManager = (LocationManager) requireActivity().getSystemService(LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,3,locationListener); } catch (Exception e){ e.printStackTrace(); } when wrote this code it give me error why it happen I am not understand when I use the the dot after `locationManager` there are 9 function overloading and I used `.requestLocationUpdates(String provider,minTimeMs,minDistanceM,locationListner );` but still getting error please anyone help me. `.requestLocationUpdates(String provider,minTimeMs,minDistanceM,locationListner );` I am using right one still getting if iam wrong one use please tell me
|java|android|locationmanager|
const requestNotificationPermission = async () => { try { if (Platform.OS === 'android') { const granted = await PermissionsAndroid.request( PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS, ); console.log({granted}); if (granted === PermissionsAndroid.RESULTS.GRANTED) { console.log('Notification permission granted'); } else { console.log('Notification permission denied'); // Linking.openSettings(); } } } catch (error) { console.error('Error requesting notification permission:', error); } }; I have already included in AndroidManifest file <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> buildToolsVersion = "33.0.0" minSdkVersion = 21 compileSdkVersion = 33 targetSdkVersion = 33 googlePlayServicesVersion = "21.0.1" Running on Android 11 physical device I have checked many solutions but no luck. Thanks
I am using below code for POST_NOTIFICATIONS in a React Native app but every time it return never_ask_again
|react-native|notifications|
I'm working in DataBricks with Python/PySpark. I have several output columns that copy a single input column. One of the output columns is the lower-case version of the upper-case or mixed-case input column, which I need to rename this way before I drop it. Because I am also casting its type, I use the `withColumn()` command (rather than the `withColumnRenamed()` command). This works fine the first time but fails afterward. DataBricks/PySpark is a case-sensitive language, so this should work. What's wrong?
DataBricks PySpark withColumn() Fails After First Success
Why can I not increase my Java heap space?
null
The code below uses a **background callback** (dash) to retrieve a value. Every 3 seconds, `update_event(event, shared_value)` sets an `event` and define a `value`. In parallel, `listening_process(set_progress)` waits for the `event`. This seems to work nicely and the waiting time is low (say a few seconds). When the waiting time is below 1 second (say 500ms), `listening_process(set_progress)` is missing values. Is there a way for the **background callback** to refresh faster ? It looks like the server updates with a delay of a few hundred of ms, independently of the rate at which I set the `event`. [![enter image description here][1]][1] ``` import time from uuid import uuid4 import diskcache import dash_bootstrap_components as dbc from dash import Dash, html, DiskcacheManager, Input, Output from multiprocessing import Event, Value, Process from datetime import datetime import random # Background callbacks require a cache manager + a unique identifier launch_uid = uuid4() cache = diskcache.Cache("./cache") background_callback_manager = DiskcacheManager( cache, cache_by=[lambda: launch_uid], expire=60, ) # Creating an event event = Event() # Creating a shared value shared_value = Value('i', 0) # 'i' denotes an integer type # Updating the event # This will run in a different process using multiprocessing def update_event(event, shared_value): while True: event.set() with shared_value.get_lock(): # ensure safe access to shared value shared_value.value = random.randint(1, 100) # generate a random integer between 1 and 100 print("Updating event...", datetime.now().time(), "Shared value:", shared_value.value) time.sleep(3) app = Dash(__name__, background_callback_manager=background_callback_manager) app.layout = html.Div([ html.Button('Run Process', id='run-button'), dbc.Row(children=[ dbc.Col( children=[ # Component sets up the string with % progress html.P(None, id="progress-component") ] ), ] ), html.Div(id='output') ]) # Listening for the event and generating a random process def listening_process(set_progress): while True: event.wait() event.clear() print("Receiving event...", datetime.now().time()) with shared_value.get_lock(): # ensure safe access to shared value value = shared_value.value # read the shared value set_progress(value) @app.callback( [ Output('run-button', 'style', {'display': 'none'}), Output("progress-component", "children"), ], Input('run-button', 'n_clicks'), prevent_initial_call=True, background=True, running=[ (Output("run-button", "disabled"), True, False)], progress=[ Output("progress-component", "children"), ], ) def run_process(set_progress, n_clicks): if n_clicks is None: return False, None elif n_clicks > 0: p = Process(target=update_event, args=(event,shared_value)) p.start() listening_process(set_progress) return True, None if __name__ == '__main__': app.run(debug=True, port=8050) ``` EDIT : found a solution using `interval`. ``` @app.callback( [ Output('run-button', 'style', {'display': 'none'}), Output("progress-component", "children"), ], Input('run-button', 'n_clicks'), prevent_initial_call=True, interval= 100, #### **THIS IS NEW** background=True, running=[ (Output("run-button", "disabled"), True, False)], progress=[ Output("progress-component", "children"), ], ) ``` But then, what is the advantage of this approach over a `dcc.interval` ? In both case, there is polling. The only advantage I can see is that the consumer receives the updated value at the *exact* same time it is produced. [1]: https://i.stack.imgur.com/mHARa.gif
I wanted to calculate the average of company score and property score by ignoring the 0's for the below picture (pic1) in pivot table ![Pic1][1] [1]: https://i.stack.imgur.com/xkRtt.png When I average the column in pivot table it includes the 0's as gives the average as shown in below picture (pic2) : ![Pic2][2] [2]: https://i.stack.imgur.com/m9aGE.png Expected average is 65.53 for company and 75 for property in pivot average. Kindly help in getting the expected results in pivot table
null
I am new in react native expo. I am trying to create water reminder app, with react native expo and SQLite. I am constantly getting this error message when adding inserting data into table. ChatGPT and Google Gemini both not being able to solve. LOG > Table created successfully ERROR Error checking date in database: > {"_complete": false, "_error": null, "_running": true, > "_runningTimeout": false, "_sqlQueue": {"first": undefined, "last": > undefined, "length": 0}, "_websqlDatabase": {"_currentTask": > {"errorCallback": [Function anonymous], "readOnly": false, > "successCallback": [Function anonymous], "txnCallback": [Function > anonymous]}, "_db": {"_closed": false, "_name": "waterTracker.db", > "close": [Function closeAsync]}, "_running": true, "_txnQueue": > {"first": undefined, "last": undefined, "length": 0}, "closeAsync": > [Function bound closeAsync], "closeSync": [Function bound closeSync], > "deleteAsync": [Function bound deleteAsync], "exec": [Function bound > exec], "execAsync": [Function bound execAsync], "execRawQuery": > [Function bound execRawQuery], "transactionAsync": [Function bound > transactionAsync], "version": "1.0"}} ``` import React, { useState, useEffect } from 'react'; import { View, Text, Button, StyleSheet } from 'react-native'; import * as SQLite from 'expo-sqlite'; import { format } from 'date-fns'; const db = SQLite.openDatabase('waterTracker.db'); const App = () => { const [dailyIntake, setDailyIntake] = useState(0); const [currentDate, setCurrentDate] = useState(''); const [isDbInitialized, setIsDbInitialized] = useState(false); useEffect(() => { const initializeDatabase = () => { db.transaction(tx => { tx.executeSql( 'CREATE TABLE IF NOT EXISTS waterIntake (id INTEGER PRIMARY KEY AUTOINCREMENT, date DATE, intakeChange INTEGER, totalIntake INTEGER)', [], () => { console.log('Table created successfully'); setIsDbInitialized(true); }, error => { console.error('Error creating table: ', error); } ); }); }; initializeDatabase(); const date = format(new Date(), 'yyyy-MM-dd'); setCurrentDate(date); db.transaction(tx => { tx.executeSql( 'SELECT * FROM waterIntake WHERE date = ?', [date], (_, { rows }) => { if (rows.length === 0) { db.transaction(tx => { tx.executeSql( 'INSERT INTO waterIntake (date, totalIntake) VALUES (?, ?)', [date, 0], // Set totalIntake to initial value () => { console.log('Today\'s date inserted into the database'); }, error => { console.error('Error inserting date into the database: ', error); } ); }); } else { // Fetch and set daily intake if date exists in the database setDailyIntake(rows.item(0).totalIntake); } }, error => { console.error('Error checking date in database: ', error); } ); }); }, []); const addWater = () => { const intakeChange = 1; if (isDbInitialized) { updateIntakeAndSaveHistory(intakeChange); } else { console.error('Database is not initialized yet.'); } }; const deleteWater = () => { if (dailyIntake > 0) { const intakeChange = -1; if (isDbInitialized) { updateIntakeAndSaveHistory(intakeChange); } else { console.error('Database is not initialized yet.'); } } }; const updateIntakeAndSaveHistory = (intakeChange) => { const newIntake = dailyIntake + intakeChange; setDailyIntake(newIntake); db.transaction(tx => { tx.executeSql( 'INSERT INTO waterIntake (date, intakeChange, totalIntake) VALUES (?, ?, ?)', [currentDate, intakeChange, newIntake], (_, results) => { if (results.rowsAffected > 0) { console.log('Water intake history saved successfully'); } else { console.log('Failed to save water intake history'); } }, error => { console.error('Error saving water intake history: ', error); } ); }); }; return ( <View style={styles.container}> <Text style={styles.header}>Water Tracker</Text> <Button title="Add Glass" onPress={addWater} /> <Text style={styles.text}>Daily Intake: {dailyIntake} glasses</Text> <Button onPress={deleteWater} title="Delete Glass" /> <Text style={styles.text}>Today's Date: {currentDate}</Text> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#fff', }, header: { fontSize: 24, fontWeight: 'bold', marginBottom: 20, }, text: { fontSize: 18, marginBottom: 10, }, }); export default App; ```
null
When I click add to cart on my django ecommerce website, the items are not added to cart and in the console an error message appears: > VM40:1 Uncaught (in promise) Syntax Error: Unexpected token '<', "<!DOCTYPE "... is not valid JSON) and (POST http://127.0.0.1:8000/update_item/ 404 (Not Found) I tried adding a CSRF token in my `views.py` and `checkout.html` files but the CSRF token is not even displayed. Here is my `view.py` code. ``` from django.shortcuts import render from django.http import JsonResponse import json import datetime from .models import * def store(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: #Create empty cart for now for non-logged in user items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] products = Product.objects.all() context = {'products':products, 'cartItems':cartItems} return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: #Create empty cart for now for non-logged in user items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'store/cart.html', context) from django.views.decorators.csrf import csrf_exempt @csrf_exempt def checkout(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: #Create empty cart for now for non-logged in user items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'store/checkout.html', context) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) total = float(data['form']['total']) order.transaction_id = transaction_id if total == order.get_cart_total: order.complete = True order.save() if order.shipping == True: ShippingAddress.objects.create( customer=customer, order=order, address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], zipcode=data['shipping']['zipcode'], ) else: print('User is not logged in') return JsonResponse('Payment submitted..', safe=False) ``` checkout.html ``` {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-6"> <div class="box-element" id="form-wrapper"> <form id="form"> {% csrf_token %} <div id="user-info"> <div class="form-field"> <input required class="form-control" type="text" name="name" placeholder="Name.."> </div> <div class="form-field"> <input required class="form-control" type="email" name="email" placeholder="Email.."> </div> </div> <div id="shipping-info"> <hr> <p>Shipping Information:</p> <hr> <div class="form-field"> <input class="form-control" type="text" name="address" placeholder="Address.."> </div> <div class="form-field"> <input class="form-control" type="text" name="city" placeholder="City.."> </div> <div class="form-field"> <input class="form-control" type="text" name="state" placeholder="State.."> </div> <div class="form-field"> <input class="form-control" type="text" name="zipcode" placeholder="Zip code.."> </div> <div class="form-field"> <input class="form-control" type="text" name="country" placeholder="Zip code.."> </div> </div> <hr> <input id="form-button" class="btn btn-success btn-block" type="submit" value="Continue"> </form> </div> <br> <div class="box-element hidden" id="payment-info"> <small>Paypal Options</small> <button id="make-payment">Make payment</button> </div> </div> <div class="col-lg-6"> <div class="box-element"> <a class="btn btn-outline-dark" href="{% url 'cart' %}">&#x2190; Back to Cart</a> <hr> <h3>Order Summary</h3> <hr> {% for item in items %} <div class="cart-row"> <div style="flex:2"><img class="row-image" src="{{item.product.imageURL}}"></div> <div style="flex:2"><p>{{item.product.name}}</p></div> <div style="flex:1"><p>${{item.product.price|floatformat:2}}</p></div> <div style="flex:1"><p>x{{item.quantity}}</p></div> </div> {% endfor %} <h5>Items: {{order.get_cart_items}}</h5> <h5>Total: ${{order.get_cart_total|floatformat:2}}</h5> </div> </div> </div> <script type="text/javascript"> var shipping = '{{order.shipping}}' var total = '{{order.get_cart_total|floatformat:2}}' if (shipping == 'False'){ document.getElementById('shipping-info').innerHTML = '' } if (user != 'AnonymousUser'){ document.getElementById('user-info').innerHTML = '' } if (shipping == 'False' && user != 'AnonymousUser'){ //Hide entire form if user is logged in and shipping is false document.getElementById('form-wrapper').classList.add("hidden"); //Show payment if logged in user wants to buy an item that does not require shipping document.getElementById('payment-info').classList.remove("hidden"); } var form = document.getElementById('form') csrftoken = form.getElementsByTagName("input")[0].value console.log('Newtoken' ,form.getElementsByTagName("input")[0].value) /dform.addEventListener('submit', function(e){ e.preventDefault() console.log('Form Submitted...') document.getElementById('form-button').classList.add("hidden"); document.getElementById('payment-info').classList.remove("hidden"); }) document.getElementById('make-payment').addEventListener('click', function(e){ submitFormData() }) function submitFormData(){ console.log('Payment button clicked') var userFormData = { 'name':null, 'email':null, 'total':total, } var shippingInfo = { 'address':null, 'city':null, 'state':null, 'zipcode':null, } if (shipping != 'False'){ shippingInfo.address = form.address.value shippingInfo.city = form.city.value shippingInfo.state = form.state.value shippingInfo.zipcode = form.zipcode.value } if (user == 'AnonymousUser'){ userFormData.name = form.name.value userFormData.email = form.email.value } console.log('Shipping Info:', shippingInfo) console.log('User Info:', userFormData) var url = "/process_order/" fetch(url, { method:'POST', headers:{ 'Content-Type':'applicaiton/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'form':userFormData, 'shipping':shippingInfo}), }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); alert('Transaction completed'); window.location.href = "{% url 'store' %}" }) } </script> {% endblock content %} ```
I am experiencing a 404 error in the console on my django project
null
I dont have xp with java, but i guess the question is more about oop than clean arch. But if java classes accept inheritance and abstract classes, or just inheritance, you can make a class with the specific behavior (canDoX()) an then extends in both classes. But, have a chance to use the MyData class instead MyDataWithHalfOfFields?
tokens in local storage isn't the more secure approach. httpOnly cookie is better to ensure javascript can't access the token. httpOnly cookies are sent with every request to backend, so even if building a single page application, you can still use this more secure approach. lots of content online can go into more depth over the differences in approach. but the default should be httpOnly cookie.
```csharp public virtual void CompositeImage(byte[] buffer, int bufferWidth, int bufferHeight, byte[] image, int imageWidth, int imageHeight, int x, int y) { for (int i = 0; i < imageHeight; i++) { for (int j = 0; j < imageWidth; j++) { if (j > bufferWidth) { continue; } if (i > bufferHeight) { continue; } int index = Math.Min((i * imageWidth + j) * 4, image.Length - 4); int bufferIndex = ((y + i) * bufferWidth + (x + j)) * 4; if (bufferIndex < 0 || bufferIndex >= buffer.Length - 4) return; Pixel back = new Pixel( buffer[bufferIndex + 3], buffer[bufferIndex + 2], buffer[bufferIndex + 1], buffer[bufferIndex] ); Pixel fore = new Pixel( image[index], image[index + 1], image[index + 2], image[index + 3] ); if (fore.A < 255) { Color blend = fore.color.Blend(back.color, 0.15d); buffer[bufferIndex] = blend.B; buffer[bufferIndex + 1] = blend.G; buffer[bufferIndex + 2] = blend.R; if (back.A == 255) buffer[bufferIndex + 3] = 255; else buffer[bufferIndex + 3] = blend.A; } else { buffer[bufferIndex] = fore.color.B; buffer[bufferIndex + 1] = fore.color.G; buffer[bufferIndex + 2] = fore.color.R; buffer[bufferIndex + 3] = 255; } //back = back.Composite(fore); } } } ```
Install the below in virtual environment ``` pip install llama-index qdrant_client torch transformers ``` ``` pip install llama-index-llms-ollama ``` Sample code : ``` # Just runs .complete to make sure the LLM is listening from llama_index.llms.ollama import Ollama from llama_index.core import Settings llm = Ollama(model="mistral") response = llm.complete("Who is Laurie Voss? write in 10 words") print(response)
For install **cudatoolkit and cudnn** by Anaconda you can use these following command `conda install -c conda-forge cudatoolkit=11.2 cudnn=8.1.0` on command prompt You must aware the **tensorflow version** must be less than **2.11** For check if the everything installed properly 1) In command prompt check `nvidia-smi` command. if shows command not found you must install the latest GPU driver 2) Use this python script to config the GPU in programming --- import tensorflow as tf if tf.config.list_physical_devices('GPU'): print('GPU is available.') else: print('GPU is NOT available. Make sure TensorFlow version less than 2.11 and Installed all GPU drivers.') config = tf.compat.v1.ConfigProto() config.gpu_options.allow_growth = True session = tf.compat.v1.Session(config=config)
I'm having an issue with Excel Code editor. From time to time it crashes and only shows white window. Do you know what might be an issue? I was able to fix it once, by relogging to Microsoft account everywhere, but it's pretty annoying. [![screenshot][1]][1] [1]: https://i.stack.imgur.com/8tbv9.png
Excel Code Editor doesn't work (blank window)
|excel|typescript|
I have interfaces **Angular Typescript Class** interface A_DTO { type: string, commonProperty: string, uniquePropertyA: string, etc.. } interface B_DTO { type: string, commonProperty: string, uniquePropertyB: string, etc... } type AnyDTO = A_DTO | B_DTO I have an object, fetched from an API. When it is fetched, it immediately gets cast to A_DTO or B_DTO, by reading the 'type' property. But after that, it then it gets saved to a service, for storage, where it gets saved to a single variable, but of typ AnyDTO (I call that service variable with the components I work with - casting back to AnyDTO, doesn't cause any properties to be lost, so I'm happy) **Angular Template** But, in a component, I have some template code, @if(object.type == "Type_A") { // do something // I can do object.commonProperty // but I cannot access object.uniquePropertyA } @ else { object.type == "Type_B") { // do something // I can do object.commonProperty // but I cannot access object.uniquePropertyB } Note, above, object gets read as type, AnyDTO = A_DTO | B_DTO **Angular Typescript Class** I tried creating a type guard on the interface, in the typescript class code, e.g. protected isTypeA(object: any): object is A_DTO { return object?.Type === "Type_A"; }, **Angular Template** Then @if(isTypeA(object) && object.type == "Type_A") { // do something // I can do object.commonProperty // but I still cannot access object.uniquePropertyA... } @ else { object.type == "Type_B") { // do something // but I cannot access object.uniquePropertyB } Even with the typeguard being called in the template, inside the @if, 'object' still gets treated as type: A_DTO | B_DTO. Despite what I read on the internet, type narrowing does not happen. So can only access the common properties from 'object'. I also tried to explicity type cast in the template, using things like (object as A_DTO).uniquePropertyA, but that doesn't work in the Angular template area Any ideas on a ***dynamic*** solution, (that ideally does not involve create separate variables for each subtype in the Typescript class)? Cheers, ST
|python|pyspark|databricks|
DataBricks/PySpark is, indeed, a case-sensitive language, but using the `withColumn()` command this way - to re-cast and re-name an existing column from upper/mixed-case to lower-case (or any combination of case-change that does not also change the actual column name) - causes the `withColumn()` command to revert to a `withColumnRenamed()` outcome, such that the input column remains afterward (a lower-case duplicate is not created) but is simply renamed/re-cast. All subsequent calls to use the original upper/mixed-case column name will fail because it no longer exists. For example: df = df \ .withColumn("new_lower_case_column_name", col("Mixed_Case_Column_Name").cast(SomeType()) \ # SUCCESS .withColumn("mixed_case_column_name", col("Mixed_Case_Column_Name").cast(SomeType()) \ # SUCCESS .withColumn("new_additional_lower_case_column_name", col("Mixed_Case_Column_Name").cast(SomeType()) \ # FAIL At output, `df.columns` contains `"mixed_case_column_name"` and `"new_lower_case_column_name"` but does not contain `"new_additional_lower_case_column_name"`. Many solutions will resolve this issue, including saving the case-change-name call for last, using the case-change-name for all subsequent calls, or use of a nomenclature (naming convention) that ensures the changed case name will differ from its original (e.g., using a prefix/suffix), and etc....
I am trying to configure spring gateway using spring boot 3 version, java 17 version, and kotlin language. However, it seems that the spring security settings are not applied. as postman POST If I call it with http://127.0.0.1:11001 I get a 403 Forbidden error and An expected CSRF token cannot be found The result is Regarding this, I already created a SecurityConfig class and set it as below, but it doesn't work. The github address used for this configuration is as follows: https://github.com/arubear1321/studyspringgateway.git If I configure it with the same java version, it works fine. I don't think there's anything special to set, so why doesn't it work? --- SecurityConfig.kt ``` import org.slf4j.LoggerFactory import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity import org.springframework.security.config.web.server.ServerHttpSecurity import org.springframework.security.web.server.SecurityWebFilterChain @Configuration @EnableWebFluxSecurity @EnableReactiveMethodSecurity class SecurityConfig { private val logger = LoggerFactory.getLogger(SecurityConfig::class.java) @Bean fun securityWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { logger.info("Configuring SecurityWebFilterChain") http .csrf { it.disable() } .authorizeExchange { it.anyExchange().permitAll() } .formLogin{ it.disable() } .httpBasic{ it.disable() } return http.build() } } ``` application.yml ``` server: port: 11001 shutdown: graceful spring: application: name: api-gateway lifecycle: timeout-per-shutdown-phase: 60s cloud: gateway: default-filters: - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin globalcors: corsConfigurations: '[/**]': allowedOrigins: "*" allowedHeaders: "*" allowedMethods: - GET - POST - OPTION - PUT routes: - id: api uri: http://127.0.0.1:11002 predicates: - Path=/api/** logging: level: root: TRACE org.springframework.security: TRACE ```
It's about a course selection. First we select the course, depending on that we select the level and then a batch as given in the code. but finally I want to select either 1 or more subjects inluding all subjects which selects all the given subjects I also want to pass these data as a form to the backend. so I need values and names to include in each input **HTML code** ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="output.css"> <link href="https://cdnjs.cloudflare.com/ajax/libs/flowbite/2.3.0/flowbite.min.css" rel="stylesheet" /> <title>Document</title> </head> <body class="bg-[#FFF4C4] dark:bg-gray-900 "> <section> <div class="flex flex-col items-center justify-center px-6 py-8 mx-auto md:my-24 md:h-screen lg:py-0"> <!-- centering --> <div class="w-full bg-white shadow-md rounded-2xl dark:border md:mt-0 md:max-w-4xl xl:p-0 dark:bg-gray-800 dark:border-gray-700"> <!-- content --> <div class="p-6 space-y-4 md:space-y-1 sm:p-6"> <!-- padding inside --> <h1 class="h-10 text-xl font-bold leading-tight tracking-tight text-gray-900 md:text-2xl dark:text-white"> Course Registration </h1> <div class="grid grid-cols-none gap-4 p md:grid-cols-2"> <div> <div> <form class="max-w-sm mx-auto"> <label class="block mb-2 text-base font-medium text-black dark:text-white">Select a course</label> <select class="block w-full px-4 py-3 mb-4 text-base text-gray-900 border border-yellow-300 rounded-lg shadow-xl bg-gray-50 focus:ring-red-500 focus:border-red-500 disabled:opacity-30 disabled:border-none" id="course"> <option selected >Choose a course</option> </select> <label class="block mb-2 text-base font-medium text-black dark:text-white">Select a level(s)</label> <select class="block w-full px-4 py-3 mb-4 text-base text-gray-900 border border-yellow-300 rounded-lg shadow-xl disabled:opacity-30 disabled:border-none bg-gray-50 focus:ring-red-500 focus:border-red-500 " id="level"> <option selected >Choose a level</option> </select> <label class="block mb-2 text-base font-medium text-black dark:text-white">Select a batch</label> <select class="block w-full px-4 py-3 mb-4 text-base text-gray-900 border border-yellow-300 rounded-lg shadow-xl disabled:opacity-30 disabled:border-none bg-gray-50 focus:ring-red-500 focus:border-red-500 " id="batch"> <option selected >Choose a batch</option> </select> <label class="block mb-2 text-base font-medium text-black dark:text-white">Select subject(s)</label> <select class="block w-full px-4 py-3 mb-4 text-base text-gray-900 border border-yellow-300 rounded-lg shadow-xl disabled:opacity-30 disabled:border-none bg-gray-50 focus:ring-red-500 focus:border-red-500 " id="subject"> <option selected >Choose a subject</option> </select> </form> </div> <div> <button id="dropdownCheckboxButton" data-dropdown-toggle="dropdownDefaultCheckbox" class="text-black bg-yellow-300 hover:bg-red-500 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center inline-flex items-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800" type="button">Select Course <svg class="w-2.5 h-2.5 ms-3" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 10 6"> <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 4 4 4-4" /> </svg> </button> <!-- Dropdown menu --> <div id="dropdownDefaultCheckbox" class="z-10 hidden w-48 bg-white divide-y divide-gray-100 rounded-lg shadow dark:bg-gray-700 dark:divide-gray-600"> <ul class="p-3 space-y-3 text-sm text-gray-700 dark:text-gray-200" aria-labelledby="dropdownCheckboxButton"> <li> <div class="flex items-center"> <input id="checkbox-item-1" type="checkbox" value="" class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-700 dark:focus:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"> <label for="checkbox-item-1" class="text-sm font-medium text-gray-900 ms-2 dark:text-gray-300">Default checkbox</label> </div> </li> <li> <div class="flex items-center"> <input checked id="checkbox-item-2" type="checkbox" value="" class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-700 dark:focus:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"> <label for="checkbox-item-2" class="text-sm font-medium text-gray-900 ms-2 dark:text-gray-300">Checked state</label> </div> </li> <li> <div class="flex items-center"> <input id="checkbox-item-3" type="checkbox" value="" class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-700 dark:focus:ring-offset-gray-700 focus:ring-2 dark:bg-gray-600 dark:border-gray-500"> <label for="checkbox-item-3" class="text-sm font-medium text-gray-900 ms-2 dark:text-gray-300">Default checkbox</label> </div> </li> </ul> </div> </div> </div> </div> </div> </div> </div> </div> </div> </section> <script src="../node_modules/flowbite/dist/flowbite.min.js"></script> <script src="select.js"></script> <!-- <script src="try.js"></script> --> </body> </html> ``` **JS code** ``` var CourseLevelBatchSubject = { BIT: { "Full Degree": { "Batch 501": ["All subjects"], }, "Semester 1": { "Batch 501": ["IM", "IS", "CS", "PC", "Programming", "All subjects"], }, "Semester 2": { "Batch 601": ["Com 1", "MC", "SE", "DB", "WAD 1", "All subjects"], }, "Semester 3": { "Batch 701": ["Com 2", "OOAD", "DSA", "DMS", "WAD 2", "All subjects"], }, "Semester 4": { Batch: ["UED", "EAD", "ITPM", "ASD", "CN", "All subjects"], }, "Semester 5": { Batch: ["FME", "SDP", "PP", "PIS", "SNA", "MC 2", "All subjects"], }, "Semester 6": { Batch: ["ETIS", "SQA", "MAD", "NSA", "EBT", "All subjects"], }, "Semester 2 to 6": { Batch: ["All subjects"] }, "Semester 3 to 6": { Batch: ["All subjects"] }, "Semester 4 to 6": { Batch: ["All subjects"] }, "Semester 5 to 6": { Batch: ["All subjects"] }, Project: { Batch: ["No subjects (Only project)"] }, }, BCS: { "All levels": {}, "Certificate Level": {}, "Diploma Level": {}, "PGD in IT": {}, Project: {}, }, FIT: {}, }; window.onload = function () { const selectcourse = document.getElementById("course"), selectlevel = document.getElementById("level"), selectbatch = document.getElementById("batch"), selectsubject = document.getElementById("subject"), selects = document.querySelectorAll("select"); selectlevel.disabled = true; selectbatch.disabled = true; selectsubject.disabled = true; selects.forEach((select) => { if (select.disabled == true) { select.style.cursor = "auto"; } else { select.style.cursor = "pointer"; } }); for (let course in CourseLevelBatchSubject) { selectcourse.options[selectcourse.options.length] = new Option( course, course ); } // select course selectcourse.onchange = (e) => { selectlevel.disabled = false; selectbatch.disabled = true; selectsubject.disabled = true; selectlevel.length = 1; selectbatch.length = 1; selectsubject.length = 1; for (let level in CourseLevelBatchSubject[e.target.value]) { selectlevel.options[selectlevel.options.length] = new Option( level, level ); } }; // select level selectlevel.onchange = (e) => { selectbatch.disabled = false; selectsubject.disabled = true; selectbatch.length = 1; selectsubject.length = 2; for (let batch in CourseLevelBatchSubject[selectcourse.value][ e.target.value ]) { selectbatch.options[selectbatch.options.length] = new Option( batch, batch ); } }; //change batch selectbatch.onchange = (e) => { selectsubject.disabled = false; selectsubject.length = 1; let subjects = CourseLevelBatchSubject[selectcourse.value][selectlevel.value][ e.target.value ]; for (let i = 0; i < subjects.length; i++) { selectsubject.options[selectsubject.options.length] = new Option( subjects[i], subjects[i] ); } }; }; ``` I have used tailwind with flowbite component. It's fine if u don't use any styling. I only want the code itself
How to create a dynamic select list with multiselect as the last select box, only using html and js
|javascript|html|forms|tailwind-css|
null
> Message: Response status code does not indicate success: 403 (This request is not authorized to perform this operation.). The above error occurs when you don't have enough permission or you're passing the wrong SAS token to access the storage account. > The network restriction on the Storage Account is: **Enabled from all networks** If your storage account networking is enabled from all networks, then you don't need to pass the VM IP address in your SAS token. In my environment, I created a virtual machine and created a SAS token without passing the IP address. The same script executed successfully. **Script:** [System.Environment]::SetEnvironmentVariable('myDevSas', 'sp=racwl&st=2024-03-13T05:53:48Z&se=2024-03-13T13:53:48Z&spr=https&sv=2022-11-02&sr=c&sig=xxxx', [System.EnvironmentVariableTarget]::Machine) function SendToStorageAccount { param ( [string] $zipFileName ) $myDevSas = [System.Environment]::GetEnvironmentVariable('myDevSas','Machine') #The target URL with SAS Token $uri = "https://venkat789.blob.core.windows.net/logs/$($zipFileName)?$($myDevSas)" #Define required Headers $headers = @{ 'x-ms-blob-type' = 'BlockBlob' } #Upload File... $apiCall try { $apiCall = Invoke-RestMethod -Uri $uri -Method Put -Headers $headers -InFile $zipFileName Write-Output $apiCall Write-Output "The file $($zipFileName) uploaded successfully" Remove-Item $zipFileName } catch { "Message: $($_.Exception.Message)" "CategoryInfo $($_.CategoryInfo)" "FullyQualifiedErrorId: $($_.FullyQualifiedErrorId)" "StackTrace: $(($_.ScriptStackTrace -replace '^'))" Write-Output $apiCall Write-Output "The file $($zipFileName) FAILED to upload" } } $fileName = "antarctica-latest-free.zip" SendToStorageAccount $fileName **Output:** The file antarctica-latest-free.zip uploaded successfully ![Enter image description here](https://i.imgur.com/GAEi5NC.png)
null
{"OriginalQuestionIds":[45095523],"Voters":[{"Id":442760,"DisplayName":"cafce25","BindingReason":{"GoldTagBadge":"rust"}}]}
I hosted a next js website on firebase using firebase cli successfully. Now I'm trying to configure github actions to deploy it automatically. I am struck on this step: *? For which GitHub repository would you like to set up a GitHub workflow? (format: user/repository)* My repo is inside an organization and I don't know what to input here. I tried user/org-name/repo-name , user/repo-name , org-name/repo-name , (org-name/repo-name) but it doesn't work. Please help. For org-name/repo-name I am getting the following error. Error: HTTP Error: 403, Policy update access denied. Note: I'm the owner of the organization and I gave the necessary permissions.
null
`path="/:profile"` has the same specificity as `path="/:postpage"`, so the first route encountered when matching routes to the current URL path is the one that is rendered. Based on the URL in the screenshot it looks like you are navigating to the string literal `"/:profile"`, so I suspect you meant to render a route on `path="/profile"` specifically, and that the post page on `path="/:postpage"` is the dynamic route. Update the profile route to `path="/profile"`. ```jsx <Route path="/profile" element={<ProfilePage />} /> <Route path="/:postpage" element={<PostPage />} /> ``` Ensure you are linking to the correct profile page path now. ```jsx <Link to="/profile">Profile</Link> ```
The issue is that python's `print()` doesn't have a return value, meaning it will always return `None`. `eval` simply evaluates some expression, and returns back the return value from that expression. Since `print()` returns `None`, an `eval` of some print statement will also return `None`. ``` >>> from_print = print('Hello') Hello >>> from_eval = eval("print('Hello')") Hello >>> from_print is from_eval is None True ``` What you need is a io stream manager! Here is a possible solution that captures any io output and returns that if the expression evaluates to `None`. ```python from contextlib import redirect_stdout, redirect_stderr from io import StringIO # NOTE: I use the arg name `code` since `input` is a python builtin def execute_code_helper(code): # Capture all potential output from the code stdout_io = StringIO() stderr_io = StringIO() with redirect_stdout(stdout_io), redirect_stderr(stderr_io): # If `code` is already a string, this should work just fine without the need for formatting. result = eval(code) return result, stdout_io.getvalue(), stderr_io.getvalue() def execute_code(code): result, std_out, std_err = execute_code_helper(code) if result is None: # This code didn't return anything. Maybe it printed something? if std_out: return std_out.rstrip() # Deal with trailing whitespace elif std_err: return std_err.rstrip() else: # Nothing was printed AND the return value is None! return None else: return result ``` As a final note, this approach is heavily linked to `eval` since `eval` can only evaluate a single statement. If you want to extend your bot to multiple line statements, you will need to use [exec][1], which changes the logic. Here's a great resource detailing the differences between `eval` and `exec`: [https://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile][2] [1]: https://docs.python.org/3/library/functions.html#exec [2]: https://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile
null
I have a table, one column with emails, the one next to it with serial numbers. I want to find the maximum serial number value for every email using this formula. =TEXT(MAX(IF($A$1:$A$100=A4, MID($B$1:$B$100, 5, 5)+0)), "\VUAM00000") to achieve something like this ![enter image description here](https://i.stack.imgur.com/zcueG.png) I keep getting error #value! , after chasing my tail for so long I observed something really strange.. the formula works , as long as the serial does not have the letter "M" or apparently "N" too!! so `=TEXT(MAX(IF($A$1:$A$100=A4, MID($B$1:$B$100, 5, 5)+0)), "\VUA**X**00000")` works! also `=TEXT(MAX(IF($A$1:$A$100=A4, MID($B$1:$B$100, 5, 5)+0)), "\VUA**T**00000")` works `=TEXT(MAX(IF($A$1:$A$100=A4, MID($B$1:$B$100, 5, 5)+0)), "\VUA**M**00000")` does not work `=TEXT(MAX(IF($A$1:$A$100=A4, MID($B$1:$B$100, 5, 5)+0)), "\VUA**N**00000")` does not work either , but i don't care really i just found it weird that excel does not like these 2 letters. so my question is, why is the formula working with some letters and some not , and how do i get it to work note, i can't change the convention, its auto generated and has to be VUAM I pretty much know it's the letter "M" that's causing the issue, i have tried using Right instead of Mid, with same result #value! =TEXT(MAX(IF($A$1:$A$100=K3, RIGHT($B$1:$B$100, 5)+0)), "\VUAM00000") also simplifying the formula to =MAX(IF($A$1:$A$100=K3, RIGHT($B$1:$B$100, 5)+0)) works too ,or does its respective job in the formula, so the max part is fine , its when you add the rest the error occurs.
I am trying to modify the following url: [`https://sslecal2.investing.com/?columns=exc_importance&category=_employment,_economicActivity,_inflation,_credit,_centralBanks,_confidenceIndex,_balance,_Bonds&importance=1,2,3&features=datepicker,timezone,timeselector,filters&countries=5&calType=day&timeZone=15&lang=51`](https://sslecal2.investing.com/?columns=exc_importance&category=_employment,_economicActivity,_inflation,_credit,_centralBanks,_confidenceIndex,_balance,_Bonds&importance=1,2,3&features=datepicker,timezone,timeselector,filters&countries=5&calType=day&timeZone=15&lang=51) This takes me to a table view but I would like to change the date to be a specific date. I can alter the date range to be eg. from 2023-12-06 to 2023-12-06. Once I do this, I can see (with DevTools) that there is some kind of request (to ajax.php) that goes through that specifies `dateFrom=2023-12-06` & `dateTo=2023-12-06` but if i add those to the long URL, nothing changes. Is there a way of doing this in 1 request? I really dont know much about web requests. I was trying to use this into Obsidian as an iframe. the addition of the extra features makes no difference.
how do I change a URL with form to include additional selection
|html|ajax|url|webforms|
null
I have been getting this error for a long now when trying to install hadoop on ubuntu.. ``` :~/hadoop$ bin/hdfs namenode -format Unrecognized option: - Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit. ``` I tried to format the namenode using the command but rather got this error as unrecognized command
|java|ubuntu|hadoop|hdfs|namenode|
I have access to 2 nodes, each has 2 GPUs. I want to have 4 processes, each has a GPU. I use `nccl` (if this is relevant). Here is the Slurm script I tried. I tried different combinations of setup. It works occasionally as wanted. Most of time, it creates 4 processes in 1 node, and allocate 2 processes to 1 GPU. It slows down the program and cause out of memory, and makes `all_gather` fail. How can I distribute processes correctly? ``` #!/bin/bash #SBATCH -J jobname #SBATCH -N 2 #SBATCH --cpus-per-task=10 # version 1 #SBATCH --ntasks-per-node=2 #SBATCH --gres=gpu:2 #SBATCH --gpu-bind=none # version 2 #SBATCH --ntasks-per-node=2 #SBATCH --gres=gpu:2 # version 3 #SBATCH --ntasks=4 #SBATCH --ntasks-per-node=2 #SBATCH --gres=gpu:2 # version 4 #SBATCH --ntasks=4 #SBATCH --ntasks-per-node=2 #SBATCH --gres=gpu:2 #SBATCH --gpus-per-task=1 # # version 5 #SBATCH --ntasks=4 #SBATCH --ntasks-per-node=2 #SBATCH --gpus-per-task=1 module load miniconda3 eval "$(conda shell.bash hook)" conda activate gpu-env nodes=( $( scontrol show hostnames $SLURM_JOB_NODELIST) ) nodes_array=($nodes) head_node=${nodes_array[0]} head_node_ip=$(srun --nodes=1 --ntasks=1 -w "$head_node" hostname --ip-address) echo Node IP: $head_node_ip export LOGLEVEL=INFO export NCCL_P2P_LEVEL=NVL srun torchrun --nnodes 2 --nproc_per_node 2 --rdzv_id $RANDOM --rdzv_backend c10d --rdzv_endpoint $head_node_ip:29678 mypythonscript.py ``` In python script: ``` dist.init_process_group(backend="nccl") torch.cuda.set_device(int(os.environ["LOCAL_RANK"])) ```
I'm trying to pass an array of objects like this but I'm getting an Error: '"type: object" is forbidden here'. ``` requestBody: required: true content: multipart/form-data: schema: type: object additionalProperties: false required: - posts properties: posts: type: array items: type: object properties: id: type: integer url: type: string ```
How to pass an array of objects to multipart/form-data?
|yaml|multipartform-data|
null
I suggest checking out this article about outlook's css quirks: **[A Guide to Rendering Differences in Microsoft Outlook Clients][1]**. It talks about using VML as a workaround. Issue: <!--[if mso]> <table align="center" border="0" cellspacing="0" cellpadding="0" style="width:100%; border-collapse: collapse;"> <tr> <td style="background-color:#ececec;"> <![endif]--> <table bgcolor="#ececec" align="center" border="0" cellspacing="0" cellpadding="0" style="width:100%; border-collapse: collapse;"> <tr> <td bgcolor="#ffffff" style="text-align: justify;width: 50%;"> <table bgcolor="#ffffff" border="0" cellspacing="0" cellpadding="0" style="border-collapse: collapse;"> <tr> <td bgcolor="#ffffff" style="padding-left: 30px; padding-right: 10px; "> <img width="40" height="40" alt="" src="https://www.example.com/pub/media/wysiwyg/icons/icon-number1.png" style="vertical-align: middle; display: inline-block; width: 40px; height: 40px;"> </td> <td bgcolor="#ffffff" style="width: 74%; padding-top: 20px;padding-bottom: 20px;"> <div style="vertical-align: middle; display: inline-block;"> <h3 style="margin: 0; padding: 0;">Australia's No. 1</h3> <span>Replica lighting store</span> </div> </td> </tr> </table> </td> <td bgcolor="#ffffff" style="text-align: justify;width: 50%;"> <table bgcolor="#ffffff" border="0" cellspacing="0" cellpadding="0" style="border-collapse: collapse;"> <tr> <td bgcolor="#ffffff" style="padding-left: 30px; padding-right: 10px; "> <img width="40" height="40" alt="" src="https://www.example.com/pub/media/wysiwyg/icons/icon-huge-range.png" style="vertical-align: middle; display: inline-block; width: 40px; height: 40px;"> </td> <td bgcolor="#ffffff" style="width: 74%; padding-top: 20px;padding-bottom: 20px; "> <div style="vertical-align: middle; display: inline-block; "> <h3 style="margin:0; padding:0;">Huge range</h3> <span>20,000+ products</span> </div> </td> </tr> </table> </td> </tr> <tr> <td bgcolor="#ffffff" style="text-align: justify;width: 50%;"> <table bgcolor="#ffffff" border="0" cellspacing="0" cellpadding="0" style="border-collapse: collapse;"> <tr> <td bgcolor="#ffffff" style="padding-left: 30px; padding-right: 10px;"> <img width="40" height="40" alt="" src="https://www.example.com/pub/media/wysiwyg/icons/icon-fast-shipping.png" style="vertical-align: middle; display: inline-block; width: 40px; height: 40px;"> </td> <td bgcolor="#ffffff" style="width: 74%; padding-top: 20px;padding-bottom: 20px;"> <div style="vertical-align: middle; display: inline-block; "> <h3 style="margin:0; padding:0;">Fast shipping</h3> <span>24hr dispatch on most items</span> </div> </td> </tr> </table> </td> <td bgcolor="#ffffff" style="text-align: justify;width: 50%;"> <table bgcolor="#ffffff" border="0" cellspacing="0" cellpadding="0" style="border-collapse: collapse;"> <tr> <td bgcolor="#ffffff" style="padding-left: 30px; padding-right: 10px; "> <img width="40" height="40" alt="" src="https://www.example.com/pub/media/wysiwyg/icons/icon-30-days.png" style="vertical-align: middle; display: inline-block; width: 40px; height: 40px;"> </td> <td bgcolor="#ffffff" style="width: 74%; padding-top: 20px;padding-bottom: 20px;"> <div style="vertical-align: middle; display: inline-block; "> <h3 style="margin:0; padding:0;">30 days returns</h3> <span>For peace of mind</span> </div> </td> </tr> </table> </td> </tr> </table> <!--[if mso]> </td> </tr> </table> <![endif]--> [1]: https://www.litmus.com/blog/a-guide-to-rendering-differences-in-microsoft-outlook-clients
This is Powershell/WPF (The loaded assemblies are pasted from my project and mostly not needed for this) I am making an animated flyout button, it works as intended, I click the button, it slides into position, at the end of the animation it hides and a different button appears in its place with the opposite animation ready waiting to be clicked, this behavior toggles fine. I would like to make clicking anywhere (not solely the second button) trigger moving the second button back. In the real script a popup window appears, and my intent is to make it dismissible by clicking anywhere outside the window. I currently have this working but if the button isnt directly clicked the close animation gets skipped because I cant(don't know how to) trigger it without the button. I know it's highly likely someone knows how to do this in C#, and I am willing to take examples and figure out how to make a comparable PS codebehind, so I tagged C# too, but if there is a PS options someone knows, that would be perfect. ``` Add-Type -AssemblyName PresentationFramework, System.Drawing, System.Windows.Forms, WindowsFormsIntegration, presentationCore [xml]$xaml=' <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" WindowStartupLocation="CenterScreen" WindowStyle="None" Background="Transparent" AllowsTransparency="True" Width="500" Height="300"> <Window.Resources> <ControlTemplate x:Key="NoMouseOverButtonTemplate" TargetType="Button"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/> </Border> <ControlTemplate.Triggers> <Trigger Property="IsEnabled" Value="False"> <Setter Property="Background" Value="{x:Static SystemColors.ControlLightBrush}"/> <Setter Property="Foreground" Value="{x:Static SystemColors.GrayTextBrush}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Window.Resources> <Canvas> <Button Name="MovableButton1" Canvas.Left="70" Canvas.Top="0" FontSize="12" FontFamily="Calibri" FontWeight="Light" BorderBrush="#111111" Foreground="#EEEEEE" Background="#111111" Height="18" Width="70" Template="{StaticResource NoMouseOverButtonTemplate}">Button1<Button.Triggers> <EventTrigger RoutedEvent="PreviewMouseUp"> <BeginStoryboard> <Storyboard> <DoubleAnimation Name="ButtonAnimation1" From="70" To="207" Duration="0:0:0.25" Storyboard.TargetProperty="(Canvas.Left)" AutoReverse="False" FillBehavior="Stop"/> </Storyboard> </BeginStoryboard></EventTrigger> </Button.Triggers> </Button> <Button Name="MovableButton2" Canvas.Left="207" Canvas.Top="0" Visibility="Hidden" FontSize="12" FontFamily="Calibri" FontWeight="Light" BorderBrush="#111111" Foreground="#EEEEEE" Background="#111111" Height="18" Width="70" Template="{StaticResource NoMouseOverButtonTemplate}">Button2<Button.Triggers> <EventTrigger RoutedEvent="PreviewMouseUp"> <BeginStoryboard> <Storyboard> <DoubleAnimation Name="ButtonAnimation2" From="207" To="70" Duration="0:0:0.25" Storyboard.TargetProperty="(Canvas.Left)" AutoReverse="False" FillBehavior="Stop"/> </Storyboard> </BeginStoryboard></EventTrigger> </Button.Triggers> </Button> </Canvas> </Window>' $reader=(New-Object System.Xml.XmlNodeReader $xaml) $window=[Windows.Markup.XamlReader]::Load($reader) $Button1=$Window.FindName("MovableButton1") $Button2=$Window.FindName("MovableButton2") $ButtonAnimation1=$Window.FindName("ButtonAnimation1") $ButtonAnimation2=$Window.FindName("ButtonAnimation2") $Button1.Add_Click({ write-host FirstButtonClicked }) $Button2.Add_Click({ write-host SecondButtonClicked }) $ButtonAnimation1.Add_Completed({ write-host AnimationCompleted $Button1.Visibility="Hidden" $Button2.Visibility="Visible" }) $ButtonAnimation2.Add_Completed({ write-host AnimationCompleted $Button1.Visibility="Visible" $Button2.Visibility="Hidden" }) $window.Show() $appContext=New-Object System.Windows.Forms.ApplicationContext [void][System.Windows.Forms.Application]::Run($appContext) ``` The full project for reference: https://github.com/illsk1lls/PowerPlayer
Trigger WPF doubleanimation from Powershell codebehind
|c#|wpf|powershell|
The two below alternate possibilities apply to both Python versions 2 and 3. Choose the way you prefer. All use cases are covered. Example 1 --------- Module is being imported from a subdirectory (`./bar/baz`) of a directory of currently running module (`/some/path/foo`). main script: /some/path/foo/foo.py module to import: /some/path/foo/bar/baz/mymodule.py Add in `foo.py` import sys, os sys.path.append(os.path.join(sys.path[0], 'bar', 'baz')) from mymodule import MyModule Example 2 --------- Module is being imported from a subdirectory (`./bar/baz`) of **parent** directory (`/some/path/`) of currently running module (`/some/path/foo`). main script: /some/path/foo/foo.py module to import: /some/path/bar/baz/mymodule.py Add in `foo.py` import sys, os sys.path.append(os.path.join(os.path.dirname(sys.path[0]), 'bar', 'baz')) from mymodule import MyModule Explanations ------------ * `sys.path[0]` is `/some/path/foo` in both examples * `os.path.join('a','b','c')` is more portable than `'a/b/c'` * `os.path.dirname(mydir)` is more portable than `os.path.join(mydir,'..')` See also -------- Documentation about importing modules: * in [Python 2](https://docs.python.org/2/tutorial/modules.html) * in [Python 3](https://docs.python.org/3/tutorial/modules.html)
To use `require` and `import` together, you need to use dynamic `import()` expressions to load an ES module into a CommonJS context. A common Node.js error message that provides a solution looks like this: ``` Error [ERR_REQUIRE_ESM]: require() of ES Module <path> from <path> not supported. Instead change the require of <path> in <path> to a dynamic import() which is available in all CommonJS modules. ``` Here is an example of using `lodash` and `lodash-es`: ```js const lodash = require('lodash') async function main() { const output = lodash.concat(['hello'], ['world']) const lodashEs = await import('lodash-es') console.log(lodashEs.join(output, ' ')) } main() ```
You can scroll to a particular view in a `ScrollView` by using its id. This can either be done using a `ScrollViewReader` (as suggested in a comment) or by using a `.scrollPosition` modifier on the `ScrollView` (requires iOS 17). Here is an example of how it can be done using `.scrollPosition`. - The images used here are just system images (symbols). The symbol name is used as its id. - The images in the scrolled view all have different heights. This makes it difficult for a `LazyVStack` to predict the scroll distance correctly, so a `VStack` is used instead. But if your images all have the same height then you could try using a `LazyVStack`. - Set the target to scroll to in `.onAppear`. - You could try using different anchors for the scroll, but it may be difficult to control the exact screen position of the target image. ```swift struct ContentView: View { private let imageNames = ["hare", "tortoise", "dog", "cat", "lizard", "bird", "ant", "ladybug", "fossil.shell", "fish"] private let threeColumnGrid: [GridItem] = [.init(), .init(), .init()] var body: some View { NavigationStack { LazyVGrid(columns: threeColumnGrid, alignment: .center, spacing: 20) { ForEach(imageNames, id: \.self) { imageName in NavigationLink(destination: ScrollPostView(imageNames: imageNames, selectedName: imageName)){ Image(systemName: imageName) .resizable() .scaledToFit() .padding() .frame(maxHeight: 100) .background(.yellow) .clipShape(RoundedRectangle(cornerRadius: 15)) } .overlay( RoundedRectangle(cornerRadius: 15) .stroke(Color.black, lineWidth: 2) ) } } } } } struct ScrollPostView: View { let imageNames: [String] let selectedName: String @State private var scrollPosition: String? var body: some View { ScrollView { VStack { ForEach(imageNames, id: \.self) { imageName in Image(systemName: imageName) .resizable() .scaledToFit() .padding() .background(selectedName == imageName ? .orange : .yellow) .clipShape(RoundedRectangle(cornerRadius: 15)) } } .scrollTargetLayout() } .scrollPosition(id: $scrollPosition) .onAppear { scrollPosition = selectedName } } } ``` ![Animation](https://i.stack.imgur.com/oICcO.gif)
null
null
null
null
null
We're upgrading our PHP Laravel system, and one of the key concerns is the compatibility of passwords between the old and new systems. The passwords in the old system contain hashing function, and we need to ensure a smooth transition to the new hashing method without disrupting users' access. What would be the best way to handle this situation effectively in PHP Laravel? Any insights or suggestions would be greatly appreciated.
My question is a bit complex, but I'll try to make it clear. I want to create a Bash function. Now, here's the interesting part - I want to do this by referencing what the user will type. Since I don't know what that is, I'll optionally refer to it as $2, $3. How can I make it so that I can extract the commands that the user will type? For example - function check() { case $1 in -c) if [ -x $2 || -x ${@} ] then ${@} $* # these ("$@ & $*) represent what goes into this function fi esac } Then I call the function - "check -c /usr/". Working with the func, for example: if [ check -c | grep "/usr" != 0 ] # "check -c" is my func then cd /usr/ fi Or: check -c /usr/ && ls * If it succeeds, how do I continue writing what I want to do after "check -c /usr/"? Right after? Or in a new line? It's a bit like making a programming language - how do I make it so that these commands I type into the functions run? In short - I would like to create such functions for programming myself. Or should such things be done in C? If so, can I get links to study it? The point of this is to make programming easier for myself. I hope that was clear. If not, I can't explain it any better than that. Thanks in advance for your help!!!! I just tested this, but not with much success.
Custom Bash functions & custom statements - Need some advice
|c|linux|bash|function|shell|
null
We have web application which supports desktop and mobile chrome browsers . we are planning to create common driver for all platforms, like below RemoteWebdriver driver=initializeMobileWebdriver() and RemoteWebdrver driver=initializeDesktopWebdriver() in test class , if I use if else then I can able to run tests in parallel on Bothe the devices but if I dont use then we can not run tests in parallel what I want, I have to run same or different test on both mobile and desktop and then share the feedback. can someone help to run tests in local and hybrid
Run web tests in parallel on mobile and desktop with unique driver
|selenium-webdriver|appium|remotewebdriver|
Full working sample code: ```lang-hcl # variables.tf variable "envs" { description = "List of environments" type = list(string) default = [ "dev", "stg" ] } variable "tables" { description = "Dyanamodb tables" type = map(object({ hash_key = string attributes = list(map(string)) })) default = { "dynamo-db-table" = { hash_key = "key" attributes = [ { name = "key" type = "S" } ] } } } ``` ```lang-hcl # main.tf locals { # Create a map of environment to tables environment_tables = flatten([ for enviroment in var.envs : [ for table_key, table_value in var.tables : { table_name = "${enviroment}-${table_key}" hash_key = table_value.hash_key attributes = table_value.attributes } ] ]) } # dummy resource, for testing purposes only resource "null_resource" "dynamodb_table" { for_each = { for table in local.environment_tables : table.table_name => table } triggers = { name = each.key hash_key = each.value.hash_key # no need to use jsonencode in real code attributes = jsonencode(each.value.attributes) } } ``` Output of `terraform plan`: ```lang-txt Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols: + create Terraform will perform the following actions: # null_resource.dynamodb_table["dev-dynamo-db-table"] will be created + resource "null_resource" "dynamodb_table" { + id = (known after apply) + triggers = { + "attributes" = jsonencode( [ + { + name = "key" + type = "S" }, ] ) + "hash_key" = "key" + "name" = "dev-dynamo-db-table" } } # null_resource.dynamodb_table["stg-dynamo-db-table"] will be created + resource "null_resource" "dynamodb_table" { + id = (known after apply) + triggers = { + "attributes" = jsonencode( [ + { + name = "key" + type = "S" }, ] ) + "hash_key" = "key" + "name" = "stg-dynamo-db-table" } } Plan: 2 to add, 0 to change, 0 to destroy. ```
Have Html Code like this : ``` <div style="padding-right: 12px;"> <ul class="menu-items"> <li class="menu-item active" onclick="onMenuClick(this)"> <i class="fa-duotone fa-house-chimney"></i> پیشخوان </li> <li accessibility="edit_or_add_product" class="menu-item"> <i onclick="onMenuClick(this)" class="fa-duotone fa-compass"></i> موقعیت </li> <li class="menu-item" data-bs-toggle="collapse" data-bs-target="#cRequestMenu" aria-expanded="false" aria-controls="cRequestMenu"> <i class="fa-duotone fa-code-pull-request-draft"></i> مدیریت درخواست ها <ul class="menu-items collapse" id="cRequestMenu"> <li class="menu-item" onclick="onMenuClick(this)"> <i class="fa-duotone fa-arrow-progress"></i> پیگیری درخواست </li> </ul> </li> <li class="menu-item" onclick="onMenuClick(this)"><i class="fa-duotone fa-people-pants"></i>جمعیت</li> <li class="menu-item" data-bs-toggle="collapse" data-bs-target="#cMenuSystem" aria-expanded="false" aria-controls="cMenuSystem"> <i class="fa-duotone fa-server"></i> سیستم <ul class="menu-items collapse" id="cMenuSystem"> <li class="menu-item" onclick="openLink('Application/Log/log4j2' , this)"> <i class="fa-duotone fa-bug"></i> لاگ / دیباگ </li> </ul> </li> <li class="menu-item" onclick="onMenuClick(this)"> <i class="fa-solid fa-arrow-right-from-bracket"></i> خروج از سیستم </li> </ul> </div> ``` and js like this : ``` function openLink(href, elm) { window.open(href, '_blank').focus(); onMenuClick(elm); } function onMenuClick(elm) { let menu_items = document.getElementsByClassName('menu-item'); for (let i = 0; i < menu_items.length; ++i) { menu_items[i].classList.remove('active'); } elm.classList.add("active"); } ``` The result of my Code its here as Gif: [UI](https://i.stack.imgur.com/y5Zqr.gif) What I need is after click on Expanded UL item the expanded not going to Callops! and user sees what them clicked. in the other explation :what I want is user if expand the list and click on item the item shows active and not close the list.
Bootstrap Collapse this ul items onclick
|javascript|html|
null
A quick aside, we can cast to-and-fro from one table type to another, with restrictions: /** create a TYPE **/ CREATE TYPE tyNewNames AS ( a int, b int , c int ) ; SELECT /** note: order, type & # of columns must match exactly**/ ROW((rec).*)::tyNewNames AS "rec newNames" -- f1,f2,f3 --> a,b,c , (ROW((rec).*)::tyNewNames).* -- expand the new names ,'<new vs. old>' AS "<new vs. old>" ,* FROM ( SELECT /** inspecting rec: PG assigned stand-in names f1, f2, f3, etc... **/ rec /* a record*/ ,(rec).* -- expanded fields f1, f2, f3 FROM ( SELECT ( 1, 2, 3 ) AS rec -- an anon type record ) cte0 )cte1 ; +---------+-+-+-++------------+--------+--+--+--+ |rec |rec | |newnames |a|b|c|<new vs. old>|oldnames|f1|f2|f3| +---------+-+-+-++------------+--------+--+--+--+ |(1,2,3) |1|2|3|<new vs. old>|(1,2,3) |1 |2 |3 | +---------+-+-+-++------------+--------+--+--+--+ db fiddle(uk) [https://dbfiddle.uk/dlTxd8Y3][1] [1]: https://dbfiddle.uk/dlTxd8Y3
|javascript|reactjs|react-router|react-router-dom|
I have encountered an issue when rendering a visualization of a 2d matrix using Pygame (I am aware this not the best library for the job ... but anyway). The issue arises when I attempt to render each node in the matrix as a rectangle. Each node is an instance of the Node class and has x1, y1, x2, and y2 values derived from it's position in the array. x1 and y1 are the coordinates for the first point of the rectangle and x2 and y2 are the coordinates are the second point. When I use lines to represent the nodes, everything seems to render as I expected. However when I use rectangles, the rectangles clump together. I noticed these are the rectangles representing the nodes after the 0th row and col positions in the 2d list. Does anyone know why this is? I have provided script A (lines) and script B (rectangles) with images of the output for review. [Output for script A][1], [Output for script B][2] Script A (lines) ``` import pygame import time pygame.init() class Node: count = 0 def __init__(self, row, col): Node.count += 1 self.id = Node.count self.row = row self.col = col self.x1 = col * 10 self.y1 = row * 10 self.x2 = col * 10 + 5 self.y2 = row * 10 + 5 def display(matrix): for i in matrix: print(i) matrix = [[Node(i, j) for j in range(10)] for i in range(10)] win = pygame.display.set_mode((500, 500)) win.fill((0, 0, 0,)) for i in range(len(matrix)): for node in matrix[i]: pygame.draw.line(win, (0, 0, 255), (node.x1, node.y1), (node.x2, node.y2), width=1 ) pygame.display.update() time.sleep(0.1) ``` Script B (rectangles) ``` import pygame import time pygame.init() class Node: count = 0 def __init__(self, row, col): Node.count += 1 self.id = Node.count self.row = row self.col = col self.x1 = col * 10 self.y1 = row * 10 self.x2 = col * 10 + 5 self.y2 = row * 10 + 5 def display(matrix): for i in matrix: print(i) matrix = [[Node(i, j) for j in range(10)] for i in range(10)] win = pygame.display.set_mode((500, 500)) win.fill((0, 0, 0,)) for i in range(len(matrix)): for node in matrix[i]: pygame.draw.rect(win, (0, 0, 255), (node.x1, node.y1, node.x2, node.y2)) pygame.display.update() time.sleep(0.1) ``` The fact that the lines render in the correct positions leaves me puzzled as to why the rectangles are not as they are both using the same coordinates.
I'm calling a REST API endpoint via Azure Data Factory using copy activity. The API returns 404 - not found for valid queries where no data is found. Whether this is the appropriate response or not (I have no control over the API), is there a way to access the API status code (i.e. not Azure error code?) in ADF? I want the pipeline to return 'success' when a 404 not found is returned, but still fail when other errors occur. I have set up an 'on failure' error handling activity, but I'm getting stuck on how to distinguish between 'valid' errors & 404s due to no data. [Activity output](https://i.stack.imgur.com/Tpw41.png) The error message string contains the status code (& response), which is what I'm after. Ideally I'd like to compare against these without doing a string comparison, especially seeing as the message appears to be constructed using the exact response fields I'm after. The 404 only occurs for some query parameters & the response is the same via Postman, so I'm relatively confident it is an intended response from the API. Based on [Azure data factory - getting the HTTP Status of a web activity output](https://stackoverflow.com/questions/71556696/azure-data-factory-getting-the-http-status-of-a-web-activity-output) I'm not sure if this can be done exactly, but thought I'd (a) check & (b) see if anyone can suggest a better approach.
you can use render function in your story to close the modal. like this: export const DefaultModal: Story = { args: { avatarUrl: 'https://placehold.co/100', isOpen: true, hasFullImage: true, }, render: (args) => { const [{ value }, updateArgs] = useArgs(); const onCloseModal = () => { updateArgs({isOpen: false}); } return <ItemModals {...args} /> } };
|php|laravel-8|bcrypt|laravel-10|