text
stringlengths
15
59.8k
meta
dict
Q: I want a list to append more than one arguments. python d =[] for i in range(len(X_test)): d.append(X_test[i], y_test[i], y_pred[i]) print(X_test[i]," ", y_test[i], " ", y_pred[i]) print(d) This is output --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [33], in <cell line: 2>() 1 d =[] 2 for i in range(len(X_test)): ----> 3 d.append(X_test[i], y_test[i], y_pred[i]) 4 print(X_test[i]," ", y_test[i], " ", y_pred[i]) 6 print(d) TypeError: list.append() takes exactly one argument (3 given) If I just the output without appending, This is what I get: d =[] for i in range(len(X_test)): print(X_test[i]," ", y_test[i], " ", y_pred[i]) print(d) This is the output --------------------------------------------------------------------------- [1.5] 37731.0 40835.10590871474 [10.3] 122391.0 123079.39940819163 [4.1] 57081.0 65134.556260832906 [3.9] 63218.0 63265.36777220843 [9.5] 116969.0 115602.64545369372 [8.7] 109431.0 108125.89149919583 [9.6] 112635.0 116537.23969800597 [4.] 55794.0 64199.96201652067 [5.3] 83088.0 76349.68719257976 [7.9] 101302.0 100649.13754469794 So this is what I am trying to do. I want a list to append 3 arguments. So that my list will look like: [[1.5, 37731.0, 40835.10590871474] [10.3, 122391.0, 123079.39940819163] [4.1, 57081.0, 65134.556260832906] [3.9, 63218.0, 63265.36777220843] [9.5, 116969.0, 115602.64545369372] [8.7, 109431.0, 108125.89149919583] [9.6, 112635.0, 116537.23969800597] [4.0, 55794.0, 64199.96201652067] [5.3, 83088.0, 76349.68719257976] [7.9, 101302.0, 100649.13754469794]] A: It looks like you want a list of lists. Try changing line 3 into d.append([X_test[i], y_test[i], y_pred[i]]) to append the three items as a list. A: You can only append one value. In this case, you want to append one list of 3 values. d.append([X_test[i], y_test[i], y_pred[i]]) If you wanted to append 3 separate values at once, use the same list as an argument to the extend method instead. >>> d = [] >>> d.extend([1,2,3]) >>> d [1, 2, 3] A: d = [] for i in range(len(X_test)): e = [] e.append(X_test[i]) e.append(y_test[i]) e.append(y_pred[i]) d.append(e) print(X_test[i]," ", y_test[i], " ", y_pred[i]) print(d) Output : 1.5 37731.0 40835.10590871474 10.3 122391.0 123079.39940819163 4.1 57081.0 65134.556260832906 3.9 63218.0 63265.36777220843 [ [1.5, 37731.0, 40835.10590871474], [10.3, 122391.0, 123079.39940819163], [4.1, 57081.0, 65134.556260832906], [3.9, 63218.0, 63265.36777220843] ] A: I think you are looking for something like this. X_test = ['1.5', '10.3', '4.1'] y_test = ['37731.0', '122391.0', '57081.0' ] y_pred = ['40835.10590871474','123079.39940819163','65134.556260832906'] d = list() for i in range(len(X_test)): if X_test[i] and y_test[i] and y_pred[i]: d.append([X_test[i], y_test[i], y_pred[i]]) for item in d: print(item)
{ "language": "en", "url": "https://stackoverflow.com/questions/72748363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to remove first selected tab from sheets selected for printing I have the code, which identifies filled tabs with corresponding responsible person and then prints them as one file: Sub printS() Dim sht As Worksheet For Each sht In ThisWorkbook.Worksheets With sht If Not IsError(Application.Match("Person1", .Range("C:C"), 0)) And .Index > 3 And Not IsEmpty(.Cells(13, 1)) Then sht.Tab.ColorIndex = 7 sht.Select (False) End If End With Next ActiveWindow.SelectedSheets.PrintOut End Sub The problem is that Excel includes the tab, where the macro button is located into the selection. As result I get blank page in the beginning of each PDF. Is there any way to remove tab with macro buttons from tab selection by correcting existing code? Thank you. A: One way would be an If statement control inside the loop. Sub printS() Dim sht As Worksheet For Each sht In ThisWorkbook.Worksheets With sht If .name <> sheets("THAT SHEET NAME HERE").name then 'this control will exclude your button sheet If Not IsError(Application.Match("Person1", .Range("C:C"), 0)) And .Index > 3 And Not IsEmpty(.Cells(13, 1)) Then sht.Tab.ColorIndex = 7 sht.Select (False) End If End if 'close block if End With Next ActiveWindow.SelectedSheets.PrintOut End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/46465526", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to activate centralWidget in QT Designer I was looking at this article How to make a Qt Widget grow with the window size? but when i got to the answer I got stuck on "activating" the central widget. I notice an icon with a red circle so I guess that means its disabled. I've been searching the net to try to figure out how to "activate" it but I am not having any luck. Can someone please help me out? A: Have a look at the layout system. That icon does not mean your QWidget is disabled, that just mean you do not apply a layout on it. Try to press like Ctrl+1 in order to apply a basic layout. If nothing has changed, you might need to put a QWidget inside the central widget first and then apply the layout.
{ "language": "en", "url": "https://stackoverflow.com/questions/27536884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: why expandable collapse not working when i click expandable button for collapse it not working how can solve this problem ExpandablePanel( collapsed: ExpandableButton( child: Container( height: 54.h, width: double.maxFinite, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20.r), border: Border.all( color: Color(0xffBDBDBD), )), child: Padding( padding: EdgeInsets.symmetric(horizontal: 13.w), child: Container( child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Obx( () => CustomBigText( text: controller.selectName.value, size: 14.sp, color: Color(0xff4F4F4F), ), ), SvgPicture.asset( "assets/svg/arrow_downward_ios.svg") ], ), ), ), ), ), expanded: ExpandableButton( child: Obx( () => Container( height: 265.h, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20.r), color: kwhite, // boxShadow: [ // BoxShadow( // offset: Offset(0, 4), // blurRadius: 21, // spreadRadius: 0, // color: Color(0xff000000).withOpacity(0.22)) // ], ), child: ListView.builder( itemCount: controller.selected.length, itemBuilder: (_, index) { return Padding( padding: EdgeInsets.symmetric( horizontal: 13.w), child: InkWell( onTap: () { controller.selectName.value = controller.selected[index]; }, child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: EdgeInsets.all(5.w), child: CustomBigText( ontap: () {}, text: "${controller.selected[index].toString()}", size: 14.sp, color: Color(0xff4F4F4F), ), ), Divider( thickness: 1.h, color: Color(0xffBDBDBD), ), ], ), ), ), ); })), ), ), ),
{ "language": "en", "url": "https://stackoverflow.com/questions/75604612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Pyspark ERROR:py4j.java_gateway:An error occurred while trying to connect to the Java server (127.0.0.1:50532) Hello I was working with Pyspark, implementing a sentiment analysis project using ML package for the first time. The code was working good but suddenly it becomes showing the error mentioned above: ERROR:py4j.java_gateway:An error occurred while trying to connect to the Java server (127.0.0.1:50532) Traceback (most recent call last): File "C:\opt\spark\spark-2.3.0-bin-hadoop2.7\python\lib\py4j-0.10.6-src.zip\py4j\java_gateway.py", line 852, in _get_connection connection = self.deque.pop() IndexError: pop from an empty deque During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\opt\spark\spark-2.3.0-bin-hadoop2.7\python\lib\py4j-0.10.6-src.zip\py4j\java_gateway.py", line 990, in start self.socket.connect((self.address, self.port)) ConnectionRefusedError: [WinError 10061] Aucune connexion n’a pu être établie car l’ordinateur cible l’a expressément refusée Does someone can help please Here is the full error description? A: Add more resources to Spark. For example if you're working on local mode a configuration like the following should be sufficient: spark = SparkSession.builder \ .appName('app_name') \ .master('local[*]') \ .config('spark.sql.execution.arrow.pyspark.enabled', True) \ .config('spark.sql.session.timeZone', 'UTC') \ .config('spark.driver.memory','32G') \ .config('spark.ui.showConsoleProgress', True) \ .config('spark.sql.repl.eagerEval.enabled', True) \ .getOrCreate() A: I encountered this error while trying to use PySpark within a Docker container. In my case, the error was originating from me assigning more resources to Spark than Docker had access to. A: Just restart your notebook if you are using Jupyter nootbook. If not then just restart the pyspark . that should solve the problem. It happens because you are using too many collects or some other memory related issue. A: I encountered the same problem while working on colab. I terminated the current session and reconnected. It worked for me! A: Maybe the port of spark UI is already occupied, maybe there are other errors before this error. Maybe this can help you:https://stackoverflow.com/questions/32820087/spark-multiple-spark-submit-in-parallel spark-submit --conf spark.ui.port=5051
{ "language": "en", "url": "https://stackoverflow.com/questions/51359802", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Customize error messages in the database with connection I'm new to PHP, and wanted to make my connection back a custom message without making show those warnings. But when I add the check nothing happens, my complete code below. <?php class Connect { private $Connect; public function Connect() { $this->Connection(); if(connection_aborted() == TRUE) { $this->Connection(); } } public function Connection() { global $Config; $this->Connect = new mysqli($Config['mysql']['hostname'], $Config['mysql']['username'], $Config['mysql']['password'], $Config['mysql']['database'], $Config['mysql']['dataport']); if($this->Connect == false){ exit('The connection fails, check config.php'); } return false; } } ?> A: You can use different methodes $this->Connect = new mysqli( $Config['mysql']['hostname'], $Config['mysql']['username'], $Config['mysql']['password'], $Config['mysql']['database'], $Config['mysql']['dataport']) or die('The connection fails, check config.php'); or if (!$this->Connection) { die('The connection fails, check config.php'); } I should put the error in the die part too if I was you: die('Connection failed' . mysqli_connect_error());
{ "language": "en", "url": "https://stackoverflow.com/questions/29883780", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Arithmetic Operations on complex type in C not optimized I thought the function f below, when compiled, will be optimized and will be equivalent to the function g below. // 4 multiplications and 2 additions. // 2 multiplications and 1 addition for imaginary part will be discarded. float f(float complex x, float complex y) { return crealf(x * conjf(y)); } // 2 multiplications and 1 addition. float g(float complex x, float complex y) { return crealf(x) * crealf(y) + cimagf(x) * cimagf(y); } But, as for gcc, * *with -O3 option, f still does 4 muls and 2 adds. *with -Ofast option, f is optimized and does 2 muls and 1 add (equivalent to g). I know -Ofast will ignore some specifications and execute aggressive optimizations while -O3 does not. But I don't know what specification is respected here by -O3 option and ignored by -Ofast option. Could anyone explain what I am missing? (Or just gcc -O3 misses optimization?) A: -Ofast enables all optimization options that -O3 enables but includes for instance also -ffast-math. The -ffast-math is most likely the explanation for the difference. It breaks IEEE754 conformance for the sake of speed. You should note that it is "wrong" to implement complex multiplication using the school type formula re(A)*re(B) - im(A)*im(B) + i*(...). I write "wrong" in quotes because it is optional for the compiler to implement correct behavior (correct in the sense that it behaves in the spirit of IEEE754). In case you have Inf or NaN in your source operands A or B the formula gives incorrect results. Since -ffast-math assumes that Inf or NaN do not occur in calculations, the compiler is free to use the school type formula. Otherwise it may emit more complex code that gives correct results for all valid inputs including Inf and/or NaN.
{ "language": "en", "url": "https://stackoverflow.com/questions/65144034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to start animations one after another for a view? I'm trying to play animations one after another on pre-honeycomb devices. I've tried to play animations one after another using the AnimationSet and the startOffset value of each animation without luck. I've also tried to create a new class that manages the animations to start one after another, but it also doesn't work. Here's the code: public class AnimationChain { private final List<Animation> mAnimations = new ArrayList<Animation>(); private AnimationListener mAnimationListener; private final View mViewToAnimate; public AnimationChain(final View viewToAnimate) { this.mViewToAnimate = viewToAnimate; } public void addAnimation(final Animation animation) { mAnimations.add(animation); } public void setAnimationListener(final AnimationListener animationListener) { this.mAnimationListener = animationListener; } public List<Animation> getAnimations() { return this.mAnimations; } public Animation getLastAnimation() { final int size = mAnimations.size(); if (size == 0) return null; return mAnimations.get(size - 1); } public void startAnimations() { if (mAnimations.size() == 0) return; for (int i = 0; i < mAnimations.size(); ++i) { final Animation currentAnimation = mAnimations.get(i); final Animation nextAnimation; if (i != mAnimations.size() - 1) nextAnimation = mAnimations.get(i + 1); else nextAnimation = null; currentAnimation.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(final Animation animation) { if (mAnimationListener != null) mAnimationListener.onAnimationStart(animation); } @Override public void onAnimationRepeat(final Animation animation) { if (mAnimationListener != null) mAnimationListener.onAnimationRepeat(animation); } @Override public void onAnimationEnd(final Animation animation) { if (mAnimationListener != null) mAnimationListener.onAnimationEnd(animation); if (nextAnimation != null) mViewToAnimate.startAnimation(nextAnimation); } }); } final Animation firstAnimation = mAnimations.get(0); mViewToAnimate.startAnimation(firstAnimation); } } It seems that it does call the next animation to start, but it doesn't do anything that I can see. Using a single animation works fine for any animation though. Can anyone please help me? What have I done wrong? Also, if I try to work on honeycomb version and above, will this problem still exist ? How will I handle it there? Maybe using the 9-old-android library can help? A: What Animations are you using? I tried it with a TranslateAnimation and RotateAnimation, it is working. Also where are you calling the startAnimations from?
{ "language": "en", "url": "https://stackoverflow.com/questions/16320629", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: use java class service inside rules I want to declare service class inside drl file to call the function,I used the following code but the then code don't work after declaring RouteService inside when RouteService.java public class RouteService { @Inject RouteRepository routeRepository; public void Save(Route route){ routeRepository.save(route); } .drl file ruls when $todo : Todo(route.getId() == 5202) $routeService : RouteService() then Score $score = new Score(); $score.setRunid(10); $score.setDomain("domain"); $score.setStatus("Active"); $score.setValue(52); $routeService.save($score); end Can anyone show me how use java class service inside rules in .drl file? A: * *first import user service class. *then set it as a global variable inside the drool file. import com.intervest.notification.service.RadiusFilterService; global RadiusFilterService radiusFilterService; rule "your rule name" when $map : Map(); then Map $originDataMap = (Map) $map.get("originDataMap"); Long $hashValue = (Long) $originDataMap.get("request") end *then where the rule engine define. @Autowired private RouteService routerService; kieRuntime.setGlobal("RouteService", RouteService);
{ "language": "en", "url": "https://stackoverflow.com/questions/35378976", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Mysql LIKE query doesn't work So I'm trying a basic query like this: SELECT `City`.* FROM `city` WHERE (City 'LIKE %a%') But I get this error in return: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''LIKE %a%') LIMIT 0, 30' at line 1 I guess I'm missing something out! A: SELECT `City`.* FROM `city` WHERE (City LIKE '%a%') You weren't using your single quotes correctly. It is: City LIKE '%a%' Not: City 'LIKE %a%'
{ "language": "en", "url": "https://stackoverflow.com/questions/16817855", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-5" }
Q: iOS Core Graphics fill inverse of path? I am drawing a custom shape using CGPathCreateMutable() and CGPathAddArcToPoint. As expected, when I close and fill my path I get the shape which I just drew. However, what I am looking to do is fill the inverse of the path that I have just drawn. That is, if I have drawn a circular path, I want to fill everything except for this circle that I have just drawn. Is there any way to do an inverse fill? Or another solution would be if I could fill between 2 paths if that is possible? That way I can create a rect path of my bounding frame and then fill between that and my custom path. A: If you draw to paths and fill them using Even Odd (EO) fill, that should get you what you want (fill the inner part). Default fill on OSX (and iPhone) is non zero winding (NZW) fill You could probably get the same effect using non zero winding too, by changing the winding of the different parts accordingly (the 'clockwise' parameter), but using even odd will be much simpler.
{ "language": "en", "url": "https://stackoverflow.com/questions/11026658", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Setting VCTargetsPath to multiple directories So, I've been trying to generate cocos2d-x static libraries, and I ran cmd as admin, and entered cocos gen-libs After about ten minutes, I got an issue about cpp windows props. I found out through here that I was supposed to set the VCTargetsPath so gen-libs could use some build tools. So, I did that, ran gen-libs again, and got error messages about the v140_xp toolset not being found. So, I then set the VCTargets path so it used that toolset. After using gen-libs again, it said it couldn't find the v120 toolset (the one it was set to use in the first VCTargetsPath change). tl;dr I need to know how to make it so my VCTargetsPath can refer to more than one directory at once, so I can build the cocos2d-x static libraries on my machine without hassle. If it helps any, I'm on Windows 10 64-bit, using cocos2d-x v3.15.1
{ "language": "en", "url": "https://stackoverflow.com/questions/44908436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Server side clusters of coordinates based on zoom level Thanks to this answer I managed to come up with a temporary solution to my problem. However, with a list of 6000 points that grows everyday it's becoming slower and slower. I can't use a third party service* therefore I need to come up with my own solution. Here are my requirements: * *Clustering of the coordinates need to work with any zoom level of the map. *All clusters need to be cached *Ideally there won't be a need to cluster (calculate distances) on all points if a new point is added. So far I have implemented quadtree that returns the four boundaries of my map and returns whatever coordinates are within the viewable section of the map. What I need and I know this isn't easy is to have clusters of the points returned from the DB (postgres). A: I don't see why you have to "cluster" on the fly. Summarize at each zoom level at a resolution you're happy with. Simply have a structure of X, Y, # of links. When someone adds a link, you insert the real locations (Zoom level max, or whatever), then start bubbling up from there. Eventually you'll have 10 sets of distinct coordinates if you have 10 zoom levels - one for each different zoom level. The calculation is trivial, and you only have to do it once. A: I am currently doing dynamic server-side clustering of about 2,000 markers, but it runs pretty quick up to 20,000. You can see discussion of my algorithm here: Map Clustering Algorithm Whenever the user moves the map I send a request with the zoom level and the boundaries of the view to the server, which clusters the viewable markers and sends it back to the client. I don't cache the clusters because the markers can be dynamically filtered and searched - but if they were pre-clustered it would be super fast!
{ "language": "en", "url": "https://stackoverflow.com/questions/1487704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Need advice (GUI, widgets) - implement area selection on a plot (I am new to GUI programming; experienced programmer otherwise) (Using wxPython; but generic advice welcome) I am looking for advice / direction on implementing a widget that can do area selection on a plot. Any pointers from experienced users would be much appreciated. What needs to be done is: * *Implement a two dimensional plot. *Implement a resizeable square that can be moved around to select an area on the plot. *Report the plot points that fall within that area. I realize that given the coordinates of the square and a sorted list of plot points, the contained plot points are easy to compute. I am just not sure of the widgets / graphics techniques to use to implement the plot itself and the resizeable square. Thanks for any help! A: For points 1 and 2 you could try WxMpl : http://agni.phys.iit.edu/~kmcivor/wxmpl/ It's a module for matplolib embedding in wxPython. Zooming in/out works out of the box.
{ "language": "en", "url": "https://stackoverflow.com/questions/845799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Prevent column expanding height of container I have a two-col layout built with Vuetify, where the left column contains media of varying aspect ratio, and the right column contains a playlist. When the playlist gets too long, it expands the height of the container leaving an empty area under the media. I'm trying to have it so if the right column has too much content it scrolls, without expanding the container. I've tried setting a max height, but as the aspect ratio of the media can vary, the maximum height isn't know, meaning it can get cut off too early. <v-card dark> <v-row no-gutters class="playlist-container"> <v-col cols="8" class="pa-0"> <!-- media element, could be image or video of any aspect ratio --> <img src="https://placehold.it/1400x700"> </v-col> <v-col cols="4" class="pa-0"> <!-- playlist container --> <v-layout fill-height column justify-space-between> <!-- playlist items --> <v-list class="pa-0" class="playlist-items"> <v-subheader>Category title</v-subheader> <v-list-item two-line link v-for="(video, idx) in items" :key="idx"> <v-list-item-avatar class="ma-2 ml-0 font-weight-bold"> {{ idx + 1 }} </v-list-item-avatar> <v-list-item-content> <v-list-item-title>{{ video.title }}</v-list-item-title> <v-list-item-subtitle>example &bull; 1k stats</v-list-item-subtitle> </v-list-item-content> <v-list-item-action-text class="mr-2"> 6:39 </v-list-item-action-text> </v-list-item> </v-list> <!-- bottom link --> <v-list class="pa-0"> <v-divider /> <v-list-item two-line link> <v-list-item-avatar class="mr-4"> <v-icon size="32" color="primary">play_circle_filled</v-icon> </v-list-item-avatar> <v-list-item-content> <v-list-item-title>Lorem ipsum</v-list-item-title> <v-list-item-subtitle>Bottom text</v-list-item-subtitle> </v-list-item-content> </v-list-item> </v-list> </v-layout> </v-col> </v-row> </v-card> Here is a minimal demo: https://codepen.io/benlewisjsy/pen/ExjjGeq A: I was able to do it by adding a class to the playlist items v-list, with the below: .playlist-container .playlist-items { flex-basis: 0px; flex-grow: 1; overflow-y: auto; } A: Get the current height of the right-hand column as a computed property using document.getElementById and element.offsetHeight, then set the playlist container: <v-col class="pa-0 overflow-y-auto" :style="{'max-height': `${height}px`}"> where height is the computed height.
{ "language": "en", "url": "https://stackoverflow.com/questions/60169432", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Check SAP Netweaver and ABAP Version Information I have the following SAP configuration: System-->Status SM51: Q1. Which release is this: SAP ERP Central Component (ECC) 5.0: 2004 SAP ERP Central Component (ECC) 6.0: October 2005 SAP enhancement package 1 for SAP ERP 6.0: December 2006 SAP enhancement package 2 for SAP ERP 6.0: July 2007 or later? Q2. Which SAP Netweaver version i am running on? Q3. What version of ABAP am i using? A: So-so, you have: * *Platform version is Netweaver 7 (2004s) *SAP ERP release is 6.0 and it was issued in 2005. Yes, ECC 6.0 was issued particularly in 2005 and your installation date Aug 29 2006 gives nothing than the installation date. You have no Enhancement Packs, only 6th Support Pack. *ABAP version is 7.0 without any EHP. More on this can be found here. A: The System Status screens have a little bit evolved since ABAP 7.0. Here they are for ABAP 7.52 SP 0 (SAP_ABA or SAP_BASIS), S/4HANA 1709 On Premise, SAP kernel 7.53 SP 2, HANA 2.0 --Netweaver "version" is meaningless, it's more a marketing name-- : * *Menu System > Status: *Click button Details of Product Version: * *First tab "Installed Software Component Versions": *Second tab "Installed Product Versions": *Click button Other kernel information:
{ "language": "en", "url": "https://stackoverflow.com/questions/40243603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Processing large amounts of data quickly I'm working on a web application where the user provides parameters, and these are used to produce a list of the top 1000 items from a database of up to 20 million rows. I need all top 1000 items at once, and I need this ranking to happen more or less instantaneously from the perspective of the user. Currently, I'm using a MySQL with a user-defined function to score and rank the data, then PHP takes it from there. Tested on a database of 1M rows, this takes about 8 seconds, but I need performance around 2 seconds, even for a database of up to 20M rows. Preferably, this number should be lower still, so that decent throughput is guaranteed for up to 50 simultaneous users. I am open to any process with any software that can process this data as efficiently as possible, whether it is MySQL or not. Here are the features and constraints of the process: * *The data for each row that is relevant to the scoring process is about 50 bytes per item. *Inserts and updates to the DB are negligible. *Each score is independent of the others, so scores can be computed in parallel. *Due to the large number of parameters and parameter values, the scores cannot be pre-computed. *The method should scale well for multiple simultaneous users *The fewer computing resources this requires, in terms of number of servers, the better. Thanks A: A feasible approach seems to be to load (and later update) all data into about 1GB RAM and perform the scoring and ranking outside MySQL in a language like C++. That should be faster than MySQL. The scoring must be relatively simple for this approache because your requirements only leave a tenth of a microsecond per row for scoring and ranking without parallelization or optimization. A: If you could post query you are having issue with can help. Although here are some things. Make sure you have indexes created on database. Make sure to use optimized queries and using joins instead of inner queries. A: Based on your criteria, the possibility of improving performance would depend on whether or not you can use the input criteria to pre-filter the number of rows for which you need to calculate scores. I.e. if one of the user-provided parameters automatically disqualifies a large fraction of the rows, then applying that filtering first would improve performance. If none of the parameters have that characteristic, then you may need either much more hardware or a database with higher performance. A: I'd say for this sort of problem, if you've done all the obvious software optimizations (and we can't know that, since you haven't mentioned anything about your software approaches), you should try for some serious hardware optimization. Max out the memory on your SQL servers, and try to fit your tables into memory where possible. Use an SSD for your table / index storage, for speedy deserialization. If you're clustered, crank up the networking to the highest feasible network speeds.
{ "language": "en", "url": "https://stackoverflow.com/questions/6614471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I use show component inside a ListItemText? I used the ListItemText to display the list and my goal is to use the show component in the react-admin when each row of the list is clicked, but the function related to the display is not executed? How should it be done? Contacts.js /// --- List --- export const ContactList = (props) => { const classes = useStyles(); return ( <List className={classes.list} {...props} pagination={false} exporter={false} filters={<ContactFilter/>}> <ContactSimpleList/> </List> ) }; /// --- Child list --- const ContactSimpleList = () => { const {ids, data} = useListContext(); const handleClick = (id) => { ShowContact(id); } return ( <> {ids.map(id => ( <ListItem key={id} button> <ListItemAvatar> <Avatar alt="Profile Picture" src={data[id].person}/> </ListItemAvatar> <ListItemText primary={data[id].name} onClick={() => handleClick(id)}/> </ListItem> ))} </> ); } /// --- Show --- export const ShowContact = (props) => ( <Show {...props} actions={<ShowActionsOnTopToolbar/>} title={<ContactTitle/>}> <SimpleShowLayout> <TextField source="id"/> <TextField source="name"/> <TextField source="numbers.number" label="Number"/> <TextField source="numbers.type" label="Type Call"/> </SimpleShowLayout> </Show> ); A: This is what you need to do; replace Typography with your component <ListItemText disableTypography primary={ <Typography>Pedroview</Typography> } />
{ "language": "en", "url": "https://stackoverflow.com/questions/65256085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SFDC - Query all contacts shared with a given user? I'm somewhat of a SFDC novice when it comes to integration, but is there any way I can query just the contacts shared with a given user, taking into account all the ways the share can occur? Essentially just see the same contacts the user would see in within the platform? A: I think this is what you are looking for. I added some inline comments to explain what each step is doing. The end result should be all the contacts that can be read by a specified user in your org. // add a set with all the contact ids in your org List<contact> contacts = new List<contact>([Select id from Contact]); Set<ID> contactids = new Set<ID>(); for(Contact c : contacts) contactids.add(c.id); // using the user record access you can query all the recordsids and the level of access for a specified user List<UserRecordAccess> ura = new List<UserRecordAccess>([SELECT RecordId, HasReadAccess, HasTransferAccess, MaxAccessLevel FROM UserRecordAccess WHERE UserId = 'theuserid' AND RecordId in: contactids ] ); // unfortunatelly you cannot agregate your query on hasReadAccess=true so you'd need to add this step Set<id> readaccessID = new Set<ID>(); for(UserRecordAccess ur : ura) { if(ur.HasReadAccess==true) { readaccessID.add(ur.RecordID); } } // This is the list of all the Contacts that can be read by the specified user List<Contact> readAccessContact = new List<Contact>([Select id, name from contact where id in: readaccessID]); // show the results system.debug( readAccessContact);
{ "language": "en", "url": "https://stackoverflow.com/questions/37192455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make .NET embedded web browsers accept complex HTML+JS content I'm experimenting with Windows 8 "Modern" application programming. What I want to do is use a WinRT WebView component to host a map rendered by the OpenLayers web mapping API. I created a small "Metro"/C# application which hosts a WebView as the main UI component. I also created a simple HTML page which uses OpenLayers. When I open this HTML page in IE or Chrome in Win8, the page renders correctly, i.e. the sample map appears. When I run the "Metro" app, nothing appears, and no errors are displayed or logged. Nothing. I switched to a simple WinForms app, thinking that either my understanding of WinRT is immature or there is something wrong in the HTML (although why it displays in both browsers...) When I run the WinForms app, I do get an error. A dialog appears, which contains: "An error has occurred in the script on this page." Error: Syntax error URL: about:OpenLayers.js After some google searches, I come across a Microsoft IE extension called "mark of the web" (at this point, I'm thinking "mark of the devil" is more appropriate). Apparently if you want to host a web page containing "active content" in IE, you must annotate your HTML content with a marker indicating that it is OK to. Basically, a suitably formatted HTML comment must occur in the first 2048 bytes of the HTML content. For my situation, the appropriate "mark of the web" would appear to be: "saved from url=(0014)about:internet" I placed it as an HTML comment as the first element in the section. It makes no difference. Same error occurs when I run the WinForms app. Of course, all is OK when I run IE. The issue has something to do with enhanced IE security (I won't specify the details here). MS has made it much harder (!!!) to use web pages which contain "active content", especially if the web pages are being displayed from locally caches, as opposed to being fetched from a web server. There's even a complete site for dealing with some of the issues. And, I'm at something of a loss as to how to proceed. I've tried changing IE's security settings to allow "active content", I've used "mark of the web" with and without changing security settings. Nothing appears to work. So, does anybody in SO have any experience with dealing with this? This is really baffling me.
{ "language": "en", "url": "https://stackoverflow.com/questions/12196781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Amazon Transcribe Python API: Event handler processes audio only after the stream ends (Didn't get answer in AWS re-post, so trying here) I am sending streaming audio data from web browser as a blob via websocket. In backend, I am using Django Channels' AsyncWebsocketConsumer to receive it, then send it to Amazon Transcribe and attempt to reply to the browser with the transcript in near real-time. I am able to send the transcription for a single blob, but couldn't send it in a streaming manner. I see the event handler is triggered only if the stream ends, which led me to think, maybe I am incorrectly using either the asyncio or transcribe API. What I have tried so far, apart from the code below: Created a separate stream for each audio chunk. The error amazon_transcribe.exceptions.InternalFailureException: An internal error occurred. is thrown. * *Used asyncio.gather function to group stream.input_stream.send_audio_event function and handler.handle_events function. The handler is not invoked. *Used asyncio.create_task(handler.handle_events) to create a non-blocking task for the handler. The handler is not invoked and also it didn't wait for 15 seconds. The task got completed immediately. stream_client = TranscribeStreamingClient(region="us-west-2") class AWSTranscriptHandler(TranscriptResultStreamHandler): def __init__(self, transcript_result_stream): self.channel_layer = get_channel_layer() self.channel_name = "test" super().__init__(transcript_result_stream) async def handle_transcript_event(self, transcript_event: TranscriptEvent): results = transcript_event.transcript.results for result in results: if not (result.is_partial): for alt in result.alternatives: await self.channel_layer.send( self.channel_name, {"type": "send_transcript", "message": alt.transcript}, ) class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): await self.accept() await self.send( text_data=json.dumps( {"type": "connection_established", "channel_name": self.channel_name} ) ) self.stream = await stream_client.start_stream_transcription( language_code="en-US", media_sample_rate_hz=48000, media_encoding="ogg-opus", ) self.handler = AWSTranscriptHandler(self.stream.output_stream) async def disconnect(self, close_code): await self.stream.input_stream.end_stream() async def receive(self, text_data=None, bytes_data=None): if bytes_data: await self.stream.input_stream.send_audio_event(audio_chunk=bytes_data) await self.handler.handle_events() async def send_transcript(self, event): await self.send( text_data=json.dumps({"type": "transcript", "message": event["message"]}) )
{ "language": "en", "url": "https://stackoverflow.com/questions/72875996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Upload Bitmap in a Stream using WCF I am trying to upload images captured from my WebCam to a WCF Service. I have the whole service that works bug free - tested with images/files on my HD. The problem is, that the image from the webcam is saved in a BitMap (C#). The service takes Stream as input parameter. When I use image.Save(mystream,System.Drawing.Imaging.ImageFormat.Png); client.SendFile(mystream); A 0 byte stream is uploaded. How do I get this working? Thanks. A: I suppose you must seek back to the beginning after saving the image to the stream using mystream.Seek(0, SeekOrigin.Begin), because the current position in the stream is just after the last written byte.
{ "language": "en", "url": "https://stackoverflow.com/questions/9615894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to configure RabbitMQ with LDAP for AD Groups? I had managed to configure RabbitMQ with LDAP and authenticate it, if it is for an individual AD account. I am using the following configurations: RabbitMQ Config file: auth_backends,[{rabbit_auth_backend_ldap, rabbit_auth_backend_internal},rabbit_auth_backend_internal] In RabbitMQ management, I had manually created a username with no password set (it works). But, lets say I have an AD Group (called "Rabbit User Group") that has 3 users inside (User1, User2, User3). The location of the "Rabbit User Group" is in: sample.companyname.com > City Name (OU) > Groups (OU) > IT Groups (OU) > "Rabbit User Group" (Security Group) How should I configure it in RabbitMQ management and also for the config file so that, once I update the particular group, all members inside the group will be able to authenticate and have the same permissions (e.g. only this group has admin rights) in RabbitMQ? I want to avoid needing to manually create each individual user in the RabbitMQ management for authentication?. I had added the following into my RabbitMQ config file { tag_queries, [ {administrator,{in_group,'CN="Rabbit User Group",OU="City Name", OU=Groups, OU="IT Group",DC=sample,DC=companyname,DC=com',"uniqueMember"}}, {management, {constant, true}} ] } and tried creating a username called "Rabbit User Group" into the RabbitMQ management without a password. But when I tried to login as "User1", I am unable to log in. This is my overall config file: [ { rabbit, [ { auth_backends,[{rabbit_auth_backend_ldap, rabbit_auth_backend_internal},rabbit_auth_backend_internal] } ] }, { rabbitmq_auth_backend_ldap, [ {servers, ["sample.companyname.com","192.168.63.123"]}, {dn_lookup_attribute, "userPrincipalName"}, {dn_lookup_base, "DC=AS,DC=companyname,DC=com"}, {user_dn_pattern, "${username}@as.companyname.com"}, {use_ssl, false}, {port, 636}, {log, true}, { tag_queries, [ {administrator,{in_group,'CN="Rabbit User Group",OU="City Name", OU=Groups, OU="IT Group",DC=sample,DC=companyname,DC=com',"uniqueMember"}}, {management, {constant, true}} ] } ]%% rabbitmq_auth_backend_ldap, } ]. A: You need to set the "dn_lookup_attribute" to distinguishedName (DN) instead of the userPrincipalName / sAMAccountName so that it will use this user's DN for member checking in the in_group. As shown below: {dn_lookup_attribute, "distinguishedName"}, {user_dn_pattern, "CN=${username},OU=Users,DC=sample,DC=companyname,DC=com"}, Instead of: {dn_lookup_attribute, "userPrincipalName"}, {user_dn_pattern, "${username}@as.companyname.com"}, Microsoft Active Directory and OpenLDAP are different LDAP service flavors and have different user list attribute for groups. The Microsoft Active Directory Group for the users list is called "member" while the OpenLDAP group is called "uniqueMember". Overall config file: [ { rabbit, [ { auth_backends, [rabbit_auth_backend_ldap, rabbit_auth_backend_internal] } ] }, { rabbitmq_auth_backend_ldap, [ {servers, ["sample.companyname.com","192.168.63.123"]}, {dn_lookup_attribute, "distinguishedName"}, {dn_lookup_base, "DC=AS,DC=companyname,DC=com"}, {user_dn_pattern, "CN=${username},OU=Users,DC=sample,DC=companyname,DC=com"}, {use_ssl, false}, {port, 636}, {log, true}, { tag_queries, [ {administrator,{in_group,"CN=Rabbit User Group,OU=City Name, OU=Groups, OU=IT Group,DC=sample,DC=companyname,DC=com","member"}}, {management, {constant, true}} ] } ]%% rabbitmq_auth_backend_ldap, } ].
{ "language": "en", "url": "https://stackoverflow.com/questions/58970322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is this possible to code like this : public static T GetValue(string name,Type T){...} I need to code like this: public static T GetValue(this SerializationInfo si, string name,Type T) { return (T) si.GetValue(name, typeof (T)); } I already know that the following code can work properly public static T GetValue<T>(this SerializationInfo si, string name) { return (T) si.GetValue(name, typeof (T)); } and my code is in c#, can anyone help? A: No you cannot do that, because generics are assessed at compilation (and you are asking for dynamic generics). Can you provide some more context on the usage? How are you getting your t parameter to pass to your desired example? If it's simply by typeof(int) as a parameter, then why not use the generic exmaple? Consider this example: Type t = GetTypeInfoBasedOnNameInAFile(); int a = GetValue(someSerializationInfo, "PropertyName", t); How can the compiler know that Type t is going to be castable to int at runtime? What you could do is have GetValue return an Object and then: Type t = GetTypeInfoBasedOnNameInAFile(); int a = (int)GetValue(someSerializationInfo, "PropertyName", t); But of course, if you are doing that it implies you know the expected types at compile time, so why not just use a generic parameter. You can perhaps achieve what you are after (I'm not sure on the context/usage) by using dynamic variables. A: The return type T in the first example does not refer to any valid type: T in that case is simply the name of a parameter passed to the method. You either know the type at design time or you don't, and if you don't then your only choice is to return the type Object, or some other base type or interface. A: You can do a runtime conversion to a type: Convert.ChangeType(sourceObject, destinationType); I believe that is the syntax. Of course, this will throw an exception if the cast is not possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/5906513", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why does JavaScript's document.cookie require a web server? 'document.cookie' in JavaScript does not work without a web server. Using the protocol for local file-access 'document.cookie' will always contain an empty string. Please see the accepted answer in this StackOverflow Question! As far as I know are cookies text-files stored in some sub-directory of the particular used browser. Containing key-value pairs. So, after setting a cookie it should be there on the client-side. Why has a web server to be involved? I have made myself this demo: writeMessage(); // Call the function when page is loaded. => No cookie there. function writeMessage() { var message; document.cookie.indexOf('foo') === -1 ? message = 'Cookie does not exist.' : message = 'Cookie is there!'; document.querySelector('div').innerHTML = message } document.querySelector('button').addEventListener('click', () => { document.cookie = "foo=bar"; writeMessage(); // Call the function again when the cookie has been set. }); <div class="message"></div> <button>Set Cookie</button> When the button is clicked then the cookie is set. Then the function checks if a cookie exists. It finds that this is true and shows the according message. !! There haven't been a second request to the web server !! So why doesn't work cookies when using file URI scheme for accessing the page?
{ "language": "en", "url": "https://stackoverflow.com/questions/44744085", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why doesn't lock! stop others from updating? This is my class: class Plan < ActiveRecord::Base def testing self.with_lock do update_columns(lock: true) byebug end end def testing2 self.lock! byebug end end I opened two rails consoles. In first console: p = Plan.create => (basically success) p.id => 12 p.testing2 (byebug) # simulation of halting the execution, (BYEBUG) # I just leave the rails console open and wait at here. I expect others won't be able to update p because I still got the lock. On second console: p = Plan.find(12) => (basically said found) p.name = 'should not be able to be stored in database' => "should not be able to be stored in database" p.save! => true # what????? Why can it update my object? It's lock in the other console! lock! in testing2 doesn't lock while with_lock in testing does work. Can anybody explain why lock! doesn't work? A: #lock! uses SELECT … FOR UPDATE to acquire a lock. According to PostgreSQL doc. FOR UPDATE causes the rows retrieved by the SELECT statement to be locked as though for update. This prevents them from being locked, modified or deleted by other transactions until the current transaction ends. You need a transaction to keep holding a lock of a certain row. Try console1: Plan.transaction{Plan.find(12).lock!; sleep 100.days} console2: p = Plan.find(12) p.name = 'should not be able to be stored in database' p.save #with_lock acquire a transaction for you, so you don't need explicit transaction. (This is PostgreSQL document. But I think other databases implement similar logic. )
{ "language": "en", "url": "https://stackoverflow.com/questions/54472961", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unable to click an image using selenium I have the below HTML, kindly help me in writing a java code to hit the "Patient" Button. <span id="addPat"> <span style="cursor: hand;" onclick="javascript:AddPatient();"> <img width="17" height="17" class="btnRowIcon" src="../Images/V10Icons/Add.gif"/> A: You'll have to identify the span in some way; that could look something like this: WebElement patientButton = driver.findElement(By.xpath("//span/span[child::img[@class='btnRowIcon']]")); Depending on the structure of your site this may or may not work. Once you have the element however you can click it with patientButton.click(). A: A better alternative to blalasaadri's answer, would be to use CSS selectors. They are faster, cleaner, and just.. better. WebElement image = driver.findElement(By.cssSelector("span#addPat img.btnRowIcon")); // now you can perform what you want to on the image. image.getAttribute("src")... A: I agree with sircapsalot, you can also wait for presence of element using implicit or explicit waits.. Here is an example using explicit wait : WebDriverWait image = new WebDriverWait(driver,60); image.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("span#id img.btnRowIcon"))); image.click(); The above code will wait for 60 secs for the image to be visible, * *Image will be clicked if found before 60, else an exception will be thrown..
{ "language": "en", "url": "https://stackoverflow.com/questions/20047935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Possible to store and use @AuthenticatedPrincipal after login I have a Spring-boot JavaFX 11 client and Feathersjs (node) backend connected via websocket using socket.io.client-java. I am able to establish connection, make request and so on but I was thinking if I am able to store the authenticated user information and retrieve using Spring-Security @AuthenticatedPrincipal. For example, // JavaFX client, fill up the credential and login @Service public class UserService { @FXML public void login() throws JSONException { JSONObject obj = new JSONObject(); obj.put("strategy", "local"); obj.put("email", "[email protected]"); obj.put("password", "password"); socket.emit("create", "authentication", obj, onLogin()); } private Ack onLogin() { return args -> { Auth auth; try { ObjectMapper mapper = new ObjectMapper(); auth = mapper.readValue(args[1].toString(), Auth.class); String prettyAuth = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(auth); System.out.println("prettyAuth" + prettyAuth); // store to @AuthenticatedPrincipal } catch (JsonProcessingException e) { e.printStackTrace(); } }; } } // So I will get back something like { "accessToken" : "eyJhbGciOiJIUzI1NiIsInR5cCI6ImFjY2VzcyJ9.eyJpYXQiOjE2MDI5NjM5ODAsImV4cCI6MTYwMzA1MDM4MCwiYXVkIjoiaHR0cHM6Ly95b3VyZG9tYWluLmNvbSIsImlzcyI6ImZlYXRoZXJzIiwic3ViIjoiNWY4YWIxMTU5OTMyY2QxYjZjZGM2MDZjIiwianRpIjoiMjA5ZThkZDItYzMyOS00YzdmLWE1NWYtM2UyMjc5Y2VlNDAxIn0.Es6Q2zM8UWYQqcWaBdY-7_jBxLH4zF2j-xxxxxx-xxx", "authentication" : { "strategy" : "local" }, "user" : { "_id" : "5f8ab1159932cd1b6cdc606c", "isVerified" : "true", "__v" : "0", "email" : "[email protected]", "createdAt" : 1602924821157, "updatedAt" : 1602924821157 } } How can I store my user-info so that I can retrieve via @AuthenticatedPrincipal anytime I want it. For example... // Making a HTTP request HttpHeaders headers = new HttpHeaders(); headers.setBearerAuth(accessToken); // can grab the token via @AuthenticatedPrincipal? // display profile public String getMyProfile(@AuthenticatedPrincipal user) { return user.name; } // access control @PreAuthorize("#username == authentication.principal.username") public String getMyRoles(String username) { //... } I have read up quite a bit but don't quite understand how to use it in this case. Any guidance would be appreciated. Thank you. Update: Based on some additional research, I defined the UsernamePasswordAuthenticationToken right after I am authenticated. // this is done on `onLogin` right after String prettyAuth = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(auth); System.out.println("prettyAuth" + prettyAuth); Authentication authentication = new UsernamePasswordAuthenticationToken(auth.getUser(), null, AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(authentication); System.out.println("authentication" + authentication); And it looks great where I can get the Authentication object authenticationorg.springframework.security.authentication.UsernamePasswordAuthenticationToken@818f7503: Principal: User(_id=5f8ab1159932cd1b6cdc606c, isVerified=true, __v=0, [email protected], createdAt=Sat Oct 17 16:53:41 SGT 2020, updatedAt=Sat Oct 17 16:53:41 SGT 2020); Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER But when I try to access the Authentication object from elsewhere, System.out.println("Auth is" + SecurityContextHolder.getContext().getAuthentication()); I am getting a null, any idea? Update: I have figured out the cause of it. Authentication authentication = new UsernamePasswordAuthenticationToken(auth.getUser(), "password", AuthorityUtils.createAuthorityList("ROLE_USER")); SecurityContextHolder.getContext().setAuthentication(authentication); This is defined inside a EventThread so because it is bound to ThreadLocal, when I access it back on ApplicationThread, I get back a null context. I tried to set SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL); but it doesn't work which I think that it will work only if you have the context set before spawning another thread. It works if I set to SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_GLOBAL); but I not sure if it is ok to do so.. I thought it could be as this is a client application.
{ "language": "en", "url": "https://stackoverflow.com/questions/64406896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Testing socket.io with mocha io.sockets.on('connection', function (socket) { // getSessionID is parsing socket.request.headers.cookie for sid let sessionID = getSessionID(socket); }); i'm using socket.request.headers.cookie to get the session id and then mapping that to socket id.... So my problem is when i'm running mocha tests i won't have any session or cookies set. I really don't want to modify my server to cater to the test i.e. passing through a fake session ID as query. I was thinking of using selenium but would it be overkill is there a simpler approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/46477242", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is it possible to find out if a value exists twice in an arraylist? I have an integer arraylist.. ArrayList <Integer> portList = new ArrayList(); I need to check if a specific integer has already been entered twice. Is this possible in Java? A: My solution public static boolean moreThanOnce(ArrayList<Integer> list, int searched) { int numCount = 0; for (int thisNum : list) { if (thisNum == searched) numCount++; } return numCount > 1; } A: This will tell you if you have at least two same values in your ArrayList: int first = portList.indexOf(someIntValue); int last = portList.lastIndexOf(someIntValue); if (first != -1 && first != last) { // someIntValue exists more than once in the list (not sure how many times though) } If you really want to know how many duplicates of a given value you have, you need to iterate through the entire array. Something like this: /** * Will return a list of all indexes where the given value * exists in the given array. The list will be empty if the * given value does not exist at all. * * @param List<E> list * @param E value * @return List<Integer> a list of indexes in the list */ public <E> List<Integer> collectFrequency(List<E> list, E value) { ArrayList<Integer> freqIndex = new ArrayList<Integer>(); E item; for (int i=0, len=list.size(); i<len; i++) { item = list.get(i); if ((item == value) || (null != item && item.equals(value))) { freqIndex.add(i); } } return freqIndex; } if (!collectFrequency(portList, someIntValue).size() > 1) { // Duplicate value } Or using the already availble method: if (Collections.frequency(portList, someIntValue) > 1) { // Duplicate value } A: If you are looking to do this in one method, then no. However, you could do it in two steps if you need to simply find out if it exists at least more than once in the List. You could do int first = list.indexOf(object) int second = list.lastIndexOf(object) // Don't forget to also check to see if either are -1, the value does not exist at all. if (first == second) { // No Duplicates of object appear in the list } else { // Duplicate exists } A: You could use something like this to see how many times a specific value is there: System.out.println(Collections.frequency(portList, 1)); // There can be whatever Integer, and I use 1, so you can understand And to check if a specific value is there more than once you could use something like this: if ( (Collections.frequency(portList, x)) > 1 ){ System.out.println(x + " is in portList more than once "); } A: Set portSet = new HashSet<Integer>(); portSet.addAll(portList); boolean listContainsDuplicates = portSet.size() != portList.size(); A: I used the following solution to find out whether an ArrayList contains a number more than once. This solution comes very close to the one listed by user3690146, but it does not use a helper variable at all. After running it, you get "The number is listed more than once" as a return message. public class Application { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<Integer>(); list.add(4); list.add(8); list.add(1); list.add(8); int number = 8; if (NumberMoreThenOnceInArray(list, number)) { System.out.println("The number is listed more than once"); } else { System.out.println("The number is not listed more than once"); } } public static boolean NumberMoreThenOnceInArray(ArrayList<Integer> list, int whichNumber) { int numberCounter = 0; for (int number : list) { if (number == whichNumber) { numberCounter++; } } if (numberCounter > 1) { return true; } return false; } } A: Here is my solution (in Kotlin): // getItemsMoreThan(list, 2) -> [4.45, 333.45, 1.1, 4.45, 333.45, 2.05, 4.45, 333.45, 2.05, 4.45] -> {4.45=4, 333.45=3} // getItemsMoreThan(list, 1)-> [4.45, 333.45, 1.1, 4.45, 333.45, 2.05, 4.45, 333.45, 2.05, 4.45] -> {4.45=4, 333.45=3, 2.05=2} fun getItemsMoreThan(list: List<Any>, moreThan: Int): Map<Any, Int> { val mapNumbersByElement: Map<Any, Int> = getHowOftenItemsInList(list) val findItem = mapNumbersByElement.filter { it.value > moreThan } return findItem } // Return(map) how often an items is list. // E.g.: [16.44, 200.00, 200.00, 33.33, 200.00, 0.00] -> {16.44=1, 200.00=3, 33.33=1, 0.00=1} fun getHowOftenItemsInList(list: List<Any>): Map<Any, Int> { val mapNumbersByItem = list.groupingBy { it }.eachCount() return mapNumbersByItem } A: By looking at the question, we need to find out whether a value exists twice in an ArrayList. So I believe that we can reduce the overhead of "going through the entire list just to check whether the value only exists twice" by doing the simple check below. public boolean moreThanOneMatch(int number, ArrayList<Integer> list) { int count = 0; for (int num : list) { if (num == number) { count ++ ; if (count == 2) { return true; } } } return false; }
{ "language": "en", "url": "https://stackoverflow.com/questions/14177897", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: using Linq with dynamic c# objects When i run the following code : var aList = new List<string>{"a", "b", "c"}; dynamic a = aList.Where(item => item.StartsWith("a")); dynamic b = a.Count(); Microsoft.CSharp.RuntimeBinder.RunTimeBinderException raises. But when I write a code snippet like this: public interface IInterface { } public class InterfaceImplementor:IInterface { public int ID = 10; public static IInterface Execute() { return new InterfaceImplementor(); } } public class MyClass { public static void Main() { dynamic x = InterfaceImplementor.Execute(); Console.WriteLine(x.ID); } } it's work. Why first code snippet doesn't work? A: Because the Count method is an extension method on IEnumerable<T> (Once you call Where, you don't have a list anymore, but an IEnumerable<T>). Extension methods don't work with dynamic types (at least in C#4.0). Dynamic lookup will not be able to find extension methods. Whether extension methods apply or not depends on the static context of the call (i.e. which using clauses occur), and this context information is not currently kept as part of the payload. Will the dynamic keyword in C#4 support extension methods? A: Extension methods are syntactic sugar that allow you to call a static method as if it was a real method. The compiler uses imported namespaces to resolve the correct extension method and that is information the runtime doesn't have. You can still use the extension methods, you just have to call them directly in their static method form like below. var aList = new List<string>{"a", "b", "c"}; dynamic a = aList.Where(item => item.StartsWith("a")); dynamic b = Enumerable.Count(a);
{ "language": "en", "url": "https://stackoverflow.com/questions/6677962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: 404 Error After Adding Argument To URL Path Ive got a users profile page and an update_profile page. My projects urls.py: re_path(r'^profile/(?P<username>[\w-]+)/$', include('users.urls')), My users.urls: path('', views.profile, name='profile'), path('update_profile', views.update_profile, name='update_profile'), Prior to adding the username argument to the url both of these links were working. Since adding the username argument, I can access the profile page but the update_profile page throws a 404 error. My understanding is that if the address bar reads www.site/profile/testuser/update_profile the projects urls.py will strip the www.site/profile/testuser/ and pass just update_profile to the profile apps urls.py, which then should match the path ive given. * *Why isnt this working? *On my profile page I have a check that ensures the username passed in matches the logged in user (so users can only access their own profiles). I will need a similar check on the update_profile page, but currently arent passing username to the update profile page. How could I perform this check without passing it in a second time like /profile/testuser/update_profile/testuser? Thank you. A: These are the answers to your questions: 1. Your url is not working because of there is a $ at the end of users.urls url. $ is a zero width token which means an end in regex. So remove it. 2. You do not need to add <username> at the profile_update url. If you are using UpdateView, then add slug_url_kwarg attribute to UpdateView, like: class MyUpdateView(UpdateView): slug_url_kwarg = "username" If you are using function based view, then simply use: def myview(request,username): ....
{ "language": "en", "url": "https://stackoverflow.com/questions/62295616", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: dismissModalViewController with transition: left to right I was using a nice method to dismiss my modal view controller: [self dismissModalViewControllerWithTransition:2]; which makes a slide transition from left to right, like a navigation controller does to pop a view. As this method is a non-public method, apple will not accept it. How can I program this kind of animation in my code (slide from left to right, to dismiss a modal view, and slide from right to left to present a modal view) ? Thanks in advance A: Try this: I asume you are dismissing a view controller 2 from view controller 1. In view controller 2 you are using this [self dismissModalViewControlleAnimated: NO]]; Now In the first view controller, in viewWillAppear: method add the code CATransition *animation = [CATransition animation]; [animation setDelegate:self]; [animation setType:kCATransitionPush]; [animation setSubtype:kCATransitionFromLeft]; [animation setDuration:0.50]; [animation setTimingFunction: [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut]]; [self.view.layer addAnimation:animation forKey:kCATransition]; A: I have accepted the answer from Safecase, but I would like to publish my final solution here: 1) To present a modal view controller with a from right to left transition I have written following method: -(void) presentModalView:(UIViewController *)controller { CATransition *transition = [CATransition animation]; transition.duration = 0.35; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; transition.type = kCATransitionMoveIn; transition.subtype = kCATransitionFromRight; // NSLog(@"%s: self.view.window=%@", _func_, self.view.window); UIView *containerView = self.view.window; [containerView.layer addAnimation:transition forKey:nil]; [self presentModalViewController:controller animated:NO]; } 2) To dismiss a modal view with an slide transition left to right: -(void) dismissMe { CATransition *transition = [CATransition animation]; transition.duration = 0.35; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; transition.type = kCATransitionMoveIn; transition.subtype = kCATransitionFromLeft; // NSLog(@"%s: controller.view.window=%@", _func_, controller.view.window); UIView *containerView = self.view.window; [containerView.layer addAnimation:transition forKey:nil]; [self dismissModalViewControllerAnimated:NO]; } Thanks guys! A: This Swift 4 ModalService class below is a pre-packaged flexible solution that can be dropped into a project and called from anywhere it is required. This class brings the modal view in on top of the current view from the specified direction, and then moves it out to reveal the original view behind it when it exits. Given a presentingViewController that is currently being displayed and a modalViewController that you have created and wish to display, you simply call: ModalService.present(modalViewController, presenter: presentingViewController) Then, to dismiss, call: ModalService.dismiss(modalViewController) This can of course be called from the modalViewController itself as ModalService.dismiss(self). Note that dismissing does not have to be called from the presentingViewController, and does not require knowledge of or a reference to the original presentingViewController. The class provides sensible defaults, including transitioning the modal view in from the right and out to the left. This transition direction can be customised by passing a direction, which can be customised for both entry and exit: ModalService.present(modalViewController, presenter: presentingViewController, enterFrom: .left) and ModalService.dismiss(self, exitTo: .left) This can be set as .left, .right, .top and .bottom. You can likewise pass a custom duration in seconds if you wish: ModalService.present(modalViewController, presenter: presentingViewController, enterFrom: .left, duration: 0.5) and ModalService.dismiss(self, exitTo: .left, duration: 2.0) Head nod to @jcdmb for the Objective C answer on this question which formed the kernel of the solution in this class. Here's the full class. The values returned by the private transitionSubtype look odd but are set this way deliberately. You should test the observed behaviour before assuming these need 'correcting'. :) import UIKit class ModalService { enum presentationDirection { case left case right case top case bottom } class func present(_ modalViewController: UIViewController, presenter fromViewController: UIViewController, enterFrom direction: presentationDirection = .right, duration: CFTimeInterval = 0.3) { let transition = CATransition() transition.duration = duration transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.type = kCATransitionMoveIn transition.subtype = ModalService.transitionSubtype(for: direction) let containerView: UIView? = fromViewController.view.window containerView?.layer.add(transition, forKey: nil) fromViewController.present(modalViewController, animated: false) } class func dismiss(_ modalViewController: UIViewController, exitTo direction: presentationDirection = .right, duration: CFTimeInterval = 0.3) { let transition = CATransition() transition.duration = duration transition.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) transition.type = kCATransitionReveal transition.subtype = ModalService.transitionSubtype(for: direction, forExit: true) if let layer = modalViewController.view?.window?.layer { layer.add(transition, forKey: nil) } modalViewController.dismiss(animated: false) } private class func transitionSubtype(for direction: presentationDirection, forExit: Bool = false) -> String { if (forExit == false) { switch direction { case .left: return kCATransitionFromLeft case .right: return kCATransitionFromRight case .top: return kCATransitionFromBottom case .bottom: return kCATransitionFromTop } } else { switch direction { case .left: return kCATransitionFromRight case .right: return kCATransitionFromLeft case .top: return kCATransitionFromTop case .bottom: return kCATransitionFromBottom } } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/11412467", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "17" }
Q: Read fields in Lotus Notes Documents Through VBA I am trying to write VBA code that will read data from fields in a Lotus Notes document. Currently, I am able to read data using the FieldGetText method, however this only works when I have the document open. I need to be able to loop through documents without opening them, as there are several hundred. I need to be able to read these same fields from many documents, but cannot figure out how to loop through them. My code currently is: Set LotusNotes = CreateObject("Notes.NotesUiWorkspace") Set CurrentDoc = LotusNotes.CurrentDocument While Not (CurrentDoc Is Nothing) ' Affectation of data DueDate = CurrentDoc.FieldGetText("RevDueDate") DueTime = CurrentDoc.FieldGetText("RevDueTime") DateClosed = CurrentDoc.FieldGetText("DateClosed") Wend I understand that this uses a Front End object. I was able to use a Back End object that could loop through documents (without them being open), however the data (for the dates, specifically) did not match the field text from the documents. That code looked like this: Set LotusNotes = CreateObject("Notes.NotesSession") Set db = LotusNotes.GetDatabase("") Set view = db.GetView(view_name) view.AutoUpdate = False Set columnview = view.AllEntries Set doc = view.GetFirstDocument While Not (doc Is Nothing) revDate = doc.GetItemValueDateTimeArray("RevDueDate") revDate = doc.RevDueDate Set doc = view.GetNextDocument(doc) Wend Basically, I'm just wondering if it's possible to loop through multiple files using the NotesUIWorkspace class that I tried first, or if it's possible to somehow use FieldGetText in the NotesWorkspace class instead. Any help is appreciated, thanks. A: You're using the Notes "front-end" classes rooted at Notes.NotesUIWorkspace. These are OLE classes, which means that they need the Notes client to be running and they work on the open document. There are also back-end classes rooted at Notes.NotesSession. These are also OLE classes, so they still need the Notes client to be running but they can access other documents (and other databases, servers, etc.). There is also a set of back-end classes rooted at Lotus.NotesSession. Note the different prefix. These are COM classes, so they do not need the Notes client to be running - though it does have to be installed and configured, and your code will have to provide the user's password since the client won't prompt for it. You can find documentation and examples for the NotesSession class here. Down near the bottom of the page, you'll find links to information about using them via OLE or COM. You can find a bunch of examples based on using the COM classes here, including one that traverses the documents in a view in database. Apart from the inital setup of the session, it would be the same if you use OLE. A: It is possible, and also better to use the 'Back end' object Notes.NotesSession. So try this: Set doc = view.GetFirstDocument While Not (doc Is Nothing) 'Check if you have the field in the document if doc.HasItem("RevDueDate") Then revDate = doc.getFirstItem("RevDueDate").Text End If Set doc = view.GetNextDocument(doc) Wend It is also possible to use Notes.NotesUiWorkspaceobject by opening every document in the client, getting the fields data and closing the document but I would highly recommend NOT TO make it like this as there is high possibility that you will crash the Notes client, if you need to loop on more documents.
{ "language": "en", "url": "https://stackoverflow.com/questions/44162649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to enable labels and contours for various layers (geoJson) in leaflet? I'm writing a web-viewer with Leaflet using multiple layers (some with Tiles and some with geosjson contours) that I had processed using GDAL. I'd like to display a label with the value of the contour when I activate the respective layer, and disable it when it is not visible. The same with all contour layers. I have tried this code but the labels are displayed at load, without hiding if I deactivate the layer. L.geoJson(mydataset, {onEachFeature: function(feature, layer) { var label = L.marker(layer.getBounds().getCenter(), { icon: L.divIcon({ className: 'label', html: feature.properties.MY_VARIABLE, iconSize: [100, 40] }) }).addTo(map); } }); I know that }).addTo(map) could be the cause of that. Thanks for the suggestions
{ "language": "en", "url": "https://stackoverflow.com/questions/71620130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the best way to synchronize XmlWriter access to a file to prevent IOExceptions? There are multiple places in an application which call XmlWriter.Create on the same file, all accessed through the following function. When one calls while another is still writing, I get an IOException. What's the best way to lock or synchronize access? Here's the function that's being used: public void SaveToDisk() { try { XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; using (XmlWriter writer = XmlWriter.Create(SaveFileAbsolutePath, settings)) { XamlWriter.Save(this, writer); writer.Close(); } } catch (Exception ex) { // Log the error System.Diagnostics.Debug.WriteLine(ex.Message); // Rethrow so we know about the error throw; } } UPDATE: It looks like the problem isn't just from calls to this function, but because another thread is reading the file while this function is writing to is. What's the best way to lock so we don't try to write to the file while it's being read? A: Using a lock can solve your concurrency problem and thus avoid the IOException, but you must remember to use the same object either on SaveToDisk and ReadFromDisk (i assume this is the reading function), otherwise it's totally useless to lock only when you read. private static readonly object syncLock = new object(); public void SaveToDisk() { lock(syncLock) { ... write code ... } } public void ReadFromDisk() { lock(syncLock) { ... read code ... } } A: A static lock should do the job quickly and simply: private static readonly object syncLock = new object(); then... public void SaveToDisk() { lock(syncLock) { ...your code... } } You can also use [MethodImpl(MethodImplOptions.Synchronized)] (on a static method that accepts the instance as an argument - for example, an extension method), but an explicit lock is more versatile. A: I'd actually use a ReaderWriterLock to maximise concurrency. You can allow multiple readers but only one writer at a time. private ReaderWriterLock myLock = new ReaderWriterLock(); public void SaveToDisk() { myLock.AcquireWriterLock(); try { ... write code ... } finally { myLock.ReleaseWriterLock(); } } public void ReadFromDisk() { myLock.AcquireReaderLock(); try { ... read code ... } finally { myLock.ReleaseReaderLock(); } } Just make sure to open the file with FileShare.Read so that subsequent reads don't fail.
{ "language": "en", "url": "https://stackoverflow.com/questions/442235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: I am trying to make a program that asks a user for file.txt and use the frequency of the letters to draw a bar chart. And i am stack I am trying to write a program that asks a user for file.txt and uses the frequency of the letters to draw a bar chart. And I am stuck. I'm not able to get the frequency of the letters to draw the bar graph. I need help accessing the count of the letters to calculate the height of the chart. package com.company; import javax.imageio.stream.ImageInputStream; import javax.swing.*; import java.awt.*; import java.io.*; import java.util.HashMap; import java.util.Scanner; public class BarGraph { public static void main(String[] args) throws IOException { // getting file name from user Scanner input= new Scanner(System.in); System.out.print("Please enter a file name: "); String myFile=input.nextLine().trim(); // using HashMap to store characters HashMap<Integer,Integer> hash = new HashMap<>(); // reading each line of text BufferedReader nyk = new BufferedReader(new FileReader(myFile)); String m; while (true) { String eachline = nyk.readLine(); if (eachline==null){break;}// breaks if there is nothing on the line m = eachline.toLowerCase();// setting all characters to lower case for (int i=0; i<m.length();i++){ char x = m.charAt(i); if (x!= ' '){ int charvalue = hash.getOrDefault((int) x,0);// setting default value to 0 hash.put((int) x , charvalue +1 );// increasing the value of the character } } } nyk.close(); for (int character: hash.keySet()){ System.out.println((char) character + "= "+ hash.get(character)); } }} class Bars extends JPanel{ public void paintComponent(Graphics g){ super.paintComponent(g); } public static void main(String[] args) { Bars t = new Bars(); JFrame jf = new JFrame(); jf.setTitle("Barchart"); jf.setSize(600,400); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.add(t); } } A: You have this set up as two different classes, each with their own "main" method. Presumably you only want to be running one of them. The thing to do, from what I can see, would be to define "Bars" as an inner class (or at least a separate class that "BarGraph" has a dependency on) and move all of the code you have in its "main" method to a constructor instead (or maybe some sort of "init" method if you prefer.) Once that's done, you add code in the "main" method of BarGraph, after you're done parsing your file, to actually create one of these "Bars" objects and initialize it. Once it's initialized, you can create a method in "Bars" to add data to the graph from your "hash" data structure and use that method from within BarGraph's main method.
{ "language": "en", "url": "https://stackoverflow.com/questions/61876304", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replace a string with a new string on a condition I'm making a program where a user inputs name, P, S or T, and number of rounds. It will then check if they are equal, or not (one wins depending on condition of choices? This is a rock, paper, scissors game). And then, if they are equal, I want it to print a replaced version of iChoice and iComputerChoice in the JOPtionPane. (Since in this case, it will only print P, S or T). These are the replacements: "P" = "Paper" // "S" = "Scissors" // "T" = "Stone" Below is the code block: if(iComputerchoice.equals(iChoice)) { JOptionPane.showMessageDialog (null, "Computer: " +iComputerchoice + "\n" + "" +iName + ": " + "" +iChoice + "\nIt's a tie!", "Result", JOptionPane.PLAIN_MESSAGE); } Example: iComputerchoice = P iChoice = P Computer = Paper // Your Name = Paper // It's a tie! I know a way to do this but it's kinda long. I'm wondering if there's a shorter way to do this. Thanks! A: in many ways. For instance, write a method that will do the conversion for you: private String convertChoice(String abbr) { if (abbr.equals("T")) return "Stone"; else if (abbr.equals("S")) return "Scissors"; else return "Paper"; } then use convertChoice(iChoice) instead of iChoice when updating the value in your JOptionPane. A: Well I don't know it's a good/bad way, but was just curious so tried this out , you can use a HashMap to write your "keys" and display its value when needed. Map<String,String> map=new HashMap(); map.put("p","paper"); map.put("t","Stone"); map.put("s","Scissor"); A demo short example: Scanner scan=new Scanner(System.in); System.out.println("T-Stone..P-paper..S-Scissors..enter"); String choice=scan.nextLine().toLowerCase().trim(); Map<String,String> map=new HashMap(); map.put("p","paper"); map.put("t","Stone"); map.put("s","Scissor"); //s b p-> scissor beats paper final String test="s b p , t b s , p b t"; String vals[]={"p","s","t"}; String ichoice=vals[new Random().nextInt(3)+0];//((max - min) + 1) + min if(ichoice.equalsIgnoreCase(choice)){ JOptionPane.showMessageDialog(null," Tie !!--"+map.get(ichoice)); System.exit(1); } String match=ichoice+" b "+choice; if(test.contains(match)) JOptionPane.showMessageDialog(null," CPU Won!!--!"+map.get(ichoice)); else JOptionPane.showMessageDialog(null," YOU Won!!--"+map.get(ichoice));
{ "language": "en", "url": "https://stackoverflow.com/questions/31229126", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: special characters problem after cleaning stop-words I am new to text analysis with Python and struggling to clean my data from special characters. I have survey data where one of the columns has comments. I want to analyse these comments and find the most frequent words. I try to exclude the stop words by using pandas.Series.str.replace. Here is my code: stop_words = set(stopwords.words('english')) # get the relevant column from the dataset: df_comments = df.iloc[:,[-3]].dropna() #clean it from stop words pat = r'\b(?:{})\b'.format('|'.join(stop_words)) df['comment_without_stopwords'] = df["comment"].str.replace(pat, '') df['comment_without_stopwords'] = df['comment_without_stopwords'].str.replace(r'\s+', ' ') # get the most frequent 20 words: result = df['comment_without_stopwords'].str.split(expand=True).stack().value_counts(normalize=True, ascending = False).head(20) But as a result I get the following characters: ., and - in my top list as can be seen below. How can I get rid of them? staff 0.015001 need 0.009265 work 0.007942 - 0.007059 action 0.006618 project 0.005074 contract 0.005074 . 0.004853 field 0.004412 support 0.004412 employees 0.004191 projects 0.004191 HR 0.003971 time 0.003971 HQ 0.003971 needs 0.003750 field 0.003530 training 0.003530 capacity 0.003530 good 0.003530 dtype: float64
{ "language": "en", "url": "https://stackoverflow.com/questions/71744412", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PHP keep record of unsuccessful logins How can I keep a record of the unsuccessful logins to my website? I would like the users browser, IP address, the username that was entered to attempt to login with, and the date and time the login was attempted, all to be stored in a text file. Although this would be easier in a database, I would like it in a text file. Here is my code: <head> <title>Landing page</title> <link rel="stylesheet" type="text/css" href="css.css"> <div class="loginform"> <form method="post"> <input type ='text' name="username"> <input type ='text' name="password"> <input type ='submit' name="submit"> </form> </div> </head> <body> <?php if (isset($_POST['submit'])) { $conn = new PDO("mysql:host=localhost;dbname=user_login",'root',''); $name = $_POST["username"]; $pass = $_POST["password"]; $sql = "SELECT * FROM users WHERE Username = ? AND Password = ?"; $q = $conn->prepare($sql); $q->execute(array($name,$pass)); $count = $q->rowCount(); if ($count==1) { session_start(); $_SESSION["logged_in"] = "YES"; echo "<h1>You are now logged in</h1>"; echo "<p><a href='secure1.php'>Link to protected file</a></p>"; echo "<p><a href='secure2.php'>Link to protected file #2</a></p>"; echo "<p><a href='public.html'>Link to public page</a></p>"; $q->setFetchMode(PDO::FETCH_BOTH); while($row = $q->fetch()) { echo '<p>Welcome <b>'.$row['Firstname'].$row['Lastname'].'</b><br></p>'; //Just to show you output $_SESSION["Firstname"] = $row['Lastname']; } echo '<p><a href="logout.html">logout</a></p>'; } else { session_start(); $_SESSION["logged_in"] = "NO"; echo "<h1>You are NOT logged in </h1>"; echo "<p><a href='secure1.php'>Link to protected file</a></p>"; echo "<p><a href='secure2.php'>Link to protected file #2</a></p>"; echo "<p><a href='public.html'>Link to public page</a></p>"; echo "<p>Welcome <b>Guest</b></p>"; } } ?> </body> </html> Thanks in advance A: if you really want to save all login failed attempts in a text file, then this $file = 'failedlogins.txt'; $entry = "Username: ". $name . " - " . $_SERVER['REMOTE_ADDR'] . " - " . date('l jS \of F Y h:i:s A') . "\r\n"; file_put_contents($file, $entry, FILE_APPEND); or $f = fopen("failedlogins.txt", "a"); $entry = "Username: ". $name . " - " . $_SERVER['REMOTE_ADDR'] . " - " . date('l jS \of F Y h:i:s A') . "\r\n"; fwrite($f, $entry); fclose($f); it will output on the file something like: Username: Superman - 127.0.0.1 - Thursday 18th of June 2015 11:59:08 AM Username: Batman - 127.0.0.1 - Thursday 18th of June 2015 11:59:08 AM
{ "language": "en", "url": "https://stackoverflow.com/questions/30911623", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: ViewModel event fires multiple times I'm using MVVM Light for my application and I have also implemented the INavigationService for going back/for between pages. So in a common scenario, it's like this MainPage > Categories > Rounds > DataPage. In the DataPage, I'm making a request to fetch the results and depending on the result returned from the callback I call the .GoBack() method to pop the current page from the stack and return to Rounds. What I have noticed is that if I hit first the DataPage and the .GoBack() gets called and then tap on a different round the callback method will be fired twice, and if I go back and in again thrice, and continues like this. Essentially this means that the .GoBack() will be called again and the navigation gets messed up. I believe this has to do with not cleaning up the previous VM's, I tried changing this behavior with the UnRegister / Register class from SimpleIOC but no luck. A: In the ViewModel class public void UnsubscribeFromCallBack() { this.event -= method; } In the .xaml.cs page protected override void OnDisappearing() { base.OnDisappearing(); PageViewModel vm = (this.BindingContext as PageViewModel); vm.UnSubscribeFromCallback(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/44312721", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why do i get the error " duplicate key value violates unique constraint "" DETAIL: Key (id_application)=(PR-1005576039) already exists my models.py def document_id(): random_numbers = random.randint(1000000000, 1009999999) doc_id = "PR-" + str(random_numbers) return doc_id class Document(models.Model): id_application = models.CharField(default=document_id(), unique=True, editable=False) applicant_name = models.CharField(max_length=100) to_whom = models.CharField(max_length=255, blank=False) comment = models.TextField(blank=False) email = models.EmailField(blank=False) through_whom = models.CharField(max_length=255, blank=False) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) status = models.CharField(max_length=255, choices=STATUS_CHOICES, default='Pending') is_private = models.BooleanField(default=False) stage = models.CharField(max_length=255, choices=STAGES, default='Departmental Review') uploaded_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) the problem happens every two times i create a document application, for some reasons it is using the last document application id. I am using a postgresql database. A: Your problem is in this line: id_application = models.CharField(default=document_id(), unique=True, editable=False) Although it might seem intuitive that document_id() is called every time you create a new instance of Document, this is not true. This is evaluated only once and later the randomly generated value will be the same. So, in case you didn't provide the value for id_application when instantiating your model, you will get a duplicated value error when creating a second instance. To avoid this, you need to provide the default in the __init__ of the model instead and remove the default kwarg from the field definition for clarity. def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.id_application is None: self.id_application = document_id() Or, you can also pass the function to the default and it will get called when creating each object. See the docs. # Note that there are no parenthesis id_application = models.CharField(default=document_id, unique=True, editable=False)
{ "language": "en", "url": "https://stackoverflow.com/questions/73918243", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to convert string text from notepad into array line by line? I am a beginner in programming. I am currently learning how to convert texts from notepad into array line by line. An instance of the text in notepad, I am a high school student I love banana and chicken I have 2 dogs and 3 cats and so on.. In this case, the array[1] will be string 'I love banana and chicken'. The lines in the notepad can be updated and I want the array to be dynamic/flexible. I have tried to use scanner to identify each of the lines and tried to transfer them to array. Please refer to my code: import java.util.*; import java.io.*; import java.util.Scanner; class Test { public static void main(String[] args) throws Exception { File file = new File("notepad.txt"); Scanner scanner = new Scanner(file); String line; int i = 0; int j = 0; while (scanner.hasNextLine()) { i++; } String[] stringArray = new String[i]; while (scanner.hasNextLine()) { line = scanner.nextLine(); stringArray[j] = line; j++; } System.out.println(stringArray[2]); scanner.close(); } } I am not sure why there is runtime-error and I tried another approach but still did not produce the result that I want. A: The first loop would be infinite because you check if the scanner has a next line, but never advance its position. Although using a Scanner is fine, it seems like a lot of work, and you could just let Java's nio package do the heavy lifting for you: String[] lines = Files.lines(Paths.get("notepad.txt")).toArray(String[]::new); A: You can simply do it by creating an ArrayList and then converting it to the String Array. Here is a sample code to get you started: public static void main(String[] args) throws FileNotFoundException { Scanner in = new Scanner(new File("notepad.txt")); List<String> outputList = new ArrayList<>(); String input = null; while (in.hasNextLine() && null != (input = in.nextLine())) { outputList.add(input); } String[] outputArray = new String[outputList.size()]; outputArray = outputList.toArray(outputArray); in.close(); } A: Since you want array to be dynamic/flexible, I would suggest to use List in such case. One way of doing this - List<String> fileLines = Files.readAllLines(Paths.get("notepad.txt"));
{ "language": "en", "url": "https://stackoverflow.com/questions/41512196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to get stats how much lines are committed by a user? Is there any way to get stats how much lines are committed by a certain user (in all repositories he contributes to)? A: On Github for a particular repository you can go to the graphs tab: As you can see there are a number of options there. To get the number of lines that a user has changed select the Contibutions option. This will display a card for each user with the number of commits and number of lines added and removed, similarly to the below:
{ "language": "en", "url": "https://stackoverflow.com/questions/17850249", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Type 'number' is not assignable to type 'Element' I am creating custom hook useArray in react with typescript which perform methods of array like push, update, remove etc. In js it is working fine but in ts there are some errors. below are the code from files: useArray.ts import { useState } from "react"; export default function useArray<T extends Element>(defaultValue: T[]): { array: T[], set: React.Dispatch<SetStateAction<T[]>>, push: (elemet: T) => void, remove: (index: T) => void, filter: (callback: (n: T) => boolean) => void, update: (index: number, newElement: T) => void, clear: () => void } { const [array, setArray] = useState(defaultValue); function push(element: T) { setArray((a) => [...a, element]); } function filter(callback: (n: T) => boolean) { setArray((a) => a.filter(callback)); } function update(index: number, newElement: T) { setArray((a) => [ ...a.slice(0, index), newElement, ...a.slice(index + 1, a.length), ]); } function remove(index: number) { setArray((a) => [...a.slice(0, index), ...a.slice(index + 1, a.length)]); } function clear() { setArray([]); } return { array, set: setArray, push, filter, update, remove, clear }; } App.tsx import ArrayComp from "./components/ArrayComp"; function App() { return ( <div className="App"> <ArrayComp /> </div> ); } export default App; ArrayComp.tsx import useArray from "./useArray"; function ArrayComp() { const { array, set, push, remove, filter, update, clear } = useArray([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ]); return ( <div> <h1>Updated array: </h1> <div> {array.join(", ")} </div> <button onClick={() => set([1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 15, 34, 21])}> set to[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 15, 34, 21] </button> <button onClick={() => push(5)}> Add 5 </button> <button onClick={() => update(3, 5)}> update 5 at index 3 </button> <button onClick={() => filter((n) => n < 10)}> filter numbers less than 10 </button> <button onClick={() => remove(3)}> Remove forth Element </button> <button onClick={clear}> Empty array </button> </div> ); } export default ArrayComp; I am getting this error: "Type 'number' is not assignable to type 'Element'" at multiple places. I want that array elements can be of any possible type but I don't want to make its type as any. any suggestions will be appreciated. A: solution : With using generics it is working fine. useArray.ts : `import { useState } from "react"; export default function useArray<T>(defaultValue: T[]): { array: T[], set: React.Dispatch<SetStateAction<T[]>>, push: (elemet: T) => void, remove: (index: number) => void, filter: (callback: (n: T) => boolean) => void, update: (index: number, newElement: T) => void, clear: () => void } { const [array, setArray] = useState(defaultValue); function push(element: T) { setArray((a) => [...a, element]); } function filter(callback: (n: T) => boolean) { setArray((a) => a.filter(callback)); } function update(index: number, newElement: T) { setArray((a) => [ ...a.slice(0, index), newElement, ...a.slice(index + 1, a.length), ]); } function remove(index: number) { setArray((a) => [...a.slice(0, index), ...a.slice(index + 1, a.length)]); } function clear() { setArray([]); } return { array, set: setArray, push, filter, update, remove, clear }; }`
{ "language": "en", "url": "https://stackoverflow.com/questions/71909628", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: DELETE operation returns ERROR: There was an unexpected error (type=Forbidden, status=403). Forbidden I am working on a spring-boot project which includes thymeleaf, spring-security. It works fine when I perform - showing products-list, showing products-details, adding new product, updating existing product. But when I perform - deleting an product, it gives the following ERROR: Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Thu Jul 18 16:59:16 BDT 2019 There was an unexpected error (type=Forbidden, status=403). Forbidden Here is my code: product_list.html <!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Product List</title> <link rel="stylesheet" th:href="@{/css/bootstrap.css}"> </head> <body> <div class="container"> <h1>Product List</h1> <hr> <a class="btn btn-success" th:href="@{/products/add}">Create New Product</a> <hr> <table class="table"> <thead> <tr> <th>Product ID</th> <th>Name</th> <th>Brand</th> <th>Made In</th> <th>Price</th> <th>Actions</th> </tr> </thead> <tbody> <tr th:each="theProduct:${theProducts}"> <td th:text="${theProduct.id}">Product ID</td> <td th:text="${theProduct.name}">Name</td> <td th:text="${theProduct.brand}">Brand</td> <td th:text="${theProduct.madein}">Made In</td> <td th:text="${theProduct.price}">Price</td> <td> <a class="btn btn-info" th:href="@{'/products/show/' + ${theProduct.id}}">View</a> <a class="btn btn-warning" th:href="@{'/products/edit/' + ${theProduct.id}}">Edit</a> <a class="btn btn-danger" th:data-the-product-id="${theProduct.id}" data-toggle="modal" data-target="#deleteConfirmationModal">Delete</a> <div class="modal fade" id="deleteConfirmationModal" tabindex="-1" role="dialog" aria-labelledby="deleteConfirmationModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete Confirmation</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> Are you sure you want to DELETE the Product. <br> <form id="deleteForm" action="#" th:method="DELETE"> <button type="submit" class="btn btn-danger">Delete Employee</button> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> </td> </tr> </tbody> </table> </div> <script th:src="@{/js/jquery-3.3.1.js}"></script> <script th:src="@{/js/popper.js}"></script> <script th:src="@{/js/bootstrap.js}"></script> <script> $('#deleteConfirmationModal').on('show.bs.modal', function (event) { var anchorLink = $(event.relatedTarget) var theProductId = anchorLink.data('theProductId') var modal = $(this) $("#deleteForm").attr("action", "/products/delete/" + theProductId) }) </script> </body> </html> ProductController.java package com.example.demo.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestMapping; import com.example.demo.dao.ProductRepository; import com.example.demo.entity.Product; @Controller @RequestMapping("/products") public class ProductController { @Autowired private ProductRepository productRepository; @GetMapping("/index") public String index(Model theModel) { List<Product> theProducts = productRepository.findAll(); theModel.addAttribute("theProducts", theProducts); return "product/product_list"; } @GetMapping("/add") public String add(Model theModel) { Product theProduct = new Product(); theModel.addAttribute("theProduct", theProduct); return "product/product_add_form"; } @GetMapping("/show/{productId}") public String show(@PathVariable int productId, Model theModel) { Product theProduct = productRepository.findById(productId).get(); if(theProduct == null) { return null; } theModel.addAttribute("theProduct", theProduct); return "product/product_detail"; } @PostMapping("/create") public String create(@ModelAttribute("theProduct") Product theProduct) { theProduct.setId(0); productRepository.save(theProduct); return "redirect:/products/index"; } @GetMapping("/edit/{productId}") public String edit(@PathVariable(name="productId") int productId, Model theModel) { Product theProduct = productRepository.findById(productId).get(); theModel.addAttribute("theProduct", theProduct); return "product/product_edit_form"; } @PutMapping("/update") public String update(@ModelAttribute("theProduct") Product theProduct) { productRepository.save(theProduct); return "redirect:/products/index"; } @DeleteMapping("/delete/{productId}") public String delete(@PathVariable int productId) { Product tempProduct = productRepository.findById(productId).get(); if(tempProduct == null) { return null; } productRepository.deleteById(productId); return "redirect:/products/index"; } } LoginController.java package com.example.demo.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class LoginController { @RequestMapping("/login") public String login() { return "login"; } @GetMapping("/") public String home(Model theModel) { return "redirect:/products/index"; } } SecurityConfig.java package com.example.demo.config; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.User.UserBuilder; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private DataSource dataSource; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { UserBuilder users = User.withDefaultPasswordEncoder(); auth.inMemoryAuthentication().withUser(users.username("admin").password("Admin.123").roles("EMPLOYEE", "ADMIN")); } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/css/**") .permitAll() .antMatchers("/js/**") .permitAll() .anyRequest() .authenticated() .and() .formLogin() .loginPage("/login") .loginProcessingUrl("/authenticateTheUser") .permitAll() .and() .logout() .permitAll(); } } A: Try disabling csrf token in your configuration: @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/css/**") .permitAll() .antMatchers("/js/**") .permitAll() .anyRequest() .authenticated() .and() .formLogin() .loginPage("/login") .loginProcessingUrl("/authenticateTheUser") .permitAll() .and() .logout() .permitAll() .and().csrf().disable(); } A: fortunately you add "modal" inside thymeleaf each loop, so edit your html from according my code .... <form id="deleteForm" th:action="${'/products/delete/' + theProductId}" th:method="DELETE"> <button type="submit" class="btn btn-danger">Delete Employee</button> </form> this is tested code ...working fine .. you just miss "th:action" for that it dose not work as thymeleaf form. so thymeleaf dose not provide hidden "_csrf" field;
{ "language": "en", "url": "https://stackoverflow.com/questions/57093492", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can i use orderby only for every 10 rows in postgres I need order every 10 row of a single column table and fetch the rows of n interval. Iam using where mod(rownum,10) for doing the second part. But i cant find a way to orderby every nth row before fetching the first and last row of n rows.Please help The table is like => Column 15 18 13 14 11 16 17 12 19 20 9 2 3 5 4 6 7 8 1 10 This is the query iam currently using==> Select column from (select column,row_number() over (order by column) as rn from table ) t where mod(rn,10)=0 or mod(rn,10)=1; This will fetch Column 1 10 11 20 But what i want is Column 11 20 1 10 Ps: i cant orderby whole column then fetch every 1st and 10th row,i want to orderby first 10 column fetch 1st and 10th row then orderby next 10 colum fetch 11th to 20th etc.. And i can only fire the query one time only A: Like this: SELECT col, rn, (rn - 1) / 10 AS trunc FROM (SELECT col, row_number() over (order by col) as rn FROM data ) t WHERE mod(rn,10)=0 or mod(rn,10)=1 ORDER BY (rn - 1) / 10 DESC ; Result: +------+----+-------+ | col | rn | trunc | +------+----+-------+ | 11 | 11 | 1 | | 20 | 20 | 1 | | 1 | 1 | 0 | | 10 | 10 | 0 | +------+----+-------+ Working Example
{ "language": "en", "url": "https://stackoverflow.com/questions/68791379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: inserting and selecting multiple values of checkbox in mssql stored procedure here is where I get the values of the checkboxes. It is working. ` echo "<div class='table-responsive' >"; echo "<table class='table table bordered' style='font-size: 14px'>"; echo "<th style = ''> Action</th>"; echo "<th style = ''>Document</th>"; echo "</div>"; $cntr = 1; while ($row = sqlsrv_fetch_array($loadDocs)) { echo "<tr>"; echo "<td style = 'text-align:center;width:10%'> <input type='checkbox' id='NAMING".$cntr."' value='".$row['DocCode']."' /></td>"; echo"<td style = 'width:10%''>".$row["DocDesc"]."</td>"; echo "</tr>"; $cntr++; } ?>` Help this is my php code for the selection and insertion of checkbox values in mssql stored procedure. I cant figure out what is wrong with the code. Please help. `<?php if(isset($_POST['BTN_Proceed'])) { $x=1; $BankName = $_POST['BankName']; $BankCode = $_POST['BankCode']; $DocCode = $_POST['DocCode']; $rowCount = $_SESSION["rowCount"]; while ($x < $rowCount) { $insertDocsParam = array(array($BankName,SQLSRV_PARAM_IN), array($BankCode,SQLSRV_PARAM_IN), array($Doccode,SQLSRV_PARAM_IN), array($_POST["NAMING".$x],SQLSRV_PARAM_IN),); $insertDocs = sqlsrv_query($conn, '{CALL sp_SRP_Insert_Doc (?,?,?,?)}', $insertDocsParam) or die( print_r( sqlsrv_errors(), true));; $x++; } } ?>` This is my Stored Procedure for the insert query what else do I need to add here? Because Im also getting the checkbox data from sql server. `ALTER PROCEDURE [dbo].[sp_SRP_Insert_Doc] (@BankName nvarchar(50),@BankCode nvarchar(5),@DocCode nvarchar(5)) AS BEGIN SET NOCOUNT ON; BEGIN INSERT INTO [dbo].[ZREF_ROUT_INCO_DOC] (BankName,BankCode,DocCode) VALUES (@BankName,@BankCode,@DocCode) END END`
{ "language": "en", "url": "https://stackoverflow.com/questions/53440025", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Referencing current row in FILTER clause of window function In PostgreSQL 9.4 the window functions have the new option of a FILTER to select a sub-set of the window frame for processing. The documentation mentions it, but provides no sample. An online search yields some samples, including from 2ndQuadrant but all that I found were rather trivial examples with constant expressions. What I am looking for is a filter expression that includes the value of the current row. Assume I have a table with a bunch of columns, one of which is of date type: col1 | col2 | dt ------------------------ 1 | a | 2015-07-01 2 | b | 2015-07-03 3 | c | 2015-07-10 4 | d | 2015-07-11 5 | e | 2015-07-11 6 | f | 2015-07-13 ... A window definition for processing on the date over the entire table is trivially constructed: WINDOW win AS (ORDER BY dt) I am interested in knowing how many rows are present in, say, the 4 days prior to the current row (inclusive). So I want to generate this output: col1 | col2 | dt | count -------------------------------- 1 | a | 2015-07-01 | 1 2 | b | 2015-07-03 | 2 3 | c | 2015-07-10 | 1 4 | d | 2015-07-11 | 3 5 | e | 2015-07-11 | 3 6 | f | 2015-07-13 | 4 ... The FILTER clause of the window functions seems like the obvious choice: count(*) FILTER (WHERE current_row.dt - dt <= 4) OVER win But how do I specify current_row.dt (for lack of a better syntax)? Is this even possible? If this is not possible, are there other ways of selecting date ranges in a window frame? The frame specification is no help as it is all row-based. I am not interested in alternative solutions using sub-queries, it has to be based on window processing. A: You are not actually aggregating rows, so the new aggregate FILTER clause is not the right tool. A window function is more like it, a problem remains, however: the frame definition of a window cannot depend on values of the current row. It can only count a given number of rows preceding or following with the ROWS clause. To make that work, aggregate counts per day and LEFT JOIN to a full set of days in range. Then you can apply a window function: SELECT t.*, ct.ct_last4days FROM ( SELECT *, sum(ct) OVER (ORDER BY dt ROWS 3 PRECEDING) AS ct_last4days FROM ( SELECT generate_series(min(dt), max(dt), interval '1 day')::date AS dt FROM tbl t1 ) d LEFT JOIN (SELECT dt, count(*) AS ct FROM tbl GROUP BY 1) t USING (dt) ) ct JOIN tbl t USING (dt); Omitting ORDER BY dt in the widow frame definition usually works, since the order is carried over from generate_series() in the subquery. But there are no guarantees in the SQL standard without explicit ORDER BY and it might break in more complex queries. SQL Fiddle. Related: * *Select finishes where athlete didn't finish first for the past 3 events *PostgreSQL: running count of rows for a query 'by minute' *PostgreSQL unnest() with element number A: I don't think there is any syntax that means "current row" in an expression. The gram.y file for postgres makes a filter clause take just an a_expr, which is just the normal expression clauses. There is nothing specific to window functions or filter clauses in an expression. As far as I can find, the only current row notion in a window clause is for specifying the window frame boundaries. I don't think this gets you what you want. It's possible that you could get some traction from an enclosing query: http://www.postgresql.org/docs/current/static/sql-expressions.html When an aggregate expression appears in a subquery (see Section 4.2.11 and Section 9.22), the aggregate is normally evaluated over the rows of the subquery. But an exception occurs if the aggregate's arguments (and filter_clause if any) contain only outer-level variables: the aggregate then belongs to the nearest such outer level, and is evaluated over the rows of that query. but it's not obvious to me how. A: https://www.postgresql.org/docs/release/11.0/ Window functions now support all framing options shown in the SQL:2011 standard, including RANGE distance PRECEDING/FOLLOWING, GROUPS mode, and frame exclusion options https://dbfiddle.uk/p-TZHp7s You can do something like count(dt) over(order by dt RANGE BETWEEN INTERVAL '3 DAYS' PRECEDING AND CURRENT ROW)
{ "language": "en", "url": "https://stackoverflow.com/questions/31396434", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: Rails 3 in controller test for field change In the controller of a Rails 3 app, I'm trying to test if a field changes and then flash a message on the redirect page. This is the code I'm trying: class CostprojectsController < ApplicationController def update @costproject = Costproject.find(params[:id]) @costquestion = @costproject.costquestion nextpath = edit_costquestion_path(@costquestion) if params[:tab1] nextpath = costprojects_editcostestimates_path(:id => @costproject.id) if params[:tab2] nextpath = costprojects_editattachments_path(:id => @costproject.id) if params[:tab3] if nextpath == nil if User.current.admin? nextpath = costprojects_path else nextpath = clients_costcurrent_path end end flash[:success] = "Project Submitted" if @costproject.submit_date_changed? respond_to do |format| if @costproject.update_attributes(params[:costproject]) format.html { redirect_to nextpath } format.json { render json: @costproject } else format.html { render action: "edit" } format.json { render json: @costproject.errors, status: :unprocessable_entity } end end end This is the line not working: flash[:success] = "Project Submitted" if @costproject.submit_date_changed? @costproject.submit_date is a valid field - and it's getting updated during the test. A: You are updating your @costproject AFTER the if condition, I guess you should do it before. You should consider doing it only if update_attributes returns true, as in following code: respond_to do |format| if @costproject.update_attributes(params[:costproject]) flash[:success] = "Project Submitted" if @costproject.previous_changes.include?(:submit_date) format.html { redirect_to nextpath } format.json { render json: @costproject } else format.html { render action: "edit" } format.json { render json: @costproject.errors, status: :unprocessable_entity } end end
{ "language": "en", "url": "https://stackoverflow.com/questions/37278902", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do I output installation status using gtk in c? int main( int argc, char *argv[] ) { GtkWidget *window; gtk_init (&argc, &argv); window = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_widget_show (window); gtk_main (); return 0; } The above is just a empty winform,I want to output dynamic information in it(not editable), how should I do that? A: You need a GtkTextView which you can set to be not editable. I suggest you look at this excellent GTK tutorial which explains what widgets are available in GTK and how to put them together, accompanied by lots of example code.
{ "language": "en", "url": "https://stackoverflow.com/questions/2730621", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Limiting the two way binding with vuejs / variable values change when modifying another variable I have a 'client-display' component containing a list of clients that I get in my store via mapGetter. I use 'v-for' over the list to display all of them in vuetify 'v-expansion-panels', thus one client = one panel. In the header of those panels, I have a 'edit-delete' component with the client passed to as a prop. This 'edit-delete' basically just emits 'edit' or 'delete' events when clicked on the corresponding icon with the client for payload. When I click on the edit icon, the edit event is then catched in my 'client-display' so I can assign the client to a variable called 'client' (sorry I know it's confusing a bit). I pass this variable to my dialog as a prop and I use this dialog to edit the client. So the probleme is : When I edit a client, it does edit properly, but if I click on 'cancel', I find no way to revert what happened in the UI. I tried keeping an object with the old values and reset it on a cancel event, but no matter what happens, even the reference values that I try to keep in the object change, and this is what is the most surprising to me. I tried many things for this, such as initiating a new object and assigning the values manually or using Object.assign(). I tried a lot of different ways to 'unbind' all of this, nothing worked out. I'd like to be able to wait for the changes to be commited in the store before it's visible in the UI, or to be able to have a reference object to reset the values on a 'cancel' event. Here are the relevant parts of the code (I stripped a lot of stuff to try and make it easier to read, but I think everything needed is there): Client module for my store I think this part works fine because I get the clients properly, though maybe something is binded and it should not const state = { clients: null, }; const getters = { [types.CLIENTS] : state => { return state.clients; }, }; const mutations = { [types.MUTATE_LOAD]: (state, clients) => { state.clients = clients; }, }; const actions = { [types.FETCH]: ({commit}) => { clientsCollection.get() .then((querySnapshot) => { let clients = querySnapshot.docs.map(doc => doc.data()); commit(types.MUTATE_LOAD, clients) }).catch((e) => { //... }); }, } export default { state, getters, mutations, ... } ClientsDisplay component <template> <div> <div> <v-expansion-panels> <v-expansion-panel v-for="c in clientsDisplayed" :key="c.name" > <v-expansion-panel-header> <div> <h2>{{ c.name }}</h2> <edit-delete :element="c" @edit="handleEdit" @delete="handleDelete" /> </div> </v-expansion-panel-header> <v-expansion-panel-content> //the client holder displays the client's info <client-holder :client="c" /> </v-expansion-panel-content> </v-expansion-panel> </v-expansion-panels> </div> <client-add-dialog v-model="clientPopup" :client="client" @cancelEdit="handleCancel" /> </div> </template> <script> import { mapGetters, mapActions } from 'vuex'; import * as clientsTypes from '../../../../store/modules/clients/types'; import ClientDialog from './ClientDialog'; import EditDelete from '../../EditDelete'; import ClientHolder from './ClientHolder'; import icons from '../../../../constants/icons'; export default { name: 'ClientsDisplay', components: { ClientHolder, ClientAddDialog, EditDelete, }, data() { return { icons, clientPopup: false, selectedClient: null, client: null, vueInstance: this, } }, created() { this.fetchClients(); }, methods: { ...mapGetters({ 'stateClients': clientsTypes.CLIENTS, }), ...mapActions({ //this loads my clients in my state for the first time if needed 'fetchClients': clientsTypes.FETCH, }), handleEdit(client) { this.client = client; this.clientPopup = true; }, handleCancel(payload) { //payload.uneditedClient, as defined in the dialog, has been applied the changes }, }, computed: { isMobile, clientsDisplayed() { return this.stateClients(); }, } } </script> EditDelete component <template> <div> <v-icon @click.stop="$emit('edit', element)" >edit</v-icon> <v-icon @click.stop="$emit('delete', element)" >delete</v-icon> </div> </template> <script> export default { name: 'EditDelete', props: ['element'] } </script> ClientDialog component Something to note here : the headerTitle stays the same, even though the client name changes. <template> <v-dialog v-model="value" > <v-card> <v-card-title primary-title > {{ headerTitle }} </v-card-title> <v-form ref="form" > <v-text-field label="Client name" v-model="clientName" /> <address-fields v-model="clientAddress" /> </v-form> <v-card-actions> <v-btn @click="handleCancel" text >Annuler</v-btn> <v-btn text @click="submit" >Save</v-btn> </v-card-actions> </v-card> </v-dialog> </template> <script> import AddressFields from '../../AddressFields'; export default { name: 'ClientDialog', props: ['value', 'client'], components: { AddressFields, }, data() { return { colors, clientName: '', clientAddress: { province: 'QC', country: 'Canada' }, clientNote: '', uneditedClient: {}, } }, methods: { closeDialog() { this.$emit('input', false); }, handleCancel() { this.$emit('cancelEdit', { uneditedClient: this.uneditedClient, editedClient: this.client}) this.closeDialog(); }, }, computed: { headerTitle() { return this.client.name } }, watch: { value: function(val) { // I watch there so I can reset the client whenever I open de dialog if(val) { // Here I try to keep an object with the value of this.client before I edit it // but it doesn't seem to work as I intend Object.assign(this.uneditedClient, this.client); this.clientName = this.client.name; this.clientContacts = this.client.contacts; this.clientAddress = this.client.address; this.clientNote = ''; } } } } </script> A: To keep an independent copy of the data, you'll want to perform a deep copy of the object using something like klona. Using Object.assign is a shallow copy and doesn't protect against reference value changes.
{ "language": "en", "url": "https://stackoverflow.com/questions/63385761", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: navigate ListViewItem through arrow Up and Down Keys in C# I made a simple application where i have some TextBoxes and One ListItemView. When i enter a data into Textbox it shows result in ListItemView from database. And when i press Arrow keys Down it focus on ListItemView and then i Navigate ListItemView Through arrow key Up and Down. And when i pressed Enter in selected item of ItemListView it shows content from ItemListView to TextBox. That's All my Purpose But the problem is how can i do it? A: I use this code if(e.KeyCode==Keys.F1){ this.ActiveControl=listView1;}
{ "language": "en", "url": "https://stackoverflow.com/questions/50302875", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: What is difference between PORTABLE and Machine Independent? This might be silly question but I am confused between portable and machine independent. What is Java, c#.net : portable or machine independent? A: Machine Independence Machine independence refers to the idea of software that can be executed irrespective of the machine on which it executes. A piece of Machine dependent software might be something written to use, say assembly instructions that are specific to a certain architecture. For example, if you write a C++ application with inline assembly that relies on special processor instructions such as for example, SIMD instructions, then that peice of software is machine dependent because it has specific machine requirements - it can only work on a machine that supports that specific required SIMD instruction set. In contrast, C# and Java compile to bytecode that is executed by a virtual machine which takes that bytecode and executes it as native code directly on the processor. In this case the virtual machine is machine dependent because it will execute against the specific hardware it is written for - for example, only a 32 bit Intel processor, or an ARM Smartphone. The Java and C# applications that run on the virtual machine however are machine independent because they care not what the underlying platform is, as long as there is a virtual machine to translate to the underlying paltform for them. That abstraction layer, the virtual machine, helps separate the application from the underlying hardware and that is the reason why those applications can be machine independent. Portability Portability is a separate but related concept, it is a broad term that covers a number of possibilities. A piece of software is portable simply if it can be built and executed or simply executed on more than one platform. This means that machine independent software is inherently portable as it has to be by nature. There are broadly two facets to portability - hardware portability, and software portability. Ignoring for the moment .NET implementations such as Mono and focussing purely on Microsoft's .NET implementation it is fair to say that .NET is hardware portable because it can be executed on any hardware that supports the .NET runtime, however because Microsoft's implementation is only available on Windows and Windows descended operating systems it is fair to say that it is not particularly software portable - without Mono it cannot be executed on Mac OS X or Linux. In contrast, Java could be said to be both hardware portable and software portable because it can run on multiple operating systems like Windows, OS X, Linux hence it is software portable, and hardware portable because it can run on different hardware architectures such as ARM, x86 and x64. Finally, there is also the question of language portability. Many would argue that although a C++ application compiled for Windows will not natively execute on Linux, it is possible to write C++ code in such a way that the same set of source code can be compiled on both Linux and Windows with no changes - this means that you can port the same application to different operating systems simply by just compiling it as is. In this respect we can say that whilst a compiled C++ application is not portable, the source code for a C++ application can be portable. This applies to a number of other languages including C. Disclaimer This is a somewhat simplified explanation and there are many edge cases that break these rules which make it such a complex and subjective subject - for example it is possible to write a Java application that is machine dependent if for example you use the Java native interfaces. A: Portable means that you can run this programm without any installation. Machine independent means that the same code can be executed on different OS. This question could be helpfull, too. A: From Wikipedia: Software is portable when the cost of porting it to a new platform is less than the cost of writing it from scratch. The lower the cost of porting software, relative to its implementation cost, the more portable it is said to be. Machine-independent software, on the other hand, does not need any work to be ran on another machine (ex. from Windows to Mac OS). It is by this definition also highly portable. A: What is difference between PORTABLE and Machine Independent? There is no real answer to this. It depends on whose definitions of "portable" and "machine independent" you chose to accept. (I could pick a pair of definitions that I agree with and compare those. But I don't think that's objective.) What is Java, c#.net : portable or machine independent? You could argue that Java and C# are neither portable or machine independent. * *A Java or C# program only runs on a platform with a JVM or CLR implementation, and a "compliant" implementation of the respective standard libraries. Ergo, the languages are not machine independent (in the literal sense). *There are many examples of Java (and I'm sure C#) programs that behave differently on different implementations of Java / C#. Sometimes it is due to differences in runtime libraries and/or the host operating system. Sometimes it is due to invalid assumptions on the part of the programmer. But the point is that Java / C# software often requires porting work. Ergo, they are not portable (in the literal sense.)
{ "language": "en", "url": "https://stackoverflow.com/questions/16544203", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: AWS S3 Folder deleted History Is there ways to get deleted history of AWS s3 bucket? Problem Statement : Some of s3 folders got deleted . Is there way to figure out when it got deleted A: There are at least two ways to accomplish what you want to do, but both are disabled by default. The first one is to enable server access logging on your bucket(s), and the second one is to use AWS CloudTrail. You might be out of luck if this already happened and you had no auditing set up, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/35909182", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Matlab ocv.dll error The Specified Module Could Not Be Loaded I am trying to use face detector of Matlab Vision Toolbox Example I am getting this error when I run the script: MATLAB:dispatcher:loadLibrary Can't load 'C:\Program Files\MATLAB\R2015a\bin\win64\ocv.dll': The specified module could not be found. Caught MathWorks::System::FatalException My system is Win-64 and I don't have OpenCv installed on my system.What is the reason of getting this error ? UPDATE: ocv.dll is existing in the specified location A: The OpenCV DLL comes with the Computer Vision System Toolbox for MATLAB. It sounds like the Computer Vision System Toolbox is not correctly installed on your computer.
{ "language": "en", "url": "https://stackoverflow.com/questions/33844426", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert to file from Hard Disk I'm trying to make a small app (dictionary) that translates from English to Arabic and vice versa. I have 2 files in the debug folder English.txt and Arabic.txt. I am trying in my form to make it possible for the user to insert new words to the files but I don't know if StreamWriters are working while StreamReaders are. I think that my Seek statements don't work the right way either. Here is my code that I tried: FileStream englishFile = new FileStream("English.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamReader engSR = new StreamReader(englishFile); StreamWriter engSW = new StreamWriter(englishFile); FileStream arabicFile = new FileStream("Arabic.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter arabSW = new StreamWriter(arabicFile); StreamReader arabSR = new StreamReader(arabicFile); string line = engSR.ReadLine(); string[] arr = line.Split('|'); int numberOfLines = int.Parse(arr[1]) + 1; englishFile.Seek(0, SeekOrigin.Begin); engSW.WriteLine("*|{0}", numberOfLines); arabSW.WriteLine("*|{0}", numberOfLines); englishFile.Seek(0, SeekOrigin.End); line = engSR.ReadLine(); engSW.WriteLine("{0}|{1}", numberOfLines, englishin.Text); arabicFile.Seek(0, SeekOrigin.End); line = arabSR.ReadLine(); arabSW.WriteLine("{0}|{1}", numberOfLines, arabicin.Text); arabicFile.Close(); englishFile.Close(); Where englishin and arabicin are the two text-boxes. Sadly there is no change that occurs in the file. I have also tried : string line = engSR.ReadLine(); string[] arr = line.Split('|'); int numberOfLines = int.Parse(arr[1]) + 1; englishFile.Seek(0, SeekOrigin.Begin); engSW.WriteLine("*|{0}", numberOfLines); arabSW.WriteLine("*|{0}", numberOfLines); //englishFile.Seek(0, SeekOrigin.End); line = engSR.ReadLine(); while (line != null) line = engSR.ReadLine(); engSW.WriteLine("{0}|{1}", numberOfLines, englishin.Text); //arabicFile.Seek(0, SeekOrigin.End); line = arabSR.ReadLine(); while (line != null) line = arabSR.ReadLine(); arabSW.WriteLine("{0}|{1}", numberOfLines, arabicin.Text); I don't really know what's the problem with the writer. A: you need to close your StreamReader and StreamWriter, in onder to save your written text, you need to close StreamWriter Extra https://msdn.microsoft.com/en-us/library/system.io.streamwriter%28v=vs.110%29.aspx System.IO is IDisposable, you should dispose it after read and write. private static void Main() { FileStream englishFile = new FileStream("English.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamReader engSR = new StreamReader(englishFile); StreamWriter engSW = new StreamWriter(englishFile); FileStream arabicFile = new FileStream("Arabic.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); StreamWriter arabSW = new StreamWriter(arabicFile); StreamReader arabSR = new StreamReader(arabicFile); char delimiter = '|'; try { englishFile.Seek(0, SeekOrigin.Begin); while(!engSR.EndOfStream){ string line = engSR.ReadLine(); string[] arr = line.Split(delimiter); for (int j = 0; j < arr.Count();j++ ) { if (j > 0) { arabSW.Write(delimiter); } String outStr = ConvertStr(arr[j]); arabSW.Write(outStr); } arabSW.Write(arabSW.NewLine); } } catch { } finally { arabSW.Close(); //arabSR.Close(); engSR.Close(); //engSW.Close(); arabicFile.Close(); englishFile.Close(); } } i tried this, it work well A: The problem is that i have to make flush whenever i finished writing so after seeking to the begin and writing i should flush and at the end of the method i should close the StreamWriter as they said. string line = engSR.ReadLine(); string[] arr = line.Split('|'); int numberOfLines = int.Parse(arr[1]) + 1; englishFile.Seek(0, SeekOrigin.Begin); engSW.WriteLine("*|{0}", numberOfLines); arabicFile.Seek(0, SeekOrigin.Begin); arabSW.WriteLine("*|{0}", numberOfLines); engSW.Flush(); arabSW.Flush(); englishFile.Seek(0, SeekOrigin.End); line = engSR.ReadLine(); engSW.WriteLine("{0}|{1}", numberOfLines, englishin.Text); arabicFile.Seek(0, SeekOrigin.End); line = arabSR.ReadLine(); arabSW.WriteLine("{0}|{1}", numberOfLines, arabicin.Text); } catch { } finally { engSW.Close(); arabSW.Close(); arabSR.Close(); engSR.Close(); arabicFile.Close(); englishFile.Close(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/30294031", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can i align my components vertically and 3 in a row? On my react project i want align my components to vertical. But when i use div and make it flex , my component width is changing and looking bad. what should i do ? I using tailwindcss but if you dont know it you can tell normal css too. I can use normal css too. My component : <div className=""> <div className="mt-6 ml-5 bg-gray-50 border rounded-lg border-gray-200 shadow-md w-3/12 h-full mb-10"> <div className="flex mt-2"> <div className="border border-gray-500 ml-2 mt-2 pl-1 pr-1 pt-2 "> <FontAwesomeIcon icon={faEtsy} className="text-2xl text-red-600" /> </div> <div className="relative"> <span className="ml-3 pt-2 relative text-xl font-medium"> {prop.PharmacyName} </span> <br /> <span className="ml-4 text-blue-800">{prop.PharmacyNumber}</span> </div> </div> <Divider /> <div className=""> <p className="px-2 py-1 font-medium text-base text-gray-700"> {prop.PharmacyAdress} </p> </div> </div> </div> How i calling my component : data.map((x, index) => { return ( <div className="flex align-center"> <PharmacyCard className="relative" key={index} props={x} /> </div> )}) How its looks like : https://prnt.sc/1covi9m How i want : https://prnt.sc/1cow1sq I using that component like 30-40 times with mapping. So i want to see like 3 component in a row. Thanks for all replies! A: You just need to put the .flex in upper level like the below: <div className='flex align-center'> {data.map((x, index)=>{<PharmacyCard className="relative" key={index} props={x} />})}</div> hope this link will assist you to get the flexbox better https://codepen.io/enxaneta/full/adLPwv A: So i want to see like 3 component in a row. Since you have clear idea about the layout, I suggest to wrap you components in another div with grid and three columns; something like this: <div className="grid grid-cols-3"> {data.map((x, index)=>{<PharmacyCard className="relative" key={index} props={x} />})} </div> Depending on your design, you may add gap class as well. Also consider removing w-3/12 class from components so they fill grid's width.
{ "language": "en", "url": "https://stackoverflow.com/questions/68430407", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: validating a user's value length (javascript) I am practicing my javascript beginners knowledge on a simple form. I want the user to enter a 10 digits phone number (in case it's less than 10 or more than 10 I have created the invalid style class so the user will only be allowed to enter 10 digits for his phone number). Also, once they entered the phone number of 10 digits, the user should be able to click "+" and get a second box for a second phone number (the second box will appear when you click + only if the user entered 10 digits for his first phone number). I used an if() for validating the phone number, but it doesn't seem to work. Below is my code, any ideas maybe? <!DOCTYPE html> <html> <head> <title>Numere de telefon</title> <style> .invalid { background-color: rgb(139,0,0,0.2); color: darkgreen; border: 1px green solid; } </style> <script> function minL(elem,event,nr){ var v = elem.value; if(v.length < nr ){ elem.classList.add("invalid"); } else if (v.length > nr) { elem.classList.add("invalid"); } else { elem.classList.remove("invalid"); } } function addInput(elem,event){ event.preventDefault(); var container = document.querySelector("#containerNrTel"); if(minL(document.querySelector("[name=numarTelefon]"))){ container.innerHTML += '<input type="text" placeholder="nr telefon" />'; } } </script> </head> <body> <form> <fieldset> <legend>Cont nou</legend> <input type="text" placeholder="nume"> <input type="text" placeholder="prenume"> <input type="text" placeholder="nr telefon" name="numarTelefon" oninput="" onchange="minL(this,event,10);"> <input type="button" value="+" onclick="addInput(this,event);"> <div id="containerNrTel"></div> <input type="button" value="Submit"> </fieldset> </form> </body> </html> Thanks in advance, Ioana A: There are two main issues. * *The call to minL in the addInput function doesn't have the right number of parameters. *minL doesn't return a boolean value when addInput expects it to. function minL(elem,event,nr){ var v = elem.value; if(v.length < nr ){ elem.classList.add("invalid"); } else if (v.length > nr) { elem.classList.add("invalid"); } else { elem.classList.remove("invalid"); return true; } } function addInput(elem,event){ event.preventDefault(); var container = document.querySelector("#containerNrTel"); if(minL(document.querySelector("[name=numarTelefon]"), event, 10)){ container.innerHTML += '<input type="text" placeholder="nr telefon" />'; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/53274375", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: HTML options not showing I am adding some options through JavaScript to my HTML page but the options don't seem to be appearing. I do see them when I inspect them with F12 but they are not showing. Important Note: Using bootstrap! <select class="browser-default" id='userSelect' name="userSelect"> <option default>-</option> </select> JavaScript: var sel = document.getElementById("userSelect"); for (var key in result) { if (result.hasOwnProperty(key)) { var opt = document.createElement('option'); opt.innerHTML = result[key].contactName; opt.value = result[key].id; sel.appendChild(opt); } } I did check if result has any value so that is not the problem (otherwise the options wouldn't appear). I think bootstrap is the problem here, because I read some things about it that it can be a problem in this case. Does anyone know how to solve this? HTML Chrome Inspector: A: It looks like you use bootstrap-select plugin. After every DOM manipulation to select you need to use refresh method of selectpicker. for (var key in result) { if (result.hasOwnProperty(key)) { var opt = document.createElement('option'); opt.innerHTML = result[key].contactName; opt.value = result[key].id; sel.appendChild(opt); } } $('#userSelect').selectpicker('refresh');
{ "language": "en", "url": "https://stackoverflow.com/questions/64892568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to make global variables in android? After google i found three ways: 1. static variables 2. extending Application and using getApplicationContext 3. SharedPreferences A: EDIT: read comments pls, i don't want to delete it, because it may help other who fell into the same trap... Be careful with static variables!! I wrote an app which uses them, but on some devices it works, on some it doesn't. the problem is, if one activity edits that variable, finishes and the focus returns to another activity, the changes are not recognized. i haven't found a solution for this and somehow i don't get it working with getApplicationContext either... Usually i would say that i made a mistake, but in both cases, it is working on an SGSII with Android 4.0.4 but it isn't on SGSIII with 4.1... :( So as a consequence i assume that they've changed the use of global variables, maybe out of security reasons, so that every activity gets an own instance of that variable or so, i have no idea
{ "language": "en", "url": "https://stackoverflow.com/questions/13491109", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Issue running java program from batch file, runs fine in IDE I'm doing some basic java homework for a class on my new laptop - issue is, I can't seem to get the program to compile and run from my batch file using the directions the instructor gave me. I've set the Path variable to my JDK inside the Environment Variables settings. My program is a simple shipping program to keep track of shipment information - I have the program working flawlessly in NetBeans (which our instructor advised us to use for developing the code), but he's going to be testing them using batch files, so we're also advised to test them on our systems with one we create prior to turning them in - pretty straightforward. Issue is, I cannot seem to get this to work. I've never done it before, but I've used .bat files to compile and run C++ programs, as well as using makefiles on a unix system, so I feel like I'm absolutely stupid for not figuring this out on my own, but none of my searches have returned any fruitful solutions that help at all. My program consists of 3 .java files: Shipment.java - an interface that contains abstracted methods that are implemented in the ShipmentHW1 class ShipmentHW1.java - a class that implements the abstracted methods from Shipment and has constructors, etc to create a usable object TestShipment.java - the main class of this program, which utilizes and creates ShipmentHW1 objects based on preset parameters. This is super duper basic stuff here, and again, it runs perfectly fine inside the NetBeans IDE. The instructions given to us state to have the batch file inside the package directory (which in this case I've set aside a seperate folder on my desktop titled "shipping", which is the package name - shouldn't be any issues there), where the 3 .java files are located as well. They say if you don't need to explicitly list the path to the JDK, then you can simply have javac TestShipment.java java TestShipment.java pause Afterwards I get errors talking about how it "cannot find symbol Shipment s = new ShipmentHW1();" I've tried adding imports, but since they're in the same package it shouldn't even be an issue. Directory path is C:\Users\X\Desktop\shipping All 7 files are contained within: TestShipment.java TestShipment.class Shipment.java Shipment.class ShipmentHW1.java ShipmentHW1.class doHW1.bat Does anyone have any idea? I can provide more information if I've been too vague Also, I'm on Windows 8 if that makes any difference A: Solved Batch file now reads javac TestShipment.java Shipment.java ShipmentHW1.java cd .. java shipment.TestShipment pause and it works like a charm. Anyone have any ideas why I had to call the package.class instead of just compiling it regularly? A: Try doing javac TestShipment.java java TestShipment pause A: Without seeing the contents of TestShipment.java, I'll assume you have some dependency on the Shipment and ShipmentHW1 classes. As such, when you execute a program that uses the TestShipment class, you need to have the .class files for each of the three (and any other dependencies). So you will have to compile Shipment.java and ShipmentHW1.java as well before running your java command. If they are in the same package, you're good, if not, you will have to specify an appropriate value for the -cp option. When running java with a class name, you need to specify the fully qualified class name. A: If your .java files are declared to be in the 'shipping' package, then you probably need to be running java from the parent directory of 'shipping', e.g. cd <path>/shipping javac TestShipment.java cd .. java shipping/TestShipment
{ "language": "en", "url": "https://stackoverflow.com/questions/21244748", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to make a webpage display dynamic data in real time using Python? I am working on making a GUI front end for a Python program using HTML and CSS (sort of similar to how a router is configured using a web browser). The program assigns values given by the user to variables and performs calculations with those variables, outputting the results. I have a few snags to work out: * *How do I design the application so that the data is constantly updated, in real-time? I.e. the user does not need to hit a "calculate" button nor refresh the page to get the results. If the user changes the value in a field, all other are fields simultaneously updated, et cetera. *How can a value for a variable be fetched from an arbitrary location on the internet, and also constantly updated if/when it is updated at the source? A few of the variables in the program are based on current market conditions (e.g. the current price of gold). I would like to make those values be automatically entered after retrieving them from certain sources that, let us assume, do not have APIs. *How do I build the application to display via HTML and CSS? Considering Python cannot be implemented like PHP, I am seeking a way to "bridge the gap" between HTML and Python, without such a "heavy" framework like Django, so that I can run Python code on the server-side for the webpage. I have been looking into this for a quite some time now, and have found a wide range of what seem to be solutions, or that are nearly solutions but not quite. I am having trouble picking what I need specifically for my application. These are my best findings: Werkzeug - I believe Werkzeug is the best lead I have found for putting the application together with HTML and Python. I would just like to be reassured that I am understanding what it is correctly and that is, in fact, a solution for what I am trying to do. WebSockets - For displaying the live data from an arbitrary website, I believe I could use this protocol. But I am not sure how I would implement this in practice. I.e. I do not understand how to target the value, and then continuously send it to my application. I believe this to be called scraping? A: Question 1. For that you would need javascript, javascript is used for adding behaviour to websites. I would recommend using a javascript framework called Jquery for that. You would do this by adding an html "id" or "class" to the inputs that have the value you want to recieve from the users and an "id" to the field where you would display the results of those calculations. You would create an javascript event that basically tracks whenever any html object that has the class you used for the inputs above was changed, when that happens you do your calculations, and post the results on the result field you decided, using it's "id" identifier. Take a look at this link for more info Question 2. For that you would have to do what is called "Web scraping": First you read the html source code of the page you want to get the information from and look at the ID of the HTML object you want to get the information from (If it doesn't have an ID, you would then have to look at the Hierarchy of it (What is also known as the Document Object Model DOM), looking at with Objects it's inside of) then you create a script that reads the HTML and looks for that ID or follows the Hierarchy you discovered and reads the text in that HTML object. Remember that HTML is just text. I'm more used to the Ruby programming language, in ruby there is a module you download for that, but I'm sure that there is one called "Mechanize" for Python. Question 3. You could use Flask which is a light and simple micro-framework for python Python, from the needs you describe, it sounds like perfect fit. A: To achieve your goal, you need good knowledge of javascript, the language for dynamic web pages. You should be familiar with dynamic web techniques, AJAX, DOM, JSON. So the main part is on the browser side. Practically any python web server fits. To "bridge the gap" the keyword is templates. There are quite a few for python, so you can choose, which one suites you best. Some frameworks like django bring their own templating engine. And for your second question: when a web site doesn't offer an API, perhaps the owner of the site does not want, that his data is abused by others.
{ "language": "en", "url": "https://stackoverflow.com/questions/28786932", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Keep getting "None" at every input statement I was just making a Rock , Paper and scissor game in python(Version 3.9+) but whenever I try to run , there is NONE written at every input statement... My whole program works fine but I am really annoyed with "NONE" is there anything I am doing something wrong in my code. I will really appreciate your help! Here is my code: import random num__round = int(input("Enter the number of rounds you want to play for: ")) rounds = 1 while rounds <= num__round: comp_choices = ["Rock" , "Paper" , "Scissor"] print("Round number", rounds) user_action = str(input(print("Enter your choice from ===> Rock , Paper or Scissor"))).lower() comp_actions = str(random.choice(comp_choices)).lower() if user_action == comp_actions: print("You Chose==>" , user_action , "Computer Chose ==>" , comp_actions , "\nRound draw\n") elif user_action == 'rock': if comp_actions == 'paper': print("You Chose==>" , user_action , "\nComputer Chose ==>" , comp_actions) print("Paper defeats rock!\n<===You lost this round===>,Computer won this round!\n") else: print("You Chose==>" , user_action , "\nComputer Chose ==>" , comp_actions) print("Rock breaks scissor!\n<===You won this round!===>\n") elif user_action == 'paper': if comp_actions == 'rock': print("You Chose==>" , user_action , "\nComputer Chose ==>" , comp_actions , "\n") print("Paper defeats rock!\n<===You won this round===>,Computer lost!" , "\n") else: print("You Chose==>" , user_action , "\nComputer Chose ==>" , comp_actions) print("Scissor torn the paper into pieces!\n<===You lost this round===>,Computer won!\n") else: if comp_actions == 'rock': print("You Chose==>" , user_action , "\nComputer Chose ==>" , comp_actions ) print("Rock brutally breaks the scissor!\n<===You lost this round===>,Computer won\n") else: print("You Chose==>" , user_action , "\nComputer Chose ==>" , comp_actions) print("Scissor torn down the paper!\n<===You won this round===>,Computer lost this round!\n") rounds = rounds + 1 And here is the "None" written in every input statement: Enter your choice from ===> Rock , Paper or Scissor None rock A: input is willing to prompt your "Enter your choice from ===> Rock , Paper or Scissor" on its own but you also put a print there. So first print prints what you give it, and then its return value (print returns None) is passed to input and input then prompts this None (if you notice, it's on a newline actually because your print gave a newline). So you dont need print there: user_action = str(input("Enter your choice from ===> Rock , Paper or Scissor")).lower() More, you don't need to cast str the input's result because it's always a string (if succeeds), so user_action = input("Enter your choice from ===> Rock, Paper or Scissors: ").lower() A: I copied this myself and got the NONE to go away by moving the input().lower() out of the print statement print("Enter your choice from ===> Rock , Paper or Scissor") user_action = str(input()).lower() comp_actions = str(random.choice(comp_choices)).lower() A: Simply remove the print() from your input: str(input("Enter your choice from ===> Rock , Paper or Scissor\n")).lower() A: whenever you see none its because your using print twice change this: user_action = str(input(print("Enter your choice from ===> Rock , Paper or Scissor"))).lower() to this: user_action = str(input("Enter your choice from ===> Rock , Paper or Scissor")).lower() you are saying to print the function and then print the string that will take and input, which is in your function so your saying print twice, when you only need to say print the function and since the string that will take and input is in your function it will print it out.
{ "language": "en", "url": "https://stackoverflow.com/questions/70516213", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Scala IDE failing to be installed I have checked here but I cannot find anybody with the same kind of issue. I am trying to install the 4.7.0 version of the Scala IDE based on Eclipse available at http://scala-ide.org/download/current.html for Windows 10. While the download seems to be working fine, once I unzip the file I get a pop-up message that says "Error: Could not create the Java Virtual Machine. Error: A fatal exception has occurred. Program will exit." The configuration file eclipse.ini (still within the downloaded scala IDE) is: *-startup plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar --launcher.library plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.500.v20170531-1133 -vmargs -Xmx2G -Xms200m -XX:MaxPermSize=384m* I have tried to increase the heap memory size to 512 and 1024 MB or using winzip instead of winrar for installing the program (apparently, there was some issue with WinRAR according to some people) but to no avail. Do you have any idea of what could be wrong?
{ "language": "en", "url": "https://stackoverflow.com/questions/75509176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: PowerPoint VBA - Click on shape then press another shape to change the colour I am new to VBA (since this morning so please treat me like an idiot and you will be about right!) and am stuck on something that seems as though it should be very simple. I am working in PowerPoint and have a set of circles and below them a red and a green coloured square. I would like to be able to select a relevant circle and then click on the appropriate square to change that circle only to red or green, as below Select your option: O O O O O Change colour: [Red] [Green] At the moment I am using animations and triggers but I have LOTS of circles and I only want to change them one at a time. A: +1 to Siddharth for that answer. There's another bit that won't be apparent if you're just getting started out. You can have PPT pass a reference to the clicked shape when the shape triggers a macro (caution: Mac PPT is buggy/incomplete. This won't work there). Using Siddharth's suggestion as a jumping off point, you can do something like this: Option Explicit Sub SelectMe(oSh As Shape) ' assign this macro to each of the shapes you want to color ' saves time to assign it to one shape, then copy the shape as many ' times as needed. ActivePresentation.Tags.Add "LastSelected", oSh.Name End Sub Sub ColorMeRed(oSh As Shape) ' assign this macro to the "color it red" shape ' when this runs because you clicked a shape assigned to run the macro, ' oSh will contain a reference to the shape you clicked ' oSh.Parent returns a reference to the slide that contains the shape ' oSh.Parent.Shapes(ActivePresentation.Tags("LastSelected")) returns a reference ' to the shape whose name is contained in the "LastSelected" tag, ' which was applied in the SelectMe macro above. ' Whew! If Len(ActivePresentation.Tags("LastSelected")) > 0 Then With oSh.Parent.Shapes(ActivePresentation.Tags("LastSelected")) .Fill.ForeColor.RGB = RGB(255, 0, 0) End With End If End Sub Sub ColorMeBlue(oSh As Shape) ' assign this macro to the "color it blue" shape If Len(ActivePresentation.Tags("LastSelected")) > 0 Then With oSh.Parent.Shapes(ActivePresentation.Tags("LastSelected")) .Fill.ForeColor.RGB = RGB(0, 0, 255) End With End If End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/20504384", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to show week number using Angular material v12 I am using Angular material datepicker. https://material.angular.io/components/datepicker/ Is there is way to show week numbers of this datepicker? A: Unfortunately, no. It's been requested from the Angular Material team but they responded with this: https://github.com/angular/material/issues/10003#issuecomment-364730323 We have no plans to add an option to visually display the week number on the calendar as this is not part of the Material Design Spec. Week numbers would be great feature to add, but won't happen until Google decides to add it to the Material Design Spec.
{ "language": "en", "url": "https://stackoverflow.com/questions/67787892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Parsing JSON response in Blackberry I am getting a below JSON Response from the server please let me know how to parse this. I only need ---------------------------7da7d113c0dea Content-Type: application/json Content-Length: 338 Request-Id: 714a31e1-1b2c-4e10-8ce1-7b7c4204ff66 response-type: rfc_json status-code: 200 processing-time: 74993 {"EXPORTING":{"OUT_CATEGORY_CODE_DESC":[{"CONTENT":"1","LIST_ID":"","DESCRIPTION": "Business Area","DISABLED":""},{"CONTENT":"2","LIST_ID":"", "DESCRIPTION":"Industry","DISABLED":""},{"CONTENT":"5","LIST_ID":"", "DESCRIPTION":"Vendor","DISABLED":""}], "OUT_MESSAGE":"","OUT_SOLUTION_DETAILS":[], "OUT_SUBCATEGORY_SEARCH":[]},"IMPORTING": null} ---------------------------7da7d113c0dea-- i would like to retrive values OUT_CATEGORY_CODE_DESC[],OUT_SOLUTION_DETAILS":[] and OUT_SUBCATEGORY_SEARCH":[] . Do you have any sample code here? A: There is a package over on JSON.org called org.json.me which is a port of org.json to Java ME.
{ "language": "en", "url": "https://stackoverflow.com/questions/7319994", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: validates_presence_of and with templates ruby on rails I'm trying to validate some ratio buttons making sure the user as selected one of them. I do this by using: validates_presence_of In addition, I have specific template that I use for the page's layout. Normally, without the template layout, The anything that is missing is highlighted automatcially by the validates_pressense_of helper in red. However, with with the template, I only see the displayed words which is probably a result of the template. Is there some way fix this and have the missing fields highlighted in red with the template? Here is the snippet of the .css file i'm using for the template: body{ background:#F4DDB1; margin:0; font: 10pt/14pt 'Lucida Grande', Verdana, Helvetica, sans-serif; } A:link{ color:#275A78; text-decoration:none; } A:hover{ color:#333333; text-decoration:underline; } A:active{ color:#275A78; text-decoration:none; } A:active:hover{ color:#333333; text-decoration:underline; } A:visited{ color:#275A78; text-decoration:none; } A:visited:hover{ color:#333333; text-decoration:underline; } #header{ background:url(../images/headerbg.gif) no-repeat #F4DDB1 top left; width:282px; height:439px; margin-right:auto; /* *margin-left:0; */ margin-bottom:0; text-align:right; float:left; } #wrap{ width:782px; margin-right:auto; margin-left:auto; } #container{ background:#F8EBD2; width:500px; /*margin-left:282px; margin-top:-452px; */ float:right; } #navcontainer{ /* * */position:absolute; width:282px; margin-right:auto; margin-top:435px; margin-left:60px; } #navlist li{ margin-left:15px; list-style-type: none; text-align:right; padding-right: 20px; font-family: 'Lucida Grande', Verdana, Helvetica, sans-serif; font-size:12px; color:#666666; } #navlist li a:link { color: #666666; text-decoration:none; } #navlist li a:visited { color: #999999; text-decoration:none; } #navlist li a:hover {color: #7394A0; text-decoration:none; } h3{ font-size:21px; font-weight:bold; color:#8C7364; } .content{ padding:10px; width: 100% text-align:justify; font: 9pt/14pt 'Lucida Grande', Verdana, Helvetica, sans-serif; } #footer{ background:transparent; height:66px; text-align:center; font: 8pt/14pt 'Lucida Grande', Verdana, Helvetica, sans-serif; color:#333333; } #title{ position:absolute; top:440px; left:9px; padding-left:9px; font: 14pt/12pt 'Lucida Grande', Verdana, Helvetica, sans-serif; color:#275A78; } The code will be in this portion: <div class="content"> <!-- here is your page content --> <%= yield :layout %> <!-- end page content --> </div> http://www.otoplusvn.com/TherapistSurvey/counselor_questionaries/new If you don't click on any radio buttons, and press submit you only see the error messages, but the fields aren't highlighted. Any Advise appreciated, Thanks, Derek A: The highlights from Rails comes from CSS that targets : .field and .field_with_errors These classes are generated with the following HAML in Rails : .field = f.label :type = f.check_box :type In HTML : <% form_for(@plant) do |f| %> <%= f.error_messages %> <b>Plant Name</b> <p> <%= f.label :name %><br /> <%= f.text_field :name %> .. What does your HAML look like for say, one of your fields? A: <table cellpadding ="5" cellspacing="3" width="100%"> <% for rating_option in [0,1,2,3,4,5,6] -%> <td align ="center"> <%= radio_button("counselor_effectiveness", category, @temp[rating_option])%> </td> <% end -%> </table> I'm still really new to css and ruby on rails. The above code is used to generate the radio buttons. Are you saying that in the css i can control the color of the background of the radio buttons (being highlighted) through the css? If so , how is that done? Thanks, D
{ "language": "en", "url": "https://stackoverflow.com/questions/3481290", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: 'pointerenter' event not working on touch device I have the following html template of a table. My intention is that a user is able to highlight each table cell when they drag their pointer across each table cell. The following code works on mouse device however function that is supposed to fire on pointerenter event does not work when it is being used on touch device. <table class="defect-map" @pointerup="finishDrag"> <tr class="list-group-item" v-for="item in rows" v-bind:key="item.y" style="touch-action:none;" > <template v-for="patch in item.patches"> <td @pointerdown="startDrag(patch, this)" @pointerenter="handleDrag(patch)" @click="highlightImg(patch)" v-bind:key="patch.x" :class="assignClass(patch)"> <!-- <div> insert some div here</div> --> </td> </template> </tr> </table> These are the functions startDrag, handleDrag and finishDrag that are tied to pointerdown, pointerenter and pointerup respectively. startDrag(patch, e) { this.mouseDown = true console.log("mouse down event...") this.handleDrag(patch) e.target.setPointerCapture(e.pointerId); }, handleDrag(patch) { if (this.mouseDown) { this.highlightPatch(patch) } }, finishDrag(e) { console.log('mouse up event...'); this.mouseDown = false; e.target.releasePointerCapture(e.pointerId); }, The above functions work fine when using mouse device but not so when using touch device. I've tried enabling and disabling style="touch-action:none;" however both options does not seem to work.
{ "language": "en", "url": "https://stackoverflow.com/questions/74260529", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android WebView fails at loading URL stating net::ERR_INSUFFICIENT_RESOURCE I am using a WebView in my application and upon the click of a button the user is supposed to go from 'URL A' to 'URL B' , but it looks like the WebView makes an effort- I see URL B in the background of the loader but within a fraction of seconds it loops back to 'URL A'. When I checked the android studio log I found an error stating net::ERR_INSUFFICIENT_RESOURCES . No where else in my application have I noticed such a glitch and there are so many urls the user can go to and fro with no backfire. The URL B a grid showing a maximum of 10 photos. Hence I don't feel its heavy on resources. URL A has a list of more photos and data in it. What could be the possible cause for such an error? A: This happens when chrome tries to load a large number of images/resources in a short period of time.Have a look at this. Try disabling the chrome plugin adblock plus and try.Still it may take long time to load
{ "language": "en", "url": "https://stackoverflow.com/questions/52659586", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SwiftUI: Call a function of a programmatically created view I am trying to make a SwiftUI ScrollView scroll to a certain point in an abstracted view when a button is pressed in a view which is calling the abstracted view programmatically. Here is my code: struct AbstractedView: View { @Namespace var view2ID var body: some View { ScrollView { VStack { View1() View2() .id(view2ID) View3() } } } func scrollToView2(_ proxy: ScrollViewProxy) { proxy.scrollTo(view2ID, anchor: .topTrailing) } } As you can see, when scrollToView2() is called (in a ScrollViewReader), the AbstractedView scrolls to view2ID. I am creating a number of AbstractedView's programmatically in a different View: struct HigherView: View { var numAbstractedViewsToMake: Int var body: some View { VStack { HStack { ForEach (0..<numAbstractedViewsToMake, id: \.self) { _ in AbstractedView() } } Text("button") .onTapGesture { /* call each AbstractedView.scrollToView2() } } } } If I stored these views in an array in a struct inside my HigherView with a ScrollViewReader for each AbstractedView would that work? I feel as though there has to be a nicer way to achieve this, I just have no clue how to do it. I am new to Swift so thank you for any help. P.S. I have heard about UIKit but I don't know anything about it, is this the right time to be using that? A: Using the comments from @Asperi and @jnpdx, I was able to come up with a more powerful solution than I needed: class ScrollToModel: ObservableObject { enum Action { case end case top } @Published var direction: Action? = nil } struct HigherView: View { @StateObject var vm = ScrollToModel() var numAbstractedViewsToMake: Int var body: some View { VStack { HStack { Button(action: { vm.direction = .top }) { // < here Image(systemName: "arrow.up.to.line") .padding(.horizontal) } Button(action: { vm.direction = .end }) { // << here Image(systemName: "arrow.down.to.line") .padding(.horizontal) } } Divider() HStack { ForEach(0..<numAbstractedViewsToMake, id: \.self) { _ in ScrollToModelView(vm: vm) } } } } } struct AbstractedView: View { @ObservedObject var vm: ScrollToModel let items = (0..<200).map { $0 } // this is his demo var body: some View { VStack { ScrollViewReader { sp in ScrollView { LazyVStack { // this bit can be changed accordingly ForEach(items, id: \.self) { item in VStack(alignment: .leading) { Text("Item \(item)").id(item) Divider() }.frame(maxWidth: .infinity).padding(.horizontal) } }.onReceive(vm.$direction) { action in guard !items.isEmpty else { return } withAnimation { switch action { case .top: sp.scrollTo(items.first!, anchor: .top) case .end: sp.scrollTo(items.last!, anchor: .bottom) default: return } } } } } } } } Thank you both!
{ "language": "en", "url": "https://stackoverflow.com/questions/73054957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Where is the configuration file for application in Tibco administrator (version 5.3) I want to find the configuration file for application configurations in Tibco administrator. Then I can know all runtime configurations of my application. I tried to findout in the path /opt/sw/tibco/tra/domain/SOADEV/datafiles/[my app]_root but this configuration is out of date, and is not latest configuration. Here is example: The configuration file contains "ExchangeRate" item Tibco Admin doesn't display ExchangeRate item (in path Global/Vn) A: tibco/tra/domain/[ENV_NAME]/datafiles/[my app]_root is actually right place where all Global variables values and package code are stored after package deployment. I am guessing you are looking to the wrong package or something wrong with the deployment. All global variables should be stored in [my app]_root\defaultVars\defaultVars.substvar or subfolders [my app]_root\defaultVars\[folder_name]\defaultVars.substvar the variable can be deployment settable and service settable. Please see more details here https://community.tibco.com/questions/difference-between-global-variables-earservice-and-service-instance-levels Also there are several ways global variables can be overridden. Please see https://support.tibco.com/s/article/Tibco-KnowledgeArticle-Article-47854 1). In Designer -> Global Variables panel, click the pencil icon (Open Advanced Editor) at top right, select the global variable and right click ->  “Override Variable”. 2). Use the Project -> “Save as” option to save as a new project. Global variables will then be editable. 3). Go to Tester -> "Advanced" test settings with the "-p PATH/properties.cfg" argument, with PATH being the absolute path and properties the file that override global variables. 4).Change the variable in TIBCO administrator GUI during deployment. 5). Manually edit the bwengine.tra.
{ "language": "en", "url": "https://stackoverflow.com/questions/68552883", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: php for each sorting by category joomla k2 Hi I have this code from joomla k2 template <div id="itemListPrimary" class="clearfix"> <?php $thearray = $this->primary ;?> <?php foreach($thearray as $key=>$item): ?> <div class="itemContainer"> <?php $this->item=$item; echo $this->loadTemplate('item'); ?> </div> <?php endforeach; ?> </div> Now it is taking items from main category and sub categories and displaying items like this. item, item, item, item, I need it to take items from main and subcategories and display them like this: category1 item item category2 item item category3 item item and etc. How can I do this? uptade: The array is constructed like that or at least few lines of it Array ( [0] => stdClass Object ( [id] => 41 [title] => test2 [alias] => test2 [catid] => 8 [published] => 1 [introtext] => test2 [fulltext] => [video] => [gallery] => [extra_fields] => [] [extra_fields_search] => [created] => 2012-08-27 16:37:51 [created_by] => 62 [created_by_alias] => [checked_out] => 0 [checked_out_time] => 0000-00-00 00:00:00 [modified] => 0000-00-00 00:00:00 [modified_by] => 0 [publish_up] => 2012-08-27 16:37:51 [publish_down] => 0000-00-00 00:00:00 [trash] => 0 [access] and somethere in the bottom is the category name in it. A: There is only one method. You have to reorder your array foreach($thearray as $key=>$item) { $items[$item->catid][] = $item; } foreach($items AS $catid => $cat_items) { echo '<h3>'.$catid.'</h3>'; foreach($cat_items AS $item) echo $item->name.'<br>'; } Something like this.
{ "language": "en", "url": "https://stackoverflow.com/questions/11148163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How can I make the mock location provider to work I have a need to create a test application which can mock the location. On clicking button, the latitude and longitude values provided in text box need to be set as the mock location. I am trying to build this using simple way using fused location provider APIs Location mockLocation = new Location("flp"); mockLocation.setLatitude(12); mockLocation.setLongitude(82); mockLocation.setAccuracy(1.0f); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mockLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos()); } mockLocation.setTime(new Date().getTime()); Criteria criteria = new Criteria(); criteria.setAccuracy( Criteria.ACCURACY_FINE ); String provider = locationManager.getBestProvider( criteria, true ); if ( provider == null ) { Log.e( "", "No location provider found!" ); return; } // provider and LocationManager.GPS_PROVIDER are same - "gps" locationManager.setTestProviderLocation(LocationManager.GPS_PROVIDER, mockLocation); // --> I am getting exception here I gave all possible permissions in manifest file: ACCESS_COARSE_LOCATION ACCESS_FINE_LOCATION ALLOW_MOCK_LOCATIONS ACCESS_MOCK_LOCATION Also manually enabled developer options, application permissions, and mock location provider app in settings. I am getting except on setTestProviderLocation: java.lang.IllegalStateException: Could not execute method for android:onClick at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390) at android.view.View.performClick(View.java:6266) at android.view.View$PerformClick.run(View.java:24730) at android.os.Handler.handleCallback(Handler.java:793) at android.os.Handler.dispatchMessage(Handler.java:98) at android.os.Looper.loop(Looper.java:173) at android.app.ActivityThread.main(ActivityThread.java:6698) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:782) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385) ... 9 more Caused by: java.lang.IllegalArgumentException: Provider "gps" unknown at android.os.Parcel.readException(Parcel.java:1955) at android.os.Parcel.readException(Parcel.java:1897) at android.location.ILocationManager$Stub$Proxy.setTestProviderLocation(ILocationManager.java:1340) at android.location.LocationManager.setTestProviderLocation(LocationManager.java:1305) Any way to fix this? Thanks, raj A: Since Android 10 my fake location app has the same issue and the app is crashing with: java.lang.IllegalArgumentException: Provider "gps" unknown But on older Android versions same code is working. I tested it on 6,7,8 and 9. My temporary solution for it is to catch the exception (until I find a better way). The mock should still work. try { mLocationManager.removeTestProvider(getBestProvider()); } catch (IllegalArgumentException e) { // handle the error e.getMessage() } Druing debugging I can see the provider gps inside the locationManager list like mLocationManager.getProvider(getBestProvider())
{ "language": "en", "url": "https://stackoverflow.com/questions/55888539", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Content on HTML/CSS page moves when the 'Tab' key is pressed I've created a custom login page for my Salesforce Community which consists of some HTML and CSS (all within the Visualforce page), but when I use the tab key some content on the page shifts. From my research it seems to be from the content being larger than the container it is within, but what would be a fix for this? Having some of the content be slightly cut off is part of the style (look and feel) of the page so I'd rather not simply expose the content all the way if possible. /* **CSS within my Visualforce page** */ /* CSS Reset */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, button, form, fieldset, input, textarea { margin: 0; padding: 0; outline: 0; border: 0; background: transparent; vertical-align: baseline; font-size: 100%; } body { line-height: 1; } h1, h2, h3, h4, h5, h6 { font-weight: normal; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } /* remember to define focus styles! */ :focus { outline: 0; } /* remember to highlight inserts somehow! */ ins { text-decoration: none; } del { text-decoration: line-through; } /* tables still need 'cellspacing="0"' in the markup */ table { border-spacing: 0; border-collapse: collapse; } address, caption, cite, code, dfn, em, strong, var { font-weight: normal; font-style: normal; } caption, th { text-align: left; font-weight: normal; font-style: normal; } html { background-color: #3a3a3a; } body { min-height: 100%; height: 100%; background: url(http://subtlepatterns.subtlepatterns.netdna-cdn.com/patterns/navy_blue.png) repeat; font-weight: lighter; font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; -webkit-font-smoothing: subpixel-antialiased; } a { color: #b1c; text-decoration: none; } p { display: block; width: 300px; margin-left: -180px; margin-top: -5px; } p a { color: #a4a4a4; font-size: 10px; text-decoration: none; } p a:hover { color: #1d83cc; border-bottom: 1px solid gray } <!-- Hyperlink Color -->#warp { position: relative; margin: 100px auto 0; width: 400px; text-align: center; color: white; } form { display: block; width: 100%; height: 300px; } h1 { color: #b6b6b6; font-weight: bolder; font-size: 60px; } .admin { height: 250px; float: left; width: 200px; border-right: 1px solid #333333; text-align: left; left: 0; top: 0; transition: all 200ms ease-in 100ms; } .cms { height: 250px; top: 70px; left: -62px; float: right; width: 150px; text-align: right; transition: all 200ms ease-in 100ms; } .admin, .cms { position: relative; display: block; overflow: hidden; transform: rotate(30deg); } .cms h1 { margin-left: -10px; color: #838385; } .roti, .rota { position: relative; display: block; transform: rotate(-30deg); } .admin:hover h1, .cms:hover h1 { color: #1d83cc; } <!-- Header Hover Color -->.rota { margin-top: 80px; margin-left: 35px; } .roti { margin-top: 80px; margin-right: 55px; } input, button { margin: 4px; padding: 8px 6px; width: 350px; background: white; color: black; font-size: 10px; transition: all 1s ease-out; } .button { margin-left: -230px; background: #303030; color: white; text-align: right; cursor: pointer; transition: all 1s ease-out; } button:hover { background: #1d83cc; <!-- ???Color -->transition: all 0.3s ease-in; } input:hover { box-shadow: inset 0 0 5px rgba(29, 131, 204, 1) } <!-- Button Hover Color -->input:focus { background: gray; color: white } .up { top: 100px; left: -60px; } .down { top: -100px; left: 60px; } <!-- **HTML within my Visualforce page** --> <div id="warp"> <form action="" id="formu"> <div class="admin"> <div class="rota"> <h1>PORTAL</h1> <apex:inputtext styleClass="input" value="{!username}" html-placeholder="Username" /> <apex:inputsecret styleClass="input" value="{!password}" html-placeholder="Password" /> </div> </div> <div class="cms"> <div class="roti"> <h1>BW</h1> <apex:commandbutton styleClass="button" value="Login" action="{!doLogin}" /> <p> <apex:commandLink value="Forgot password?" action="{!forgotPassword}" /> </p> </div> </div> </form> </div>
{ "language": "en", "url": "https://stackoverflow.com/questions/68013060", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to show the value stored in an array in Objective-C I have stored data in an array from XML Parsing. In the array I have stored latitude and longitude of the start and end point. Now I want to show the value of lat and long in the table view's cell.text. How can I access this? What syntax do I use so that I show the value of the element stored in the array? When I print to console it shows that the array has 12 objects. The values stored in the array are: araystp= ( Step: 0x563f160, Step: 0x563f860, Step: 0x56400d0, Step: 0x56408e0, Step: 0x56410f0, Step: 0x5641990, Step: 0x5642290, Step: 0x5642ae0, Step: 0x56434a0, Step: 0x5643e80, Step: 0x56446f0, Sleg: 0x5623850 ) A: Following is the code to get stored value from your xml calss. for (int i = 0 ; i <[array count];i++) { XmlClass *class1 = (XmlClass*) [array objectAtIndex:i]; NSString *strLat = class1.latitude; NSString *strLong = class1.longitude; } A: suppose u have use array in XML file is listofPoint in which u have add your class's object.Now u synthesize a NSMutableArray in app delegate file. And where you are doing parsing event there after completion of parsing make copy of array listofPoint to appdelegate array. and in next class define object of class which you have add in listofPoint array. And use this syntax. yourclass *Object=[[yourclass alloc]init]; Object=[appDelegate.Array objectAtIndex:0]; NSLog(@"%f",Object.var); it will work. A: for (int i = 0 ; i <[array count];i++) { YourXmlClass *x = [array objectAtIndex:i] NSString *s = x.latitude; NSString *s1 = x.longitude; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7130545", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How Can Structure Notify Other Threads Correctly About An Event? I'm trying to write a threadsafe structure to keep key - value pairs and to automatically remove them after certain time delay. The problem is, that the container should notify other threads about deletion. I've also tried to use notifyAll() in a synchronized block, but the problem persists. import java.util.Objects; import java.util.concurrent.*; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.stream.Collectors; import java.util.stream.Stream; class Container <K extends Comparable<K>, V> { private ConcurrentHashMap <K, V> a; private final int delay = 2; private final Lock lock = new ReentrantLock(); private final Condition removed = lock.newCondition(); public Container() { a = new ConcurrentHashMap<>(); } public synchronized void put(K k, V o) { lock.lock(); a.put(k, o); new Thread(() -> { try { TimeUnit.SECONDS.sleep(delay); a.remove(k, o); removed.signalAll(); lock.unlock(); } catch (InterruptedException e){ e.printStackTrace(); } }).start(); } public V get(int k) { return a.get(k); } @Override public String toString() { return Stream.of(a) .filter(Objects::nonNull) .map(Object::toString) .collect(Collectors.joining(", ", "{", "}")); } } public class Main { public static void main(String [] args) throws InterruptedException { Container<Integer, Integer> c = new Container<>(); c.put(0, 10); System.out.println(c); c.put(1, 11); c.put(2, 12); TimeUnit.SECONDS.sleep(3); System.out.println(c); } } Program finishes with code 0 and prints expected values: first element and the empty structure. But in either way I got the IllegalMonitorStateException. Any thoughts, thanks. A: public synchronized void put(K k, V o) { a.put(k, o); new Thread(() -> { try { TimeUnit.SECONDS.sleep(delay); lock.lock(); a.remove(k, o); removed.signalAll(); lock.unlock(); } catch (InterruptedException e){ e.printStackTrace(); } }).start(); } Try this maybe. You re locking the lock and unlocking the lock in different threads. The thread that call theput method is the one using lock.lock() so it is the only one that can unlock it. The code inside the new Thread(....) belong to another thread so calling lock.unlock() there will not work. Also in the current code I don't see any use of the lock and condition, you can just remove all this (unless you plan on using it somewhere else we don't see), you can put and remove from a concurrent map with worrying about managing the access yourself. A: In order to wait or notify (await and signal if using Condition) the thread, which performs an action, must own the lock it's trying to wait or notify on. From your example: you put a lock in the main thread (lock.put()), then start a new thread. The new thread does not own the lock (it's still held by the main thread), but despite that you try to invoke signalAll() and get IllegalMonitorStateException. In order to fix the problem you should: 1. Release the lock the main thread holds when it's ready (you never release it at the moment). 2. Lock in the new thread first and only then call signalAll() 3. Release the lock in the new thread when you're ready. Do it in the finally clause of the try-catch block to guarantee that the lock gets released in case of an exception. Also a few moments: - in order to be notified a thread must be waiting for notification. - synchronization on the put() method is redundant, since you're already using a ReentrantLock inside. A: We have a few things to look at here: * *lock *removed which is a condition created using lock Your main thread acquires a lock on lock in the put method. However it never releases the lock; instead it creates a new Thread that calls removed.signalAll(). However this new thread does not hold a lock lock which would be required to do this. I think what you need to do is to make sure that every thread that locks lock also unlocks it and that every thread calling signalAll also has a lock. public synchronized void put(K k, V o) { a.put(k, o); new Thread(() -> { try { TimeUnit.SECONDS.sleep(delay); lock.lock(); // get control over lock here a.remove(k, o); removed.signalAll(); lock.unlock(); } catch (InterruptedException e) { e.printStackTrace(); } }).start(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/57140379", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I set didEndOnExit in code rather than Interface Builder? Possible Duplicate: Assign a method for didEndOnExit event of UITextField How can I add didEndOnExit to a UITextField in pure code rather than IB? Thanks! A: Assuming your talking about textFieldDidEndEditing: or textFieldShouldReturn:. You would implement the method in your view controller, and set the text fields delegate to self like so: - (void)viewDidLoad { [super viewDidLoad]; // .... myTextField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 50, 25)]; myTextField.delegate = self; [self.view addSubview:myTextField]; } - (void)textFieldDidEndEditing:(UITextField *)textField { if (textField == myTextField) { // Do stuff... } } - (BOOL)textFieldShouldReturn:(UITextField *)textField { if (textField == myTextField) { return YES; } return NO; } - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if ((myTextField.text.length + string.length) < 5) { return YES; } return NO; } Then, in your header file in the @interface you can specify that you are a UITextFieldDelegate like this: @interface MyViewController : UIViewController <UITextFieldDelegate> { // .... UITextField *myTextField; // .... } // Optionally, to make myTextField a property: @property (nonatomic, retain) UITextField *myTextField; @end UITextField Reference UITextFieldDelegate Reference Edit (as per your comment, this should work): - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if ((myTextField.text.length + string.length) < 5) { return YES; } return NO; }
{ "language": "en", "url": "https://stackoverflow.com/questions/7771985", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Pipe output of cat to cURL to download a list of files I have a list URLs in a file called urls.txt. Each line contains 1 URL. I want to download all of the files at once using cURL. I can't seem to get the right one-liner down. I tried: $ cat urls.txt | xargs -0 curl -O But that only gives me the last file in the list. A: xargs -P 10 | curl GNU xargs -P can run multiple curl processes in parallel. E.g. to run 10 processes: xargs -P 10 -n 1 curl -O < urls.txt This will speed up download 10x if your maximum download speed if not reached and if the server does not throttle IPs, which is the most common scenario. Just don't set -P too high or your RAM may be overwhelmed. GNU parallel can achieve similar results. The downside of those methods is that they don't use a single connection for all files, which what curl does if you pass multiple URLs to it at once as in: curl -O out1.txt http://exmple.com/1 -O out2.txt http://exmple.com/2 as mentioned at https://serverfault.com/questions/199434/how-do-i-make-curl-use-keepalive-from-the-command-line Maybe combining both methods would give the best results? But I imagine that parallelization is more important than keeping the connection alive. See also: Parallel download using Curl command line utility A: Here is how I do it on a Mac (OSX), but it should work equally well on other systems: What you need is a text file that contains your links for curl like so: http://www.site1.com/subdirectory/file1-[01-15].jpg http://www.site1.com/subdirectory/file2-[01-15].jpg . . http://www.site1.com/subdirectory/file3287-[01-15].jpg In this hypothetical case, the text file has 3287 lines and each line is coding for 15 pictures. Let's say we save these links in a text file called testcurl.txt on the top level (/) of our hard drive. Now we have to go into the terminal and enter the following command in the bash shell: for i in "`cat /testcurl.txt`" ; do curl -O "$i" ; done Make sure you are using back ticks (`) Also make sure the flag (-O) is a capital O and NOT a zero with the -O flag, the original filename will be taken Happy downloading! A: As others have rightly mentioned: -cat urls.txt | xargs -0 curl -O +cat urls.txt | xargs -n1 curl -O However, this paradigm is a very bad idea, especially if all of your URLs come from the same server -- you're not only going to be spawning another curl instance, but will also be establishing a new TCP connection for each request, which is highly inefficient, and even more so with the now ubiquitous https. Please use this instead: -cat urls.txt | xargs -n1 curl -O +cat urls.txt | wget -i/dev/fd/0 Or, even simpler: -cat urls.txt | wget -i/dev/fd/0 +wget -i/dev/fd/0 < urls.txt Simplest yet: -wget -i/dev/fd/0 < urls.txt +wget -iurls.txt A: A very simple solution would be the following: If you have a file 'file.txt' like url="http://www.google.de" url="http://www.yahoo.de" url="http://www.bing.de" Then you can use curl and simply do curl -K file.txt And curl will call all Urls contained in your file.txt! So if you have control over your input-file-format, maybe this is the simplest solution for you! A: Or you could just do this: cat urls.txt | xargs curl -O You only need to use the -I parameter when you want to insert the cat output in the middle of a command. A: This works for me: $ xargs -n 1 curl -O < urls.txt I'm in FreeBSD. Your xargs may work differently. Note that this runs sequential curls, which you may view as unnecessarily heavy. If you'd like to save some of that overhead, the following may work in bash: $ mapfile -t urls < urls.txt $ curl ${urls[@]/#/-O } This saves your URL list to an array, then expands the array with options to curl to cause targets to be downloaded. The curl command can take multiple URLs and fetch all of them, recycling the existing connection (HTTP/1.1), but it needs the -O option before each one in order to download and save each target. Note that characters within some URLs ] may need to be escaped to avoid interacting with your shell. Or if you are using a POSIX shell rather than bash: $ curl $(printf ' -O %s' $(cat urls.txt)) This relies on printf's behaviour of repeating the format pattern to exhaust the list of data arguments; not all stand-alone printfs will do this. Note that this non-xargs method also may bump up against system limits for very large lists of URLs. Research ARG_MAX and MAX_ARG_STRLEN if this is a concern.
{ "language": "en", "url": "https://stackoverflow.com/questions/9865866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "88" }
Q: How to make make this code clearer? I am sorry if it is a simple problem for you.But i am really struggling with this problem In our application we have plenty of ajax calls in each and every page. We are using jQuery ajax. Presently what we are doing is When we get the result from like myresults, we are passing to a function populate where we are building the result. function populate(myresults) { var str='<table>'; for(var i in myresults){ str+='<tr>'; str+=myresults[i].name; str+='</tr>'; } str+='</table>'; $('#divId').html(str); } Not exactly we are building tables in all places. The code is working perfectly, but I think writing of code like this is not the right approach. How can I can beautify my code. I can use jQuery or javascript. A: You should try to look for TemplateEngine - it could allow to decrease code count and make it more clear. What Javascript Template Engines you recommend? A: You should run your code through a linting engine like JSLint or JSHint and you should familiarize yourself with good practice. Here's one way (of more than one possible solution) to optimize your code: function populate(myresults) { var table = $(document.createElement('table')); $(myresults).each(function (i) { var row = $(document.createElement('tr')), cell = $(document.createElement('td')).text(myresults[i].name); row.append(cell); table.append(row); }); $('#divId').append(table); } A: Maybe, creating a new DOM element more correct ? Like this: function populate(myresults) { var str= $('<table />)'; for(var i in myresults){ str.append($('<td />').text(myresults[i].name).appendTo($('<tr />'))); } $('#divId').empty().append(str); } A: You could do it this way: function populate(myResults) { var tab = $('<table />'); for(var i in myResults){ if (myResults.hasOwnProperty(i)) { var tr = $('<tr />'); tr.append($('<td /'>, {text: i.name})); tab.append(tr); } } $('#divId').append(tab); } Using a template engine as suggested by the others would be preferable as it's a better, more maintainable approach.
{ "language": "en", "url": "https://stackoverflow.com/questions/16277531", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to invalidate redis cache with mysql? I want to use redis as cache for mysql, and the main idea is: Query * *read from redis *if not exist, read from mysql, and add to redis cache Add * *write to mysql directly Update&Delete * *write to mysql *invalidate the cache of redis My question is: how to invalidate the cache? I know I can delete it, or set a expire time, is it a usual way, or are there any standard methods to invalidate the cache? Thanks! A: You would need a trigger to tell redis that mysql data has been updated. * *This can be a part of your code, whenever you save data to mysql, you invalidate the redis cache as well. *You can use streams like http://debezium.io/ to capture changes in the database, and take neccessary actions like invalidating cache.
{ "language": "en", "url": "https://stackoverflow.com/questions/47388755", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is the $_SESSION array not being changed? I am having trouble assigning a variable to an array within the $_SESSION array. It looks like it is assigning, but when I do a print_r at the end of the program the $_SESSION variable appears unchanged. Here is the code. <?php session_start(); print_r($_SESSION[cart_array]); $NewGroupName="NewGroupName"; foreach($_SESSION[cart_array] as $row) { if ($row['groupId'] == "26141"){ echo "The initial GroupName is" . $row['GroupName'] . "<br>"; echo "The GroupName should be " . $NewGroupName."<br>"; $row['GroupName'] = $NewGroupName; echo "The actual GroupName is " . $row['GroupName']."<br>"; } } print_r($_SESSION[cart_array]); ?> The first print_r: Array ( [0] => Array ( [groupId] => 26141 [GroupName] => 'Crystal Farm - Ten Yard Case Pack' [StylePatternColor] => A-CF-10 [Price] => 5.65 [StandardPutUp] => 320 [Discount] => 0 [DiscountText] => [StkUnit] => YDS [ListPrice] => 5.65 [Quantity] => 1 [PromiseDate] => 10/01/2017 [DoNotShipBefore] => 02-01-2017 [ColorName] => 32 Ten Yard Bolts [PatternName] => [SKUDescription] => [KitPerYardDiscount] => False [KitPerYardDiscountText] => False [Kit] => False ) [] => Array ( [DoNotShipBefore] => ) ) The assingment seems to work: The initial GroupName is'Crystal Farm - Ten Yard Case Pack' The GroupName should be NewGroupName The actual GroupName is NewGroupName But, the final print_r shows we have not changed the value of GroupName. Array ( [0] => Array ( [groupId] => 26141 [GroupName] => 'Crystal Farm - Ten Yard Case Pack' [StylePatternColor] => A-CF-10 [Price] => 5.65 [StandardPutUp] => 320 [Discount] => 0 [DiscountText] => [StkUnit] => YDS [ListPrice] => 5.65 [Quantity] => 1 [PromiseDate] => 10/01/2017 [DoNotShipBefore] => 02-01-2017 [ColorName] => 32 Ten Yard Bolts [PatternName] => [SKUDescription] => [KitPerYardDiscount] => False [KitPerYardDiscountText] => False [Kit] => False ) [] => Array ( [DoNotShipBefore] => ) ) Any help would be appreciated. A: You don't change $_SESSION anywhere in your code. The foreach just exposes a copy of each element. You could change it by using a reference &: foreach($_SESSION['cart_array'] as &$row) { Also, notice that quotes are required for string indexes $_SESSION['cart_array']. If you had error reporting on you would see a Notice for Undefined constant: cart_array. A: From php.net: In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference. <?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; } // $arr is now array(2, 4, 6, 8) unset($value); // break the reference with the last element ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/44853368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Kotlin delegate's ReadOnlyProperty with generic type value dose not cast correctly in getValue I am expecting to see the output black white with below code package delegate import kotlinx.coroutines.runBlocking import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty open class Color(private val name: String) { override fun toString(): String { return name } } class Black : Color("black") class White : Color("white") class ColorCollection { private val black = Black() private val white = White() val list = listOf(black, white) } class Palette { val black: Black by ColorDelegate() val white: White by ColorDelegate() val colorCollection = ColorCollection() } class ColorDelegate<T> : ReadOnlyProperty<Palette, T> { override fun getValue(thisRef: Palette, property: KProperty<*>): T { return thisRef.colorCollection.list.mapNotNull { it as? T }.first() } } fun main() = runBlocking { val palette = Palette() println(palette.black) println(palette.white) } However, I only get black output and then Exception in thread "main" java.lang.ClassCastException: delegate.Black cannot be cast to delegate.White. I found that with this line thisRef.colorCollection.list.mapNotNull { it as? T }, I am expecting it only returns the value in the list that can be safely cast to the generic type, otherwise return null. For example, when accessing black delegated property in Palette, I should only see 1 black element returned by thisRef.colorCollection.list.mapNotNull { it as? T },It actually returns two (black and white). it as? T somehow always works regardless of what T is. I also tried putting a breakpoint at that line, tried "abcdef" as T?, it also works, which I expect to see cast exception that String cannot be cast to Black... Is this a bug...? A: Remember that Type Erasure is a thing in Kotlin, so the runtime does not know what the T in it as? T, and hence cannot check the cast for you. Therefore, the cast always succeeds (and something else will fail later down the line). See also this post. IntelliJ should have given you an "unchecked cast" warning here. So rather than checking the type using T, you can check the type using the property argument: class ColorDelegate<T> { operator fun getValue(thisRef: Palette, property: KProperty<*>) = // assuming such an item always exists thisRef.colorCollection.list.first { property.returnType.classifier == it::class } as T } fun main() { val palette = Palette() println(palette.black) // prints "black" println(palette.white) // prints "white" } Here, I've checked that the class of the returnType of the property (i.e. the property on which you are putting the delegate) is equal to the list element's runtime class. You can also e.g. be more lenient and check isSubclassOf. Do note that this wouldn't find any element in the list if the property's type was another type parameter, rather than a class, e.g. class Palette<T> { ... val foo: T by ColorDelegate() ... } But alas, that's type erasure for you :( A: This is due to type erasure with generics. Casting to a generic type always succeeds because generic types are not known at runtime. This can cause a runtime exception elsewhere if the value is assigned to a variable of a concrete mismatched type or a function it doesn't have is called on it. Since casting to generic types is dangerous (it silently works, allowing for bugs that occur at a different place in code), there is a compiler warning when you do it like in your code. The warning says "unchecked cast" because the cast occurs without type-checking. When you cast to a concrete type, the runtime checks the type at the cast site and if there is a mismatch it immediately throws ClassCastException, or resolves to null in the case of a safe-cast as?. Info about type erasure in the Kotlin documentation
{ "language": "en", "url": "https://stackoverflow.com/questions/69688701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: python regex capturing array indicies and brackets this issue has me scratching my head. I have not yet been able to construct a regex which returns the captured groups I require. I've also been working with Pythex, and experimentation has not yet been successful. Example source string: 'token[0][1]' I'm interested in a regex which will capture each of the array offsets, including the square brackets in separate groups. e.g. g1 = '[0]', g2 = '[1]', for example. The closest I can get is something like this: r'(\[[\w]\])*' Of course, this does not work. Any tips would be appreciated. Thanks. A: Use r'(\[\d+\])' should capture what you want, like this: import re s = 'token[0][1]' g1, g2 = re.findall(r'(\[\d+\])', s) print g1, g2 [0] [1]
{ "language": "en", "url": "https://stackoverflow.com/questions/26982259", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert rows with unique numeric ID I have table dbo.Register with unique ID column. I need to insert many rows into this table with, but any with unique identifier, like: INSERT INTO dbo.Register (ID, Name, State, Comment) Select NEWID(), Name, State, Comment From dbo.OtherTable But NEWID() returns long string of characters: 2D0D098E-2FFE-428A-B4EF-950C89FFF83A, but i need unique integer ID. e.g next free ID in this table. Edit. I can't modify this table. I only need to insert rows into current structure. Sample Records: +--------+------------+--------------+------------+ | ID | Name | State | Comment | +--------+------------+--------------+------------+ | 153299 | Zapytania | Przyjeto | NieDotyczy | | 153300 | Zapytania | Przyjeto | NieDotyczy | | 153301 | Zapytania | Przyjeto | NieDotyczy | | 153302 | Zapytania | Przyjeto | NieDotyczy | | 153303 | Zapytania | Przyjeto | NieDotyczy | | 153304 | Dyspozycje | Zakonczono | NieDotyczy | | 153305 | Zapytania | DoRealizacji | NULL | | 153306 | Zapytania | Przyjeto | NieDotyczy | | 153307 | Zapytania | Przyjeto | NieDotyczy | | 153308 | Dyspozycje | Przyjeto | NieDotyczy | +--------+------------+--------------+------------+ Definition of ID column already is: [ID] [int] IDENTITY(1,1) NOT NULL, A: You can do this by doing like below DECLARE @ID INT; SELECT @ID=ISNULL(MAX(ID),0) FROM dbo.Register --Isnull to handle first record for the table INSERT INTO dbo.Register (ID, Name, State, Comment) Select ROW_NUMBER() OVER(ORDER BY(SELECT 1))+ @ID, Name, State, Comment From dbo.OtherTable Per the edit there is no need of specifying the column in Insert list. You can skip the column and do INSERT & SELECT. INSERT INTO dbo.Register ( Name, State, Comment) Select Name, State, Comment From dbo.OtherTable Better you need to look at IDENTITY (Property) (Transact-SQL) A: Run next script .... ALTER TABLE dbo.Register DROP column ID ALTER TABLE dbo.Register add ID int identitity (1, 1) INSERT INTO dbo.Register (Name, State, Comment) Select Name, State, Comment From dbo.OtherTable EDIT: With new info, just do INSERT INTO dbo.Register (Name, State, Comment) Select Name, State, Comment From dbo.OtherTable ID Column will take care of itself ... A: If you can't make ID an IDENTITY column which would be a much better idea, you could instead use a SEQUENCE. CREATE SEQUENCE [dbo].[RegisterId] START WITH 153309 INCREMENT BY 1; GO and then, INSERT [dbo].[Register] ( [ID], [Name], [State], [Comment] ) SELECT NEXT VALUE FOR [dbo].[RegisterId] [ID], [Name], [State], [Comment] FROM [dbo].[OtherTable]; alternatively, if you can't change the schema you could use a temporary table to make use of an IDENTITY column, DECLARE @maxId INT = SELECT MAX([ID]) + 1 FROM [dbo].[Register]; DECLARE @createTemp NVARCHAR(4000) = N' CREATE TABLE #TempRegister ( [ID] INT IDENTITY(' + CAST(@maxId, NVARCHAR(14)) + ', 1), [Name] NVARCHAR(?), [State] NVARCHAR(?), [Comment] NVARCHAR(?) );'; EXEC sp_executesql @createTemp; GO INSERT #TempRegister ( [Name], [State], [Comment] ) SELECT [Name], [State], [Comment] FROM [dbo].[OtherTable]; INSERT [dbo].[Register] SELECT [ID], [Name], [State], [Comment] FROM #TempRegister; DROP TABLE #TempRegister;
{ "language": "en", "url": "https://stackoverflow.com/questions/41823217", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding a project to Xcode Workspace like CocoaPods I like Xcode workspaces and CocoaPods. So I want to stick to them and their setup and want to create a workspace, containing other projects, like this structure: - MyApp.workspace |-- MyApp.project |-- Pods.project |-- AnotherApp.project Most of the posts about adding dependencies to existing projects suggests nesting them, like: - MyApp.workspace |-- MyApp.project |-- AnotherApp.project |-- Pods.project But, I'm not sure if this is the correct approach. I think I should put them to the same level as both Pods and AnotherApp provide libs/reusable codes to MyApp. Which one do you suggest and why? And also if you provide any walkthroughs or tutorials about the first setup I would be very appreciated, because most of them gives examples like the second one but without the workspace. A: I am not sure if I fully understand the question so please forgive if I miss something. I desired a similar setup, multiple projects in a workspace, but all managed by Cocoapods. I needed the projects to link to each other. My motive was promoting MVC separation, so I had an App project (view), a Controller project, a Model project. The shell of a project is here: https://github.com/premosystems/iOSMVCTemplate/tree/1.0/MVC-Example/iOS/MVCApp Here are the basic steps: * *Create your projects, and add a podspec to each one. (e.g. controller podspec like this one: https://github.com/premosystems/iOSMVCTemplate/blob/1.0/MVC-Example/iOS/MVCApp/Controller/ProximityController/ProximityController.podspec) *Add a Podfile that links all of the podspecs together. https://github.com/premosystems/iOSMVCTemplate/blob/1.0/MVC-Example/iOS/MVCApp/Podfile *And of course pod install :) Be sure to reference the podspecs you create in the Podfile using the :path=> development directive before they are referenced by any podspecs so cocoapods will know not to look in the public repository. I have been using this a month or so, and it works pretty well. Only drawback is that indexing and compile time take longer than I would like, and pod update is really slow. Before adding and new files, .h, .m to any podspecs you must run pod update. Best of luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/18624316", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: UIViewController isEditing - Property observer doesn't work I was trying to implement property observers on my custom UIViewController but I noticed it was not working with the isEditing property. Do you guys have an idea why? class MasterViewController: UIViewController { // MARK: - Properties override var isEditing: Bool { didSet { print("VC is editing") } } } A: According to the documentation for isEditing Use the setEditing(_:animated:) method as an action method to animate the transition of this state if the view is already displayed. And from setEditing(_:animated:) Subclasses that use an edit-done button must override this method to change their view to an editable state if isEditing is true and a non-editable state if it is false. This method should invoke super’s implementation before updating its view. TL;DR You'll want to override setEditing(_:animated:) instead. A: It's for those who can't find any example how setEditing works. SWIFT 5 : override func setEditing(_ editing: Bool, animated: Bool) { if yourTableView.isEditing == true { yourTableView.isEditing = false //change back } else { yourTableView.isEditing = true // activate editing editButtonItem.isSelected = true // select edit button } }
{ "language": "en", "url": "https://stackoverflow.com/questions/49801470", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Add extra fields via hook woocommerce_default_address_fields? We want to add extra fields to the billing and shipping addresses to the account of registered customers (users with Customer role). We also want the user to be able to edit those extra fields in their settings panel, under ”My Account” -> ”Addresses” -> ”Edit" I found a way to do this, namely to implement the hook woocommerce_default_address_fields, and append extra address fields there. When doing so I noticed the fields were saved to the user account, and showed up in the checkout. So this seems to work. Now I wonder if this is the best way to add extra address fields?
{ "language": "en", "url": "https://stackoverflow.com/questions/49289437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I make PHP think that the files are in a parent directory? As the title says, how can I make PHP think that the files are in a parent directory? For example, my file structure looks like this: - website - - css - - js - - images And I want PHP to think that the directory js is always in ../js (parent directory)? Can this be done with .htaccess? Thanks. A: You can place this rule in /website/js/.htaccess: RewriteEngine On RewriteBase /website/js/ RewriteRule ^(.*)$ /js/$1 [L] A: You can change the current directory to something like this: <?php // Get current directory $cur_dir = getcwd(); //change the dir chdir("../js"); //do something here //back to your main current dir if you have still something to do chdir($cur_dir); ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/25236414", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: VS Code doesn't process Erlang Makefile I'm working on an old erlang code that uses Makefiles to compile. The makefile defines some "include" paths: # Erlang include directories. HRL_INCLUDE_DIRS = \ ../include My module imports modules from that path and uses it: -include("logger.hrl"). VS Code doesn't seem to find this file (red squiggly line under the include statement and function calls.), because logger should have relative or absolute path. The Makefile does the magic behind the scenes but VS Code doesn't read it. How to configure VS Code to read the makefile? A: The question is where the red squiggly line is coming from. Are you using the erlang-ls extension? If so, you probably need to configure include_dirs in an erlang_ls.config file in the root of your project. include_dirs: - "path/to/include"
{ "language": "en", "url": "https://stackoverflow.com/questions/73318417", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do you specify a minimum required version with the Mozilla addon-sdk cfx tool? Building a traditional Firefox extension, you would set the minVersion field in the install.rdf. Since that is abstracted away by package.json and cfx, is there any way to set a minVersion? Motivation: Because of certain changes to behavior in the contextMenu API, my add-on only works as expected from a certain versions of the Addon-SDK and upwards. I'd like to enforce this constraint. A: From the Add-on SDK docs Changing minVersion and maxVersion Values
{ "language": "en", "url": "https://stackoverflow.com/questions/15290808", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to change data in vue-component In Vue component I have some data that comes from a localStorage. if (localStorage.getItem("user") !== null) { const obj_user = localStorage.getItem('user'); var user = JSON.parse(obj_user); } else { user = null; } return { user } After in this component I have to check this data. I do it like this <li v-if="!user"><a href="/login">Login</a></li> <li v-if="user"> <a href="#"><span>{{user.name}}</span></a> </li> But the data does not change immediately, but only after the page is reloaded. Right after I login in on the page and redirected the user to another page, I still see the Login link. What am I doing wrong? Maybe there is some other way how to check and output data from the localstorage in component? Thank you in advance. A: It looks like the issue may be related to they way that your user variable is not a piece of reactive stateful data. There isn't quite enough code in your question for us to determine that for sure, but it looks like you are close to grasping the right way to do it in Vue. I think my solution would be something like this... export default { data() { return { user: null, } }, methods: { loadUser() { let user = null; if (localStorage.getItem("user")) { const obj_user = localStorage.getItem("user"); user = JSON.parse(obj_user); } this.user = user; } }, created() { this.loadUser(); } } I save the user in the data area so that the template will react to it when the value changes. The loadUser method is separated so that it can be called from different places, like from a user login event, however I'm making sure to call it from the component's created event. In reality, I would tend to put the user into a Vuex store and the loadUser method in an action so that it could be more globally available.
{ "language": "en", "url": "https://stackoverflow.com/questions/67987215", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: dropdown button not working on looping it in Angular I am working in Angular , * *Where I have created a tree based structure *on going down to tree structure there is a dropdown button name "Dropdown" *Problem is on clicking to "Dropdown" button dropdown is not working . Kindly check I am putting stackblitz link below for the code https://stackblitz.com/edit/angular-tree-un?file=src%2Fapp%2Fapp.component.html A: I made some changes please see whether it's as per your expected output or not. Ts file myFunction(value) { console.log(value); if (value == 1) { this.availableBtn = !this.availableBtn; } if (value == 2) { this.vaccanttoggle = !this.vaccanttoggle; } } HTML File <div id="myDropdown" *ngIf="availableBtn"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> seems like there is problem with class="dropdown-content". remove it and try.
{ "language": "en", "url": "https://stackoverflow.com/questions/59640911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Alter the Main WP_Comment_Query (comments at the bottom of posts)? My plugin retrieves a few comments at the beginning of the post through my own WP_Comment_Query. I save these IDs so I can then alter the WP_Comment_Query request and not fetch these IDs. When I use the pre_get_comments hook to hide these already-fetched IDs, they are also hidden from my first query at the beginning of each post. It defies the point. $this->loader->add_action( 'pre_get_comments', $plugin_public, 'hide_the_comments' ); public function hide_the_comments( $comment_query ) { $comment_query->query_vars['comment__not_in'] = $the_ids_to_hide; } How can we target the bottom request only, just like there is is_main_query() for the post loop? A: * *Create a private variable, eg private $count = 0; *Increment it each time your function is run *Don't hide the comments if it's the first time you're running it :) A: If you need to target the "main" WP_Query_Comments() within the comments_template() core function, then the comments_template_query_args filter is available since WordPress 4.5: $comment_args = apply_filters( 'comments_template_query_args', $comment_args ); $comment_query = new WP_Comment_Query( $comment_args ); See ticket #34442 for more info and a simple example here.
{ "language": "en", "url": "https://stackoverflow.com/questions/37097405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error with jekyll-sitemap when run rake generate to user jekyll with octopuses I am building a blog with octopuses and Jekyll on GitHub with Mac OSX and I followed every step on the octopuses website. Error with sitemap occurred when I run rake generate. ## Generating Site with Jekyll identical source/stylesheets/screen.css Configuration file: /Users/WangWei/Documents/GitHubPage/octopress/_config.yml Source: source Destination: public Generating... Error reading file /Library/Ruby/Gems/2.0.0/gems/jekyll-sitemap-0.6.1/lib/sitemap.xml: No such file or directory - /Users/WangWei/Documents/GitHubPage/octopress/source/Library/Ruby/Gems/2.0.0/gems/jekyll-sitemap-0.6.1/lib/sitemap.xml Any one can help? A: This is a bug of jekyll-sitemap and it has already been fixed. You can upgrade jekyll-sitemap to v0.6.2 and everything will be ok. https://github.com/jekyll/jekyll-sitemap/issues/54
{ "language": "en", "url": "https://stackoverflow.com/questions/26797789", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: curl https inside docker return: unable to get local issuer certificate I have a problem with cURL inside docker container jenkins-slave, when execute curl inside container get this error: curl https://mytool.domain.com curl: (60) SSL certificate problem: unable to get local issuer certificate More details here: https://curl.haxx.se/docs/sslcerts.html  curl failed to verify the legitimacy of the server and therefore could not establish a secure connection to it. To learn more about this situation and how to fix it, please visit the web page mentioned above. * *I have installed ca-certificate trough package manager *added certificate.cer to /usr/local/share/ca-certificate *executed command "update-ca-certificates" I have tried to run curl with : curl --cert certificate.cer https://mytool.domain.com, but get same error whats wrong? NB: outside container ssl work and no error is retrived
{ "language": "en", "url": "https://stackoverflow.com/questions/75600706", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Walking Core Data graph to-many relationships always seems awkward, is there a better way? I'm able to get things working fine with Core Data and to achieve my desired results, but I always feel it very awkward when walking to-many relationships because NSSet is, for my typical purposes, fairly useless. An example is if I have obtained a NSManagedObject of Entity "Zoo" with attribute "nameOfZoo" and to-many relationship "animalCages", the to-many relationship pointing to Entity "AnimalCage" which has attribute "nameOfSpecies" and to-many relationship pointing to Entity "IndividualAnimal" Zoo [nameOfZoo] ->> AnimalCage [nameOfSpecies] ->> Animals So, getting the top level Zoo object, that's simple. But then I want to get the data for nameOfSpecies "Canus Lupus". The code I want to write is this: // Normal NSEntityRequest or whichever it is, I have no gripe with this NSManagedObject *zoo = ..the request to get the one Zoo..; // I want to get the object where the key "nameOfSpecies" is set to "CanusLupus" NSManagedObject *wolf = [[zoo animalCages] object:@"Canus Lupus" forKey:@"nameOfSpecies"]; Obviously, I can't obtain wolf in this manner. Instead, I have to write like 10 lines of code (feels like 100 lines of code) to first obtain the set, then set up a search predicate request, and declare an error variable, execute the request, then get an array of the results, then get the first element of that array.. and if I want to walk further down the tree, to find the animal named "Wolfy" for instance, then I have to do it all over again. Am I doing things correctly or am I foolishly an easier way? I guess I can put a category on NSSet, maybe I will, but I feel like there should be a built in better way. If not, why? A: If you have a data model like this: Zoo{ name:string animalCages<-->>AnimalCage.zoo } AnimalCage{ nameOfSpecies:string zoo<<-->Zoo.animalCages animals<-->>Animal.animalCage } Animal{ name:string animalCage<<-->AnimalCage.animals } The to find a specific AnimalCage by name of species for a given Zoo object: NSString *soughtSpecies=@"Canis Lupis"; // normally this variable would be passed in to the method NSPredicate *p=[NSPredicate predicateWithFormat:@"nameOfSpecies==%@", soughtSpecies]; NSSet *wolves=[[zoo animalCages] filteredSetUsingPredicate:p]; Or you can use objectPassingTest: if you like blocks. If you use custom NSManagedObject subclasses, then you get custom accessor methods and can use self.dot notation so the above would be: Zoo *zoo= // fetch the appropriate zoo object NSString *soughtSpecies=@"Canis Lupis"; NSPredicate *p=[NSPredicate predicateWithFormat:@"nameOfSpecies==%@", soughtSpecies]; NSSet *wolves=[zoo.animalCages filteredSetUsingPredicate:p]; If you know before hand that you are going to have to find cages a lot, you could wrap the above up in a method on your Zoo class e.g. @implementation Zoo //... other stuff -(AnimalCage *) cageForSpecieNamed:(NSString *) specieName{ NSPredicate *p=[NSPredicate predicateWithFormat:@"nameOfSpecies==%@", specieName]; NSSet *wolves=[self.animalCages filteredSetUsingPredicate:p]; return [wolves anyObject]; // assuming one cage per species } Objective-c is intentionally verbose because it was supposed to be "self documenting" and the editor written for the language at the beginning had autocomplete. So, if your used to a more expressive language it might seem you are doing a lot of work but logically you aren't.
{ "language": "en", "url": "https://stackoverflow.com/questions/6762253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to concatenate the data on one line instead of two? I spend a lot of time at the office manually combining latitudes and longitudes to paste into a program that locates our customers and sets up for repairs. As an example... I copy this from the customers information page: 43.481075 CPE LON -84.787613 I then manually modify it to look like: 43.481075 -84.787613 I'm attempting to come up with some code that will do this for me. the problem I'm encountering is, no matter what I try the latitude and longitude always end up on separate lines 43.481075 -84.787613 I've tried removing vblf,vbcrlf and vbnewline before combining the strings "lat" and "lon". I've tried using lat & lon, lat + lon, latlon = String.Concat(lat, " ", lon) and in my last attempt, I used stringbuilder to try and concatenate. It always gives both on separate lines. What am I missing? Here's my latest version: Imports System.Text.RegularExpressions Imports System.Text Public Class Form1 Public c As Integer Public lastlat As Integer Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click ' Copy string to format from clipboard Dim strClipText As String = Clipboard.GetText ' Remove CPE LON from String Dim clean As String = strClipText.Replace("CPE LON", "") strClipText = clean strClipText = Replace(strClipText, vbLf, "") strClipText = Replace(strClipText, vbCrLf, "") strClipText = Replace(strClipText, vbNewLine, "") 'Get string length Dim length As Integer = strClipText.Length ' Find minus sign (Start of Longitude) For c1 = 1 To length - 1 Dim cchk As Char = strClipText(c1) If cchk = "-" Then c = c1 lastlat = c1 - 1 End If Next Dim lastc As Integer = length - 1 Dim cchk1 As String = strClipText(lastc) Dim lat As String = strClipText.Substring(0, lastlat) Dim lon As String Dim lon1 As String For curc = c To lastc lon1 = strClipText(c) lon = lon & lon1 c = c + 1 Next Dim builder As StringBuilder = New StringBuilder(lat) Dim llen As Integer = lat.Length builder.Insert(llen, lon) Dim latlon As String = builder.ToString() Clipboard.Clear() My.Computer.Clipboard.SetText(latlon) End Sub End Class A: It sounds like you're doing a lot of work manipulating the string that's causing you bugs. I think it would be easier to go with Regex to solve this. Try this code: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click ' Copy string to format from clipboard Dim strClipText As String = Clipboard.GetText Dim regex = New Regex("-{0,1}\d+(\.\d+|)") Dim latlon = String.Join(" ", regex.Matches(strClipText).OfType(Of Match)().Select(Function(m) m.Value)) Clipboard.Clear() My.Computer.Clipboard.SetText(latlon) End Sub A: Please notice that you're never replacing the carriage return. Don't forget that these constants turn into actual ASCII characters or combinations of ASCII characters * *vbCr == Chr(13) *vbLf == Chr(10) *vbCrLf == Chr(13) + Char(10) *vbNewLine == Chr(13) + Char(10) Now, in your code, you're doing this: strClipText = Replace(strClipText, vbLf, "") strClipText = Replace(strClipText, vbCrLf, "") strClipText = Replace(strClipText, vbNewLine, "") Which does these three things: * *Replace Chr(10) with an empty string *Replace Chr(13)+Char(10) with an empty string *Replace Chr(13)+Char(10) with an empty string Thus, you're never getting rid of the Chr(13) which will sometimes show as a new line. Because, even if the lines begin life as Char(13) + Char(10) (vbCrLf) when you replace vbLf with an empty string, you're breaking up the Char(13) + Char(10). Do something like this instead: strClipText = Replace(strClipText, vbCrLf, "") strClipText = Replace(strClipText, vbNewLine, "") strClipText = Replace(strClipText, vbCR, "") strClipText = Replace(strClipText, vbLf, "")
{ "language": "en", "url": "https://stackoverflow.com/questions/55320027", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Updating a joined table PHP MySQL In MySQL I know its possible to select from two tables that have been joined, but is it possible to update the same two tables using a join? Or will I have to update each table individually? A: Yes, e.g. UPDATE table1 t1 JOIN table2 t2 ON t2.id = t1.id -- Your keys. SET t1.column = '...', t2.column = '...' -- Your Updates WHERE ... -- Your conditional
{ "language": "en", "url": "https://stackoverflow.com/questions/6536812", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }