text
stringlengths
15
59.8k
meta
dict
Q: Android: Handling screens that are the same dpi level but different I have gone through all of the Android docs about handling multiple screen sizes but I still haven't been able to find an answer to this question or how to handle this. If there are two phones that have the same dpi level (such as both being hdpi) I can provide one resource for them and set the layout parameters as such: <ImageView android:id="@+id/icon" android:layout_width="94dp" android:layout_height="94dp" > The "icon" in this instance is large enough so that it will scale down to fit that layout in all cases. In an ideal world, I would assume that the icon would appear the exact same size on all hdpi devices, however when I tested it out on a LG G2x and a HTC Sensation, the image is smaller on the Sensation. So is Android always just using a factor of 1.5x when calculating the size the hdpi image? Is there something I can do to guarantee the size will be the exact same on all hdpi devices? Thanks. A: You can use this to help you out with the proyect http://developer.android.com/training/multiscreen/screensizes.html A: The answer was that the system does use a standard multiplier for each dpi level (1.5x for hdpi for example). In order to get around this I just used the .xdpi and .ydpi values of DisplayMetrics and do my calculations off of those real values. A: Usually when ever we want to do like this we usually use wrap_content. so once try layout_width = "wrap_content",layout_height = "wrap_content". Such that ANdroid SDK will look.
{ "language": "en", "url": "https://stackoverflow.com/questions/10055204", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I installed scott user creating file but It wasn't the scott It mentioned like USER is "" as u know it usually downloads together with scott.sql file but Idk why but It couldn't download it so, eventually, I did it by myself. even directory wasn't created so I made it those by myself as well. anyway, even though I did it and succeeded to create user, it didn't have the name like that pic and as u know we don't have any way to change user's name so I couldn't. How can I change it to scott like normal?
{ "language": "en", "url": "https://stackoverflow.com/questions/59163561", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: whats wrong in my code? why the error msg The following code works just fine I can get the results I want if I ignore the error message once I run it. the error I get is: Debug Error! Program:c:\qt\qt5.5.1\5.5\msvc2013_64\bin\Qt5Cored.dll Module: 5.5.1 File: global\qglobal.cpp Line: 2966 ..... if I chose to ignore error the console app displays all data correctly it shows the correct bits array it also shows correct character for the binary array and last it gives also the correct byte decimal value for the byte char... this is the error in console: ASSERT: "uint(i) < uint(size())" in file c:\work\build\qt5_workdir\w\s\qtbase\sr c\corelib\tools\qbytearray.h, line 464 this is correct output: Bits are: QBitArray(0110 0011) Byte Char is "c" Decimal format Bytes are: 99 Code used: QBitArray Alphabits(8); Alphabits[0] = false; Alphabits[1] = true; Alphabits[2] = true; Alphabits[3] = false; Alphabits[4] = false; Alphabits[5] = false; Alphabits[6] = true; Alphabits[7] = true; QByteArray Alphabytes; // Convert from QBitArray to QByteArray for(int b=0; b<Alphabits.count();++b) { Alphabytes[b/8] = (Alphabytes.at(b/8) | ((Alphabits[b]?1:0)<<(7-(b%8)))); } qDebug() << "Bits are:" << Alphabits; qDebug() << "Byte Char is" << Alphabytes; qDebug() << "Decimal format Bytes are: "<< static_cast<quint8>(Alphabytes[0]); A: Ok, i figure out where is the problem. This is because when you inside for make call Alphabytes.at(b/8) for the first time, the size of Alphabytes is zero, so you try get index that is out of array range. Replace this with Alphabytes[b/8] = (Alphabytes[b/8] |....... A: It seems that in release mode everything compiles and even no errors or warnings etc are detected so this is strange it only happens in debug mode so I think ill report this in QT bug tracking maybe... Unless anyone can figure out why this error only happens when debugging...
{ "language": "en", "url": "https://stackoverflow.com/questions/34772787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ThreadLocal garbage collection From javadoc Each thread holds an implicit reference to its copy of a thread-local variable as long as the thread is alive and the ThreadLocal instance is accessible; after a thread goes away, all of its copies of thread-local instances are subject to garbage collection (unless other references to these copies exist). from that it seems that objects referenced by a ThreadLocal variable are garbage collected only when thread dies. But what if ThreadLocal variable a is no more referenced and is subject for garbage collection? Will object references only by variable a be subject to garbage collection if thread that holds a is still alive? for example there is following class with ThreadLocal variable: public class Test { private static final ThreadLocal a = ...; // references object b } This class references some object and this object has no other references to it. Then during context undeploy application classloader becomes a subject for garbage collection, but thread is from a thread pool so it does not die. Will object b be subject for garbage collection? A: TL;DR : You cannot count on the value of a ThreadLocal being garbage collected when the ThreadLocal object is no longer referenced. You have to call ThreadLocal.remove or cause the thread to terminate (Thanks to @Lii) Detailed answer: from that it seems that objects referenced by a ThreadLocal variable are garbage collected only when thread dies. That is an over-simplification. What it actually says is two things: * *The value of the variable won't be garbage collected while the thread is alive (hasn't terminated), AND the ThreadLocal object is strongly reachable. *The value will be subject to normal garbage collection rules when the thread terminates. There is an important third case where the thread is still live but the ThreadLocal is no longer strongly reachable. That is not covered by the javadoc. Thus, the GC behaviour in that case is unspecified, and could potentially be different across different Java implementations. In fact, for OpenJDK Java 6 through OpenJDK Java 8 (and other implementations derived from those code-bases) the actual behaviour is rather complicated. The values of a thread's thread-locals are held in a ThreadLocalMap object. The comments say this: ThreadLocalMap is a customized hash map suitable only for maintaining thread local values. [...] To help deal with very large and long-lived usages, the hash table entries use WeakReferences for keys. However, since reference queues are not used, stale entries are guaranteed to be removed only when the table starts running out of space. If you look at the code, stale map entries (with broken WeakReferences) may also be removed in other circumstances. If stale entry is encountered in a get, set, insert or remove operation on the map, the corresponding value is nulled. In some cases, the code does a partial scan heuristic, but the only situation where we can guarantee that all stale map entries are removed is when the hash table is resized (grows). So ... Then during context undeploy application classloader becomes a subject for garbage collection, but thread is from a thread pool so it does not die. Will object b be subject for garbage collection? The best we can say is that it may be ... depending on how the application manages other thread locals the thread in question. So yes, stale thread-local map entries could be a storage leak if you redeploy a webapp, unless the web container destroys and recreates all of the request threads in the thread pool. (You would hope that a web container would / could do that, but AFAIK it is not specified.) The other alternative is to have your webapp's Servlets always clean up after themselves by calling ThreadLocal.remove on each one on completion (successful or otherwise) of each request. A: ThreadLocal variables are hold in Thread ThreadLocal.ThreadLocalMap threadLocals; which is initialized lazily on first ThreadLocal.set/get invocation in the current thread and holds reference to the map until Thread is alive. However ThreadLocalMap uses WeakReferences for keys so its entries may be removed when ThreadLocal is referenced from nowhere else. See ThreadLocal.ThreadLocalMap javadoc for details A: If the ThreadLocal itself is collected because it's not accessible anymore (there's an "and" in the quote), then all its content can eventually be collected, depending on whether it's also referenced somewhere else and other ThreadLocal manipulations happen on the same thread, triggering the removal of stale entries (see for example the replaceStaleEntry or expungeStaleEntry methods in ThreadLocalMap). The ThreadLocal is not (strongly) referenced by the threads, it references the threads: think of ThreadLocal<T> as a WeakHashMap<Thread, T>. In your example, if the classloader is collected, it will unload the Test class as well (unless you have a memory leak), and the ThreadLocal a will be collected. A: ThreadLocal contains a reference to a WeakHashMap that holds key-value pairs A: It depends, it will not be garbage collected if your are referencing it as static or by singleton and your class is not unloaded, that is why in application server environment and with ThreadLocal values, you have to use some listener or request filter the be sure that you are dereferencing all thread local variables at the end of the request processing. Or either use some Request scope functionality of your framework. You can look here for some other explanations. EDIT: In the context of a thread pool as asked, of course if the Thread is garbaged thread locals are. A: Object b will not be subject for garbage collection if it somehow refers to your Test class. It can happen without your intention. For example if you have a code like this: public class Test { private static final ThreadLocal<Set<Integer>> a = new ThreadLocal<Set<Integer>>(){ @Override public Set<Integer> initialValue(){ return new HashSet<Integer>(){{add(5);}}; } }; } The double brace initialization {{add(5);}} will create an anonymous class which refers to your Test class so this object will never be garbage collected even if you don't have reference to your Test class anymore. If that Test class is used in a web app then it will refer to its class loader which will prevent all other classes to be GCed. Moreover, if your b object is a simple object it will not be immediately subject for GC. Only when ThreadLocal.ThreadLocalMap in Thread class is resized you will have your object b subject for GC. However I created a solution for this problem so when you redeploy your web app you will never have class loader leaks.
{ "language": "en", "url": "https://stackoverflow.com/questions/17104452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: How do you find duplicated elements of a vector that outputs the integer appearance of that duplicate instead of a logical? We know that the duplicated() function outputs a vector of logicals. What I want, however, is a vector of integers such that, if this is the (n+1)th time that this particular element appears, the corresponding element of the output vector is n. For example, if we call the function that I'm looking for "intDuplicate()" then I would want the following output: > x <- sample(c('a','b','c'),10,replace=T) > y <- intDuplicate(x) > x [1] "c" "b" "b" "a" "a" "b" "c" "b" "b" "c" > y [1] 0 0 1 0 1 2 1 3 4 2 So, for example, y[9] = 4 because this is the fifth occurrence of 'b' (i.e. fourth duplication). Is there a vectorized way to do this? A: Here's a possible solution using base R (not sure if vectorized enough for you) as.numeric(ave(x, x, FUN = seq)) - 1L ## [1] 0 0 1 0 1 2 1 3 4 2 Or something similar using data.table package library(data.table) as.data.table(x)[, y := seq_len(.N) - 1L, by = x][] # x y # 1: c 0 # 2: b 0 # 3: b 1 # 4: a 0 # 5: a 1 # 6: b 2 # 7: c 1 # 8: b 3 # 9: b 4 # 10: c 2 Or maybe a dplyr option library(dplyr) data.frame(x) %>% group_by(x) %>% mutate(y = row_number() - 1L) # Source: local data frame [10 x 2] # Groups: x # # x y # 1 c 0 # 2 b 0 # 3 b 1 # 4 a 0 # 5 a 1 # 6 b 2 # 7 c 1 # 8 b 3 # 9 b 4 # 10 c 2
{ "language": "en", "url": "https://stackoverflow.com/questions/29615834", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Access a ViewModel from another ViewModel I'm developing an WPF using MVVM pattern, C# and .NET Framework 4.6.1. I have a Window that contains an UserControl (Control1) and that UserControl contains another UserControl (Control2). I have chosen this way to do it instead of using a Dialog Window (Control2 acts as Dialog Window). Both user controls have a Viewmodel (Control1VM and Control2VM). I use Control2 as a form to let users input some data that I need to start the application. This is the MainWindow with Control1: And this is Control2 over Control1. My problem is that I don't know how to hide Control2 when I click on OK or Cancel button. This is how Control2 is set on Control1: <Grid x:Name="gridControl2" Margin="30" Grid.RowSpan="6" Grid.ColumnSpan="3" Visibility="{Binding GridControl2Visibility}"> <local:Control2 x:Name="userControlControl2" /> </Grid> To show Control2 and set GridControl2Visibility to Visible in Control1VM: public Visibility GridControl2Visibility { get { return gridControl2Visibility; } set { if (gridControl2Visibility != value) { gridControl2Visibility = value; RaisePropertyChangedEvent("GridControl2Visibility"); } } } How can I hide Control2 when I click on Ok or Cancel button in Control2? My problem is that GridControl2Visibility is on Control1VM and I can't access that class from Control2VM. A: Use a service that both view models can access and that stores the info whether Control2 should be visible or not. Ideally, the service would be registered as singleton with your di-container and injected into the view models. Alternatively, you can use an event aggregator, which is basically a singleton service, too, but focused on distributing events rather than holding a state. A: You can use events, You can raise event from Control2VM and hadnle it in Control1VM and set GridControl2Visibility to false.
{ "language": "en", "url": "https://stackoverflow.com/questions/39268440", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python or Matlab rotate with spline interpolation order higher than 5 I need to do a rotation with a spline interpolation of high order >5. I insist on the fact that it is for interpolating rotated data, not upsampling. I found : https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.rotate.html?highlight=rotate#scipy.ndimage.rotate but only up to splines order 5. (I know orders > 3 are unusual, nevertheless I do need it). any idea of a Python/Matlab or way to implement higher order spline interpolation for rotation ?
{ "language": "en", "url": "https://stackoverflow.com/questions/71565039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Wilcoxon test with chicken's weight data(ChickWeight) head(ChickWeight) plot( ChickWeight$Time, ChickWeight$weight, col=ChickWeight$Diet) chick = reshape(ChickWeight, idvar=c("Chick","Diet"), timevar="Time", direction="wide") head(chick) chick = na.omit(chick) Perform a t-test of x and y, after adding a single chick of weight 200 grams to x (the diet 1 chicks). What is the p-value from this test? The p-value of a test is available with the following code: t.test(x,y)$p.value Do the same for the Wilcoxon test. The Wilcoxon test is robust to the outlier. In addition, it has less assumptions that the t-test on the distribution of the underlying data. When I try do Wilcoxon test: wilcox.test(c(x, 200), y) I get this error: Warning message: In wilcox.test.default(c(x, 200), y) : cannot compute exact p-value with ties A: Use exactRankTests::wilcox.exact: If x is a weight for example time 0 e.g. chick$weight.0 and y is a weight for example time 2 e.g. chick$weight.2 Then you could do it this way: With wilcox.test you will get a warning message: > wilcox.test(c(chick$weight.0, 200), chick$weight.2)$p.value [1] 6.660003e-14 Warning message: In wilcox.test.default(c(chick$weight.0, 200), chick$weight.2) : cannot compute exact p-value with ties Use exactRankTests::wilcox.exact() that can handle ties: t.test(chick$weight.0,chick$weight.2)$p.value 6.660003e-14 exactRankTests::wilcox.exact(c(chick$weight.0, 200), chick$weight.2)$p.value [1] 5.889809e-18
{ "language": "en", "url": "https://stackoverflow.com/questions/70724754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Repeating text in Processing language So I need to repeat text 40 times, I figured out how to do a line a certain amount of times, but using the same process for text is not working, ive tried messing around with different code but I am stuck. Any help would be great. I just need to repeat the word "text" 40 times in the program. Here is my current code: void setup() { size(640, 360); textFont(createFont("Georgia", 24)); } void draw() { background(102); textAlign(RIGHT); drawType(width * 0.10); } void drawType(float x) { fill(0); float y = 35; int spacing = 50; int endLine = 640; while (x <= endLine){ text("text", x, y, 50, 50); x = x + y + spacing; } } I'm using the language Processing, (processing.org), which is a type of JAVA. A: Just thought i would be clear with my comment: try String var=""; for(int i=0;i<40;i++) { var=var+"text"; } //Then use the variable got text(var, x, y, 50, 50); There may be built in functions to do this in a better way, but this would be a simple way to solve your problem. This method though is in-efficient as String operations are costly in Java because they are immutable. The above example would print the same string 40 times in a single line(depending upon the length of the line). If the horizontal length of the line is not sufficient, either increase the line size or decrease the spacing or decrease the number of times you are repeating the string.
{ "language": "en", "url": "https://stackoverflow.com/questions/13365276", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SQL - Select MAX or TOP 1 FROM each month I have a query that literally does nothing helpful, but hopefully paints the picture of what I am trying to accomplish. SELECT * FROM Tbl_StockData WHERE Date <= DateSerial(YEAR(Date), MONTH(Date) + 1, 1) - 1); Which basically gets all values where the date is <= the end of the month. From here, I want to select the top (or latest) day from each month of the query. I.e, the current query produces CodeName Date ---------------------- 14D 2018-09-12 14D 2018-09-13 14D 2018-09-14 14D 2018-09-17 14D 2018-09-18 14D 2018-09-19 14D 2018-09-20 14D 2018-09-21 14D 2018-09-24 14D 2018-09-25 14D 2018-09-26 14D 2018-09-27 14D 2018-09-28 14D 2018-10-01 . . . And note that it is not just 14D listed here, there are many more. What you can see here is that the end of month data is not always the 31'st or 30'th, so for each new month, for each new CodeName, I want to obtain the last value in the given month, for all months. Something that achieves this would look like CodeName Date ---------------------- 14D 2018-09-28 14D 2018-10-31 14D 2018-11-30 14D 2018-12-31 14D 2019-01-31 14D 2019-02-28 . . . Okay, well I got a bit unlucky with that one given then last 5 dates are, in fact, the EOM date, but hopefully the point is clear. If I were to select the MAX or TOP of the days in a given month, I would like it to return me the last date in the data set of the month, for all months, for all CodeNames.
{ "language": "en", "url": "https://stackoverflow.com/questions/68238384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Error when calling classroom PHP API method: courses.courseWork.list So I use the Google Classroom PHP API to integrate it with my project. When the user is requested to logging with the google account, I request the following scopes. Google_Service_Classroom::CLASSROOM_COURSES_READONLY, Google_Service_Classroom::CLASSROOM_ROSTERS_READONLY, Google_Service_Classroom::CLASSROOM_PROFILE_EMAILS, Google_Service_Classroom::CLASSROOM_COURSEWORK_STUDENTS_READONLY, Google_Service_Classroom::CLASSROOM_ANNOUNCEMENTS_READONLY Interesting enough, the accessToken generated returns the following scopes: Google_Service_Classroom::CLASSROOM_COURSES_READONLY, Google_Service_Classroom::CLASSROOM_ROSTERS_READONLY, Google_Service_Classroom::CLASSROOM_PROFILE_EMAILS, Google_Service_Classroom::CLASSROOM_STUDENT_SUBMISSIONS_STUDENTS_READONLY, Google_Service_Classroom::CLASSROOM_ANNOUNCEMENTS_READONLY The problem is that courses.courseWork.list specifically requires Google_Service_Classroom::CLASSROOM_COURSEWORK_STUDENTS_READONLY, as stated in the API reference. So as a result I'm getting an error: { "error":{ "code":403, "message":"The caller does not have permission", "errors":[ { "message":"The caller does not have permission", "domain":"global", "reason":"forbidden" } ], "status":"PERMISSION_DENIED" } } Am I doing something wrong or this might be an API bug? Adding further details on the code. First the frontend request the Authorization URL, that one where the user will login and accept the scopes being requested. This is done with the following methods: Frontend > getAuthorizationURL > getGoogleAuthorizationURL. public function getAuthorizationURL($parameters) { $classroomIntegration = new classroomIntegration(); $asyncState = $classroomIntegration->generateGoogleAsyncState(classroomIntegration::$CLASSROOM_INTEGRATION, $parameters->userID); $resultUrl = googleLogin::getGoogleAuthorizationURL("callback.php", $asyncState, [Google_Service_Classroom::CLASSROOM_COURSES_READONLY, Google_Service_Classroom::CLASSROOM_ROSTERS_READONLY, Google_Service_Classroom::CLASSROOM_PROFILE_EMAILS, Google_Service_Classroom::CLASSROOM_COURSEWORK_STUDENTS_READONLY, Google_Service_Classroom::CLASSROOM_ANNOUNCEMENTS_READONLY, Google_Service_Oauth2::USERINFO_PROFILE]); $this->respond(TRUE, $resultUrl); } public static function getGoogleAuthorizationURL($callbackRelativePath, $asyncState, $scopes){ $client = new Google_Client(); $httpHost = constant("httpHost"); $client->setAuthConfig("credentials.json"); $client->setRedirectUri("http://" . $httpHost . $callbackRelativePath); $client->setApplicationName("Dummy App"); $client->setPrompt("consent"); $client->setApprovalPrompt("consent"); foreach($scopes as $scope){ $client->addScope($scope); } $client->setAccessType("offline"); $client->setIncludeGrantedScopes(true); $client->setState($asyncState); $authUrl = $client->createAuthUrl(); return filter_var($authUrl, FILTER_SANITIZE_URL); } Than in the callback file I just get the access code, which contains the tokens and the scopes that were granted: $client->setAccessType("offline"); $code = filter_input(INPUT_GET, "code"); $accessToken = $client->fetchAccessTokenWithAuthCode($code); So basically on the list of scopes that were granted, instead of getting the Google_Service_Classroom::CLASSROOM_COURSEWORK_STUDENTS_READONLY as requested I'm being granted the Google_Service_Classroom::CLASSROOM_STUDENT_SUBMISSIONS_STUDENTS_READONLY. Problem is that courses.courseWork.list requires the first one.
{ "language": "en", "url": "https://stackoverflow.com/questions/68270941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to run a memory intensive spark streaming job using the smallest memory usage possible I am running a job that joins two kafka topics into one topic using a value. The environment I am using only allow me to assign less than 10g ram per job, the data I am trying to join is around 500k record per topic. I am pretty new to Spark, so I'd like to know if there is a way to minimize the memory consumption the code: val df_person: DataFrame = PERSONINFORMATION_df .select(from_json(expr("cast(value as string) as actualValue"), schemaPERSONINFORMATION).as("s")).select("s.*").withColumn("comsume_date", lit(LocalDateTime.now.format(DateTimeFormatter.ofPattern("HH:mm:ss.SS")))).as("dfperson") val df_candidate: DataFrame = CANDIDATEINFORMATION_df .select(from_json(expr("cast(value as string) as actualValue"), schemaCANDIDATEINFORMATION).as("s")).select("s.*").withColumn("comsume_date", lit(LocalDateTime.now.format(DateTimeFormatter.ofPattern("HH:mm:ss.SS")))).as("dfcandidate") Join topics: val joined_df : DataFrame = df_candidate.join(df_person, col("dfcandidate.PERSONID") === col("dfperson.ID"),"inner").withColumn("join_date", lit(LocalDateTime.now.format(DateTimeFormatter.ofPattern("HH:mm:ss.SS")))) Re-structure the data val string2json: DataFrame = joined_df.select($"dfcandidate.ID".as("key"),to_json(struct($"dfcandidate.ID".as("candidateID"), $"FULLNAME", $"PERSONALID",$"join_date",$"dfcandidate.PERSONID".as("personID"),$"dfcandidate.comsume_date".as("candidate_comsume_time"),$"dfperson.comsume_date".as("person_comsume_time"))).cast("String").as("value")) write them to a topic string2json.writeStream.format("kafka") .option("kafka.bootstrap.servers", "xxx:9092") .option("topic", "mergedinfo") .option("checkpointLocation", "/tmp/producer/checkpoints") .option("failOnDataLoss", false) .start() .awaitTermination() the run command: spark-submit --class taqasi_spark.App --master yarn ./spark_poc-test_memory.jar --executor-memory 10g --driver-memory 10g --executor-memory 10g --deploy-mode cluster
{ "language": "en", "url": "https://stackoverflow.com/questions/65977380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to download Git's code using SourceTree I have created a project in git.oschina.net (via website). I wish to checkout this project using Atlassian SourceTree, but have failed to do so. Please note that I am using a foreign language with my client. I have received the following error message : Authentication failed for 'https://gitee.com/weidu23/EduInfoProj.git/' You can see the error message snapshots below : SourceTree repository URL dialog box SourceTree Log Can anyone please help with this issue? Many thanks in advance A: Goto SourceTree Preferences > Accounts Add your account. A: You could try go to: ~/Library/Application Support/SourceTree and then look for a file similar to username\@STAuth-path.to.gitrepository.com and delete it. You will be prompted for a new password
{ "language": "en", "url": "https://stackoverflow.com/questions/49644475", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to query all the tables in a database to get the last existing value? I've got several databases in which every table contains data from energy-meters, structure is always like that: ------------------------------------------------------------------------- | dsid | tag | timestamp | value | startts | correctts | isfixed | ========================================================================= | 1 | EE | 1444716843 | 519.193 | 1444716000 | 1444716900 | 0 | ------------------------------------------------------------------------- | 2 | PO | 1444716843 | 0.090 | 1444716000 | 1444716900 | 0 | ------------------------------------------------------------------------- | 3 | EE | 1444717743 | 519.216 | 1444716900 | 1444717800 | 0 | ------------------------------------------------------------------------- using the following code I can read the last existing value in one table: SELECT from_unixtime(TIMESTAMP) AS DATE, VALUE FROM `KA-AIK_Labor` WHERE `timestamp` BETWEEN UNIX_TIMESTAMP('19-03-19') AND UNIX_TIMESTAMP('19-03-31 23:59:59') ORDER BY DSID DESC LIMIT 1 What I'ld like to achieve is an output like the following: ---------------------------------------------------------- | dsid | TABELNAME | DATE | VALUE | ========================================================== | 1 | KA-AIK_Labor | 2019-03-25 10:30:23 | 360884.000 | ---------------------------------------------------------- | 2 | KA-AIK_1. OG | 2019-03-25 10:44:00 | 12251.334 | ---------------------------------------------------------- I've already got some code to get a list of all tables in my Database: select table_name from information_schema.tables where TABLE_SCHEMA='KAAIK' But with my little SQL Experience I don't know how to incorporate that code into one... And additionally I'ld love to read all the tables into one like that: ------------------------------------------------------------------------------------- | dsid | DATE | TABELNAME#1 | VALUE#1 | TABELNAME#1 | VALUE#1 | ===================================================================================== | 1 | 2019-03-25 10:30:23 | KA-AIK_Labor | 360884.000 | KA-AIK_1. OG | 12251.315 | ------------------------------------------------------------------------------------- | 2 | 2019-03-25 10:45:17 | KA-AIK_Labor | 360884.010 | KA-AIK_1. OG | 12251.325 | ------------------------------------------------------------------------------------- I've the following code: SELECT from_unixtime(TIMESTAMP) AS DATE, VALUE FROM `KA-AIK_1. OG` WHERE `timestamp` BETWEEN UNIX_TIMESTAMP('19-03-24') AND UNIX_TIMESTAMP('19-03-24 11:59:59') to read a list like this: ----------------------------------- | DATE | VALUE | =================================== | 2019-03-25 10:30:23 | 12251.315 | ----------------------------------- | 2019-03-25 10:45:17 | 12251.325 | ----------------------------------- But again I can't find out how to transform/modify my code..
{ "language": "en", "url": "https://stackoverflow.com/questions/55485066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to correctly override literal operators? Ok, so I made my own class and I've overloaded an operator ""s so I can use it for my string formation. BUT, I get an error when compiling and I have no idea what it means. Could someone explain the meaning of it and how to fix it? my code: PString operator"" s(const char* text, std::size_t len) { return PString(std::string(text, len)); } my error: error: ‘PString PString::operator""s(const char*, std::size_t)’ must be a non-member function PString operator"" s(const char* text, std::size_t len) { A: Ok, so prior to asking this question I've been confused about something. Because I've added other operator overrides inside of the class, I thought that I was supposed to add that operator"" s inside of the class as well. But apparently, that is not so. I'm keeping this just as a reference to the answer @user0042 gave to me. This is what solved the problem for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/47728887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: chartSeries bounds: setting par("usr") equal to itself changes the axes I'm trying to set the bounds on a graph so I can plot indicators, then move/squish the bounds so I can plot points in the same place. However, I'm having trouble just getting started since when I change the bounds to itself the relative axis appears to change. example: Open High Low Close 2014-06-15 23:16:26 13798 13800 13797 13799 2014-06-15 23:38:13 13799 13800 13797 13798 2014-06-15 23:59:59 13798 13800 13794 13798 2014-06-16 00:21:39 13798 13800 13795 13796 2014-06-16 00:43:11 13796 13799 13795 13798 Now the following code will draw two different rectangles, the second slightly higher and to the right by about 14x6 pixels > par("usr") [1] 0.44 15.56 13793.76 13800.24 > rect(1,13796,4,13798) > par(usr=par("usr")) > rect(1,13796,4,13798) > par("usr") [1] 0.44 15.56 13793.76 13800.24 This is pretty infuriating... what I'm trying to fix is the fact that this happens when I try to plot an indicator... the bounds are automatically moved: > par("usr") [1] 0.44 15.56 13793.76 13800.24 > addMACD(slow=2,fast=1,signal=1) > par("usr") [1] 0.440000000 15.560000000 -0.008219178 0.008219178
{ "language": "en", "url": "https://stackoverflow.com/questions/24829100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detecting from which USB port input comes I have a project in which input would come from multiple peripherals (in this case, barcode scanners) and I would need to know which barcode scanner the input is coming from, but all I have found when researching this was comminicating with USB drive. I am using Java on a Raspberry Pi 2. A: I assume that your application will do specific things with data from specific bar-code scanners i.e. scanner1 is connected to cash register 1 and scanner2 to register 2 etc. Further I assume that you use some standard scanner hardware which identifies to a Linux system as an HID keyboard device. On modern Linux operating systems such as Raspbian USB devices are registered as device nodes in /dev/input/by-id. An example of a keyboard connected to my Pi is: /dev/input/by-id/usb-0130_0005-event-kbd. Linux HID device nodes allow you to directly read from them just like you would read from a file. This means that you can do something like the following, to make sure that your Java program reads from a particular barcode scanner only: DataInputStream in = new DataInputStream( new FileInputStream("/dev/input/by-id/usb-0130_0005-event-kbd")); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line; while((line = reader.readLine()) != null) { // evaluate the EAN code which is now in line } Assumption that your scanner like ours send a carriage return / line feed after each successfully scanned code. We use similar code in one of our applications to make sure, that our users not accidentally scan EAN codes in other fields such as names and description fields. In our application bar code scanners add items to an item list and keyboard input is exclusively used for other user input. On application startup in the main method we use code similar to this in order to make sure that keyboard and barcode scanners get distinguished. public static void main(String args[]) { String keyboardInput = args[0]; String barcodeInput = args[1]; // see code above how to read from the particular devices } As for application startup we use Linux command line tools to determine which device nodes refer to the barcode scanner and which to the keyboard. Basically a combination of lsusb and a set of Udev rules that get executed whenever a USB device is connected to the machine. However, this is out of the context of your question.
{ "language": "en", "url": "https://stackoverflow.com/questions/35895875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: reading entire text file using vba I'm trying to read a text file using vba. I tried the below code Open "C:\tester.txt" For Input As #1 Worksheets("UI").Range("H12").Value = Input$(LOF(1), 1) Close #1 When I run this I'm getting an error. Run-time error '62'. Input past end of file. The content of text file is: Unable to open COM10. Make sure it is connected Plus other stuff And more stuff way more stuff Thanks in advance for help. A: More Slightly modified for those who do not like VBA to have to make up explicit variables and then waste time transfer data to them.. Let With. do the job Function LoadFileStr$(FN$) With CreateObject("Scripting.FileSystemObject") LoadFileStr = .OpenTextFile(FN, 1).readall End With End Function A: brettdj's answer, slightly adjusted Public Function readFileContents(ByVal fullFilename As String) As String Dim objFSO As Object Dim objTF As Object Dim strIn As String Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTF = objFSO.OpenTextFile(fullFilename, 1) strIn = objTF.readall objTF.Close readFileContents = strIn End Function A: To read line by line: Public Sub loadFromFile(fullFilename As String) Dim FileNum As Integer Dim DataLine As String FileNum = FreeFile() Open fullFilename For Input As #FileNum While Not EOF(FileNum) Line Input #FileNum, DataLine Debug.Print DataLine Wend End Sub A: Rather than loop cell by cell, you can read the entire file into a variant array, then dump it in a single shot. Change the path from C:\temp\test.txt to suit. Sub Qantas_Delay() Dim objFSO As Object Dim objTF As Object Dim strIn 'As String Dim X Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTF = objFSO.OpenTextFile("C:\temp\test.txt", 1) strIn = objTF.readall X = Split(strIn, vbNewLine) [h12].Resize(UBound(X) + 1, 1) = Application.Transpose(X) objTF.Close End Sub A: The following code will loop through each line in the text document and print these from range H12 and downward in the UI-sheet. Sub ImportFromText() Open "C:\tester.txt" For Input As #1 r = 0 Do Until EOF(1) Line Input #1, Data Worksheets("UI").Range("H12").Offset(r, 0) = Data r = r + 1 Loop Close #1 End Sub A: Sub LoadFile() ' load entire file to string ' from Siddharth Rout ' http://stackoverflow.com/questions/20128115/ Dim MyData As String Open "C:\MyFile" For Binary As #1 MyData = Space$(LOF(1)) ' sets buffer to Length Of File Get #1, , MyData ' fits exactly Close #1 End Sub A: I think an easier alternative is Data > From Text and you can specify how often the data is refreshed in the Properties. A: Fidel's answer, over Brettdj's answer, adjusted for ASCII or Unicode and without magical numbers: Public Function readFileContents(ByVal fullFilename As String, ByVal asASCII As Boolean) As String Dim objFSO As Object Dim objTF As Object Dim strIn As String Set objFSO = CreateObject("Scripting.FileSystemObject") Set objTF = objFSO.OpenTextFile(fullFilename, IOMode:=ForReading, format:=IIf(asASCII, TristateFalse, TristateTrue)) strIn = objTF.ReadAll objTF.Close readFileContents = strIn End Function
{ "language": "en", "url": "https://stackoverflow.com/questions/20390397", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "16" }
Q: should I use strategy pattern, If I have hundreds of actions I have a class doing translate job. But it have hundreds of specific translate methods! The action code determine which method will be used! I want to use strategy pattern, but it will create hundreds of sub class! I want to name the methods end of action code and use reflection to do the translate, but I'm concern abort the execution performances. It will be called very frequently! What design pattern or patterns should I use to solve this problem! code like this: public class Test003_Translate { private static final String PREFIX = "translate"; public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Test003_Translate translate = new Test003_Translate(); Map<String, String> map = new HashMap<>(); map.put("key001", "001"); map.put("key002", "002"); map.put("key003", "003"); translate.doTranslate(map, "key001"); } private void doTranslate(Map<String, String> map, String key) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { String actionCode = map.get(key); Method method = Test003_Translate.class.getMethod(PREFIX + actionCode, String.class); String arg = "arg: "; Object s = method.invoke(this, arg); } public String translate001(String input){ return input + "001"; } public String translate002(String input){ return input + "002"; } public String translate003(String input){ return input + "003"; } } A: You could use an EnumMap (smaller and faster then a HashMap), like this: enum Key { KEY_001, .... } EnumMap<Key, Runnable> enumMap = new EnumMap<>(Key.class); enumMap.put(Key.KEY_001, YourClass::translate001); .... And usage: enumMap.get(someKey).run();
{ "language": "en", "url": "https://stackoverflow.com/questions/67533224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Load HTML source code How do I load HTML source code? I tried a few functions with no luck. This one works for me on many sites, but not all of them: function LoadWebPageToString(MyUrl: String): String; //load HTML content from a webpage to a string begin Result := 'Error'; with TIdHTTP.Create do begin try Result := Get(MyUrl); finally Free; end; end; end; When it fails, I get this error: HTTP/1.1 403 forbidden The target page is just a normal page. It loads normally via HTTP, doesn't require (think nor supports) HTTPS. Maybe it is about cookies or something? I don't know. A: One of the reasons of the HTTP/1.1 403 forbidden is which the server doesn't recognizes the user agent of the client, so try setting the useragent property like so . Request.UserAgent:='Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0';
{ "language": "en", "url": "https://stackoverflow.com/questions/17137506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Azure DevOps API Add public key I would like to be able to add a public key for SSH access to Azure DevOps via the API but I can't seem to find a way to do it in the doco. Doing it manually via the UI is not feasible since this is for many users and many projects. Thanks A: The API is not documented, however we can track it with tools... You can add SSH public keys by calling below REST API: Write a script to create the SSH keys with the ssh-keygen command for users, please see Use SSH key authentication for details. Then call the REST API to add the public keys: POST https://{Account}.visualstudio.com/_details/security/keys/Edit Content-Type: application/json Request body: {"Description":"Test1001","__RequestVerificationToken":"","AuthorizationId":"","Data":"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDGZyIoG6eH9nTm/Cu2nVDa7hTNfaMWkwayghFmYTvqCkOwao2YJesGVih1fA3oR4tPsVv4+Vr8wxPCfJCboUrL9NDoH1tAMsIlkQZHqgaJwnGNWnPrnp0r2+wjLQJFPq/pPd8xKwr6QU0BxzZ4RuLDfMFz/MR1cQ2iWWKJuO/TXYrSPtY9XqsmMC8Zo4zJln40PGZt+ecOyQCNHCXsEJ3C+QIUXSqAkb8yknZ4apLf1oqfFRngtV4w84Ua/ZLpNduPZrBcm/mCU5Jq6H37jxhx4kluheJrfpAXbvbQlPTKa2zaOHp7wb3B2E2HvESJmx5ExNuAHoygcq/QGjsRsiUR andy@xxx@ws0068"}
{ "language": "en", "url": "https://stackoverflow.com/questions/52658534", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: export xls file and microsoft office and oppen office do i need to install Microsoft Excel to be able to export xls file in c#, I have my application it run in my pc but when I test it in another pc that it don't contain Excel the application got errors !! I see this link Using Microsoft.Office.Interop.Excel without actually having Excel?, I called my client and he tell me that he use open office and Microsoft office, I can use more than library A: Depending on what you need you can use some library (free or commercial) for this: * *OpenXML 2.0 from MS *Aspose.Cells (commercial) *Flexcel (commercial) *Create Excel (.XLS and .XLSX) file from C#
{ "language": "en", "url": "https://stackoverflow.com/questions/7386409", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP with SQL Injection Ok, starting fresh > For our first assignment in a System Security class, we have to hack into the professors "cheaply organized" sql database. I know the only user is "admin" and picking a random password, the select statement generated in the php is: select user_id from user where user_username = 'admin' AND user_password = md5('noob') Now, I go for the basic starting point of trying to hack the crappy login with "admin'--" select user_id from user where user_username = 'admin'--' AND user_password = md5('noob') but the actual value being pushed to the database is select user_id from user where user_username = 'admin\'--' AND user_password = md5('noob') which doesn't help. The server uses POST to get the values from the form. I've already bypassed any value processing on my side of the send by disabling javascript. There does not appear to be anything in the php that modifies the input in any way. A: Assuming the select statement is part of a login form, then most likely it's generated something like this: $user = $_POST['username']; $pwd = $_POST['password']; $query = "SELECT .... WHERE user_username='$user' AND user_password=md5('$pwd')"; which means, you could hack in by entering: noob') or ('a'='a for the password, giving you SELECT .... AND user_password=md5('noob') or ('a'='a') ^^^^^^^^^^^^^^^^^-- your contribution The actual password might not match, but 'a' will always equal itself, so the where clause will succeed and match a record based purely on the username and return the admin user's user_id. A: As others had mentioned the escaping that you see is not the OS, but some form of encoding done in PHP (likely magic quotes, but could be a straight call to addslashes()). Basically what you need to do is send in a form of quote that will not be escaped. You should research why one would use mysql_escape_string() rather than addslashes() and/or check this out: http://forums.hackthissite.org/viewtopic.php?f=37&t=4295&p=30747 A: Try ' OR 1; -- as user name. Imagine what the SQL query from such a user name looks like. A: This has nothing to do with the operating system. The operating system simply runs the PHP package. PHP is what does sanitization, etc. Have you tried submitting the following string for user_username?: admin' OR 1=1-- #assuming mysql Would yield a query: select user_id from user where user_username = 'admin' OR 1=1 --' AND user_password = md5('noob') In mysql (assuming the database type), -- is a comment, so everything after 1=1 is ignored. As a result, you've successfully gained access. If php magic quotes are on, however, this will be slightly more difficult. You will need to submit characters outside of utf-8 or attempt overflows or submitting null bytes. A: You could also try a bit of googling after entering a string that will error out the admin and use part of message that comes back as the key words. You could also use the http://gray.cs.uni.edu/moodle/mod/forum/discuss.php?d=106 fourm to ask questions so the whole class can benifit! if you can figure out how to upload files that would be great! I want to get c99.php up to really do some damage! you could also try some "hash" verse "dash dash"
{ "language": "en", "url": "https://stackoverflow.com/questions/4703518", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fancy box making image disappear on rails Hi my fancy box image keeps disappearing whenever I click on the image,the fancy box displays the image but once I close it theirs no image. Where am I going wrong? Fancybox javascript: $(document).ready(function() { $(".single_image").fancybox(); }); Fancybox Image: <%= link_to(image_tag"blindlogo.jpg", :class=>"single_image") %> A: Updated Try to add following codes below your link_to codes, so it looks like: <%= link_to "#", "assets/blindlogo.jpg", :class=>"single_image" %> See http://fancybox.net/howto. This page says you need href in your link element.
{ "language": "en", "url": "https://stackoverflow.com/questions/9940103", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make HTML5 contenteditable div allowing only text in firefox? I want to make div with contentEditable attribute which is allowing only text. It's easily achievable in Chrome by using: <div contenteditable="plaintext-only"></div> However it doesn't work in Firefox. Is there a way how to make text-only contenteditable div in Firefox ? I know it is possible, because Google Plus has such div, but I don't know how they do it. A: I ran into this problem myself. Here is my solution which I have tested in Firefox and Chrome: Ensure the contenteditable div has the css white-space: pre, pre-line or pre-wrap so that it displays \n as new lines. Override the "enter" key so that when we are typing, it does not create any <div> or <br> tags myDiv.addEventListener("keydown", e => { //override pressing enter in contenteditable if (e.keyCode == 13) { //don't automatically put in divs e.preventDefault(); e.stopPropagation(); //insert newline insertTextAtSelection(myDiv, "\n"); } }); Secondly, override the paste event to only ever fetch the plaintext //override paste myDiv.addEventListener("paste", e => { //cancel paste e.preventDefault(); //get plaintext from clipboard let text = (e.originalEvent || e).clipboardData.getData('text/plain'); //insert text manually insertTextAtSelection(myDiv, text); }); And here is the supporting function which inserts text into the textContent of a div, and returns the cursor to the proper position afterwards. function insertTextAtSelection(div, txt) { //get selection area so we can position insert let sel = window.getSelection(); let text = div.textContent; let before = Math.min(sel.focusOffset, sel.anchorOffset); let after = Math.max(sel.focusOffset, sel.anchorOffset); //ensure string ends with \n so it displays properly let afterStr = text.substring(after); if (afterStr == "") afterStr = "\n"; //insert content div.textContent = text.substring(0, before) + txt + afterStr; //restore cursor at correct position sel.removeAllRanges(); let range = document.createRange(); //childNodes[0] should be all the text range.setStart(div.childNodes[0], before + txt.length); range.setEnd(div.childNodes[0], before + txt.length); sel.addRange(range); } https://jsfiddle.net/1te5hwv0/ A: Sadly, you can’t. As this answer points out the spec only specifies true, false and inherit as valid parameters. The subject seems to have been discussed but if I’m not mistaken only Webkit implements support for plaintext-only.
{ "language": "en", "url": "https://stackoverflow.com/questions/21205785", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Dapper multi mapping two properties of the same type Let's say I have contacts stored in my database in a flattened form, such that I query them like this: SELECT Name, HomeHouseNumber, HomePostcode, WorkHouseNumber, WorkPostcode FROM Contacts I would like a little more structure in my C# code and have this simple definition of a contact with a home and work address. class Address { public string HouseNumber { get; set; } public string Postcode { get; set; } } class Contact { public string Name { get; set; } public Address HomeAddress { get; set; } public Address WorkAddress { get; set; } } I've found I can use multi mapping do extract the home address by aliasing the columns in the select like this: IEnumerable<Contact> GetContacts() { return Connection.Query<Contact, Address, Address, Contact>( "SELECT Name, HomeHouseNumber as HouseNumber, HomePostcode as Postcode, WorkHouseNumber, WorkPostcode FROM Contacts", (contact, home, work) => { contact.HomeAddress = home; contact.WorkAddress = work; return contact; }, splitOn: "HouseNumber,WorkHouseNumber"); } However I cannot alias the work address columns in such a way that they will be mapped. Can Dapper perform this mapping for me or must I do it manually? A: The solution, incredibly, is to give the columns the same alias. I didn't think SQL would allow this, but it does and Dapper maps it all perfectly. IEnumerable<Contact> GetContacts() { return Connection.Query<Contact, Address, Address, Contact>( "SELECT Name, HomeHouseNumber as HouseNumber, HomePostcode as Postcode, WorkHouseNumber as HouseNumber, WorkPostcode as Postcode FROM Contacts", (contact, home, work) => { contact.HomeAddress = home; contact.WorkAddress = work; return contact; }, splitOn: "HouseNumber,HouseNumber"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/37567136", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Iframe with another iframe I want to extract result of checking code. Website display in that code. I marked it in source code. <div id="ember332" class="ember-view backArrowContainer"> <div id="purchaseMeta"> <h2 class="flowStatus"> UŻYJ KODU PREPAID </h2> <div class="gamertag"> <div class="title"> <script id="metamorph-2-start" type="text/x-placeholder"> ***CODE STATUS WHICH I WANT TO EXTRACT*** <script id="metamorph-2-end" type="text/x-placeholder"> </div> <div class="price"> Kod prepaid </div> </div> It is avaible when i go to this site: https://account.xbox.com/pl-PL/PaymentAndBilling/RedeemCode?token=W4HV8-6D6X3-3JVDJ-8PPG9-Q6BVR I want to extract only CODE STATUS displayed when website will go to this adres. I think it can be avaible when i can use in HTML but i don't know how. Please help me with extract this status. A: You can't extract anything from the inside of an iframe. There cannot be any interaction from the parent to the iframe. There can, therefore, be interaction between the iframe and the parent, but since you are not the owner of the iframe's webpage, this is not your case. It's a security issue. People could get scammed if this wasn't this way. For example, designing a full-page iframe with a bank webpage and retrieving everything user types... Or designing a 1x1px iframe with a facebook page to see if your user is logged on fb and check all his/her personal information. You can use a server-side language, such us PHP and get the HTML of that webpage using file_get_contents()
{ "language": "en", "url": "https://stackoverflow.com/questions/26196778", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: creating a plist file I want to write an Array to a plist wich works fine when i manually create the plist in the document folder. but When I check if the plist exist and if not to create it from the plist in main bundle nothing happen..... i did it as in the Property List Programming Guide it is written. NSString *plistRootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *plistPath = [plistRootPath stringByAppendingPathComponent:@"list.plist"]; if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) { plistPath = [[NSBundle mainBundle] pathForResource:@"list" ofType:@"plist"]; } what did I missed? edit: I tryed the function in an seperate App and it worked. So I tryed It again: NString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *plistPath = [rootPath stringByAppendingPathComponent:@"list.plist"]; self.ListArray = [NSMutableArray arrayWithContentsOfFile:plistPath]; NSLog(@"preSave: %@", [ListArray count]); NSLog(@"%@", plistPath); and the Log says: 2011-02-16 16:54:56.832 ListApp[3496:207] .../Library/Application Support/iPhone Simulator/4.0.2/Applications/267F55E4-A46A-42E0-9E1C-EAF26846F75F/Documents/list.plist but there is no file in the Dir.! A: NSString *DocPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; filePath=[DocPath stringByAppendingPathComponent:@"AlarmClock.plist"]; if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { NSString *path=[[NSBundle mainBundle] pathForResource:@"AlarmClock" ofType:@"plist"]; NSLog(@"file path: %@",filePath); NSDictionary *info=[NSDictionary dictionaryWithContentsOfFile:path]; [info writeToFile:filePath atomically:YES]; } //***Try this... A: I tryed the code on an other mac and there it works It's the same project. can anyone explain me why the plist is created on one mac but not on the other? on the IPhone also no plist is written? I guess in both cases this is cause the array I write to the plist is empty: NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; NSString *plistPath = [rootPath stringByAppendingPathComponent:@"list.plist"]; NSMutableArray *currentArray = [[NSMutableArray alloc] initWithContentsOfFile:plistPath]; NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys: [selectet valueForKey:NAME], @"name", nil]; NSLog(@" DIC. : %@", dictionary); [currentArray addObject:[dictionary copy]]; NSLog(@" %@", currentArray); [currentArray writeToFile:plistPath atomically:YES]; [currentArray release]; the dictionary has the entry but currentArray is empty.... And still it works on one mac. but not on the other and on the IPhone. Edit: For some reason it worked again. To be sure I deleted the plist from the document folder and cleared all targets. And now the Problem as before I can only write the plist when i write the dictionary to it but then i can only save the last one. And reading the plist won't work either. Can anyone Tell me why this happens and how I can solve it? Edit 2: I found the Problem: since X-Code won't create the plist when I write the array with the dictionary to the plist.When I wrote the dictionary to the plist so X-Code creates the plist but with a dictionary Root so I cant write the array to it and I also can't read it in an Array..... I created a plist in the Resources folder with a Array Root and copy it when it not exist to document folder and now it works..... isn't it amazing how such easy things can give you such an headache
{ "language": "en", "url": "https://stackoverflow.com/questions/5017461", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: store image in a folder form a list in silverlight I want to store a image in to a folder which I have selected from a list in silverlight A: In Silverlight you have only limited access to the file system for security reason. So everything what you want to save would end up in IsolatedStorage... Check out this Quickstart Video and let me know if it helps http://www.silverlight.net/learn/quickstarts/isolatedstorage/ A: In Silverlight, You have limited access to the client file system. If you are running Out Of Browser application with elevated permission, you can access User folders (My documents in windows). But you can try some workarounds like using JavaScript u can try to download file. For reference Download a picture OnClick
{ "language": "en", "url": "https://stackoverflow.com/questions/5712712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Upgrade an existing application to include ClickOnce Is it possible to introduce ClickOnce functionality to an existing application? The scenario is: Version 1.0 is already installed on client premises. I would like to send them a new setup package which will upgrade to 1.1, which has ClickOnce functionality, thereby making future upgrades "effortless". Barring that, are there any other solutions to this sort of problem? P.S.: The original application was developed with Visual Studio 2005 (that is, .NET 2.0). I'm using Visual Studio 2008 now. A: No, it is not possible with a standard ClickOnce deployment scenario. ClickOnce is a sandboxed installation on the client side. It will not know about version 1.0 that's already installed. It is simply going to check to see whether its GUID has already been installed via ClickOnce and if so update it, but only if the previous version was deployed via ClickOnce. In your case, if the user installed Version 1.1, both versions will be installed side by side. Version 1.0 will not be updated, because ClickOnce doesn't know there's an association since it was deployed via a different method. If they don't want version 1.0 anymore, they'll need to remove it manually. Once you've got version 1.1 deployed via ClickOnce, subsequent updates will work correctly. Don't think of ClickOnce as something you're "including", think of it as a method of deployment. Alternatively: I should clarify that what you're looking for is not possible with standard ClickOnce deployment. However, you mentioned you're going to send them an initial setup file. In that case you may have a workaround that's possible: * *Script the setup file to remove the version 1.0 installation automatically *Script the setup file to launch the ClickOnce installation. For subsequent updates, simply point the user to the "pure" ClickOnce setup package, and your updates should work fine. A: Make sure to test out your ClickOnce deployment very thoroughly in your client's environment. I am omitting details here, but there are many problems with ClickOnce. I have been supporting a ClickOnce application for 3.5 years now and have run into many problems with manifests, having to manually delete the sandbox storage folders so the updates install correctly, etc. - if you search online for ClickOnce problems you'll find quite a few issues in the MSDN forums and elsewhere, many of which MS does not appear to want to resolve as they've been open since Visual Studio 2005. Also, be aware of a potential gotcha in ClickOnce prior to .NET 3.5 SP1. If you do not have your own software deployment certificate from a CA recognized by the client machines, Visual Studio uses a "temporary" certificate (*.pfx) which expires one year from creation. After that time, subsequent update releases will probably not install, and will show users scary messages about certificate expiration. Microsoft fixed this in .NET 3.5 SP1, but you had to dig through the release notes to find the comments that temporary or permanent certificates were no longer required. So - if you don't have a public CA certificate, and you'll be supporting this application for some time, then make sure you're on .NET 3.5 SP1. Depending on the complexity of your scenario, since you ask about other solutions, we wound up using a "roll your own" approach that goes something like this. Each updated release increments the assembly version as needed. Build contains a custom step to auto-generate a file with the new assembly version. The deployment project copies the version file to the output directory with MSI. Each time the installed application runs, it compares its own version to the version in the version file in the deploy folder. If they differ, quit the application and launch the MSI, which we set to automatically remove older application versions. This is a "poor man's ClickOnce" for an environment where there are no application deployment tools whatsoever avl (not even AD application advertising) so we made do. Again, this approach may not be sophisticated enough for you, but it works fine for us. Best of luck. A: I think in this case the "easiest" solution would be to just use the ClickOnce deployment for the 1.1 version and as part of that new version of your application have a default configuration file with a first-run flag of some sort that, when it gets to run the first time by the user and sees that first-run flag, it looks for the previous version, copies over any existing configuration settings, and then uninstalls the previous version automatically. It would require some programming on your part, but it's the solution I settled on at a previous job to do a similar task to upgrade a utility application to use Clickonce where it didn't have that before. A: The best way I know would be to send them an install program that: * *Uninstalls the current version *Launches the ClickOnce application residing on the web. With this, you'd have a reasonable upgrade experience, and from there out, ClickOnce can handle the upgrades on its own.
{ "language": "en", "url": "https://stackoverflow.com/questions/1045300", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to share reqwest clients in actix-web server? I'm building a web server with actix-web, and one of the methods uses reqwest to make HTTP requests to an external API: #[get("/foo")] async fn foo() -> impl Responder { let resp = reqwest::get("https://externalapi.com/bar").await?; # GET request inside server ... } To improve the performance, I want to reuse the client of reqwest, because it holds a connection pool, according to the doc. However, I cannot use Arc to share the client, because the doc also has the following statement: You do not have to wrap the Client in an Rc or Arc to reuse it, because it already uses an Arc internally. How can I share the client across the function calls? Or, should I use a different library to create HTTP request inside web servers? A: Actually suggestion in the documentation is the solution: You do not have to wrap the Client in an Rc or Arc to reuse it, because it already uses an Arc internally. Simply clone the client. Please check the Client definition from the source: #[derive(Clone)] pub struct Client { inner: Arc<ClientRef>, } You can think Client as a reference holder The inner type(ClientRef) has wrapped with Arc as the documentation says and Client has Clone implementation, since there is no other fields except inner: Arc<_>, cloning the client will not cause any runtime overhead comparing to wrapping it with Arc by yourself. Additionally Client implements Send this means clone of clients can be send across threads, since there is no explicit mutable operation over Client then Mutex is not needed in here. (I said explicit because there might be an interior mutability)
{ "language": "en", "url": "https://stackoverflow.com/questions/68668229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: problems understanding java ActionListener - Performed(ActionEvent e) I have to write code for a Fibonacci program that builds a GUI with two text box and a button. A user inputs a number in text box 1 and clicks the button which then places the Fibonacci of that number. I am having problems understanding the actionPerformed part of java and would appreciate any help. Here is my code: There are 3 files. Fibonacci.java public class Fibonacci{ int Fib (int n){ int in1=1,in2=1; int sum=0;//initial value int index=1; while (index<n){ sum=in1+in2;//sum=the sum of 2 values; in1=in2;//in1 gets in2 in2=sum;//in2 gets sum index++; //increment index } return sum; } } FibonacciJPanel.java import javax.swing.*; import java.awt.*; import java.awt.event.*; public class FibonacciJPanel extends JPanel implements ActionListener { private JTextField inField = new JTextField(15); //GUI components private JTextField resultField = new JTextField(15); private JLabel prompt1 = new JLabel("Input Fibonacci>>"); private JLabel prompt2 = new JLabel("Conversion Result:"); private JButton FibonacciButton = new JButton("Fibonacci of the input"); private JPanel panelN = new JPanel(); //Panels private JPanel panelC = new JPanel(); private JPanel panelS = new JPanel(); private Fibonacci F = new Fibonacci(); public FibonacciJPanel() //Set up user panel { setLayout(new BorderLayout()); //User BorderLayout panelN.setLayout(new BorderLayout()); panelC.setLayout(new BorderLayout()); panelS.setLayout(new BorderLayout()); panelN.add("North", prompt1); //Input elements panelN.add("South", inField); panelC.add("West", FibonacciButton); //Control button panelS.add("North", prompt2); //Output elements panelS.add("South", resultField); add("North", panelN); //Input at the top add("Center", panelC); //buttons in the center add("South", panelS); //Result at the bottom FibonacciButton.addActionListener(this); //Register with listeners setSize(175,200); } //FibonacciJPanel public void actionPerformed(ActionEvent e) { String inputStr = inField.getText(); //user input int userInput = Integer.parseInt(inputStr); //convert to integer boolean result=false; if (e.getSource() == FibonacciButton); //Process and report { result = fc.sum(userInput); resultField.setText("result"); } //if }//actionPerformed() } FibonacciJApplet.java import javax.swing.*; public class FibonacciJApplet extends JApplet { public void init() { getContentPane().add(new FibonacciJPanel()); } // init() } // Fibonacci class A: You don't mention what is exactly what you don't understand. Basically when you add a button it knows how to trigger events when you click it to a thread called Event Dispatcher Thread ( EDT ). Every time you click on a button this event will notify to every "Listener" registered within that button ( They are listening for notifications ) So a simpler example would be: import javax.swing.*; import java.awt.event.*; import java.awt.*; class Click { public static void main( String ... args ) { JButton clickMe = new JButton("Click Me"); ActionListener aListener = new OneActionListener(); clickMe.addActionListener( aListener ); JFrame frame = new JFrame(); frame.add( clickMe ); frame.pack(); frame.setVisible( true ); } } class OneActionListener implements ActionListener { public void actionPerformed( ActionEvent e ) { System.out.printf("Clicked. Thread: %s, action: %s%n", Thread.currentThread().getName(), e.getActionCommand() ); } } Here you declare a class OneActionListener that implements ActionListener interface to let know the button he can handle the event ( with the actionPerformed method ) I hope this clear out a bit how this works.
{ "language": "en", "url": "https://stackoverflow.com/questions/5683503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calculating the expected value of a transformed random variable in MATLAB? I am trying to compute the following expected value for Z being lognormally distributed E[Z^eta w(F_Z (Z))^-eta] where eta is a real number, F_Z the distribution function of Z and w:[0,1]->[0,1] an increasing function. First of all, I am pretty new to Matlab so I don't know which way of integrating is the better one, numerically or symbolically. I tried symbolically. My idea was to subsequently define functions: syms x; g_1(x) = x^eta; g_2(x) = logncdf(x); g_2(x) = w(x)^-eta; g_4(x) = g_1(x) * g_3(g_2(x)); And then exp = int(g_4(x),x,0,inf) Unfortunately this doesn't work and MATLAB just posts the whole expression of g_4... Is it better to use the numerical integration quadqk? What am I doing wrong here? I already read something about MATLAB not being the best program for integration but I have to use it so switching to a different program does not help. Thanks a lot!
{ "language": "en", "url": "https://stackoverflow.com/questions/24761176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get points from a line in OpenCV? The cvLine() function can draw a straight line given two points P1(x1,y1) and P2(x2,y2). What I'm stuck at is getting the points on this line instead of drawing it straight away. Suppose I draw a line (in green) AB and another line AC. If I follow all the pixels on line AB there will be a point where I encounter black pixels (the border of the circle that encloses A) before I reach B. Again when traveling along the pixels on line AC black pixels will be encountered twice. Basically I'm trying to get the points on the (green) lines, but cvLine() doesn't seem to return any point sequence structure. Is there any way to get these points using OpenCV? A rather dumb approach would be to draw the line using cvLine() on a separate image, then find contours on it, then traverse that contour's CvSeq* (the line drawn) for the points. Both the scratch image and the original image being of same size we'd be getting the points' positions. Like I said, kinda dumb. Any enlightened approach would be great! A: I think a CvLinIterator does what you want. A: Another dirty but efficient way to find the number of points of intersection between circles and line without iterating over all pixels of the line is as follows: # First, create a single channel image having circles drawn on it. CircleImage = np.zeros((Height, Width), dtype=np.uint8) CircleImage = cv2.circle(CircleImage, Center, Radius, 255, 1) # 255-color, 1-thickness # Then create an image of the same size with only the line drawn on it LineImage = np.zeros((Height, Width), dtype=np.uint8) LineImage = cv2.line(LineImage, PointA, PointB, 255, 1) # 255-color, 1-thickness # Perform bitwise AND operation IntersectionImage = cv2.bitwise_and(CircleImage, LineImage) # Count number of white pixels now for the number of points of intersection. Num = np.sum(IntersectionImage == 255) This method is also fast as instead of iterating over pixels, it is using OpenCV and numpy libraries. On adding another circle in the image "CircleImage", you can find the number of interaction points of both the circles and the line AC.
{ "language": "en", "url": "https://stackoverflow.com/questions/6689278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: change margin for and in wkwebview kit in objective c I wanted to reduce the space in the HTML string. below is the code is am using NSString *headerString = @"<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header>"; headerString = [headerString stringByAppendingString:htmlstring]; headerString = [headerString stringByReplacingOccurrencesOfString:@"<br><br/><br/><br><br/><br/>" withString:@"<br><br/>"]; headerString = [headerString stringByReplacingOccurrencesOfString:@"<br><br/><br><br/>" withString:@"<br><br/>"]; [webviewkit loadHTMLString:headerString baseURL:nil]; I had also tried using Javascript but i am not sure what exactly the java script i should passed which will only give 1line spacing instead of mulitple line spacing : - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { [webView evaluateJavaScript:@"document.open();document.close()" completionHandler:^(id _Nullable stringresult, NSError * _Nullable error) { NSLog(@"result=>%@ error->%@",stringresult,error); }]; } But i am not able to remove the spacing properly. <header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header><div><span style="font-size: 16px;"><span style="font-size: 16px; font-family: Arial;">Hello and welcome to XYZ session!&nbsp;&nbsp;</span><br><br/><span style="font-family: Arial;">Over the next three Hello world.&nbsp; Spacing takes alot of spaces over here due to span , br and div tags.</span><br><br/><span style="font-family: Arial;">Thank you again for agreeing to participate and helping the discussion....</span><br><br/><span style="font-family: Arial;">Over here,</span><br><br/></span></div><br/><ul><br/> <li><span style="font-size: 16px;"><span style="font-family: Arial;">I will be posting questions over here in stack overflow&nbsp;</span><br><br/> </span></li><br/> <li><span style="font-size: 16px;"><span style="font-family: Arial;">Throughout the day I will read everyone's responses and sometimes respond with my own follow-up questions.&nbsp;</span><br><br/> </span></li><br/> <li><span style="font-size: 16px;"><span style="font-family: Arial;">Please be i request to provide the code in objective c</span><br><br/> </span></li><br/> <li><span style="font-size: 16px;"><span style="font-family: Arial;">Lorem Ipsum is simply dummy text of the printing and typesetting industry. &nbsp;</span><br><br/> </span></li><br/> <li><span style="font-size: 16px;"><span style="font-family: Arial;">Lorem Ipsum is simply dummy text of the printing and typesetting industry. </span><br><br/> </span></li><br/> <li><span style="font-size: 16px; font-family: Arial;">Lorem Ipsum is simply dummy text of the printing and typesetting industry. </span></li><br/></ul> A: I think you may be slightly confused about <br> tags. <br> or <br /> are self-closing/void elements/empty tags: https://www.w3schools.com/html/html_elements.asp (under the empty html section) http://xahlee.info/js/html5_non-closing_tag.html <br> is an empty element without a closing tag (the <br> tag defines a line break): So when you're subbing in <br><br /> you're actually subbing in two line breaks. From your description it sounds as if you only want one line break, so you'll want to remove one of them.
{ "language": "en", "url": "https://stackoverflow.com/questions/58070588", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regex search causes VS-Code to crash on macbook I'm trying to search for a RegEx expression using VS-Code's built-in search option. Here is the regex: (?:((\s|\w+|\d+|\]|\))+)(?<!(\bReact\b))(?<dot>\.(?!\.))+) As soon as I enter this expression, VS-Code crashes on my macbook. Is there any way to prevent this? A: You have (?<dot>\.(?!\.))+) a named capturing group in your regex. I don't believe that is supported in vscode search across files. In any case, your original regex froze vscode on my Windows machine, but when I removed the named capturing group, the regex worked fine in BOTH the find in a file widget and searching across files. So this did not freeze vscode for me: (?:((\s|\w+|\d+|\]|\))+)(?<!(\bReact\b))(\.(?!\.))+) I suggest you replace the named capturing group with just a simple capturing group.
{ "language": "en", "url": "https://stackoverflow.com/questions/74826483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where to put my xUnit tests for an F# assembly? I'm working on my first 'real' F# assembly, and trying to do things right. I've managed to get xUnit working too, but currently my test module is inside the same assembly. This bothers me a bit, because it means I'll be shipping an assembly where nearly half the code (and 80% of the API) is test methods. What is the 'right' way to do this? If I put the tests in another assembly, I think that means I have to expose internals that I'd rather keep private. I know that in C# there is a friend mechanism for tests (if that's the right terminology), is there an equivalent in F#? Alternatively, can anyone point me to an example project where this is being done 'properly'? A: you could use the InternalsVisibleTo-Attribute to expose your internals to some other assembly. http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(VS.100).aspx EDIT If your assembly is signed, you will also need to sign the Friend assembly, and provide the public key in the InternalsVisibleTo attribute: [<assembly: InternalsVisibleTo("ProcessorTests, PublicKey=0024000004800...)")>]
{ "language": "en", "url": "https://stackoverflow.com/questions/2399946", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Read & Write files from Input to Output folders: Python I have written a Python script that reads one file, replaces text, & then outputs it into another file. Instead, I would like to call an input FOLDER that contains multiple files, read these files, & then output them into a destination FOLDER. How would I approach this? Here is my code: import re with open("SanitizedFinal_E4300.txt", "rt") as fin: with open("output6.txt", "wt") as fout: for line in fin: line = line.replace('set system host-name EX4300', 'hostname "EX4300"') line = line.replace('set interfaces ge-0/0/0 unit 0 family inet address', 'ip address') line = re.sub(r'set interfaces ge-0/0/0 description (.*)', r'interface 1/1\nname "\1"', line) line = re.sub(r'set interfaces ge-0/0/1 description (.*)', r'interface 1/2\nname "\1"', line) #and so on... fout.write(line) I am using Visual Studio Code v1.63.2 A: You can use os.scandir() to iterate over files in a directory: import re, os for file in os.scandir(input_dir): with open(file, "r") as fin, open("path_to_output_dir/" + output_file_name, "w") as fout: # whatever file operations you want to do for line in fin: fout.write(line) A: Read all files in the folder through the OS module, read the contents of each file, and then modify it. import os fileList = os.listdir(path) for info in os.listdir(path): domain = os.path.abspath(path) #Get folder path info = os.path.join(domain,info) #Combining the path with the file name is the full path of each file info = open(info,'r') #Read file contents #You can modify the file here info.close()
{ "language": "en", "url": "https://stackoverflow.com/questions/71949062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Date Sorting in Java The Instruction was to create a Random dates for each object withn the range specified in the instructions below for the interview slot objects to be stored in . I am not exactly sure how to do this Create a random number of InterviewSlot objects and store them in the slots container. Use the Math.random() method to create variation in the objects created: * *Make the range of variation of the dates in hours. *The range should be 30 days, meaning that the dates could vary between say, today and 30 days from now. The max of the range would be equal to 30*24. *You can set the minimum of the range to 1. *Make the duration vary between 1 and 60. Examples of objects: Thu Apr 02 05:28:59 EDT 2020 duration:18 Fri Mar 27 00:22:32 EDT 2020 duration:48 Wed Apr 01 20:22:32 EDT 2020 duration:8 Sat Mar 28 19:22:32 EDT 2020 duration:31   import java.util.Calendar; import java.util.Date; public class InterviewSlot implements Comparable<InterviewSlot> { Calendar cal = Calendar.getInstance(); private Date startTime = cal.getTime(); private Integer duration; public InterviewSlot(Date start, Integer d) { setDuration(d); setStartTime(start); } public void setDuration(Integer duration) { this.duration = duration; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Integer getDuration() { return duration; } public Date getStartTime() { return startTime; } @Override public String toString() { // TODO Auto-generated method stub return "Interview Start " + getStartTime() + "Duration : " + getDuration(); } @Override public int compareTo(InterviewSlot s) { return this.getStartTime().compareTo(s.getStartTime()); // TODO Auto-generated method stub } } import java.awt.List; import java.util.ArrayList; public class DataCreator { public static <E extends Comparable<E>> void outputData(ArrayList<E> l) { for (E L : l) { System.out.println(L); } } public static void createIntegers(ArrayList<Integer> a, int num) { // double random = (int)(Math.random()*((100-1)+1))+1; for (int i = 0; i < num; i++) { Integer random = (int) (Math.random() * ((100 - 1) + 1)) + 1; a.add(random); } ; } public static void createData(ArrayList<InterviewSlot> slots, int num) { } } A: I will answer as if this is for real work, as you did not indicate explicitly schoolwork. ThreadLocalRandom Use ThreadLocalRandom to avoid any possible concurrency issues. There is no downside to using this class over Math.random. And this class has convenient methods for generating various types of numbers rather than just double. java.time Never use Calendar or Date. Those terrible date-time classes were supplanted years ago by the modern java.time classes defined in JSR 310. Get today's date. ZoneId z = ZoneId.of( "America/Montreal" ) ; LocalDate today = LocalDate.now( z ) ; Add random number of days within next 30 days. int days = ThreadLocalRandom.current().nextInt( 1 , 31 ) ; LocalDate localDate = today.plusDays( days ) ; Days vary in length, such as 23, 24, 25, or other number of hours. So for your date in your zone, calculate maximum number of seconds. ZonedDateTime start = localDate.atStartOfDay( z ) ; ZonedDateTime stop = localDate.plusDays( 1 ).atStartOfDay( z ) ; Duration d = Duration.between( start.toInstant() , stop.toInstant() ) ; long seconds = d.toSeconds() ; // In Java 9 and later. For Java 8, call `Duration::getSeconds`. That count of seconds becomes the maximum for our length of day. From this we pick a random number of seconds. long secondsIntoDay = ThreadLocalRandom.current().nextInt( 0 , seconds ) ; ZonedDateTime zdt = start.plusSeconds( secondsIntoDay ) ; Determine a random duration from 1 to 60 minutes for the elapsed time of each event. int minutes = ThreadLocalRandom.current().nextInt( 1 , 61 ) ; // At least one minute, and less than 61 minutes. Duration duration = Duration.ofMinutes( minutes ) ; Define your public class InterviewSlot with two member fields: a ZonedDateTime and a Duration. A: Simple solution with date for your spezific case, including an example: import java.util.Date; import java.util.Random; import org.apache.commons.lang3.time.DateUtils; public class SimpleDateGenerator { private static Random random = new Random(); public static Date getRandomDate(Date start, long timerangeSeconds) { int randomTime = (int) Math.ceil(random.nextDouble() * timerangeSeconds); return DateUtils.addSeconds((Date) start.clone(), randomTime); } public static void main(String[] args) { Date now = new Date(); System.out.println(now); for (int i = 0; i < 10; i++) { System.out.println(getRandomDate(now, 30 * 24 * 60 * 60)); } } } main gives following (example) output: Tue Mar 31 08:26:14 CEST 2020 Sun Apr 19 16:06:48 CEST 2020 Fri Apr 03 20:49:58 CEST 2020 Wed Apr 22 22:27:00 CEST 2020 Mon Apr 06 03:39:48 CEST 2020 Wed Apr 22 19:13:28 CEST 2020 Fri Apr 03 12:36:16 CEST 2020 Wed Apr 22 20:27:35 CEST 2020 Mon Apr 06 13:58:37 CEST 2020 Fri Apr 03 03:57:17 CEST 2020 Wed Apr 15 09:05:47 CEST 2020 A: As per @Basil Bourque suggestion the following code should do the trick : import java.time.*; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; public static void main(String[] args) { int numberOfRandomDates = 10; ArrayList<InterviewSlot> interviewSlotArrayList= new ArrayList<>(); for (int i = 0; i< numberOfRandomDates ; i++) { InterviewSlot interviewSlot = calculateInterviewSlot(); interviewSlotArrayList.add(interviewSlot); System.out.println(interviewSlot); } Collections.sort(interviewSlotArrayList); System.out.println("After sorting: \n"); //Using lamda interviewSlotArrayList.forEach(element -> { System.out.println(element); }); //or Using method reference interviewSlotArrayList.forEach(System.out::println); } public static InterviewSlot calculateInterviewSlot() { //Getting time zone id and setting local time according to the time zone ZoneId z = ZoneId.of("America/Montreal"); LocalDate today = LocalDate.now(z); //Getting a random day between 1 and 31 and adding it to the current date int days = ThreadLocalRandom.current().nextInt(1, 31); LocalDate localDate = today.plusDays(days); //Getting start and end time of the day as per time zone.End time is taken as next day start time(24 hr) ZonedDateTime start = localDate.atStartOfDay(z); ZonedDateTime stop = localDate.plusDays(1).atStartOfDay(z); //Duration is taken which is the max duration for that time zone. Duration duration = Duration.between(start.toInstant(), stop.toInstant()); long seconds = TimeUnit.SECONDS.convert(duration.toNanos(), TimeUnit.NANOSECONDS); //Calculating random no of seconds keeping the computed seconds as max seconds in the day long secondsIntoDay = ThreadLocalRandom.current().nextInt(0, Math.toIntExact(seconds)); ZonedDateTime zonedDateTime = start.plusSeconds(secondsIntoDay); //Calculating random no of minutes for duration int minutes = ThreadLocalRandom.current().nextInt(1, 61); Duration durationMinutes = Duration.ofMinutes(minutes); return new InterviewSlot(zonedDateTime, durationMinutes); } } InterviewSlot.java : public class InterviewSlot implements Comparable<InterviewSlot> { private ZonedDateTime startTime; private Duration duration; public InterviewSlot() { } public InterviewSlot(ZonedDateTime startTime, Duration duration) { this.startTime = startTime; this.duration = duration; } public ZonedDateTime getStartTime() { return startTime; } public void setStartTime(ZonedDateTime startTime) { this.startTime = startTime; } public Duration getDuration() { return duration; } public void setDuration(Duration duration) { this.duration = duration; } @Override public String toString() { // TODO Auto-generated method stub return "Interview Start " + getStartTime() + " Duration : " + getDuration(); } @Override public int compareTo(InterviewSlot s) { return this.getStartTime().compareTo(s.getStartTime()); // TODO Auto-generated method stub } } Generated sample output : Interview Start 2020-04-24T02:16:09-04:00[America/Montreal] Duration : PT12M Interview Start 2020-04-04T20:58:43-04:00[America/Montreal] Duration : PT38M Interview Start 2020-04-25T00:09:12-04:00[America/Montreal] Duration : PT31M Interview Start 2020-04-03T20:26:01-04:00[America/Montreal] Duration : PT22M Interview Start 2020-04-06T03:48:29-04:00[America/Montreal] Duration : PT45M Interview Start 2020-04-15T07:56:32-04:00[America/Montreal] Duration : PT34M Interview Start 2020-04-21T09:25:15-04:00[America/Montreal] Duration : PT44M Interview Start 2020-04-30T18:33:40-04:00[America/Montreal] Duration : PT52M Interview Start 2020-04-16T07:12:54-04:00[America/Montreal] Duration : PT14M Interview Start 2020-04-24T17:02:48-04:00[America/Montreal] Duration : PT50M
{ "language": "en", "url": "https://stackoverflow.com/questions/60944062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: UICollectionView showing scroll indicator for every section (header zIndex broken) When scrolling through my UICollectionView it's showing more than one scroll indicator. I've noticed there is a one for every section in the collection. See screenshot displaying three at the same time: Anyone experienced same issue? I am using Xcode 9 beta 3. My collectionview setup is quite common: private let formCollectionView: UICollectionView = { let collectionViewLayout = UICollectionViewFlowLayout() collectionViewLayout.minimumLineSpacing = 0 collectionViewLayout.minimumInteritemSpacing = 0 let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = UIColor.clear return collectionView }() Edit 10/16/2017 Even Twitter seems having this issue: A: Ok, so first of all there is a radar already. There is a proposed workaround. I was partially successful with doing this crap inside my UICollectionReusableView subclass. override func apply(_ layoutAttributes: UICollectionViewLayoutAttributes) { super.apply(layoutAttributes) DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01) { self.layer.zPosition = 0 } } I am saying partially because if you have a little bit longer UICollectionView it's still corrupted for some headers. Most of them are ok though. So it depends on your situation. Hopefully that radar will be addressed soon. A: you can fix this problem in delegate method.as in the following example Objective-C - (void)collectionView:(UICollectionView *)collectionView willDisplaySupplementaryView:(UICollectionReusableView *)view forElementKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath { if (@available(iOS 11.0, *)) { if ([elementKind isEqualToString:UICollectionElementKindSectionHeader]) { view.layer.zPosition = 0; } } } Swift func collectionView(_ collectionView: UICollectionView, willDisplaySupplementaryView view: UICollectionReusableView, forElementKind elementKind: String, at indexPath: IndexPath) { if elementKind == UICollectionView.elementKindSectionHeader { view.layer.zPosition = 0 } } A: That are not multiple scroll indicators. The z index of the header views is higher than that of the scroll indicator view. Edit: found something more interesting, if you run the view debugger the scroll indicator is positioned above the headers... something weird is going on. A: There is a simple method to fix this problem. In your section header view Class, you can override method layoutSubviews, and write: - (void)layoutSubviews { [super layoutSubviews]; self.layer.zPosition = 0; } Because, before iOS11, the section view's layer zPosition value is default 0, but in iOS11, this default value is 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/45215932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Store application config variables to database Is there any PHP open source class that can store application configuration variables in MySQL database, like Wordpress for example? I would like to store and read something like this: $config['name'] = "test1"; $config['name']['subname'] = "test2"; in MySQL database table, and database table need to look something like this Id | Name | Value | Parent Name Id | 1 | 'name' | 'test1' | null | 2 | 'subname' | 'test2' | 1 | etc. A: That need not have a class style. For example: //config.php $config['name'] = "test1"; $config['name']['subname'] = "test2"; //other php. require_once('{path to config.php}'); echo $config['name']; echo $config['name']['subname'];
{ "language": "en", "url": "https://stackoverflow.com/questions/41325970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to index a table with order by? Using a while loop I'm able to return my table in the order I want, but after implementing pagination the variable I've created (counter) resets itself on each page, frustratingly. Example code: $sql = ('SELECT id,name,logo FROM mytable ORDER BY name DESC LIMIT 25'); $query = mysqli_query($db_conx,$sql); $counter = 0; while ($row = $query->fetch_assoc()) { $counter++; echo "$counter, $row['id'], $row['name']"; echo "<br />"; } I've tried many things and can't get this to work. Obviously my logic is flawed. The loop returns the correct results, but the $counter variable breaks on each page, resetting itself indefinitely. What I am trying to do is get $counter to increase by 25 (representing results for each page) for each of the pages created by the pagination loop. Example code: for ($i=1; $i<=$total_pages; $i++) { echo "<a href='page.php?page=".$i."'>&nbsp[".$i."]</a> "; $GLOBALS["counter"]+=25; }; Obviously this was not working, so I am stumped at what I should try next. If anyone has any ideas I would love to hear them, I have heard great things about the SO community. A: You seem to display only the first 25 results at any time. You need to initialize $counter to zero if it's the first page, to 26 if it's the second page, and so on : $counter = 0; if(isset($_GET['counter'])){ $counter = intval($_GET['counter']); } You need to modify your query to fetch a different set of results for each page : $sql = 'SELECT id,name,logo FROM mytable ORDER BY name DESC LIMIT ' . mysqli_real_escape_string($db_conx, $counter . ',25'); $query = mysqli_query($db_conx,$sql); Then I assume you display a link to the other paginated pages, you need to pass it the value of $counter : <a href="results.php?counter=<?php echo $counter;?>">Next</a>
{ "language": "en", "url": "https://stackoverflow.com/questions/38844337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I address imbalanced data before training? Suppose that we want to train YOLOV3. We gathered around 5000 images for 3 different classes. Class distribution is: Class#1 = 2250 images Class #2= 2500 images Class #3= 250 images As you can see it is imbalanced and I can not train based on that data. What do I need to do? do I need to consider a data processing stage? Please do not merely say data augmentation, as data augmentation has a different meaning. I believe it does rotation and transformation during the training and makes the trained model more robust, it doesn't solve an imbalanced data set issue. How do I address imbalanced data? A: You can try to do the following to your config file: Choice 1: [yolo] focal_loss=1 Choice 2 (more effective): [yolo] counters_per_class=100, 2000, 300, ... # number of objects per class in your Training dataset To calculate the counters_per_class, refer to this link More details here Choice 3: Do both Choice 1 & Choice 2 A: for yolov7, you can : * *Adjust the focal loss with the parameter : h['fl_gamma']
{ "language": "en", "url": "https://stackoverflow.com/questions/66015722", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Exactly once delivery option for a pubsub subscription is not available for some reason I am unable to select the 'Exactly once delivery' option for my pubsub push subscription. No where on the internet does it explain why it is greyed out. (See below) Tried finding answeres everywhere, looked into docs as well but no luck. A: Looks like they only allow this feature for the 'pull' option. A: More information about Cloud Pub/Sub Exactly Once Delivery and Push Subscriptions: https://cloud.google.com/pubsub/docs/exactly-once-delivery#exactly-once_delivery_and_push_subscriptions.
{ "language": "en", "url": "https://stackoverflow.com/questions/75194449", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: laravel: can not accept post request without csrf I have added into the exceptions: protected $except = [ 'pay/finish' ]; But still I am getting MethodNotAllowedException Route is defined in web.php Route::post('/pay/finish', ['as' => 'pay.finish', 'uses' => 'PaymentController@finish']); The post request comes from another domain. A: You don't normally get a MethodNotAllowedException from an invalid CSRF token. I normally get a 419 response from CSRF issues. However, assuming the CSRF token is the problem you could move your route from web.php to api.php. Be aware this adds the prefix api/ to the URL. The middleware that checks the CSRF token is applied in your Kernel to all routes in web.php but not to those is api.php You could verify whether the CSRF check is really the problem by looking in your App\Http\Kernel file and commenting out \App\Http\Middleware\VerifyCsrfToken::class from: protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class, ], 'api' => [ 'throttle:60,1', 'bindings', ], ]; If your route then works it is CSRF and you can move the route to the API routes file and hit it at api/pay/finish with the api prefix. If not then I suggest you look at what's calling your route and check the correct http method is being called. Is it definitely sending a POST request? Do you have the _method input specified in your form that Laravel checks for POST requests to mutate them to PUT or PATCH for its edit routes?
{ "language": "en", "url": "https://stackoverflow.com/questions/59443377", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trouble linking assembly program: File format not recognized I have the following simple assembly program (downloaded from this website).: extern printf ; the C function, to be called section .data ; Data section, initialized variables msg: db "Hello world", 0 ; C string needs 0 fmt: db "%s", 10, 0 ; The printf format, "\n",'0' section .text ; Code section. global main ; the standard gcc entry point main: ; the program label for the entry point push rbp ; set up stack frame, must be alligned mov rdi,fmt mov rsi,msg mov rax,0 ; or can be xor rax,rax call printf ; Call C function pop rbp ; restore stack mov rax,0 ; normal, no error, return value ret ; return When I try to build from the command line using NASM I get no errors, and it creates the object file correctly. Then I link it using Mingw-w64 (ld) (because I am on a x64 machine) with command line option -m i368pe, but this fails with an error message: File format not recognized. After searching a bit, I found that this has to do with the fact that there I am trying to link a 32 bit object file with a 64 bit linker or the other way around. However, this does not make sense to me as I built the object file with the -f win64 flag. Also, I believe -m i386pe is a 64 bit flag for linking, so what am I doing wrong here? My commands for building/linking are: * *Build: nasm -f win64 -o test.obj test.asm *Link: ld test.obj -m i386pe -o test.exe
{ "language": "en", "url": "https://stackoverflow.com/questions/49494986", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to manage large product catalog in magento? I am looking for a website Like coverscart.com using Magento. I have 2000 mobile covers for 500 model. I am trying to create configurable products, But it's not reliable solutions. Because for every model I have to create 2000 simple products. With Configurable Total Catalog 1000000 :: 2000 Covers * 500 Model = 1000000 It's not about the creating products, It's about managing the large product catalog. Ref:: http://take.ms/goYoE Any ideas? Thanks! A: In Magento 2 provide the functionality of auto created a number of associated product base on selected attributes. Like First, you have created one attribute for mobile model, Then you have wanted, enter 500 Model name only one time. Then after you have want to create one configurable product then select model attributes >> then click on Select All menu for all selected models >> Then create a configurable product. Note: automatically created 500 simple (associated) product. Please see screenshot. http://prntscr.com/knsqxl Please check the example demo : http://blankrefer.com/?http://demo-acm2.bird.eu/admin
{ "language": "en", "url": "https://stackoverflow.com/questions/52053202", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Implement Iterator interface for ArrayAccess without container array This is my attempt at implementing https://www.php.net/manual/en/class.iterator.php for an ArrayAccess. Many examples use a container array as a private member variable; but I do not want to use a container array if possible. The main reason why I don't want a container array is because I'd like to access the property (array key) like this $DomainData->domainId all while having intellisense, etc. Demo: https://ideone.com/KLPwwY class DomainData implements ArrayAccess, Iterator { private $position = 0; public $domainId; public $color; public function __construct($data = array()) { $this->position = 0; foreach ($data as $key => $value) { $this[$key] = $value; } } public function offsetExists($offset) { return isset($this->$offset); } public function offsetSet($offset, $value) { $this->$offset = $value; } public function offsetGet($offset) { return $this->$offset; } public function offsetUnset($offset) { $this->$offset = null; } /*****************************************************************/ /* Iterator Implementation */ /*****************************************************************/ public function rewind() { $this->position = 0; } public function current() { return $this[$this->position]; } public function key() { return $this->position; } public function next() { ++$this->position; } public function valid() { return isset($this[$this->position]); } } Calling it: $domainData = new DomainData([ "domainId" => 1, "color" => "red" ]); var_dump($domainData); foreach($domainData as $k => $v){ var_dump("domainData[$k] = $v"); } actual: object(DomainData)#1 (3) { ["position":"DomainData":private]=> int(0) ["domainId"]=> int(1) ["color"]=> string(3) "red" } desired: object(DomainData)#1 (3) { ["position":"DomainData":private]=> int(0) ["domainId"]=> int(1) ["color"]=> string(3) "red" } string(24) "domainData[domainId] = 1" string(23) "domainData[color] = red" A: Let me describe a couple of ways of how you could do this. ArrayObject with custom code ArrayObject implements all of the interfaces that you want. class DomainData extends ArrayObject { public $domainId; public $color; public function __construct($data = array()) { parent::__construct($data); foreach ($data as $key => $value) { $this->$key = $value; } } } This isn't very nice, though; it copies the keys and values twice, and changing a property doesn't change the underlying array. Implement IteratorAggregate on get_object_vars() If you don't mind giving up on ArrayAccess, you could get away with only implementing an aggregate iterator. class DomainData implements IteratorAggregate { public $domainId; public $color; public function __construct($data = []) { foreach ($data as $key => $value) { $this->$key = $value; } } public function getIterator() { return new ArrayIterator(get_object_vars($this)); } } ArrayObject with property flag and doc blocks A better way would be to use doc blocks for describing your properties (described here), and then use the ARRAY_AS_PROPS flag to expose the array as properties. /** * Magic class * @property int $domainId * @property string $color */ class DomainData extends ArrayObject { function __construct($data = []) { parent::__construct($data, parent::ARRAY_AS_PROPS); } } When loaded inside PhpStorm, you'd see this: A: Please try get_object_vars() php function to Gets the accessible non-static properties of the given object according to scope. The function adds before foreach loop. It's working. $domainData = get_object_vars($domainData); foreach($domainData as $k => $v){ var_dump("domainData[$k] = $v"); } => Output string(24) "domainData[domainId] = 1" string(23) "domainData[color] = red" A: Implement Iterator interface for ArrayAccess for example <?php /** * Class Collection * @noinspection PhpUnused */ class Collection implements ArrayAccess, IteratorAggregate, JsonSerializable, Countable { /** * @var array $collection */ private array $collection; /** * @inheritDoc */ public function offsetExists($offset): bool { return isset($this->collection[$offset]); } /** * @inheritDoc */ public function offsetGet($offset) { return $this->collection[$offset]; } /** * @inheritDoc */ public function offsetSet($offset, $value) { if (empty($offset)) { return $this->collection[] = $value; } return $this->collection[$offset] = $value; } /** * @inheritDoc */ public function offsetUnset($offset): void { unset($this->collection[$offset]); } /** * @inheritDoc */ public function jsonSerialize() { return serialize($this->collection); } /** * @inheritDoc */ public function count() { return count($this->collection); } /** * @return array */ public function __debugInfo() { return $this->collection; } /** * @return mixed */ public function first() { return $this->collection[0]; } /** * @inheritDoc */ public function getIterator() { return new ArrayIterator($this->collection); } /** @noinspection MagicMethodsValidityInspection */ public function __toString() { return json_encode($this->collection, JSON_THROW_ON_ERROR, 512); } /** * @return mixed */ public function last() { return $this->collection[$this->count()-1]; } } for example using <?php $collections = new Collection(); $collections[] =12; $collections[] = 14; $collections[] = 145; $collections[] =4; print_r($collections); echo $collections; echo $collections->last(); echo $collections->first(); foreach ($collections as $collection) { echo $collection; } count($collections);
{ "language": "en", "url": "https://stackoverflow.com/questions/60689674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Having problems with aligning layers with body background I'm creating a layered parallax page that is triggered by the scrolling of the mouse. I've managed to set this up and the layers all move how I want them to. Unfortunately, I've run into a problem with the background image of the body. On the left side of the screen, there is a gap that shows the background behind it. Gap that shows the background: I've tried many different solutions but none of them seems to work. Any suggestions will be greatly appreciated. here's the snippet of my HTML that involves the section with the layers <section> <img src="./Images/stars.png" id="stars"> <img src="./Images/moon.png" id="moon"> <img src="./Images/mountains_behind.png" id="mountains_behind"> <h2 id="text">Moon Light</h2> <img src="./Images/mountains_front.png" id="mountains_front"> </section> and here's a snippet of the CSS { margin: 0; padding: 0; box-sixing: border-box; overflow-x: hidden; scroll-behavior: smooth; } body { min-height: 100vh; overflow-x: hidden; background: linear-gradient(#2b1055,#7597de); } section { position: relative; width: 100%; height: 100vh; padding: 100px; overflow-x: hidden; overflow-y: hidden; display: flex; justify-content: center; align-items: center; } section img { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; pointer-events: none; } A: I would structure the first two selectors like this: html, body { margin: 0; padding: 0; overflow-x: hidden; box-sizing: border-box; /* put these last two in a 'html {}' only selector if they are intended to be different */ scroll-behavior: smooth; } body { min-height: 100vh; background: linear-gradient(#2b1055,#7597de); } Btw, changed the type-o of box-sixing to the right property :). Never used that one before, will come very handy, thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/69585168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Render collection using a partial giving "undefined method for nil:NilClass" I'm trying to render a collection of Projects using a project partial but I'm getting the following error: undefined method `customer' for nil:NilClass Extracted source (around line #1): 1: <p><%= company_name(@project) %><p> The stacktrace is: app/helpers/projects_helper.rb:4:in `company_name' app/views/projects/_summary.html.erb:1:in app/views/customers/index.html.erb:11:in So, my index checks that their are projects to start with: <% if @projects.any? %> <%= render :partial => "projects/summary", :collection => @projects %> <% end %> My partial (_summary.html.erb) is simply: <p><%= company_name(@project) %><p> <p><%= summary_description(@project) %><p> and my ProjectsHelper company_name method is def company_name(project) if project.customer.business_name.blank? ...Do stuff... If I do the following via the rails console, it works fine: projects.first.customer.business_name.blank? I'm really confused because I thought that's what rendering a collection was supposed to do. Any help would be much appreciated. A: You should change your partial to <p><%= company_name(project) %><p> <p><%= summary_description(project) %><p> See the Rails documentation about this under "Rendering Collections". A: I figured out what the problem was. It was because I was using a differently-named partial to the model I was trying to render. I needed to just render a summary of the model, so I used a summary partial. In the partial though, the "name" of my project variable was "summary". So I changed my partial to: <p><%= company_name(summary) %><p> <p><%= summary_description(summary) %><p> and it worked. Rails is still a mystery to me with stuff like this. From this post, the answer is to use: :as => :foo <%= render :partial => "projects/summary", :collection => @projects, :as => :project %>
{ "language": "en", "url": "https://stackoverflow.com/questions/16625995", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Running into issues with django/vue (and possibly livereload) So I've got a Django/Vue project I'm trying to get off the ground. It's currently being pretty inconsistent. (I was able to get Vue to generate some things, but not others) I first got Vue working, but upon realizing I would need to wipe browser history, I followed these instructions pretty much to the letter: https://github.com/tjwalch/django-livereload-server Although it was unclear that one needed to spawn a new session and run both livereload and runserver concurrently, I eventually figured it out and got rid of the following warnings. GET http://127.0.0.1:32657/livereload.js net::ERR_CONNECTIONREFUSED But Vue is inconsistent. Something simple: <html> <head> <script src="https://unpkg.com/vue/dist/vue.js"></script> <body> <div id="app"> <p>{{ title }}</p> </div> <script> new Vue({ el: '#app', data: { title: 'yadda yadda' } }); </body> </html> And nothing on the screen. I'm not entirely sure livereload is the issue. A: Delimiters! new Vue({ el: '#app', delimiters: ['[[', ']]'], data: { title: 'yadda yadda' } Apparently I had previously set them and stopped for whatever reason. (hence the inconsistency)
{ "language": "en", "url": "https://stackoverflow.com/questions/49578439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flask sidebar shows up at the top, not on the side I am writing a simple Flask app, and I want a sidebar to always be present. I tried using the template below, but for some reason the sidebar appears at the top, not on the left-hand side where I want it. Here's what it looks like: and here's what I want it to look like: Here's the code I tried: <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!--- FontAwesome --> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css"> </head> <body> <div id="wrapper"> <!-- Sidebar --> <div id="sidebar-wrapper"> <ul class="sidebar-nav"> <li class="sidebar-brand"> <a href="#"> Start Bootstrap </a> </li> <li> <a href="#">Dashboard</a> </li> <li> <a href="#">Shortcuts</a> </li> </ul> </div> <!-- /#sidebar-wrapper --> <div id = "page-content-wrapper"> <div class="container-fluid"> <h2>Results</h2> <ul class="nav nav-pills"> <li class="active"><a data-toggle="pill" href="#topic">Topics</a></li> <li><a data-toggle="pill" href="#result1">Result1</a></li> <li><a data-toggle="pill" href="#result2">Result2</a></li> <li><a data-toggle="pill" href="#result3">Result3</a></li> <li><a data-toggle="pill" href="#result4">Result4</a></li> </ul> </div> <!-- /#container-fluid --> </div> <!-- /#page-content-wrapper --> </div> <!-- /#wrapper --> <!-- jQuery --> <script src="{{ url_for('static', filename='js/jquery.js') }}"></script> <!-- Bootstrap Core JavaScript --> <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script> <!-- Menu Toggle Script --> <script> $("#menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); }); </script> Could someone please help? A: Add these styles #wrapper { display: flex; } h2 { margin: 0 !important; } #wrapper { display: flex; } h2 { margin: 0 !important; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <!-- Latest compiled JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <!-- jQuery library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <!--- FontAwesome --> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css"> </head> <body> <div id="wrapper"> <!-- Sidebar --> <div id="sidebar-wrapper"> <ul class="sidebar-nav"> <li class="sidebar-brand"> <a href="#"> Start Bootstrap </a> </li> <li> <a href="#">Dashboard</a> </li> <li> <a href="#">Shortcuts</a> </li> </ul> </div> <!-- /#sidebar-wrapper --> <div id="page-content-wrapper"> <div class="container-fluid"> <h2>Results</h2> <ul class="nav nav-pills"> <li class="active"><a data-toggle="pill" href="#topic">Topics</a></li> <li><a data-toggle="pill" href="#result1">Result1</a></li> <li><a data-toggle="pill" href="#result2">Result2</a></li> <li><a data-toggle="pill" href="#result3">Result3</a></li> <li><a data-toggle="pill" href="#result4">Result4</a></li> </ul> <div id="result1"> Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content Result 1 Some content </div> <div id="result2"> Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 Result2 </div> <div id="result3"> Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 Result3 </div> <div id="result4"> Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 Result 4 </div> </div> <!-- /#container-fluid --> </div> <!-- /#page-content-wrapper --> </div> <!-- /#wrapper --> <!-- jQuery --> <script src="{{ url_for('static', filename='js/jquery.js') }}"></script> <!-- Bootstrap Core JavaScript --> <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script> <!-- Menu Toggle Script --> <script> $("#menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); }); $(".nav-pills a").click(function(e) { e.preventDefault(); var id = this.hash.substr(1); document.getElementById(id).scrollIntoView(); }) </script>
{ "language": "en", "url": "https://stackoverflow.com/questions/50931924", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove Local Storage in another JS file From below case, can someone help me to know how to remove localStorage which i have implemented below : var serverSelectorDemo = function() { loadrightdata(); function loadrightdata() { $('#kt_datatable_fetch_display2').html(localStorage.rightdata); }; $('#kt_datatable2').on('click','tr button', function() { var id = $(this).data('id'); $.ajax({ type: 'post', url: 'src/khu-pusat/compare/right-side/right-value.php', data: { 'rowid': id }, success: function(data) { $('#kt_datatable_nodata2').addClass('hidden'); localStorage.rightdata = data; $('#kt_datatable_fetch_display2').html(localStorage.rightdata); return false; } }); }).click(function() { $('#kt_datatable_fetch_display2').empty(); }); }; So far I can't find a way that can do this.
{ "language": "en", "url": "https://stackoverflow.com/questions/71346728", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Timeout a function in JavaScript/jQuery I've got the following problem: I'm using Google Maps on my site. I've attached the following eventListener to the map itself: google.maps.event.addListener(map, 'bounds_changed', scheduleDelayedCallback); The event bounds_changed is called every time someone drags the map. My Problem is, that it is called several times during the drag process. Now I need to find a way to call the callback function only, if it wasn't called during the last, let's say, 750 milliseconds. I did this using these two functions: function fireIfLastEvent() { var now = new Date().getTime(); if (lastEvent.getTime() + 750 <= now) { this_function_needs_to_be_delayed(); } else { $("#main").html('Lade...'); } } function scheduleDelayedCallback() { lastEvent = new Date(); setTimeout(fireIfLastEvent, 750); } This method works great in Chrome and Opera. In IE it works sometimes, in Firefox it never works (it calls the functions even if the 750 milliseconds haven passed). Is there any rock-solid way to timeout a function call? Thanks. A: You shouldn't need a timeout here. function scheduleDelayedCallback() { var now = new Date(); if (now.getTime() - lastEvent.getTime() >= 750) { // minimum time has passed, go ahead and update or whatever $("#main").html('Lade...'); // reset your reference time lastEvent = now; } else { this_function_needs_to_be_delayed(); // don't know what this is. } } Your explanation of what you want to happen isn't the clearest so let me know if the flow is wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/4034897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Connection refused error with selenium running in docker While trying nto dockerise selenium End2End tests using the selenium docker image 'selenium/standalone' i get the error : Error retrieving a new session from the selenium server Connection refused! Is selenium server started? ye selenium server starts up according to the console output..any ideas ? FROM selenium/standalone-chrome USER root # installing node RUN apt-get update RUN apt-get install -y curl RUN curl -sL https://deb.nodesource.com/setup_7.x | bash RUN apt-get install -y nodejs RUN node -v RUN npm -v # Installing Yarn #RUN rm -r /usr/local/bin/yarn RUN npm install -g -y yarn ENV PATH $PATH:/usr/local/bin/yarn #copying files WORKDIR /app COPY . . # debug RUN ls -alh . #installing yarn RUN yarn install EXPOSE 4444 RUN yarn CMD yarn test A: The problem is your approach of solving this. See you are inheriting your image from selenium/standalone-chrome which is supposed to run a Selenium browser. Now is this image you are adding your tests and specifying the CMD to run the tests. When you build and launch this image, you don't get any browser because the CMD has been overridden by you to run the test. When we build in docker we keep dependent services in different containers. It is preferred to run 1 service/process per container in most case. In your case when the test is run the browser server process is missing, so that is the reason for connection refused. So you need to be running two containers here. One for selenium/standalone-chrome and one for your test. Also your image should inherit from node: and not from selenium chrome image. You should not have node -v and npm -v commands also while building images. They create extra layers in your final image FROM node:7 USER root # installing node RUN apt-get update && apt-get install -y curl # Installing Yarn RUN npm install -g -y yarn ENV PATH $PATH:/usr/local/bin/yarn #copying files WORKDIR /app COPY . . # debug #installing yarn RUN yarn install RUN yarn CMD yarn test Now you need to create a docker-compose file to run a composition which has both your test and chrome version: '3' services: chrome: image: selenium/standalone-chrome tests: build: . depends_on: - chrome Install docker-compose and run docker-compose up command to run the above composition. Also in your tests make sure to use the URL as http://chrome:4444/wd/hub and use the Remote webdriver and not the local driver. A: i used a selenium/node-chrome image, but what resolved it was making sure my chromedriver + selenium server + nightwatch were set to the latest versions in my package.json
{ "language": "en", "url": "https://stackoverflow.com/questions/45343363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Deactivate checkbox if a condition in a text input is true in javascript I've several text inputs and an checkbox array. If the value of the text input is less than 6 deactivate the checkbox. I tried this but the checkbox is always enabled. <script> function desactivacasillas() { var formularioprincipal = document.getElementById("troncocomun"); var primerelemento = document.getElementById("1").value; if (document.getElementById("1").value < 6) { var checkbox1 = document.getElementById("checkbox1").disabled = true; } } </script> <table> <tr> <td nowrap id="materia">ALGEBRA</td> <td>5.62</td> <td> <input type="text" id="1" name="1" onkeydown="return validarnumero(event)" onkeypress="return compruebacampo(event,this)" onkeyup="desactivacasillas(event)"> </td> <td> <input type="hidden" name="carga[0]" id="checkbox1" value="0"> <input type="checkbox" name="carga[0]" id="checkbox1" value="5.62"> </td> </tr> </table> Can you tell me please what I'm doing wrong? A: Make the IDs unique. Here is the below I tried and worked <script> function desactivacasillas() { var formularioprincipal = document.getElementById("troncocomun"); var primerelemento = document.getElementById("1").value; if (document.getElementById("1").value < 6) { var checkbox1 = document.getElementById("checkbox2"); checkbox1.disabled = true; } } </script> <table> <tr> <td nowrap id="materia">ALGEBRA</td> <td>5.62</td> <td> <input type="text" id="1" name="1" value="6" onkeydown="return validarnumero(event)" onkeypress="return compruebacampo(event,this)" onkeyup="desactivacasillas(event)"> </td> <td> <input type="hidden" name="carga[0]" id="checkbox1" value="0"> <input type="checkbox" name="carga[0]" id="checkbox2" value="5.62"> </td> </tr> </table> A: Try this <!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"> </script> <script> function desactivacasillas(args) { if (document.getElementById("1").value.length < 6) { $("#checkbox2").attr("disabled", true); } else { $("#checkbox2").attr("disabled", false); } } </script> <table> <tr> <td nowrap id="materia">ALGEBRA</td> <td>5.62</td> <td> <input type="text" id="1" name="1" onkeyup="desactivacasillas(this.value)"> </td> <td> <input type="hidden" name="carga[0]" id="checkbox1" value="0"> <input type="checkbox" name="carga[0]" id="checkbox2" value="5.62"> </td> </tr> </table> </body> </html> Feel free to ask anything if you don't understand the above program. A: Try this. Use on load function in java script to disable check box while loading. and use parse Int function because input returns value as string. change the ID's of check boxes. ID's are always Unique. <script> function disableCheckbox(){ document.getElementById("checkbox2").disabled = true; } function desactivacasillas() { var formularioprincipal = document.getElementById("troncocomun"); var primerelemento = document.getElementById("1").value; if (parseInt(document.getElementById("1").value,10) > 6) { document.getElementById("checkbox2").disabled = false; } } </script> <body onload="disableCheckbox();"> <table> <tr> <td nowrap id="materia">ALGEBRA</td> <td>5.62</td> <td> <input type="text" id="1" name="1" onkeyup="desactivacasillas(event)"> </td> <td> <input type="hidden" name="carga[0]" id="checkbox1" value="0"> <input type="checkbox" name="carga[0]" id="checkbox2" value="5.62"> </td> </tr> </table> </body>
{ "language": "en", "url": "https://stackoverflow.com/questions/23166756", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Set a variable in url using php and mysql I need to set two variable in a url, $id and $job. The data should come from mysql select statement, [id] and [job_number_id]. My page displays a client job proposal and if there is more than one all proposals are displayed but the [id] and the [job_number_id] determines what is displayed on the webpage. I dont have a clue as to how this done. Any help would be greatly appreciated. Here's the code: <?php $url = 'http://localhost/estimate_lar/homepage.php'; $id = $_SESSION['id']; $query = "SELECT id, client_job_name, job_number_id FROM `job_name` WHERE `id`='$id'"; $allJobs = $db->query($query); ?> <?php foreach ($allJobs as $site_title) : ?> <p> <tr><?php echo '<a href="'.$url.'">'.$site_title['client_job_name'],$site_title['job_number_id']. '<br />'.'</a>'; ?> <td></td> </tr> </p> <?php endforeach; ?> A: If you want the variables to be avaialble in the URL you need to read them with $_GET. Getting the arguements from a url such as index.php?id=1&job_number_id=3 will look like that: if (isset($_GET['id']) && isset($_GET['job_number_id'])) {//make sure both arguments are set $id = $_GET['id']; $job_number_id = $_GET['job_number_id']; } To set it in your foreach statement: <?php foreach ($allJobs as $site_title) : ?> <p> <tr><?php $url = "http://localhost/estimate_lar/homepage.php?id=" . $site_title['id'] . "&job_number_id=" . $site_title['job_number_id']; echo '<a href="'.$url.'">'.$site_title['client_job_name'],$site_title['job_number_id']. '<br />'.'</a>'; ?> <td></td> </tr> </p> <?php endforeach; ?> PLEASE remember to read about SQL injection and making sure you are escaping your inputs. Or even better - use a prepared statement. Currently your script is volunerable, since everyone could just alter the URL and manipluate your DB. Hope this helps! A: Try this. <?php session_start(); $id = $_SESSION['id']; $url = 'http://localhost/estimate_lar/homepage.php'; if($id){ $query = "SELECT id, client_job_name, job_number_id FROM `job_name` WHERE `id`='$id'"; $allJobs = $db->query($query); }else{ echo "Id not in session"; } ?> <table> <?php if ($allJobs) { foreach ($allJobs as $site_title) : ?> <tr> <td> <a href="<?php echo $url; ?>?client_job_name=<?php echo $site_title['client_job_name'];?>&job_number_id=<?php echo $site_title['job_number_id'];?> "> <?php echo $site_title['job_number_id']. " ".$site_title['job_number_id']; ?></a> </td> </tr> <?php endforeach; ?> </table> <?php }else{ echo 'No results Found' ;} ?> This may help you.
{ "language": "en", "url": "https://stackoverflow.com/questions/21424676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Google DoubleClickStudio - video source file After creating a creative banner with an mp4 video in Google Web Designer and then upload that creative to DoubleClick the source file has changed from mp4 to webm. The issue here is that webm in Safari is pixelated and the creative/ad is not shown properly, while on other browsers its ok. Is there a setting in DoubleClickStudio to prevent it from transcoding the mp4 video and use the default mp4 instead ? ...1630672923/mv/u/mvi/1/pl/24/file/file.webm
{ "language": "en", "url": "https://stackoverflow.com/questions/69046044", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create Exception and pass AggregateException as inner exception? Imagine this scenario: Task.Run(() => { // code... }).ContinueWith(x => { var betterEx = new Exception("My custom message", x.Exception)); } , TaskContinuationOptions.OnlyOnFaulted); However, the betterEx.InnerException returns null. Question How can I create a new Exception and pass AggregateException as the inner exception? I want to make sure all the info in the aggregate is persisted and not lost.
{ "language": "en", "url": "https://stackoverflow.com/questions/51048391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to test if your REST API service supports gzip data? I am testing a REST API service that supports json and gzip data. I have tested the response from the json request payload. How to test if it handles gzip data properly? Please help? Basically the client sends a request with accept-encoding as gzip in the header, service handles the compression and the client takes care of the decompression. But I need a way to confirm that service indeed handles compressed gzip data A: gzip is basically a header + deflate + a checksum. Gatling will retain the original Content-Encoding response header so you can check if the payload was gzipped, and then trust the gzip codec to do the checksum verification and throw an error if the payload was malformed.
{ "language": "en", "url": "https://stackoverflow.com/questions/64467835", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jquery Deferred for an async function I have been reading a lot about JQuery's deferred object. And I can see how it works to de-couple code. I wrote this orignally using Async.js but would was recommended to use promise. Most examples I find just chain things to AJAX calls. I want to chain an async function but can't figure out how to do it. I am retrieving a time from the database then using that time as a parameter in a url, finally I would then like to make a AJAX call. This is where I'm at: var fetch = function (contactId, callback, errorCallback) { var buildPromise = new $.Deferred(); var getLastImportTime = function () { var querySuccess = function (tx, result) { buildPromise.resolve("7 oclock"); }; var queryError = function (tx, e) { buildPromise.reject("Error querying database"); }; database.open(); database.query("SELECT EventImportTime FROM Contact WHERE Contact.Id = ?", [contactId], querySuccess, queryError); }; var buildUrl = function (lastImportTime) { console.log("I do happen"); var url = "http://"; url += 'MobileGetChangedEvents.aspx?Reference='; url += '&LastImportTime='; url += lastImportTime; url += '&Format=JSON'; return url; }; var makeRequest = function (url) { getJSON(url, callback, errorCallback) }; $.when(getLastImportTime()).pipe(buildUrl).then(makeRequest); Also my pipe methods seems to be called first :s A: since you pass getLastImportTime function to when helper method, it should explicitly return a promise, (but in getLastImportTime() you are returning nothing and when() is expecting you to pass a promise) otherwise the helper could evaluate it as an immediate resolved (or rejected) promise. This could explain why it seems that function in pipe is executed before getLastImportTime() So try to change your function like so var getLastImportTime = function () { ... database.open(); database.query("SELECT ..."); return buildPromise.promise(); };
{ "language": "en", "url": "https://stackoverflow.com/questions/10601030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: PostgreSQL: Optimizing bulk INSERT INTO/SELECT FROM In my Postgresql schema I have a jobs table and an accounts table. Once a day I need to schedule a job for each account by inserting a row per account into the jobs table. This can done using a simple INSERT INTO.. SELECT FROM statement, but is there any empirical way I can know if I am straining my DB by this bulk insert and whether I should chunk the inserts instead? Postgres often does miraculous work so I have no idea if bulk inserting 500k records at a time is better than 100 x 5k, for example. The bulk insert works today but can take minutes to complete. One additional data point: the jobs table has a uniqueness constraint on account ID, so this statement includes an ON CONFLICT clause too. A: In PostgreSQL, it doesn't matter how many rows you modify in a single transaction, so it is preferable to do everything in a single statement so that you don't end up with half the work done in case of a failure. The only consideration is that transactions should not take too long, but if that happens once a day, it is no problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/73657585", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XML mapping to objects without attributes in C# Is there a C# library that allows mapping C# objects to XML without Attributes? I have several data sources, all of them containing XML data with the same logical-structure, but different schema. For example in one XML there might be a field called 'zip-code', in another this data will be in attribute called 'postal-code' etc. I want to deserialize all XML sources in single C# class. Obviously I can not use XMLAttrubtes, because there are different 'paths'. I want something like EclipseLink MOXy (metadata is specified in XML), but for C#. A: The XmlSerializer allows you to specify attribute overrides dynamically at runtime. Let's suppose that you have the following static class: public class Foo { public string Bar { get; set; } } and the following XML: <?xml version="1.0" encoding="utf-8" ?> <foo bar="baz" /> you could dynamically add the mapping at runtime without using any static attributes on your model class. Just like this: using System; using System.Xml; using System.Xml.Serialization; public class Foo { public string Bar { get; set; } } class Program { static void Main() { var overrides = new XmlAttributeOverrides(); overrides.Add(typeof(Foo), new XmlAttributes { XmlRoot = new XmlRootAttribute("foo") }); overrides.Add(typeof(Foo), "Bar", new XmlAttributes { XmlAttribute = new XmlAttributeAttribute("bar") }); var serializer = new XmlSerializer(typeof(Foo), overrides); using (var reader = XmlReader.Create("test.xml")) { var foo = (Foo)serializer.Deserialize(reader); Console.WriteLine(foo.Bar); } } } Now all that's left for you is to write some custom code that might read an XML file containing the attribute overrides and building an instance of XmlAttributeOverrides from it at runtime that you will feed to the XmlSerializer constructor.
{ "language": "en", "url": "https://stackoverflow.com/questions/14641646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to connect to tables and display their content? (MySQL and PHP) I have two mysql tables (products and categories). I have some mock data in both tables. Now I need to somehow attach the categories to the products. For example - The product witht he ID 1 should return the following: | product name | category | | Monitor | Technology | I know I have done this bevore, but today I simply can't seem to find the solution to this. EDIT This is waht I have so far. The connection works well and I can display the data in a Table. <?php // Include database connection include("connection.php"); // Create variables for later use $db = $conn; $tableName = "Produkte"; $columns= ['id_product', 'name_product']; // Create variable to use in index.php $fetchData = fetch_data($db, $tableName, $columns); // The function below feteches data from the tables specified and checks if the colums are emtpy by any chance. function fetch_data($db, $tableName, $columns) { // Check db connection if (empty($db)) { $message= "Database connection error"; } // Check if the columns variable is empty and not an array by any chance elseif (empty($columns) || !is_array($columns)) { $message="Product Name must be defined in an indexed array"; } // Check if table name is empty elseif (empty($tableName)) { $message= "Table Name is empty"; } // Else proceed as usual. else { $columnName = implode(", ", $columns); // The query needs to be repalced. Today my SQL stuff is leaving me a bit. $query = "SELECT p.".$columnName." AS product, c.name_category FROM $tableName p JOIN Kategorie c ON c.id_"; $result = $db->query($query); if ($result== true) { if ($result->num_rows > 0) { $row= mysqli_fetch_all($result, MYSQLI_ASSOC); $message= $row; } else { $message= "No Data Found"; } } // Throw error if error occures else{ $message= mysqli_error($db); } } return $message; } The table products has only 2 columns. An id column and a product_name column. A: It's vary basic technics: // create DBquery using JOIN statement $query = " SELECT p.name AS product, c.name AS category FROM products p JOIN categories c ON c.id = p.category_id;"; // get DB data using PDO $stmt = $pdo->prepare($query); $stmt->execute(); // show table header printf('| product name | category |' . PHP_EOL); // loop for output result as table rows while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { printf('| %-12s | %10s |' . PHP_EOL, $row['product'], $row['category']); } Try online
{ "language": "en", "url": "https://stackoverflow.com/questions/71996831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: React Native bottom tab navigator - Android screen reader only selects tab label and not tab icon as well I have a bottom tab navigator from react navigation. Previously, when you had the screen reader on, both the text and the icon of each tab could be selected as one container. Here we see both the icon and label being selected as one container for the screen reader After upgrading to RN 0.69 from 0.68, only the text in the tab bar is selectable. How can I make both the icon and text selectable as one container? If I add an accessibility label to the tab bar icon, the whole container can be selected again, but that requires that we add a label. A: You can make a custom tab bar and add accessibility as you wish in each tab bar item like this: <Tab.Navigator tabBar={(props) => <CustomTabBar/>}> <Tab.Screen .../> </Tab.Navigator> A: Thank you guys for responding. Really appreciate it! I hadn't done the correct research. In the documentation , it says that theres is a prop which you can add to the whole tab bar. https://reactnavigation.org/docs/bottom-tab-navigator/#tabbaraccessibilitylabel After adding this, the container (both the tab icon and text) was selectable as one container. It is just strange that this behaviour worked before without adding that prop.
{ "language": "en", "url": "https://stackoverflow.com/questions/75321062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: using CASE WHEN in SQL Statement I have to display information by comparing data in two ID columns, one column has 'ALL' and numbers as ID's while the other has only numbers in it as ID's. My problem is, I cannot compare character and number columns with a number column. So I am using CASE WHEN. If the value is 'ALL' then display 'ALL' in the output, else display name for the matching records. Here is the code: CASE WHEN secorg.org_id = 'ALL' THEN 'ALL' WHEN secorg.org_id = progmap.org_id THEN secorg.org_name END AS org_name, the condition is this: 'secorg.org_id = progmap.org_id' which is based on the id and I have to display secorg.org_name if the id's are same. Here is the entire query: SELECT distinct program_id, prog_name, case when Eitc_Active_Switch = '1' then 'ON' when Eitc_Active_Switch = '0'then 'OFF' End as Prog_Status, progmap.client_id, case when secorg.org_id = 'ALL' then 'ALL' --when secorg.org_id = progmap.org_id then secorg.org_name else secorg.org_name end as org_name, case when prog.has_post_calc_screen = 'True' then 'True' Else 'False' End as Referal_ID, case when progmap.program_ID IN ( 'AMC1931', 'AMCABD', 'AMCMNMI', 'AMC' ) And sec.calwinexists_ind = '1' then 'Yes' when progmap.program_ID IN ( 'AMC1931', 'AMCABD', 'AMCMNMI', 'AMC' ) And sec.calwinexists_ind = '0'then 'No' when progmap.program_ID NOT IN ( 'AMC1931', 'AMCABD', 'AMCMNMI', 'AMC' ) then 'N/A' End as calwin_interface, sec.Client_name FROM ref_programs prog (nolock) LEFT OUTER JOIN ref_county_program_map progmap (nolock) ON progmap.program_id = prog.prog_id AND progmap.CLIENT_ID = prog.CLIENT_ID INNER join sec_clients sec (nolock) on sec.client_id = progmap.Client_id Inner join sec_organization secorg (nolock) on secorg.org_id = progmap.org_id A: Why not cast the number columns to varchar columns? If you're using SQL SERVER you can do that like so: CONVERT(VARCHAR,secorg.org_id) = CONVERT(VARCHAR,progmap.org_id) You'll have to do an outer join for instances when the column that is both 'ALL' and numbers is 'All' as it won't be able to inner join to the other table. For the quick fix based on your code above you can just change the second WHEN clause to look like so (again assuming you're using MS SQL SERVER): WHEN CONVERT(VARCHAR,secorg.org_id) = CONVERT(VARCHAR,progmap.org_id) THEN secorg.org_name Try this as your query: SELECT DISTINCT program_id, prog_name, CASE Eitc_Active_Switch WHEN '1' THEN 'ON' ELSE 'OFF' END AS Prog_Status, progmap.client_id, ISNULL(secorg.org_name,'ALL') AS org_name, CASE prog.has_post_calc_screen WHEN 'True' THEN 'True' ELSE 'False' END AS Referal_ID, CASE WHEN progmap.program_ID IN ('AMC1931','AMCABD','AMCMNMI','AMC') AND sec.calwinexists_ind = '1' THEN 'Yes' WHEN progmap.program_ID IN ('AMC1931','AMCABD','AMCMNMI','AMC') AND sec.calwinexists_ind = '0' THEN 'No' WHEN progmap.program_ID NOT IN ('AMC1931','AMCABD','AMCMNMI','AMC') THEN 'N/A' END AS calwin_interface, sec.Client_name FROM ref_programs prog (nolock) LEFT OUTER JOIN ref_county_program_map progmap (nolock) ON progmap.program_id = prog.prog_id AND progmap.CLIENT_ID = prog.CLIENT_ID INNER JOIN sec_clients sec (nolock) ON sec.client_id = progmap.Client_id LEFT OUTER JOIN sec_organization secorg (nolock) ON CONVERT(VARCHAR,secorg.org_id) = CONVERT(VARCHAR,progmap.org_id) A: The case statement is fine its the field alias thats bad it shoud be END As org_name A multipart alias like secorg.org_name won't work
{ "language": "en", "url": "https://stackoverflow.com/questions/5751038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Multiple locks locking the same functions C# .Net I have a simple question about lock. Are Process1 and Process2 the same because they are eventually locking the LongProcess? Thank you. private static readonly object _Locker = new object(); public void Process1() { lock(_LockerA){ LongProcess() } } public void Process2() { if(curType == A) ProcessTypeA(); else if(curtype == B) ProcessTypeB(); } private static readonly object _LockerA = new object(); public void ProcessTypeA() { lock(_LockerA){ LongProcess() } } private static readonly object _LockerB = new object(); public void ProcessTypeB() { lock(_LockerB){ LongProcess() } } public void LongProcess() { } A: No, they are not the same. If you lock against a different object than an already existing lock, then both code paths will be allowed. So, in the case of Process2 curtype == 'b' the lock is using the _LockerB object. If one of the other locks using the _LockerA object is attempted, then they will be allowed to enter the LongProcess. A: Process1 and Process2 have the potential to lock the same object, but they are definitely not the same. Locks on the same object are however allowed (I think, rarely if ever had to do it) within the same call stack (also referred to as recursive locking in the case where Process1 invokes Process2). This could likely be better described as dependent locking. Your question is however fairly vague so you'll have to elaborate on what you mean by the same...
{ "language": "en", "url": "https://stackoverflow.com/questions/9781213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the settings and how to change settings using adb commands I am working on a project where I have to retrieve the settings of an Android phone and then change it from command prompt only using adb shell. Actually I don't know which adb command to use to get the details like SW version, current ringtone, MAC address and which to change. If anyone know that please let me know. Thanks for help in advance. A: you can use the follow commands: adb shell cat /sys/class/net/wlan0/address #mac address adb get-serialno #serial number adb shell cat /data/misc/wifi/*.conf #wifi passward
{ "language": "en", "url": "https://stackoverflow.com/questions/43385395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Update a single node XML file with PowerShell I have this XML file: environment-config.xml <?xml version="1.0" encoding="windows-1252"?> <environment>uat</environment> I would like to update the value and have this script. [string]$EnvConfigFileName = ".\environment-config.xml" $EnvironmentName = 'prod' [XML]$xmlFileContent = Get-Content $EnvConfigFileName $xmlNode = $xmlFileContent.SelectSingleNode("/environment") $xmlNode.Value = $EnvironmentName $xmlFileContent.Save($EnvConfigFileName) On execution it generates this error: Exception setting "Value": "Cannot set a value on node type 'Element'." ---> System.InvalidOperationException: Cannot set a value on node type 'Element'. Is there another way to do this? Thanks in advance. A: You can get the nodes as shown in below code and change the value. [xml]$xmlData = Get-Content $EnvConfigFileName $xmlData.environment = "Data" #Save the file $xmlData.Save($EnvConfigFileName)
{ "language": "en", "url": "https://stackoverflow.com/questions/67782312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery dynamically set incremented height to elements What I want to achieve: for each ul.container -> find the greatest li height -> add 25px to it -> apply that new height to all li within the container. I need the calculation to happen also on window resize. The problem: While this works at page load, when resizing the browser window, the height keeps incrementing by 25px at every loop. I can't seem to figure out what I am doing wrong. My code: function listHeight() { $("ul.container").each(function () { var listHeight = 0; var newHeight = 0; $("li", this).each(function () { newHeight = $(this).height(); if (newHeight > listHeight) { listHeight = newHeight; } }); $("li", this).height(listHeight += 25); }); } listHeight(); $(window).resize(function () { listHeight(); }); JSFiddle: http://jsfiddle.net/upsidown/VtypM/ Thanks in advance! A: The height increases because you set the height in the first run. After that the height remains the "max hight" + 25 and adds additional 25 to it. To prevent that just reset the height of the element to auto. function listHeight() { $("ul.container").each(function () { var listHeight = 0; var newHeight = 0; $("li", this).each(function () { var el = $(this); el.css('height', 'auto'); newHeight = el.height(); if (newHeight > listHeight) { listHeight = newHeight; } }); $("li", this).height(listHeight += 25); }); } listHeight(); $(window).resize(function () { listHeight(); }); For better performance I suggest that you debounce/throttle the function call. A: you need to add $("li", this).height("auto"); after var listHeight = 0; var newHeight = 0; view Demo A: I think you need to look at this thread. jQuery - how to wait for the 'end' of 'resize' event and only then perform an action? You need to call it at the end of the resize event. Hope it helps! A: You need to increment height only if newHeight > listHeight, I think.
{ "language": "en", "url": "https://stackoverflow.com/questions/23868195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: multiple or conditions in if else statements best way oracle pl sql I have below scenario where i have to check multiple or conditions to check if local varibale should not be equal to A, B, C, D and so on. Obviously real values are different than I refered here. I want to know which one is the best from below or any other possible way: IF(condition1 AND (myLocalVAr NOT IN ('A','B','C','D','E','F') ) ) THEN ---- -- END IF; or IF(condition1 AND (myLocalVAr <> 'A' AND myLocalVAr <> 'B' AND myLocalVAr <> 'C'--'D'--'E'--'F' --so on) ) ) THEN ---- -- END IF; A: In real world we always looking to think and code in simple and automated ways and methods, if we can't achieve our goal, then we have to looking to more complex solutions. now let's see your code, the first way is more easy straightforward to achieve your goal, if the source of A, B, C, D,...etc is from table we can directly write it like: myLocalVAr not in (select column_name from table_name) this is working fine, and any new value will be easy to handle by this approach, however "not in" clause has disadvantages: * *you have to be sure that the return values in subquery do not have any single null value, if it does, then the whole logic will be null, in this case we can handle it by using nvl function or eliminate null records by using where clause. *performance: the "not in" clause does not give us a good performance when we have a long list of values which we compre myLocalVAr with it. so we are using here "not exists" instead. the second approach you are mentioned is not practical, it is hard working, error born, and hard to manage with new values in the future, you have to add new values by yourself and modify this code every time you need to compare with new value, so we do not follow solutions like this one.
{ "language": "en", "url": "https://stackoverflow.com/questions/39208331", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HttpUrlConnection Get method returns status code 405 I am trying to fetch data from the server using HttpURLConnection. The request is a GET request. But, it always returns status code 405(BAD_METHOD). Below is the method I wrote: URL url2 = new URL("http://www.example.com/api/client_list?"); HttpURLConnection connection = (HttpURLConnection) url2 .openConnection(); connection.setRequestMethod("GET"); connection.setReadTimeout(NET_READ_TIMEOUT_MILLIS); connection.setConnectTimeout(CONNECTION_TIMEOUT_MILLIS); connection.setRequestProperty("Authorization", token); connection.setDoInput(true); connection.setDoOutput(true); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("client_id", clientRole)); OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getQuery(params)); writer.flush(); writer.close(); connection.connect(); getQuery() private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (NameValuePair pair : params) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(pair.getName(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(pair.getValue(), "UTF-8")); } return result.toString(); } While if perform the same using HttpClient, I get the desired output. Below is the same operation with HttpClient String url = "http://www.example.com/api/client_list?client_id=" + rolename; HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); httpGet.setHeader("Authorization", "Bearer " + token); httpClient.execute(httpGet); I am not getting what I am doing wrong with HttpUrlConnection. A: connection.setDoInput(true); forces POST request. Make it connection.setDoInput(false); A: The issue that I ran into with the OP's code is that opening the output stream...: OutputStream os = connection.getOutputStream(); ...implicitly changes the connection from a "GET" (which I initially set on the connection via setProperties) to a "POST", thus giving the 405 error on the end point. If you want to have a flexible httpConnection method, that supports both GET and POST operations, then only open the output stream on non-GET http calls. A: Well according to me into the GET method parameters are to be send as the part of the URL so try this. String request = "http://example.com/index.php?param1=a&param2=b&param3=c"; URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); connection.setUseCaches (false); BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println(response.toString()); try it.
{ "language": "en", "url": "https://stackoverflow.com/questions/26332041", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Swagger - Route defined in Swagger specification but there is no defined get operation I am creating a nodejs web service using swagger-ui. So I went on the online editor of swagger, did my yaml and exported it for nodejs server. When I am running in on my computer, with host as localhost (see yaml) I try to perform a PUT I got that message : Error: Route defined in Swagger specification (/test) but there is no defined get operation. at send405 (/home/guillaume/Desktop/docker-swagger2-amp/node_modules/swagger-tools/middleware/swagger-router.js:307:13) at swaggerRouter (/home/guillaume/Desktop/docker-swagger2-amp/node_modules/swagger-tools/middleware/swagger-router.js:422:16) at call (/home/guillaume/Desktop/docker-swagger2-amp/node_modules/connect/index.js:239:7) at next (/home/guillaume/Desktop/docker-swagger2-amp/node_modules/connect/index.js:183:5) at swaggerValidator (/home/guillaume/Desktop/docker-swagger2-amp/node_modules/swagger-tools/middleware/swagger-validator.js:409:14) at call (/home/guillaume/Desktop/docker-swagger2-amp/node_modules/connect/index.js:239:7) at next (/home/guillaume/Desktop/docker-swagger2-amp/node_modules/connect/index.js:183:5) at swaggerMetadata (/home/guillaume/Desktop/docker-swagger2-amp/node_modules/swagger-tools/middleware/swagger-metadata.js:451:14) at call (/home/guillaume/Desktop/docker-swagger2-amp/node_modules/connect/index.js:239:7) at next (/home/guillaume/Desktop/docker-swagger2-amp/node_modules/connect/index.js:183:5) and Failed to load http://127.0.0.1:8080/v2/test: Response for preflight has invalid HTTP status code 405 I have a get operation so I don't know what is the error. Here are my main files : YAML: swagger: "2.0" info: description: "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters." version: "1.0.0" title: "Swagger Petstore" termsOfService: "http://swagger.io/terms/" contact: email: "[email protected]" license: name: "Apache 2.0" url: "http://www.apache.org/licenses/LICENSE-2.0.html" host: "127.0.0.1:8080" basePath: "/v2" tags: - name: "test" description: "Define yours parameters launching" schemes: - "http" paths: /test: put: tags: - "test" summary: "Add Test configuration and use it to launch Test" description: "" operationId: "addTestconf" consumes: - "application/xml" - "application/json" produces: - "application/xml" - "application/json" parameters: - in: "body" name: "body" description: "test configuration that needs to be used to run test" required: true schema: $ref: "#/definitions/test" responses: 400: description: "Invalid ID supplied" 404: description: "test not found" 405: description: "Validation exception" /test/{TestId}: get: tags: - "test" summary: "Find Test config by ID" description: "Returns a Test config" operationId: "getTestConfigurationById" produces: - "application/xml" - "application/json" parameters: - name: "testId" in: "path" description: "ID of test config to return" required: true type: "integer" format: "int64" responses: 200: description: "successful operation" schema: $ref: "#/definitions/test" 400: description: "Invalid ID supplied" 404: description: "test Config not found" definitions: ........ index.js: 'use strict'; var fs = require('fs'), path = require('path'), http = require('http') var app = require('connect')(); var swaggerTools = require('swagger-tools'); var jsyaml = require('js-yaml'); var serverPort = 8080; // swaggerRouter configuration var options = { swaggerUi: path.join(__dirname, '/swagger.json'), controllers: path.join(__dirname, './controllers'), useStubs: process.env.NODE_ENV === 'development' // Conditionally turn on stubs (mock mode) }; // The Swagger document (require it, build it programmatically, fetch it from a URL, ...) var spec = fs.readFileSync(path.join(__dirname,'api/swagger.yaml'), 'utf8'); var swaggerDoc = jsyaml.safeLoad(spec); // Initialize the Swagger middleware swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) { // Interpret Swagger resources and attach metadata to request - must be first in swagger-tools middleware chain app.use(middleware.swaggerMetadata()); // Validate Swagger requests app.use(middleware.swaggerValidator()); // Route validated requests to appropriate controller app.use(middleware.swaggerRouter(options)); // Serve the Swagger documents and Swagger UI app.use(middleware.swaggerUi()); // Start the server http.createServer(app).listen(serverPort, function () { console.log('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort); console.log('Swagger-ui is available on http://localhost:%d/docs', serverPort); }); }); and my controllers : test_configuration.js: 'use strict'; var url = require('url'); var test = require('./testService'); module.exports.addTestConf = function addTestConf(req, res, next) { test.addTestConf(req.swagger.params, res, next); }; module.exports.getTestConfigurationById = function getTestConfigurationById(req, res, next) { test.getTestConfigurationById(req.swagger.params, res, next); }; test_configurationService.js: use strict'; exports.addTestConf = function(args, res, next) { res.end(); } exports.getTestConfigurationById = function(args, res, next) { res.end(); } A: The operationId must match the controller function. Looks like there is a case mismatch in your code: * *operationId: addTestconf *function name: addTestConf A: This is a CORS related problem if you try to request the Api using a different url/host than the indicated in .yaml file you'll get this error so if in your .yaml you have host: "localhost:8085" and used 127.0.0.1:8080 you may face this issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/48417779", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Wrote a hello world program in C but now I can't kill the process I wrote a simple hello world program that should print hello to the console. I compiled it using gcc. Once I tried to run the .exe file it created a little blue spinner next to my mouse pointer and it doesn't go away. I've tried to kill the process using taskkill (I'm on windows7) but it's not working. Perhaps there's a bug in the code? Things I've tried: * *ending the process from windows task manager *taskkill /IM helloworld.exe /f tl;dr A hello world program won't exit even using taskkill #include <stdio.h> int main(){ printf("Hello world"); return 0; } A: Use exit(0); in your program. Don't forget to use include <stdlib.h>
{ "language": "en", "url": "https://stackoverflow.com/questions/34696673", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Don't generate blocks without values (ASP.NET MVC) I have back-end code here is code [HttpGet] public ActionResult QuestionBlocks() { var _id = TempData["ID"]; var questBlock = db.QuestionBlocks .Where(x => x.Interview_Id == (int?) _id) .Select(x => new { ID = x.Block_ID, Question1 = x.Question1, Question2 = x.Question2, Question3 = x.Question3, Question4 = x.Question4, Question5 = x.Question5, Question6 = x.Question6, Question7 = x.Question7, Question8 = x.Question8, Question9 = x.Question9, Question10 = x.Question10, }) .ToList(); return Json(questBlock, JsonRequestBehavior.AllowGet); } But some of Questions may be without values. Here on front-end I display it on View <script> $(document).ready(function() { question_block(); }); function question_block() { $.ajax({ url: '@Url.Action("QuestionBlocks", "Interwier")', contentType: 'application/json; charset=utf-8', type: 'GET', dataType: 'json', processData: false, success: function(result) { var email = result; for (var i = 0; i <= email.length - 1; i++) { var question = '<div class="activeQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question1 + '</div>' + '<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question2 + '</div>' + '<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question3 + '</div>' + '<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question4 + '</div>' + '<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question5 + '</div>' + '<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question6 + '</div>' + '<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question7 + '</div>' + '<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question8 + '</div>' + '<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question9 + '</div>' + '<div class="hiddenQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + email[i].Question10 + '</div>'; $("#questions").append(question); $('.hiddenQue:empty').hide(); Now I hide it via $('.hiddenQue:empty').hide(); but it's not what I want, I need to not generate divs if it has not value. How I can do this? A: Just use if condition, inside for loop to check if it has question or not. it will work for you. <script> question_block(); function question_block() { $.ajax({ url: '@Url.Action("QuestionBlocks", "Home")', contentType: 'application/json; charset=utf-8', type: 'GET', dataType: 'json', processData: false, success: function (result) { var email = result; for (var i = 0; i <= email.length - 1; i++) { var question = ""; for (var j = 1; j <= 10; j++) { var getQ = email[i]["Question" + j]; if (getQ) { question += '<div class="activeQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' + getQ + '</div>'; } } if (question != "") { $("#questions").append(question); } } } }); } </script> A: You can try like this !!! <script> $(document).ready(function() { question_block(); }); function question_block() { $.ajax({ url: '@Url.Action("QuestionBlocks", "Interwier")', contentType: 'application/json; charset=utf-8', type: 'GET', dataType: 'json', processData: false, success: function(result) { var email = result; for (var i = 0; i <= email.length - 1; i++) { var question=''; var Question1=''; var Question2=''; var Question3=''; var Question4=''; var Question5=''; var Question6=''; var Question7=''; var Question8=''; var Question9=''; email[i].Question1==''?Question1='':Question1='<div class="activeQue" style="font-size:20px;position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);">' +email[i].Question1 + '</div>' question=question+Question1 //Do this for all question $("#questions").append(question); //$('.hiddenQue:empty').hide();
{ "language": "en", "url": "https://stackoverflow.com/questions/43609339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Executing a function prevents tkinter window from appearing I have a function that is going to be the main area of this program, but when I add in a new function that needs to be executed by a button, it prevents the window from appearing, or gives out an error. The function I am trying to get to appear after a button press is new_function. def bowler(): global bowler_win global batsmen bowler_win = Toplevel(master) batsmen_win_2.withdraw() variable = StringVar(bowler_win) variable.set(fielding_team[0]) title = Label(bowler_win, text = "Please choose the bowler").grid(row = 0, column = 1) w = OptionMenu(bowler_win, variable, *fielding_team) w.grid(row = 1, column = 1) def ok2(): current_bowler = variable.get() for players in batting_team: if players == current_bowler: fielding_team.remove(current_bowler) main_play() button = Button(bowler_win, text="OK", command=ok2).grid(row = 2, column = 1) #####CODE ABOVE IS ONLY TO SHOW WHERE THE FUNCTION BELOW IS EXECUTED FROM def main_play(): while innings != 3: facing_length = len(batsmen) while over != over_amount or out_full == True or facing_length <= 1: main_win = Toplevel(master) bowler_win.withdraw() ws = Label(main_win, text = " ").grid(row = 1, column = 1) title = Label(main_win, text = "Current Game").grid(row = 0, column = 1) score = Label(main_win, text = "Current Score:").grid(row = 2, column = 1) line = Label(main_win, text = "--------------").grid(row = 1, column = 1) score = Label(main_win, text = str(runs) + "/" + str(out)).grid(row = 3, column = 1) line = Label(main_win, text="--------------").grid(row=4, column=1) cur_bat = Label(main_win, text = "Facing Batsmen: " + batsmen[0]).grid(row = 5, column = 1) other_bat = Label(main_win, text = "Other Batsmen: " + batsmen[1]).grid(row = 6, column = 1) current_patner = Label(main_win, text = "Patnership: " + str(partnership_runs)).grid(row = 7, column = 1) button = Button(main_win, text = "Next Play", command = new_function).grid(row = 8, column = 1) ###THIS IS WHERE THE NEW FUNCTION IS EXECUTED If I call the function new_function after the button, the main_win window does not appear, this is the same for if I call new_function above the main_play function, the same error occurs. If I try to nest new_function below the button, I get the error UnboundLocalError: local variable 'new_func' referenced before assignment Even though its a function(and I don't have a variable named that) If anyone can help, that would be amazing
{ "language": "en", "url": "https://stackoverflow.com/questions/66128900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android dataBinding - How to get resource id of a View in xml In Android Studio my data binding itself works and is set up fine. I have a boolean defined like this: <resources> <bool name="showAds">false</bool> </resources> and in a layout.xml file i would like to referenced this boolean (which works fine) but i want to assign a id based on this boolean. Let me show you what i am trying to accomplish: I have a button that is in a relativeLayout tag and depending on this boolean i would like to reposition the button. So I have this: <Button android:id="@+id/startButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="64dip" **************** android:layout_below="@{@bool/showAds ? @+id/adone : @+id/title_main}" **************** android:layout_centerHorizontal="true" android:textColor="#0080FF" android:text="@string/start_btn_title" /> See what i want to to do? I want to layout the button below a layout called adone if the showAds boolean is true, otherwise place it below a layout called title_main. Whats the syntax for this as what I have here is not compiling. I get a compile error: expression expected after the second @ sign A: The above is the same problem as in How to get dimensions from dimens.xml None of the LayoutParams attributes have built-in support. As answered in the linked article, data binding of LayoutParams was thought to be too easy to abuse so it was left out of the built-in BindingAdapters. You are not abusing it, so you should add your own. @BindingAdapter("android:layout_below") public static void setLayoutBelow(View view, int oldTargetId, int newTargetId) { RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams(); if (oldTargetId != 0) { // remove the previous rule layoutParams.removeRule(RelativeLayout.BELOW); } if (newTargetId != 0) { // add new rule layoutParams.addRule(RelativeLayout.BELOW, newTargetId); } view.setLayoutParams(layoutParams); } As an aside, the @+id/adone in the binding syntax will not create the id. You should create the id in the View you're binding to.
{ "language": "en", "url": "https://stackoverflow.com/questions/34831472", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: When I'm deploying ios app to simulator, it is not showing me complete screen When I'm deploying ios app to simulator, it is not showing me complete screen. I've already configure proper launch images. simulator size (3.5") A: What's happening is that because your monitor is not a retina display and the device your simulating is it takes up more space on your monitor (notice the scroll bars). You can scale the simulator so you can see everything at once without scrolling by clicking on Window > Scale > The percentage you want. Aside from the scrolling issue, if the actual content doesn't display then you will need to either place it in a scroll view or set up your constraints to handle the different screen sizes.
{ "language": "en", "url": "https://stackoverflow.com/questions/32097558", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to write a template that could be specialised with an object or an int N What I'm trying to achieve is a template with a "flexible" first argument (which is most likely something like an array element, not unlike the first argument of std::vector) and a second argument. For that second argument, I want specialisations for the case where it's number (like the size parameter in a std::array), or a general class. For a class Foo, I currently have template <typename T, template <typename> typename Y > class Foo{}; The reason for that is that is then I think I can write the specialisation: template<typename T> class Foo<T, int N>{}; and, given a struct Bar{}, template<typename T> class Foo<T, Bar>{}; But the compiler (C++11, ideone.com), outputs the error "error: template argument 2 is invalid" on the lines with the specification. Presumably I've formed the unspecialised declaration incorrectly. Or is this even possible? A: You can use a helper template to wrap your integer and turn it into a type. This is the approach used, for instance, by Boost.MPL. #include <iostream> template <int N> struct int_ { }; // Wrapper template <class> // General template for types struct Foo { static constexpr char const *str = "Foo<T>"; }; template <int N> // Specialization for wrapped ints struct Foo<int_<N>> { static constexpr char const *str = "Foo<N>"; }; template <int N> // Type alias to make the int version easier to use using FooI = Foo<int_<N>>; struct Bar { }; int main() { std::cout << Foo<Bar>::str << '\n' << FooI<42>::str << '\n'; } Output: Foo<T> Foo<N> Live on Coliru
{ "language": "en", "url": "https://stackoverflow.com/questions/37880964", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Eager loading of non-singleton collections I'd like to load collections of repeated objects. My model looks like this: Item -> Identifier I'd like to load (eagerly) collections of Items that share the same Identifier, but ignore the vast majority of collections that contain one item or less. The ORM relationship is set up in both directions (Identifier.items and Item.identifier). The SQL should look like something like this: SELECT * FROM Item WHERE identifier_id IN ( SELECT identifier_id FROM Item GROUP BY identifier_id HAVING COUNT(*) > 1) A: Using a sub-query, this can be achieved as following: q = (select([Item.identifier_id, func.count(Item.id).label("cnt")]). group_by(Item.identifier_id).having(func.count(Item.id)>1)).alias("subq") qry = (session.query(Item).join(q, Item.identifier_id==q.c.identifier_id)) print qry # prints SQL statement generated items = qry.all() # result A: Here is the version I am finally using: from sqlalchemy.sql.functions import count from sqlalchemy.orm import subqueryload # … repeats = ( select( (Item.identifier, count(Item.identifier))) .group_by(Item.identifier) .having(count(Item.identifier) > 1) .alias()) for identifier in ( sess.query(Identifier) .join(repeats, repeats.c.identifier==Identifier.value) .options(subqueryload(Identifier.items)) ): for item in identifier.items: pass (Identifier is now mapped against a select and not backed by a database table, which makes import a bit faster too)
{ "language": "en", "url": "https://stackoverflow.com/questions/8392653", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Systemd can't execute script which loads kernel module When I'm trying to execute script through systemd service - I receive error message and script can't be run. init_something.service file: [Unit] Description=Loading module --module_name module [Service] Type=oneshot ExecStart=/usr/lib/systemd/init_script [Install] WantedBy=multi-user.target init_script file: #!/bin/bash - /usr/local/bin/init.sh --module_init And now if I try to start service by systemctl I receive error message: # systemctl start init_something.service Job for init_something.service failed. See 'systemctl status init_something.service' and 'journalctl -xn' for details # systemctl status init_something.service init_something.service - Loading module --module_name module Loaded: loaded (/usr/lib/systemd/init_something.service) Active: failed (Result: exit-code) since Thu 1970-01-01 08:00:24 CST; 1min 49s ago Process: 243 ExecStart=/usr/lib/systemd/init_script (code=exited, status=1/FAILURE) Main PID: 243 (code=exited, status=1/FAILURE) But if I try to run init_script manualy - it works perfectly: # /usr/lib/systemd/init_script [ 447.409277] SYSCLK:S0[...] [ 477.523434] VIN: (...) Use default settings map_size = (...) u_code version = (...) etc. And finally module is loaded successfully. So the question is - why systemctl can't execute this script, but manually it's no problem? A: For running any script file, system needs shell. But systemd do'nt have its own shell. So you need to provide shell for running script. so use ExecStart=/bin/sh /usr/lib/systemd/init_script in your service unit. [Unit] Description=Loading module --module_name module [Service] Type=oneshot ExecStart=/bin/sh /usr/lib/systemd/init_script [Install] WantedBy=multi-user.target And chmod 777 /usr/lib/systemd/init_script before running your script.
{ "language": "en", "url": "https://stackoverflow.com/questions/28565646", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Choosing any weekday as a start day to show on the calendar I have created the following function which prints a calendar with day starting from Sunday (to Saturday) ... but I want to be able to choose any day as the first day... eg. first day being Wednesday ... I tried but couldn't get it working ... Can you help me fix this? I know how to manipulate days heading array to reflect this start day but the calendar days somehow get messed up. function testme() { $month = 8; $year = 2012; $days = array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); echo $firstDayOfMonth = date('w',mktime(0,0,0,$month,1,$year)); // a zero based day number $daysInMonth = date('t',mktime(0,0,0,$month,1,$year)); $calendar = ' <!-- start cal -->'; $calendar = '<table border="1" class="calendar">'."\r\n"; $calendar .= '<thead><tr><th class="calendar-day-head">'.implode('</th><th class="calendar-day-head">',$days ).'</th></tr></thead><tbody>'; $calendar .= "\r\n".'<tr class="calendar-row">'; $calendar .= str_repeat('<td class="calendar-day-np">&nbsp;</td>', $firstDayOfMonth); // "blank" days until the first of the current week $calendar .= ''; $dayOfWeek = $firstDayOfMonth + 1; // a 1 based day number: cycles 1..7 across the table rows for ($dayOfMonth = 1; $dayOfMonth <= $daysInMonth; $dayOfMonth++) { $date = sprintf( '%4d-%02d-%02d', $year, $month, $dayOfMonth ); $calendar .= ''; $calendar .= '<td class="calendar-day"> '.$dayOfMonth.' <br />'; $calendar .= ''; $calendar .= '</td>'."\r\n"; if ($dayOfWeek >= 7) { $calendar.= '</tr>'."\r\n"; if ($dayOfMonth != $daysInMonth) { $calendar .= '<tr class="calendar-row">'; } $dayOfWeek = 1; } else { $dayOfWeek++; } } //echo 8-$dayOfWeek; $calendar .= str_repeat('<td class="calendar-day-np">&nbsp;</td>', 8 - $dayOfWeek); // "blank" days in the final week $calendar .= '</tr></table>'; $calendar .= ' <!-- end cal -->'; echo $calendar; } A: You need a value to edit $firstDayOfMonth based on the first day of the array (in this example i am starting on monday) using October 2012: <?php function testme() { $month = 10; $year = 2012; $days = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"); echo $firstDayOfMonth = date('w',mktime(0,0,0,$month,1,$year)); // a zero based day number /* IMPORTANT STATEMENT value based on the starting day of array E.G. (starting_day = value): Tuesday = 5 Wednesday = 4 Thursday = 3 Friday = 2 Saturday = 1 Sunday = 0 Monday = -1 */ $firstDayOfMonth = $firstDayOfMonth - 1; /* END IMPORTANT STATEMENT */ $daysInMonth = date('t',mktime(0,0,0,$month,1,$year)); $calendar = ' <!-- start cal -->'; $calendar = '<table border="1" class="calendar">'."\r\n"; $calendar .= '<thead><tr><th class="calendar-day-head">'.implode('</th><th class="calendar-day-head">',$days ).'</th></tr></thead><tbody>'; $calendar .= "\r\n".'<tr class="calendar-row">'; $calendar .= str_repeat('<td class="calendar-day-np">&nbsp;</td>', $firstDayOfMonth); // "blank" days until the first of the current week $calendar .= ''; $dayOfWeek = $firstDayOfMonth + 1; // a 1 based day number: cycles 1..7 across the table rows for ($dayOfMonth = 1; $dayOfMonth <= $daysInMonth; $dayOfMonth++) { $date = sprintf( '%4d-%02d-%02d', $year, $month, $dayOfMonth ); $calendar .= ''; $calendar .= '<td class="calendar-day"> '.$dayOfMonth.' <br />'; $calendar .= ''; $calendar .= '</td>'."\r\n"; if ($dayOfWeek >= 7) { $calendar.= '</tr>'."\r\n"; if ($dayOfMonth != $daysInMonth) { $calendar .= '<tr class="calendar-row">'; } $dayOfWeek = 1; } else { $dayOfWeek++; } } //echo 8-$dayOfWeek; $calendar .= str_repeat('<td class="calendar-day-np">&nbsp;</td>', 8 - $dayOfWeek); // "blank" days in the final week $calendar .= '</tr></table>'; $calendar .= ' <!-- end cal -->'; echo $calendar; } ?> The /* IMPORTANT STATEMENT */ is key because the mktime() method creates the date based on Sunday being the first day of the week so this overrides it. See Result Here: Link
{ "language": "en", "url": "https://stackoverflow.com/questions/13084755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Attempting to install Oauth on php 8.0 Amazon Linux 2 I have tried a ton of things at this point, but I'm getting this error when I try and run sudo yum install php-pecl-oauth It's telling me that I'm missing php(api) and php(zend-abi)? I don't know what to install to fix it. What exactly does this mean (I have tried installing every variation of php-common in the list and available form amazon packages) and what should I install to fix it? Error: Package: php-pecl-oauth-1.2.3-8.el7.x86_64 (epel) Requires: php(api) = 20100412-64 Installed: php-common-8.0.20-1.amzn2.x86_64 (@amzn2extra-php8.0) php(api) = 20200930-64 Available: php-common-5.4.16-43.amzn2.x86_64 (amzn2-core) php(api) = 20100412-64 Available: php-common-5.4.16-43.amzn2.0.1.x86_64 (amzn2-core) php(api) = 20100412-64 Available: php-common-5.4.16-43.amzn2.0.2.x86_64 (amzn2-core) php(api) = 20100412-64 Available: php-common-5.4.16-43.amzn2.0.3.x86_64 (amzn2-core) php(api) = 20100412-64 Available: php-common-5.4.16-43.amzn2.0.4.x86_64 (amzn2-core) php(api) = 20100412-64 Available: php-common-5.4.16-45.amzn2.0.5.x86_64 (amzn2-core) php(api) = 20100412-64 Available: php-common-5.4.16-45.amzn2.0.6.x86_64 (amzn2-core) php(api) = 20100412-64 Available: php-common-5.4.16-46.amzn2.0.2.x86_64 (amzn2-core) php(api) = 20100412-64 Available: php-common-8.0.0-2.amzn2.x86_64 (amzn2extra-php8.0) php(api) = 20200930-64 Available: php-common-8.0.2-1.amzn2.x86_64 (amzn2extra-php8.0) php(api) = 20200930-64 Available: php-common-8.0.6-1.amzn2.x86_64 (amzn2extra-php8.0) php(api) = 20200930-64 Available: php-common-8.0.8-1.amzn2.x86_64 (amzn2extra-php8.0) php(api) = 20200930-64 Available: php-common-8.0.13-1.amzn2.x86_64 (amzn2extra-php8.0) php(api) = 20200930-64 Available: php-common-8.0.16-1.amzn2.x86_64 (amzn2extra-php8.0) php(api) = 20200930-64 Available: php-common-8.0.18-1.amzn2.x86_64 (amzn2extra-php8.0) php(api) = 20200930-64 Error: Package: php-pecl-oauth-1.2.3-8.el7.x86_64 (epel) Requires: php(zend-abi) = 20100525-64 Installed: php-common-8.0.20-1.amzn2.x86_64 (@amzn2extra-php8.0) php(zend-abi) = 20200930-64 Available: php-common-5.4.16-43.amzn2.x86_64 (amzn2-core) php(zend-abi) = 20100525-64 Available: php-common-5.4.16-43.amzn2.0.1.x86_64 (amzn2-core) php(zend-abi) = 20100525-64 Available: php-common-5.4.16-43.amzn2.0.2.x86_64 (amzn2-core) php(zend-abi) = 20100525-64 Available: php-common-5.4.16-43.amzn2.0.3.x86_64 (amzn2-core) php(zend-abi) = 20100525-64 Available: php-common-5.4.16-43.amzn2.0.4.x86_64 (amzn2-core) php(zend-abi) = 20100525-64 Available: php-common-5.4.16-45.amzn2.0.5.x86_64 (amzn2-core) php(zend-abi) = 20100525-64 Available: php-common-5.4.16-45.amzn2.0.6.x86_64 (amzn2-core) php(zend-abi) = 20100525-64 Available: php-common-5.4.16-46.amzn2.0.2.x86_64 (amzn2-core) php(zend-abi) = 20100525-64 Available: php-common-8.0.0-2.amzn2.x86_64 (amzn2extra-php8.0) php(zend-abi) = 20200930-64 Available: php-common-8.0.2-1.amzn2.x86_64 (amzn2extra-php8.0) php(zend-abi) = 20200930-64 Available: php-common-8.0.6-1.amzn2.x86_64 (amzn2extra-php8.0) php(zend-abi) = 20200930-64 Available: php-common-8.0.8-1.amzn2.x86_64 (amzn2extra-php8.0) php(zend-abi) = 20200930-64 Available: php-common-8.0.13-1.amzn2.x86_64 (amzn2extra-php8.0) php(zend-abi) = 20200930-64 Available: php-common-8.0.16-1.amzn2.x86_64 (amzn2extra-php8.0) php(zend-abi) = 20200930-64 Available: php-common-8.0.18-1.amzn2.x86_64 (amzn2extra-php8.0) php(zend-abi) = 20200930-64 You could try using --skip-broken to work around the problem You could try running: rpm -Va --nofiles --nodigest Thanks so much for your help!
{ "language": "en", "url": "https://stackoverflow.com/questions/73900649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not able to run when injecting dependencies with Hilt into Android Classes I'm in the process of making an application using Hilt. But my question is, am I only able to run my app through AndroidManifest.xml? I'd like to run it through another class, but it keeps giving me a blank page. My Classes: Application class using @HiltAndroidApp @HiltAndroidApp class ExampleApplication : Application() Activity class using @AndroidEntryPoint @AndroidEntryPoint class ExampleActivity : ComponentActivity() { @RequiresApi(Build.VERSION_CODES.N) override fun onCreate(instance: Bundle?) { super.onCreate(instance) setContent { AppTheme { Surface() { ...... Manifest.xml (This is the only way I can run the class, ExampleActivity). <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <application android:name=".ui.ExampleApplication" android:allowBackup="true" android:dataExtractionRules="@xml/data_extraction_rules" android:fullBackupContent="@xml/backup_rules" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.App" tools:targetApi="31"> <activity android:name=".ExampleActivity" android:exported="true" android:label="@string/app_name" android:theme="@style/Theme.App"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <meta-data android:name="android.app.lib_name" android:value="" /> </activity> </application> </manifest> So, I've tried calling my application from another class, but I can't call ExampleActivity.kt alone, so I tried calling two classes, but it keeps giving me a blank page. Here's what I've tried: class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AppTheme { ExampleApplication() ExampleActivity() } } } } It gives a blank screen. I will create another class and make it my start class, where I will then call ExampleApplication and ExampleActivity. How am I supposed to call two classes using Hilt dependencies from another class? Of course, I have updated the manifest.xml so that it says .MainActivity. A: First of all, why do you need Hilt? What are you trying to Inject and where? ExampleApplication() is just a place where you configure app-wide settings, you are never supposed to call it from somewhere else, so you don't need that line. Furthermore, Which activity are you trying to start? MainActivity or ExampleActivity()? Calling ExampleActivity within MainActivity won't have any effect. SetContent { ... } is the place where you create the UI. If you want to open another activity from MainActivity then you need to implement navigation or use Intents.
{ "language": "en", "url": "https://stackoverflow.com/questions/75052011", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: R - Split column values into new multiple columns I have a dataframe in the form: id products 1001 milk, cheese, sugar 1002 milk 1003 cheese, eggs I would like to change it to a new data frame in the form : id product1 product2 product3 1001 milk cheese sugar 1002 milk 1003 cheese egg How can I accomplish this in R? A: We can use separate library(dplyr) library(tidyr) df1 %>% separate(products, into = paste0('product', 1:3), sep=",\\s+", extra = "merge") # id product1 product2 product3 #1 1001 milk cheese sugar #2 1002 milk <NA> <NA> #3 1003 cheese eggs <NA> Or cSplit which would automatically detect the number of elements without having to specify the columns library(splitstackshape) cSplit(df1, 'products', ', ') data df1 <- structure(list(id = 1001:1003, products = c("milk, cheese, sugar", "milk", "cheese, eggs")), class = "data.frame", row.names = c(NA, -3L)) A: Let's say we have non definite number of products in our dataframe (More than three). We can use separate_rows() from tidyverse without issues about the number of products and then reshape to wide. Here the code with data you shared (I added more items to see this approach). Here the code: library(tidyverse) #Data df <- structure(list(id = c(1001, 1002, 1003), products = c("milk, cheese, sugar, rice, soap, water", "milk", "cheese, eggs")), row.names = c(NA, -3L), class = "data.frame") The code: #Code df %>% separate_rows(products,sep = ', ') %>% group_by(id) %>% mutate(Var=paste0('V',1:n())) %>% pivot_wider(names_from = Var,values_from=products) %>% replace(is.na(.),'') Output: # A tibble: 3 x 7 # Groups: id [3] id V1 V2 V3 V4 V5 V6 <dbl> <chr> <chr> <chr> <chr> <chr> <chr> 1 1001 milk "cheese" "sugar" "rice" "soap" "water" 2 1002 milk "" "" "" "" "" 3 1003 cheese "eggs" "" "" "" ""
{ "language": "en", "url": "https://stackoverflow.com/questions/63890643", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Windows Phone 8.1 Unit Testing I have a Windows 8.1 Universal application that I have run into an issue with unit testing. I am using MSTest. I have a test that needs to make sure that an exception is thrown. The test is pretty simple, if a null value if passed in, it fails. The exception thrown should be ArgumentNullException. However, I am having trouble finding the correct way for this to pass. I tried using ExpectedExpection as an attribute but I was unable to find a reference that would work with a Windows Phone unit test project. I did find Assert.ThrowsException but was not able to find any information on how to use it. What is the best way to make sure that this exception is being thrown and for the test to pass if it does get thrown? A: In MSTest you usually use ExpectedException like this: [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestMethod1() { DoWhatEverThrowsAnArgumentNullException(); } If you don't like it that way then you can look at this project on GitHub: MSTestExtensions
{ "language": "en", "url": "https://stackoverflow.com/questions/33140516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Linq to entities does not recognize my entity types I have a problem when creating an entity model from scratch. I successfully design my objects and generate the database creation. But when I try to make a linq request like var t = from e in entity.UsersSet where e.Id == 1 select e; it seems like my 'e' variable is not recognized as a User object whereas my UsersSet property is of ObjectSet type. If I stop my expression typing at "e.Id", I have a warning from VS telling me: Argument type 'lambda expression' is not assignable to parameter type 'string' I really don't understand why it gives me this error. I checked another project and it's working fine. Maybe I miss a reference or something...any idea? A: This is a little late, but I just googled this exact problem (and ended here). I found the above solution did fix it, but then it could also be fixed by just adding "using System.Linq;" to the top resolved the issue. A: If you are certain UsersSet is some kind of a collection of User instances then you can try var t = from User e in entity.UsersSet where e.Id == 1 select e;
{ "language": "en", "url": "https://stackoverflow.com/questions/5844547", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Iterating through a multidimensional array in Python I have created a multidimensional array in Python like this: self.cells = np.empty((r,c),dtype=np.object) Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this? A: you can get the index of each element as well as the element itself using enumerate command: for (i,row) in enumerate(cells): for (j,value) in enumerate(row): print i,j,value i,j contain the row and column index of the element and value is the element itself. A: How about this: import itertools for cell in itertools.chain(*self.cells): cell.drawCell(surface, posx, posy) A: It's clear you're using numpy. With numpy you can just do: for cell in self.cells.flat: do_somethin(cell) A: No one has an answer that will work form arbitrarily many dimensions without numpy, so I'll put here a recursive solution that I've used def iterThrough(lists): if not hasattr(lists[0], '__iter__'): for val in lists: yield val else: for l in lists: for val in iterThrough(l): yield val for val in iterThrough( [[[111,112,113],[121,122,123],[131,132,133]], [[211,212,213],[221,222,223],[231,232,233]], [[311,312,313],[321,322,323],[331,332,333]]]): print(val) # 111 # 112 # 113 # 121 # .. This doesn't have very good error checking but it works for me A: If you need to change the values of the individual cells then ndenumerate (in numpy) is your friend. Even if you don't it probably still is! for index,value in ndenumerate( self.cells ): do_something( value ) self.cells[index] = new_value A: It may be also worth to mention itertools.product(). cells = [[x*y for y in range(5)] for x in range(10)] for x,y in itertools.product(range(10), range(5)): print("(%d, %d) %d" % (x,y,cells[x][y])) It can create cartesian product of an arbitrary number of iterables: cells = [[[x*y*z for z in range(3)] for y in range(5)] for x in range(10)] for x,y,z in itertools.product(range(10), range(5), range(3)): print("(%d, %d, %d) %d" % (x,y,z,cells[x][y][z])) A: Just iterate over one dimension, then the other. for row in self.cells: for cell in row: do_something(cell) Of course, with only two dimensions, you can compress this down to a single loop using a list comprehension or generator expression, but that's not very scalable or readable: for cell in (cell for row in self.cells for cell in row): do_something(cell) If you need to scale this to multiple dimensions and really want a flat list, you can write a flatten function.
{ "language": "en", "url": "https://stackoverflow.com/questions/971678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "38" }
Q: Python getpass works at second attempt when in separate module I try to use a seperate Module with a getpass() function in it, e.g. #! /usr/bin/python3 from getpass import getpass import sys def mypass(): try: password = getpass('Password: ') except Exception as e: print(e) sys.exit(1) while password == '': password = getpass('Enter password again: ') return(password) mypass() I have a main script that uses this module: #! /usr/bin/python3 import myModule ... def main(): p = myModule.mypass() print(p) #for testing only ... if __name__ == '__main__': main() When I run the myModule script directy, the password input works at the first try, when I use the main script, password input works at the second try: user@server:~$./myModule.py Password: user@server:~$ user@server:~$./main.py Password: Password: secret user@server:~$ Does someone knows why and can help me to fix this? A: The problem is that you are always calling the mypass function inside myModule. This happens also when you import it from the main module. This is why you don't see the password printed to the terminal on the first time when running the main.py file. You should put the mypass() function call in the myModule inside the if name == "main" guard. Change the code inside myModule to the following: from getpass import getpass import sys def mypass(): try: password = getpass('Password: ') except Exception as e: print(e) sys.exit(1) while password == '': password = getpass('Enter password again: ') return password if __name__ == '__main__': password = mypass() print(password) Now the mypass function won't be called when the myModule is imported.
{ "language": "en", "url": "https://stackoverflow.com/questions/69001100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Web Service authentication in Java EE When developing a Web service(Hospital Management System) using Java EE, is it necessary that for each Web Service call, it has to be checked that the user is logged in?? Which authentication method is the best JAAS, WS-Security, SAML, or a combination or using own tokens?? A: You can use filters. Here's an example of how to use filters: http://viralpatel.net/blogs/2009/01/tutorial-java-servlet-filter-example-using-eclipse-apache-tomcat.html Basically you define the url's where you want the filters to apply, the filter authorizes the user and then calls chain.doFilter(request, response); to call the requested method after authorization. You can also take a look at this jax-rs rest webservice authentication and authorization Personally, I use tokens for authorization. A: It all depends on how is your web service implemented/or its going to be. If you still have a choice I would recommend going with REST approach, authenticate the user with some kind of login functionality and then maintain users session.
{ "language": "en", "url": "https://stackoverflow.com/questions/8864879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: how to get whole string in different variables? how to get whole string in different variables? I have single string which contain 5 names and there is a space between every single name,now i want to get these five names in to different ,different string for ex i have string like below String name= ABC DEF GHI JKL MNO; and i wan to get these string like below(removing space) String a=ABC; String b=DEF; String c=GHI; String d=JKL; String e=MNO A: [EDIT: Since you've added that you're using Android, here's the Java version.. I've also left the old python version below for reference] String name = "ABC DEF GHI JKL MNO"; String[] splits = name.split(" "); String a = splits[0]; String b = splits[1]; String c = splits[2]; String d = splits[3]; String e = splits[4]; System.out.println(b); System.out.println(d); The pre-edit Python 2.7 version: name = "ABC DEF GHI JKL MNO" a, b, c, d, e = name.split() print(b) print(d) A: str.replace(" ",""); or String name = yourString.replace(" ",""); or str.split(); A: For PHP/Java/JavaScript AND C# the explode() function may be what you're looking for. Example in PHP: $strings[] = explode(" ", $name); A: I would say the majority of languages/libs have some kind of string.split(); function.
{ "language": "en", "url": "https://stackoverflow.com/questions/37614336", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: << operator in ruby I am quite new to ruby, I came across the following code in rails, but I don't know how the "<<" operator works and what it does in the below code def <<( rate ) r = Rating.new r.rate = rate r.rateable = proxy_owner ... ... end class << ActiveRecord::Base ... ... end Can anybody explain to me? Edit: here is the code https://github.com/azabaj/acts_as_rateable/blob/master/lib/acts_as_rateable.rb A: def <<( rating ): In your example, this is used to add a rating to a rateable model. (E.g. in acts_as_rateable.rb:41), similar to appending something to a string (str << "abc"). As it is within a module, it will only be included for the models that you declare as rateable. class << ClassName: All the methods inside of this block will be static / class methods (see this blog entry). (In this case, all the models will have the methods Model.example_static_method.) A: Nearly all operators in Ruby are actually instance methods called on the object preceding them. There are many different uses for << depending on the object type you're calling it on. For example, in an array this works to push the given value onto the end of the array. It looks like this is for a Rails model object, so in that case I would say that this is an auxiliary method called when you append a model object to model object collection. For example, in this case you might be appending a Rating to a Product. If you showed the whole method definition and showed what class it's in, I could provide a more specific answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/4135464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Update if record exit ,insert/save if record not exist I have a edit form which edit an array like (Invoice) , I want when i edit the Invoice_no a can also able to add the new item on the same invoice number Example the Inv_no=300 and its carry 3 arrays ([... .... ... ]), so I want to add the new one array to be 4 arrays. On my code below is update array well data but if i add new one row does not save that new one while it keep update, what can i do here to add/save the new one data. public function update(Request $request, $inv_no) { $data = $request->all(); //dd($data); $stocks = Stock::where('inv_no', $inv_no)->get(); $i = 0; foreach ($stocks as $stock) { Stock::where('inv_no', $inv_no) ->where('id', $stock->id) ->update([ 'pid' => $request->pid[$i], 'qty' => $request->qty[$i], 'inv_no' => $request->inv_no, 'user_id' => Auth::user()->id, 'Indate'=>$request->Indate, 'supplierName' => $request->supplierName, 'receiptNumber' => $request->receiptNumber, 'truckNumber' => $request->truckNumber, 'driverName' => $request->driverName, 'remark' => $request->remark, ]); $i++; } return $this->index(); } A: I think you need something like that. You have mentioned that you need to update if the invoice number exists and you also want to a new item with this invoice number. If you have any query, feel free to ask me public function update(Request $request, $inv_no) { $data = $request->all(); $stocks = Stock::where('inv_no', $inv_no)->get(); $i = 0; foreach ($stocks as $stock) { $stock->update([ 'pid' => $request->pid[$i], 'qty' => $request->qty[$i], 'user_id' => Auth::user()->id, 'Indate'=>$request->Indate, 'supplierName' => $request->supplierName, 'receiptNumber' => $request->receiptNumber, 'truckNumber' => $request->truckNumber, 'driverName' => $request->driverName, 'remark' => $request->remark, ]); $i++; } $totalPid = count($request->pid); $totalQty= count($request->qty); Stock::create([ 'pid' => $request->pid[$totalPid - 1], 'qty' => $request->qty[$totalQty - 1], 'inv_no' => $request->inv_no, 'user_id' => Auth::user()->id, 'Indate'=>$request->Indate, 'supplierName' => $request->supplierName, 'receiptNumber' => $request->receiptNumber, 'truckNumber' => $request->truckNumber, 'driverName' => $request->driverName, 'remark' => $request->remark, ]); return $this->index(); } A: You may use updateOrCreate method: foreach ($stocks as $stock) { Stock::updateOrCreate(['id' => $stock->id], [ 'pid' => $request->pid[$i], 'qty' => $request->qty[$i], 'inv_no' => $request->inv_no, 'user_id' => Auth::user()->id, 'Indate'=>$request->Indate, 'supplierName' => $request->supplierName, 'receiptNumber' => $request->receiptNumber, 'truckNumber' => $request->truckNumber, 'driverName' => $request->driverName, 'remark' => $request->remark, ]); } See Laravel docs for more info. A: I can see now what you need. If you put this where(['id', $stock->id]) you will only find and update what already exists. Since your comparing with the values you searched doing $stocks = Stock::where('inv_no', $inv_no)->get();. If you need to search where 'inv_no' is the value you inputed or create a new record, do: Stock::updateOrCreate(['inv_no', $inv_no], [ 'pid' => $request->pid[$i], 'qty' => $request->qty[$i], 'inv_no' => $request->inv_no, 'user_id' => Auth::user()->id, 'Indate'=>$request->Indate, 'supplierName' => $request->supplierName, 'receiptNumber' => $request->receiptNumber, 'truckNumber' => $request->truckNumber, 'driverName' => $request->driverName, 'remark' => $request->remark, ]); That way you are going to search any records with 'inv_no' equals the value you entered, update it or create a new value if it doesn't exists. Also, you can remove the lines $stocks = Stock::where('inv_no', $inv_no)->get(); and foreach ($stocks as $stock) {}. A: UpdateorCreate is what you need but you must twist it so it works for your needs. UpdateOrCreate can take 2 array parameters. The 1st array is basically your where clause telling the function to look for the specific parameters and if it finds them to update otherwise create a new record. Stock::updateOrCreate([ 'id' => $stock->id 'pid' => $request->pid[$i], 'inv_no' => $request->inv_no], 'qty' => $request->qty[$i], [ 'user_id' => Auth::user()->id, 'Indate'=>$request->Indate, 'supplierName' => $request->supplierName, 'receiptNumber' => $request->receiptNumber, 'truckNumber' => $request->truckNumber, 'driverName' => $request->driverName, 'remark' => $request->remark, ]); Not clear about your data but the above code will check in your database if there is a record with: * *id matching $stock->id *pid matching $request->pid[$i] *inv_no matching $request->inv_no You can extend your where clause even further, you can even use only 1 array with all your data and tell the function to look for a record which has all the fields matching otherwise create a new record.
{ "language": "en", "url": "https://stackoverflow.com/questions/61871792", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Chrome with PHP, infinite loop I have a PHP app running inside a Docker container. While testing websockets I am using an infinite loop to wait for response from the server. Endpoint is an AJAX call triggered on click, ultimately hitting this method: public function searchMessages() { while (true) { sleep(2); $message = $this->client->getMessages(); if($message){ $this->_save(...); } } } From that point on, endpoint opens and never ends. I presumed that reloading the page would get me back to my home page (where I can click the button to trigger AJAX again), but that is not the case. If I try to close/reload, Chrome is just stuck on infinite load and never shows the page again unless I kill the container. How can I keep on testing without shutting down my container over and over again?
{ "language": "en", "url": "https://stackoverflow.com/questions/53852795", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to clean the input search without hiding the keyboard ? (mobile) I am using Ionic/AngularJS and that's my question, every time I clean up the input, the keyboard disappears and I don't want that <ion-header-bar ng-show="searchBoxEnabled"> <div> <input type="search" ng-model="query"> <div ng-show="query" ng-click="query=''"> <!--must ONLY clean the input, but is also disappearing the keyboard--> </div> </div> <!--must clean the input and disappear the keyboard, this one is working properly--> <div ng-click="hideSearchBox(); query=''"> |Cancel </div> </ion-header-bar> and in the javascript side I have this couple functions in order to show and hide the input $scope.showSearchBox = function() { $scope.searchBoxEnabled = true; }; $scope.hideSearchBox = function() { $scope.searchBoxEnabled = false; }; A: I agree that it is probably the blur event on the input that causes the keyboard to go away. You could solve this with a directive on the button that refocuses on the input following a click (although I have no way to verify whether this would cause a flicker with a keyboard). Here's an illustrative example where you pass the ID of the element that you want to refocus to: app.directive("refocus", function() { return { restrict: "A", link: function(scope, element, attrs) { element.on("click", function() { var id = attrs.refocus; var el = document.getElementById(id); el.focus(); }); } } }); and the usage is: <input id="foo" ng-model="newItem"> <button ng-click="doSomething(newItem)" refocus="foo">add</button> plunker
{ "language": "en", "url": "https://stackoverflow.com/questions/28465559", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I see post body data in chrome dev tools? I have this fetch api in React that is sending data to the server. The server runs PHP and I'm having trouble accessing the data with $_POST or with file_get_contents('php://input'); So I want to check every step of the process until I can see where the error is. I also want to verify how the post data is being sent. ie I want to see the actual data and the full request from the browser. Fetch request looks like this: export function sendEmail (data) { return fetch('http://example.com/email.php', { method: 'POST', credentials: 'same-origin', headers: { Accept: 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(data) }).then(response => response.json()) } When I go into google chrome's dev tools I see the request headers, response, etc but nowhere can I see the actual data being sent. I've looked around online and no one can seem to give a clear answer. A: Fiddler might be helpful in this scenario. It will show you the post body sent to your PHP endpoint. A: In your dev tools, click Network tab, then do the request and click on it. Scroll to the Request body section. Network tab A: I recommend you axios, easier to check if success or error and cleaner: Post without any body sent; import axios from 'axios'; axios.post('http://example.com/email.php') .then(response=>response.data) .then(response=>console.log('Success:', response)) .catch(err=>console.log('Error: ',err)) With some arguments: axios.post('http://example.com/email.php', { firstName: 'Fred', lastName: 'Flintstone' }) .then(response=>response.data) .then(response=>console.log('Success:', response)) .catch(err=>console.log('Error: ',err)
{ "language": "en", "url": "https://stackoverflow.com/questions/53798887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cloud SQL API Explorer, settingsVersion I'm getting familiarized with Cloud SQL API (v1beta1). I'm trying to update authorizedNetworks (sql.instances.update) and I'm using API explorer. I think my my request body is alright except for 'settingsVersion'. According to the docs it should be: The version of instance settings. This is a required field for update method to make sure concurrent updates are handled properly. During update, use the most recent settingsVersion value for this instance and do not try to update this value. Source: https://developers.google.com/cloud-sql/docs/admin-api/v1beta3/instances/update I have not found anything useful related to settingsVersion. When I try with different srings, instead of receiving 200 and the response, I get 400 and: "message": "Invalid value for: Expected a signed long, got '' (class java.lang.String)" If a insert random number, I get 412 (Precondition failed) and: "message": "Condition does not match." Where do I obtain versionSettings and what is a signed long string? A: You should do a GET operation on your instance and fetch the current settings, those settings will contain the current version number, you should use that value. This is done to avoid unintentional settings overwrites. For example, if two people get the current instance status which has version 1, and they both try to change something different (for example, one wants to change the tier and the other wants to change the pricingPlan) by doing an Update operation, the second one to send the request would undo the change of the first one if the operation was permitted. However, since the version number is increased every time an update operation is performed, once the first person updates the instance, the second person's request will fail because the version number does not match anymore.
{ "language": "en", "url": "https://stackoverflow.com/questions/21209826", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check password when the return key is pressed? The form below works, but only when the button is clicked. Can someone please tell me how to submit this form and check the password with the script below when the enter key is pressed as well? function checkPassword() { if (document.getElementById('password').value == 'abc123') { location.href = "./yes"; } else { location.href = "./no"; } } <div class="login-box"> <form> <div class="user-box"> <input type="password" id="password"> <label>PASSWORD</label> </div> <div class="gradient-button-container"> <input class="gradient-button" type="button" value="JOIN NOW" onclick="checkPassword()" /> </div> </form> </div> A: You change type of input to "submit" <input class="gradient-button" type="submit" value="JOIN NOW" onclick="checkPassword()" /> Moreover, remove onClick and add onSubmit event with checkPassword function on form tag
{ "language": "en", "url": "https://stackoverflow.com/questions/63943972", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: The tag is unrecognized in this browser import React, { Suspense } from 'react' import { useGLTF } from '@react-three/drei' const MagicRoom = () => { // Importing model const Model = () => { const gltf = useGLTF('./libs/the_magic_room/scene.gltf', true) return <primitive object={gltf.scene} dispose={null} scale={1} /> } return ( <Suspense fallback={null}> <Model /> </Suspense> ) } export default MagicRoom I'm trying to use primitive to import gltf model in react-fibre, but it gives the above error A: primitive placeholder can be found in @react-three/fiber, importing this module will resolve the error. So the final code looks like: import React, { Suspense } from 'react' import { Canvas } from '@react-three/fiber' import { useGLTF } from '@react-three/drei' const MagicRoom = () => { // Importing model const Model = () => { const gltf = useGLTF('./libs/the_magic_room/scene.gltf', true) return <primitive object={gltf.scene} dispose={null} scale={1} /> } return ( <Canvas> <Suspense fallback={null}> <Model /> </Suspense> </Canvas> ) } export default MagicRoom
{ "language": "en", "url": "https://stackoverflow.com/questions/69687446", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I extract arguments in a function (written as a string) in R? Let suppose I have defined a function by f <- function(x,y,z) {...}. I would like to be able to transform an expression calling that function into a list of the parameters called by that function; it is the opposite of the do.call function. For example, let us say I have such a function f, and I also have a string "f(2,1,3)". How can I transform the string "f(2,1,3)" into the list of the parameters list(x=1,y=2,z=3)? A: After you've parsed your character string into an R expression, use match.call() to match supplied to formal arguments. f <- function(x,y,z) {} x <- "f(1,2,3)" ee <- parse(text = x)[[1]] cc <- match.call(match.fun(ee[[1]]), ee) as.list(cc)[-1] # $x # [1] 1 # # $y # [1] 2 # # $z # [1] 3 A: Alternatively: f <- function(x,y,z) {...} s <- "f(x = 2, y = 1, z = 3)" c <- as.list(str2lang(s)) c[-1] # $x # [1] 2 # # $y # [1] 1 # # $z # [1] 3 I was looking for a solution to this a while ago in order to reconstruct a function call from a string. Hopefully this will be of use to someone who is looking for a solution to a similar problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/34071734", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }