INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
C Shell Substring Compare My data looks like the following: 1xxxxxx file_name1 0xxxxxx file_name2 0xxxxxx file_name3 0xxxxxx file_name4 1xxxxxx file_name5 0xxxxxx file_name6 I would like to print only the file names with the first column starting with a '1'. That is, awk '{if($1 contains '1') then print $2}' file.txt However, I haven't a clue how to achieve the comparison syntax Perhaps a wildcard method might be possible? awk '{if($1 == "1"*) then print $2}' file.txt
**Try this:** awk '$1~/^1/{print $2}' file.txt You check the first column (`$1`) using a `match operator` (`~`) against pattern which looks for line starting with `1` (`/^1/`). If it is true, the action of printing second column takes place.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "linux, unix, awk, string comparison, csh" }
Server unable to find public folder in rails 3 production environment I'm using the latest rails 3 beta. The app works fine in development mode, but when I start the server in production mode via `rails server -e production`, it seems that the `public` folder can't be found. I get error messages like: ActionController::RoutingError (No route matches "/javascripts/jquery.js"): And similar messages for everything that should be in the `public` folder. I've tried this with both mongrel and webrick. I'd appreciate any help.
editing config/environments/production.rb and setting this line: config.serve_static_assets = true
stackexchange-stackoverflow
{ "answer_score": 60, "question_score": 30, "tags": "ruby on rails, production environment, ruby on rails 3" }
What is the difference between a prawn and a shrimp? Are prawns and shrimps the same thing or are they different? Basically, I think they're the same but one of my friends was arguing that they're similar but definitely not the same thing and they differ in size.
Biologically speaking, they are actually different species, but the names are so commonly used interchangeably as to completely muddle the distinctions. For example, spot prawns are actually shrimp while ridgeback shrimp are actually prawns. Prawns have claws on three of their five pairs of legs, shrimp have claws on two of their five pairs of legs. Their gills and body shape are different too. As far as cooking them goes, they are virtually identical and interchangeable. !shrimp prawn graphic Source
stackexchange-cooking
{ "answer_score": 75, "question_score": 66, "tags": "shrimp" }
How to integrate $\left(\frac{x^{n+1}}{n+1}\right)\left(\frac{1}{\sqrt{1-x^2}}\right)$ How to integrate $$\int \left(\frac{x^{n+1}}{n+1}\right)\left(\frac{1}{\sqrt{1-x^2}}\right)\,dx$$ Please help as possible... Thank you
Possible hint: You may follow the method Differential Binomial to find the proper substitution depending on what the value of $n$ is, Otherwise in all other cases for $n$, the integral of a differential binomial cannot be expressed by elementary functions. See this.
stackexchange-math
{ "answer_score": 2, "question_score": -2, "tags": "integration" }
Using Cortana's voice I'm actually creating a homemade assistant and the default speech synthetiser (in c#.aspx)) hasn't a nice voice. I would like to know if it is possible, and how, to use Cortana voice and pronunciation?
You can see how to tune Cortana's responses via this link: < And you can output text-to-speech (TTS) this way: < You can also change the Windows default voice to Cortana: < Does this help?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, speech, cortana, synthesizer" }
Discord music bot doesn't leave the server when the song ends I am working on a discord bot now named Amadeus. Amadeus plays music when he receives a given command... well... he will. Right now while I'm still working on him he only plays one song. While he connects to the voice channel and plays his song perfectly fine - he does not leave the voice channel once his song is concluded. For some reason, I guess it never detects that the song ends? Any help appreciated const connection = message.member.voice.channel.name; const channel = message.member.voice.channel; message.channel.send("Now playing Scythe OST in the " + connection + " channel."); channel.join().then(connection => { const dispatcher = connection.play('./Scythe Digital Edition - Soundtrack/01 Europa 1920.mp3'); dispatcher.on("end", end => { channel.leave() }); }) .catch(console.error);
As @Tenclea suggested, if you take a look at the Discord.js Documentation > Topics you can see that `dispatcher.on("finish", () => {})` is used. const channel = message.member.voice.channel; message.channel.send(`Now playing Scythe OST in the ${channel.name} channel.`); channel.join().then(connection => { const dispatcher = connection.play("./Scythe Digital Edition - Soundtrack/01 Europa 1920.mp3"); dispatcher.on("finish", () => channel.leave()); }).catch(e => console.log(e)) * * * `dispatcher.on("end", () => {})` will work on Discord JS version 11.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, arrays, discord, discord.js" }
Use Switch Block for 3 different values with Matlab Simulink ![model]( I have a model (depicted above) with a Switch which has 2 inputs y. One input y can take enumerated values "Green" or "Orange" and the other one can take enumerated values "Green" or "Red". I would like to know how with a switch (or another solution) can I have in output: Green + Green = Green Red + Green = Red Orange + Green = Orange Red + Orange = Red
Assign values as follows Green = 1 Orange = 2 Red = 3 Then all of your conditions are satisfied by using a `max` block, with the 2 inputs from your function blocks... Green + Green = Green % max( 1, 1 ) = 1 Red + Green = Red % max( 3, 1 ) = 3 Orange + Green = Orange % max( 2, 1 ) = 2 Red + Orange = Red % max( 3, 2 ) = 3
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "matlab, model, simulink" }
How to sort based on date-like substring? I have one column in a table in which there's some data like this: TBSPL/C/Mar12/634 KBSPL/C/jan14/735 TBDPL/C/aug13/834 SBSPL/C/july12/034 I need to sort the data based on the year in a `GridView`, but I'm getting the problem that the year is stuck in the middle of the value, for example `jan14` in `KBSPL/C/jan14/735`. Because of this, I am not able to sort it by the year. I tried this, but I'm not having any success: select * from emp order by date
You could just do: SELECT * FROM EMP ORDER BY LEFT(PARSENAME(REPLACE(DATE,'/','.'),2),2) Thanks.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "asp.net, sql server" }
Grab an object out of objects base on specific field value In my AngularJS this.device return `15` objects. Each object contain a `dataType` field and it has diff values on all 15 of them. I would like to grab/access only if `dataType == "PROTOCOL"` I would do something like this if I have access to **underscore.js** , but in this project, I don't have it. this.device.protocol = _.find(this.device, {dataType: "PROTOCOL"}); What is JS way to access this without having to do a for-loop?
You can use `Array#find`. > The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned. this.device.protocol = this.device.find(x => x.dataType === "PROTOCOL");
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript" }
Microsoft SSAS Average Calculation in Cube I m very new to cube development in SSAS. I m using Microsoft BIDS 2008. I have built a small cube, which is as mentioned below: India Pakistan GrandTotal Apr 6 10 16 May 5 6 11 I want to add a field called as average to be added beside Grand total India Pakistan GrandTotal Average Apr 6 10 16 8 May 5 6 11 5 Any inputs on this would be helpful. 5.5 in average is truncated to 5. Thanks !!!
Create a calculated member that divides current measure by the count of members in your measure group (normally a count measure is automatically created when you add a measure group). Truncation can be handled by the FORMAT_STRING property of that calculation or by using MDX functions. More info on calculated members: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "sql server, sql server 2008, ssas, mdx, bids" }
How to reduce the speed of RotateAnimation in Android How can I reduce the rotation speed of RotateAnimation instance. I'm using following code snippet to do animation. rotateAnimation = new RotateAnimation(currentRotation, currentRotation + (360 * 5), Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); currentRotation = (currentRotation + (360 * 5)); rotateAnimation.setDuration(10000); rotateAnimation.setInterpolator(new LinearInterpolator()); rotateAnimation.setRepeatCount(Animation.INFINITE); rotateAnimation.setRepeatMode(Animation.INFINITE); rotateAnimation.setFillEnabled(true); rotateAnimation.setFillAfter(true); rotateAnimation.setAnimationListener(animationInListener); recordRingImageView.startAnimation(rotateAnimation);
Increase its duration since speed = distance/time rotateAnimation.setDuration(30000);
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 3, "tags": "android, android animation, rotateanimation, linear interpolation" }
How can I add a newline after X number of characters in Perl? I was wondering how can I add a newline character (i.e. `/n` or `<br>`) after X number of characters. For example, let's say I have a perl variable $message ="aaaaabbbbbcccccdd". I want to add a newline character after every 5 characters to this variable. So when I print the variable in html it will display: aaaaa bbbbb ccccc dd What is the best way to do this? I was told to use substr or a count function, but I'm not sure how to go about it. Any help will be greatly appreciated. Thanks!
An even shorter option. $m = "aaaaabbbbbcccccdd"; $m =~ s/(.{1,5})/$1\n/gs; print $m; Outputs: aaaaa bbbbb ccccc dd Of course I think my version is the best of all presented up to now. ;)
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 6, "tags": "perl" }
.java.MyFirebaseMessagingService where to find? I want to handle pushing a push message according to the instructions < Got to the moment ![enter image description here]( But I don't have a MyFirebaseMessagingService file and I don't understand should I create it manually or should it appear when synchronizing dependencies? Tell me, did I miss something in the instructions or what do I need to do?
You need to create a class as `MyFirebaseMessagingService` and **extends** `FirebaseMessagingService` public class MyFirebaseMessagingService extends FirebaseMessagingService { //Called when a message is received. @Override public void onMessageReceived(RemoteMessage remoteMessage) {//code goes here} //Called when a new token for the default Firebase project is generated. @Override public void onNewToken(String token) {//code goes here} } **NOTE:** There can only be one service in each app that receives FCM messages. If multiple are declared in the Manifest then the first one will be chosen. You can read more on FirebaseMessagingService
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "android" }
Is there a cardinal $\kappa$ with uncountable cofinality such that $\kappa<\kappa^{\aleph_0}$? Is there a cardinal $\kappa$ with uncountable cofinality such that $\kappa<\kappa^{\aleph_0}$? The question is motivated by the observation that $\kappa< \kappa^{{\rm cf}\kappa}$ for any $\kappa$.
Assuming $\sf GCH$ then the answer is no, almost trivially. Since in that case $\kappa^{<\operatorname{cf}(\kappa)}=\kappa$ for every cardinal. If $\sf CH$ is false, then $\aleph_1$ is an example; it is possible that $\sf GCH$ is false, but only $2^{\aleph_1}=\aleph_3$ is an example, in which case, despite the failure of $\sf GCH$, the statement is true. And it is possible that the counterexamples are of this flavor, and they occur on a much later stage (e.g. $\aleph_{\omega_1+\omega}^{\aleph_0}=\aleph_{\omega_1+\omega+3}$ in which case $\aleph_{\omega_1+\omega+2}$ is an example as well). * * * So from $\sf ZFC$ this is neither provable nor disprovable, and will depend a lot on additional assumptions.
stackexchange-math
{ "answer_score": 4, "question_score": 3, "tags": "set theory, cardinals" }
Skip checkout process in Shopify I have Shopify website. I don't want the checkout process. Instead of that in cart page, I want to capture the cart record and customer address, when the person click the place order button in cart page. I don't have worked much things in Shopify.
You're going to need to create a private app with permissions to the store's Shopify Admin API to handle that logic. Also, in the cart template, you're going to have to disable the cart form altogether to prevent going to the checkout gateway and use JavaScript to submit the route form's information to the handler of your private app where it will process the cart record and customer information and then store it in a local data store.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "shopify, checkout" }
Javascript Return HTML and css content as a string but not the javascript is there a way of getting all the content of the page HTML , CSS , but exclude all the java script functions and script src? var htmlPage = $("html").html(); console.log(htmlPage); I know that will give me all of it. but I need to exclude the JS from the results
**EDIT:** fixed the regex (non-greedy version) You can try this: var htmlPage = $("html").html().replace(/<script[\s\S]*?<\/script>/mig, ""); The regular expression should match all `<script> ... </script>` tags and replace them with nothing. * * * BTW this is kind of a lucky shot because the regex itself requires the ending `</script>` to be escaped with a `\` backslash like this: `<\/script>`. This escape character is why the regex doesn't match itself, which would cause it to fail. So, it works because by escaping it correctly it isn't self-similar anymore.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, jquery, innerhtml" }
I want to get a file with endingstring.json in batch file Want to get batch file having the extension or with starting string "xyz". And want to create variable of that file so i can use that variable. set /p pathName=Enter The Value:%=% @echo %pathName% if exist {%pathName%\*.json} ( echo "gaurav" ) else ( echo "not exist" ) python dtz/manage.py loaddata %pathName%\*.json pause It is unable to find *.json
Try this: @echo off set /p pathName=Enter The Value: for /R %pathName% %%f in (*.json) do ( python dtz/manage.py loaddata "%%f" ) This will execute the python script for every json file in the input folder.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "batch file" }
XHTML Markup Validation i have my site [here][link removed] when i run it through validator, i get several errors regarding the: <embed src="inception/inception.mov" width="620" height="274" autoplay="false" controller="true" pluginspage=" if i keep the `<object>` and drop the `<embed>` then the code compiles fine. does this mean i no longer have to use the `<embed>` tag when im embedding multimedia in my page? thanks for your responses.
Yes, use `<object>` instead of `<embed>` and `<param name="xxx" ...>` insteand of embed's invalid attributes.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "xhtml, object, embed" }
Select (Select field from FieldTable) from Table I'm using MSQL 2005. I have 2 table.A and B ## Table A - ID DOVKOD - 1 KURSATIS ## Table B - ID KURALIS KURSATIS - 1 2,2522 2,2685 - 2 2,4758 2,4874 Table A has only 1 record When I execute `Select (Select DOVKOD from Table A) from Table B` I want to get same result as `Select KURSATIS from Table B` I am gonna use it in a view. How can I do that. Thanks..
You can simply use a `CASE` expression: SELECT CASE WHEN (SELECT DOVKOD FROM A) = 'KURSATIS' THEN KURSATIS ELSE KURALIS END FROM B SQL Fiddle Demo here
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql server, view" }
How to structure undergraduate level private lessons? I'm on a semester break and thankfully I was recently provided with an opportunity to hire any private teacher I like to learn even more math while on break. However, I don't really know how to approach it. What are we going to do? They'll start to explain material that I can read in the book? Solve homework together? I think it's very counter-productive because I can learn more from my mistakes. Or should I come up with questions like "Could you explain why we use open sets in differential calculus?". But I can just google them and get the answer I need. At the same time I really want to use this possibility since I was offered it. I don't want the opportunity go to waste and at the same time I feel like mathematics is a one man road. Maybe someone can provide me with an option on how to use the opportunity without being bored or counter-productive.
I agree that you need to do a lot of the heavy lifting. Furthermore, I would try to use texts that are suitable for self-study, basically always. Feel like the teacher-salary-justifiers try to push books that need an instructor more. I.e. even with a paid teacher, I think you should pedagogically optimized materials. All that said, I do think a tutor can benefit you by challenging your knowledge with drill and interrogation. Something like how tutorials work in Oxford or Cambridge or whatever. You can also, keep a notebook for your self studying and just write questions in the back to be discussed with the tutor. It will probably end up being more time efficient and accurate and interactive than SE questioning. You can plow through several in a session at once. (Also pretty much how you should use office hours.)
stackexchange-matheducators
{ "answer_score": 3, "question_score": 7, "tags": "self learning, private lessons" }
Using style rather than JSX property in react-native In React-Native 0.62.2, the proper syntax for setting resizeMode seems to be: <Image style={{width: 20, height: 20}} resizeMode="contain" /> However, I accidentally did the following: <Image style={{width: 20, height: 20, resizeMode: 'contain'}} /> and it also sets the resizeMode to contain the image. Why are both of these methods working? Are both methods equally valid? Can the same be done with other JSX properties?
Both ways are possible. If you have a look into the code (line 112), you'll see the following: const resizeMode = props.resizeMode || style.resizeMode || 'cover'; > Can the same be done with other JSX properties? No, this is clearly an exception. There was a lot of confusion going on, that's why the developers made both things possible.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "react native, jsx" }
Creating Direct Limits and Inverse Limits using Tikz I am trying to make something that looks like !enter image description here I am trying to go from here (works): \begin{tikzcd} A \arrow{r}\arrow{rd} &B \arrow{d}\arrow[leftarrow]{r} &C \arrow{ld}\\ &D \end{tikzcd} to here (doesn't work): \begin{tikzcd} A \arrow{r}\arrow{rd} \arrow{rdd} &B \arrow{d}\arrow[leftarrow]{r} &C \arrow{ld} \arrow{ldd} \\ &D &E\\ \end{tikzcd} I try many combinations but don't see how the tikz@x-y-z values work. Any help is appreciated. Thanks, Brian
You have to use three columns. \documentclass{article} \usepackage{tikz-cd} \begin{document} \[ \begin{tikzcd}[row sep=4em] X_{i} \arrow[rr,"f_{ij}"] \arrow[dr,"\phi_{i}"] \arrow[ddr,swap,end anchor={[xshift=0.2em]north west},"\psi_{i}"] && X_{j} \arrow[dl,swap,"\phi_{j}"] \arrow[ddl,end anchor={[xshift=-0.2em]north east},"\psi_{j}"] \\ & X \arrow[d,"u"] \\ & Y \end{tikzcd} \] \end{document} The `end anchor` are just to avoid the arrow ends to be too near to each other. !enter image description here
stackexchange-tex
{ "answer_score": 3, "question_score": 3, "tags": "diagrams, tikz cd" }
Does ArcMap have a Pan To Layer command? In an Attribute Table, I am able to choose Pan to Feature (rather than Zoom to Feature) to refocus the map without changing the zoom level. Is there a similar Pan to Layer option (and/or shortcut key) when in the Table of Contents, to match the Zoom to Layer? (The workaround is, obviously, Zoom to Layer and then reset the scale -- I'm just looking for a simpler way.)
The python addin button is actually simpler than I first thought. Just highlight a layer in the TOC and the button will pan to it. import arcpy, pythonaddins class ButtonClass1(object): """Implementation for pantolayer_addin.button (Button)""" def __init__(self): self.enabled = True self.checked = False def onClick(self): try: lyr = pythonaddins.GetSelectedTOCLayerOrDataFrame() mxd = arcpy.mapping.MapDocument("current") df = arcpy.mapping.ListDataFrames(mxd)[0] df.panToExtent(lyr.getExtent()) arcpy.RefreshActiveView() del lyr, mxd, df except: pass If you wanted, you could introduce code to ensure that disables the button when no layer in TOC is selected or does nothing when a data frame is selected.
stackexchange-gis
{ "answer_score": 9, "question_score": 2, "tags": "arcgis desktop, arcgis 10.1, pan" }
Why normalsize doesn't work in subcaption? Why `font=normalsize` doesn't work in subcaption? Example: \documentclass{extreport} \usepackage[utf8]{inputenc} \usepackage{caption} \usepackage{subcaption} \begin{document} \begin{table} \centering \caption{Main caption} \begin{subtable}[t]{\linewidth} \centering \captionsetup{font=normalsize} \caption*{Subcaption} \begin{tabular}{|l|l|} \hline 0 & 0 \\ \hline -1 & 1 \\ \hline \end{tabular} \end{subtable} \end{table} \end{document} ![subcaption example](
The standard setup for `subcaption` is `size=smaller`, which overrides the meaning of `\normalsize`. Use `size=normal`. But you probably want a global setup. \documentclass{report} \usepackage[utf8]{inputenc} \usepackage{caption} \usepackage{subcaption} \begin{document} \begin{table} \centering \captionsetup{justification=raggedleft, singlelinecheck=false} \caption{Main caption} \begin{subtable}[t]{\linewidth} \centering \captionsetup{justification=centering,size=normal} \caption*{Subcaption} \begin{tabular}{|l|l|} \hline 0 & 0 \\ \hline -1 & 1 \\ \hline \end{tabular} \end{subtable} \end{table} \end{document} ![enter image description here](
stackexchange-tex
{ "answer_score": 1, "question_score": 1, "tags": "tables, xetex, subcaption" }
Max line length for u-boot setenv? I have a line in my u-boot script that looks like: # set default Linux kernel boot parameters setenv bootargs console=ttyPS0,115200 root=/dev/mmcblk0p2 ro rootfstype=ext4 earlyprintk rootwait uio_pdrv_genirq.of_id="generic-uio" fsck.mode=force fsck.repair=yes What is the maximum line length to set a u-boot variable with setenv? I have seen long lines quoted before, and I would like to know what is the best practice.
This question was answered on StackOverflow, but is applicable here --- What is the maximum byte size for 1 U-Boot environment variable?, namely Tom Rini's answer here, which says: > It depends slightly on what you're doing. The overall environment is limited to CONFIG_ENV_SIZE. The amount of text you can input at a given time is CONFIG_SYS_CBSIZE.
stackexchange-unix
{ "answer_score": 1, "question_score": 0, "tags": "shell script, u boot" }
drawtext ffmpeg 'Unable to parse graph description substring' hi im trying to add text to live video stream but i keep getting error with my command, i already tried `-filter_complex` but no success `ffmpeg -loop 1 -i img1.jpg -vf 'pad=ceil(iw/2)*2:ceil(ih/2)*2:[0:v]drawtext='text=hello:fontsize=90:x=20:y=20:[email protected]'' -vcodec libx264 -vprofile baseline -x264opts keyint=40 -acodec aac -strict -2 -f flv rtmp://localhost/hls/test -y -stats -report` the error i get is `Unable to parse graph description substring: "drawtext=text=freedome:fontsize=90:x=20:y=20:[email protected]"`
For simple filterchains, where one filter operates upon the output of an earlier filter, no input pads (like `[0:v]`) should be used. Also, there is an errant colon at the end of the pad filter. It should be a comma instead, so -vf 'pad=ceil(iw/2)*2:ceil(ih/2)*2,drawtext=text="hello":fontsize=90:x=20:y=20:[email protected]' In drawtext, you may need to specify a font if fontconfig is not available on your system.
stackexchange-avp
{ "answer_score": 0, "question_score": 0, "tags": "ffmpeg" }
What's the best way to fix Pixel Aspect Ratio (PAR) issues on DirectShow? I am using a DirectShow filtergraph to grab frames from videos. The current implementation follows this graph: SourceFilter->SampleGrabber->NullRenderer This works most of the time to extract images frame by frame for further processing. However I encountered issues with some videos that do not have a PAR of 1:1. These images occur stretched in my processing steps. The only way to fix this I have found for now is to use a VMR9 renderer in windowless mode that uses GetCurrentImage() to extract a bitmap with the correct aspect ratio. But this method is not very useful for continuous grabbing of thousands of frames. My question now is: what is the best way to fix this problem? Has anyone run into this issue as well?
Sample Grabber gets you frames with original pixels. It is not exactly a problem if there is aspect ratio attached and the pixels are not "square pixels". To convert to square pixels you simply need to stretch the image respectively. It would be easier for you to do this scale step outside of DirectShow pipeline, and you have all data you need: pixels and original media type. You can calculate the corresponding resolution with square pixels and resample the picture.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++, windows, directshow, samplegrabber" }
How to reset your database in visual studio 2010 I want to wipe out all the data in the rows in the tables that I have, how do i do it?.. I want to completely delete them. I have 4 tables, and i prefer to delete/ reset them altogether.. ``
This article may help you. It uses the built in sp_MSForEachTable to check/remove constraints and then truncate the data
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "asp.net, visual studio 2010" }
Running java.exe from Windows cmd.exe I want to run `java -jar` from the JDK directory on my system: D:\Users\djpastis\Downloads\fmw_12.2.1.4.0_wls_Disk1_1of1>C:\Program Files\Java\jdk1.8.0_162\bin\java but I have this error, even the path is OK 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
Paths containing special characters, such as a SPACE, must be quoted. Microsoft put a SPACE characters in there for you. :-) The only reliable, safe way is to always quote paths. "%ProgramFiles%\Java\jdk1.8.0_162\bin\java.exe"
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "java, windows, cmd" }
Where is Customizer related data stored is the database? How would I go about finding if a image (with a certain URL) is used stored in the Customizer data?
Theme mods are stored in the options table, one field per theme. Option name is `theme_mods_themename`, for instance `theme_mods_twentyfifteen`.
stackexchange-wordpress
{ "answer_score": 28, "question_score": 17, "tags": "theme customizer" }
Convert txt file to Dictionary in Python I have a txt file that contain the following: Monday, 56 Tuesday, 89 Wednesday, 57 Monday, 34 Tuesday, 31 Wednesday, 99 I need it to be converted to a dictionary: {'Monday': [56 , 34], 'Tuesday': [89, 31], 'Wednesday': [57, 99]} Here is the code I have so far: d = {} with open("test.txt") as f: for line in f: (key, val) = line.split() d[str(key)] = val print(d) And here is the result I get from it: {'Monday,': '56'} {'Monday,': '56', 'Tuesday,': '89'} {'Monday,': '56', 'Tuesday,': '89', 'Wednesday,': '57'} {'Monday,': '34', 'Tuesday,': '89', 'Wednesday,': '57'} {'Monday,': '34', 'Tuesday,': '31', 'Wednesday,': '57'} {'Monday,': '34', 'Tuesday,': '31', 'Wednesday,': '99'} Can anyone help me with this? Thanks
d = {} with open("test.txt") as f: for line in f: (key, val) = line.split() if not key in d.keys(): d[key] = [] d[key].append(val) print (d) This should work.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python 3.x" }
DataTable to Array of arrays I have a `DataTable` which consists of dynamic rows: no | cid | wait | prio -------------------------------- 1 | 1234 | 0:57 | 0 2 | 54785 | 0:44 | 0 3 | 74125 | 0:22 | 0 I want to create an array of arrays from this, having information of each row in an individual array.
Although I applaud other users for answering your direct question regarding an array of array. I think you are making this more difficult than you need to. yourDataTable.Rows[rowIndex]["no"] is already an array containing all the values in your "no" column. yourDataTable.Rows[rowIndex]["cid"] is already an array containing all the values in your "cid" column. etc... etc.. You can access the data by either looping through the rows, or calling one directly in place of `rowIndex` as shown above, and assigning the value in the column to some other variable. If you _really_ want to get arrays of arrays (which you already have), then disregard this and refer to the other answers.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c#, arrays, datatable" }
How can give click functionality of html elements in asp.net I am facing little bit problem regarding asp, I am making grid by assigning template of li's and in these li's I have button tag. When clicking this button I want some functionality so how can attach event and give logic .aspx.cs file. Here is what I am doing:- Label1.Text += "<li style='text-align:center;'><img src='../../Images/thumbs/" + finfo.Name + "' /></br><button filePath='../../Images/thumbs/" + finfo.Name + "'>Delete</botton></li>"; You can see button tag so I want to attach click event and want to implementaion in aspx.cs file.
try using `HtmlGenericControl` and `Button` server side control. HtmlContainerControl Container = new HtmlGenericControl("li"); //set it's style etc //use button class and add it in Container Button b=new Button(); b.Click += new EventHandler(b_Click); //set it's property an on click event //add it to li; Container.Controls.Add(b); Label1.Controls.Add(container); protected void b_Click(object sender, EventArgs e) { //Your process you want to do on click. } Or better is to create a Method `Page-Method` or `service` or `http-generic-handler` and call it using java-script or jQuery.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, html, asp.net" }
Securing Jersey RESTful services with spring-security-core using jaxrs plugin I'm needing to implement some RESTful webservices for a client in a Grails app and I want to use the jaxrs plugin but I am having a heck of a time finding information on how to implement security that isn't realm based (tomcat-users.xml). I am using the spring-security-core plugin and I'd like to utilize it to authenticate against my webservices. How do I send credentials to the webservice and then authenticate those using spring security? Can someone point me in the right direction?
I found the following and used a modified version of the solution to solve my problem <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "grails, spring security, jersey, jax rs" }
Aplicación CRUD con JavaScript Estoy trabajando en una pequeña app que valide unos datos contra una BD, ahora bien tengo mi BD en MySQL y la vista realizada en HTML5, CSS y JavaScript para ciertas validaciones, me estaba preguntando, ¿ es posible que pudiera realizar desde JavaScript una conexión hacia una base de datos sin hacer uso de PHP o un webservice? Sé que JavaScript se ejecuta del lado del cliente, pero con PHP se puede realizar validaciones pero con otro lenguaje por ejemplo Java es posible?
Es posible pero nunca lo hagas del lado del cliente por cuestiones de seguridad. El servidor de tu base de datos no tiene que tener acceso nunca a internet, siempre tienes que explotarla desde un intermediario en otro servidor ya sea con PHP, JAVA, C#, etc y la cadena de conexión, pasword y usuario en archivos de configuración que no sean visibles en internet. Si estas mas acostumbrado a usar javascript puedes instalar Node.js en tu servidor y es practicamente un javascript del lado del server. ![introducir la descripción de la imagen aquí](
stackexchange-es_stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "java, javascript, crud" }
Should I worry of memory leaks using server sent events? Recently I found this technology: server sent events and I would like to use it with my backend code in **node.js** I wanted to know, if It can cause a memory leaks? Perhaps if it can open multiple connections to the same user? Or if `.close()` wasn't called?
Server sent events in Node definitely do not cause memory leaks. If you want to see an example of how to implement them I have written a two part blog post about exactly that. 1. Part 1 2. Part 2
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "node.js, memory leaks, server sent events" }
Is the round up of ample Q-divisor ample? Let $X$ be a smooth projective variety and $A$ an ample $\mathbb{Q}$-divisor on $X$. Is the round up $\ulcorner A\urcorner$ of $A$ ample? I think it's true. But I do not know how to arrange an argument.
This doesn't seem right. Let $\pi : X \to \mathbb P^2$ be the blow-up of $\mathbb P^2$ at a point, and let $A = L + 2/3 E$, where $E$ is the exceptional divisor, and $L$ is the strict transform of a line through the point. Take $H$ to be the pullback of a line in $\mathbb P^2$. Then $A$ is linearly equivalent to $(H-E)+2/3 E = H - 1/3 E$, which is ample. But the round-up of $A$ is $L+E$, linearly equivalent to $H$, which isn't ample.
stackexchange-mathoverflow_net_7z
{ "answer_score": 6, "question_score": 0, "tags": "ag.algebraic geometry" }
Getting all Classes from a Package Lets say I have a java package `commands` which contains classes that all inherit from `ICommand` can I get all of those classes somehow? I'm locking for something among the lines of: Package p = Package.getPackage("commands"); Class<ICommand>[] c = p.getAllPackagedClasses(); //not real Is something like that possible?
Here's a basic example, assuming that classes are not JAR-packaged: // Prepare. String packageName = "com.example.commands"; List<Class<ICommand>> commands = new ArrayList<Class<ICommand>>(); URL root = Thread.currentThread().getContextClassLoader().getResource(packageName.replace(".", "/")); // Filter .class files. File[] files = new File(root.getFile()).listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(".class"); } }); // Find classes implementing ICommand. for (File file : files) { String className = file.getName().replaceAll(".class$", ""); Class<?> cls = Class.forName(packageName + "." + className); if (ICommand.class.isAssignableFrom(cls)) { commands.add((Class<ICommand>) cls); } }
stackexchange-stackoverflow
{ "answer_score": 21, "question_score": 16, "tags": "java, reflection, package" }
jQuery Variable Not Accessible Outside of Function $(document).ready(function() { $.wordlist = []; $.get('../wordlist.txt', function(data){ $.wordlist = data.split('\n'); }); console.log($.wordlist); }); The `console.log($.wordlist)` consistently returns an empty array. The same `console.log` call in the `$.get()` function successfully returns the complete array. What am I doing wrong and how do I make this array globally accessible?
The `$.get` method is asynchronous. This means it is still executing when `console.log` is run. You need to place _all_ code which relies on the data returned by the request within the callback function: var wordlist = []; $.get('../wordlist.txt', function(data){ wordlist = data.split('\n'); console.log(wordlist); }); Also note that it's not a good idea to add your own variables to the jQuery (`$`) namespace.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, global variables" }
How can I convert .db to .xls? How can I convert .db to xls ? ı don't know what is it's type. Can anyone explain to me step by step?
You can download TrIDNet, which will analyze the .db file to find out specifically what kind of database it is. It's possible it could be SQLite, MS Access, etc. The interface is similar to below, but you should have some db related results when run on your specific file. From there, you should be able to determine what software needs to be used to extract the data from the .db file and convert it to an Excel spreadsheet. TrIDNet - File Identifier ![TrIDNet](
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "database, xls" }
AVPlayer play library video in view i want to play a video in a frame of a view, but the following code does not work. can you help me? MPMediaItem *song = [allVideos objectAtIndex:indexPath.row]; NSLog(@"%@",[song valueForProperty:MPMediaItemPropertyAssetURL]); NSURL *url = [song valueForProperty:MPMediaItemPropertyAssetURL]; AVPlayer *player = [[AVPlayer alloc] init]; AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil]; AVPlayerItem *playerItem = [[AVPlayerItem alloc] initWithAsset:avAsset]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem]; player = [[AVPlayer alloc]initWithPlayerItem:playerItem]; //[player seekToTime:kCMTimeZero]; [player play];
You need to use AVPlayerLayer, add this AVPlayerLayer *playerLayer=[AVPlayerLayer playerLayerWithPlayer:player]; [self.view.layer addSublayer:playerLayer]; to your code.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, video, avplayer, playback" }
NSDate Formatting I have a date string as follows: "Fri, 17 Jun 2011 19:20:51 PDT" which I need to parse into an `NSDate` format. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; [dateFormatter setDateFormat:@"EEE, d MM YYYY HH:mm:ss zzz"]; NSDate *date = [dateFormatter dateFromString:currentPubDate ]; [dateFormatter release]; The code doesn't appear to be working and I am not sure why. I have looked into the issue but searching through forums etc and can't seem to find an answer. I do believe it is an issue with the `dateFormatter`. Thanks for your help
You incorrectly specified your `setDateFormat` string. This is how you should have specified it: [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss zzz"]; `YYYY` is only used in the "Week date" format used for some industrial and commercial applications. It looks like this: `YYYY-Www-D` where 2011-W1-3 would equate to the third day of the first week of 2011. The Apple docs note that it is a common mistake to use `YYYY` instead of `yyyy`: Fixed Formats
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "ios, nsstring, nsdate, nsdateformatter" }
Android packaging error When I compile my Android Project I always get this Error: > Error generating final archive: duplicate entry: about.html But I can't find any about.html in my Project. Does anyone know how to solve the error?
Is it at all possible that you have an about.xml that is duplicated? Or maybe accidentally named about.html somewhere? Or are you using any external jars? maybe there is in issue in one of those?
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "java, android" }
SQLite SELECT not displaying in Ruby console? When I run this code: require 'sqlite3' db = SQLite3::Database.new ":memory:" db.execute 'CREATE TABLE foo (bar TEXT);' db.execute 'INSERT INTO foo VALUES ("baz");' db.execute 'SELECT * FROM foo WHERE bar="baz"' db.close I get nothing. Normally in SQLite when I run: create table foo (bar TEXT); insert into foo values ("baz"); select * from foo; I get: bar ---------- baz Why does this happen and how can I get the exact same result?
`SQLite3::Database#execute` method does not print the result. Print the record explicitly. require 'sqlite3' db = SQLite3::Database.new ":memory:" db.execute 'CREATE TABLE foo (bar TEXT);' db.execute 'INSERT INTO foo VALUES ("baz");' db.execute 'SELECT * FROM foo WHERE bar="baz"' do |row| # <---- p row # <---- end # <---- db.close
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "sql, ruby, sqlite" }
Error: identifier :"SHGetKnownFolderPath" is unidentified I am writing a Windows Store app with Visual Studio 2015 on Windows 10. My code is as follows: #define WINVER 0x0A00 #define _WIN32_WINNT 0x0A00 #include <Shlobj.h> ... HRESULT hr; hr= SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, NULL, &tempPath); I tried to adding above version and header files. still nothing changed. How can I fix this?
According to the documentation of the function, this function is available on the desktop only. > **Minimum supported client** Windows Vista [desktop apps only] You are writing a store app, and so the function is not available to you.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "c++, winapi" }
How to create a database from psql user (not linux user) I' ve studied some PostgreSQL. In the principle i' ve been teach to create a postgress's user with same name of my linux's user. Now i want to try to make an application, and for this reason i would like to create a new user associated to the database of the application. How to do that? I tried this: 1. sudo -u postgres psql postgres 2. postgres=# create user myuser with password 'myuserpassword' createdb; CREATE ROLE Then i try to access the database template1 with the user just created using: psql template1 myuser When i type `psql template1` and then tab, i don't get the user "myuser" and don't know why. Thanks for help
> When i type psql template1 and then tab, i don't get the user "myuser" and don't know why. It's bash programmable completion feature which is at play here. It appears that for `psql`, `tab` does not suggest a list of user names on the command line when the cursor is after a database name. If does produces that list however, when the cursor is after `-U`. It's not clear how it bothers you to create a database, though. Assuming you can get inside psql with `psql template1 myuser`, just issue the SQL command CREATE DATABASE dbname; If that psql invocation fails, it's probably because the policy of `pg_hba.conf` for Unix domain socket connection is `peer`. There will be an explicit error message saying so. In this case, use `psql -U username -h localhost -d template1` Another method is to create the database from a superuser account (typically `postgres`) just like you created the user, and leave its ownership this user (`OWNER` option of `CREATE DATABASE`).
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "linux, database, sql, postgresql" }
How secure is a MD5 hash of an 128bit key Apparently, for the Android KeyChain an encrypted master key is stored along the MD5 hash of the **un** encrypted Key. How secure is that? MD5 is known to have collisions, but I guess we can assume with an input space limited to 128bit values no collisions turn up? But still, given that there is no salt involved, isn't it possible for an powerful attacker to calculate rainbow tables and then instantly break every KeyChain an any Android device he gets his hands on? Why is the plain MD5 hash of the secret key used to check if the Pincode is valid?
Collisions are not useful in this case. You need a pre-image attack that can find the _correct_ input that was used to generate the hash. An alternate input that creates a collision is still not the correct key, and won't decrypt the data. Finding the correct 128-bit random input is not feasible, even with MD5.
stackexchange-security
{ "answer_score": 3, "question_score": 2, "tags": "android, md5, entropy" }
How do I view ALL blog posts in an RSS feed? I have a blog and its posts date back all the way to March of 2009. However, when I visit my feed url (it's feedburner), the oldest post that shows up on that page is one written in February of 2011. How do I view ALL posts on a blog with a feed url?
RSS feeds are usually just XML documents that are generated dynamically every time a reader requests them. They contain only as many recent posts as it is set by the tool you use. They do not contain all previous entries unless you specifically tell them to, should it be possible in the CMS you use. However, feed readers like Google Reader keep extensive archives of the feeds they have requested, so you may try to access the feed this way and check if Google Reader has archived it.
stackexchange-webmasters
{ "answer_score": 7, "question_score": 5, "tags": "rss, feeds, feedburner" }
Expected Value Biased Coin Suppose that there is a biased coin and we flip the coin until 2 of the most recent 3 flips are heads. Let $p$ be the probability that it is heads. Also, let $X$ be the random variable which represents the total flips. If the first 2 flips are heads, then $X=2$. How can we find the expected value of $X$?
This answer is for $p=\frac12$; you can work it out for general $p$ accordingly. * * * A non-terminal state is characterized by one of three combinations of the last two flips: `TH`, `HT`, `TT`, and the process effectively starts off in state `TT`. The expected numbers of total flips satisfy \begin{align} \def\n#1{n_{\textsf{#1}}} \n{HT}&=1+\frac12\n{TT}\;,\\\ \n{TH}&=1+\frac12\n{HT}\;,\\\ \n{TT}&=1+\frac12\left(\n{TH}+\n{TT}\right)\;. \end{align} Substituting the first equation into the second and then the second into the third yields $$ \n{TT}=1+\frac12\left(1+\frac12\left(1+\frac12\n{TT}\right)+\n{TT}\right)\;, $$ with solution $\n{TT}=\frac{14}3$.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "probability" }
How many ways can I arrange ROONEY KIM if R and K can't be next to each other? Please help. Me and my friend are on a debate on who is right. 1. How many ways can I arrange ROONEY KIM if R and K can't be next to each other? My friend said it's $9!/2! -2!(8!)= 181440$. I said it's $9!/2! - 8!/2!$. 2. How many ways can you arrange ARRANGED If N and D can't be together? Please help us resolve this conflict.
* $\frac{9!}{2!}$ would be the answer if the R&K rule did not apply, because of the two Os * The number of arrangements with R immediately followed by K would be $\frac{8!}{2!}$ treating RK as a single letter * The number of arrangements with K immediately followed by R would be $\frac{8!}{2!}$ treating KR as a single letter * So the number of arrangements if R and K can't be next to each other is $\frac{9!}{2!}- 2\frac{8!}{2!}$ (ARRANGEMENT does not have a D in it)
stackexchange-math
{ "answer_score": 5, "question_score": -1, "tags": "combinatorics" }
"select * into table" Will it work for inserting data into existing table I am trying to insert data from one of my existing table into another existing table. Is it possible to insert data into any existing table using `select * into` query. I think it can be done using union but in that case i need to record all data of my existing table into temporary table, then drop that table and finally than apply union to insert all records into same table eg. select * into #tblExisting from tblExisting drop table tblExisting select * into tblExisting from #tblExisting union tblActualData Here tblExisting is the table where I actually want to store all data tblActualData is the table from where data is to be appended to tblExisting. **Is it right method. Do we have some other alternative ?**
You should try INSERT INTO ExistingTable (Columns,..) SELECT Columns,... FROM OtherTable Have a look at INSERT.aspx) and SQL SERVER – Insert Data From One Table to Another Table – INSERT INTO SELECT – SELECT INTO TABLE
stackexchange-stackoverflow
{ "answer_score": 27, "question_score": 18, "tags": "sql, sql server, database, sql server 2005, tsql" }
jquery-select2 send values to server as CSV string Is it possible to send as one CSV-string all selected values in HTML `select` element with `multiple="multiple"` using jquery-select2 library?
I had a similar requirement and could not find any options to accomplish this directly through the Select2 plugin. However, it was easy enough to create a separate input element and synch it on the select's change event. var $options = $('select#options'), $optionscsv = $('input#optionscsv'); $options.select2() .on('change', function() { $optionscsv.val($options.val()); }); Here's a live example on codepen: <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, jquery, html, csv, jquery select2" }
Can someone help me related rates? A police officer is standing near a highway using a radar gun to catch speeders. He aims the gun at car that has just passed his position and, when the gun is pointing at an angle of 45 to the direction of the highway, notes that the distance between the car and the gun is increasing at a rate of 100 km/h. How fast is the car travelling? ![Task]( I have done this task using simple geometry: $$x^2+k^2=s^2$$ $$x *dx/dt=s*ds/dt$$ Then since $$x=k$$ and $$s=\sqrt{2}k$$ I find out the speed is about 141 km/h. However, I struggle with task b of this problem: b) If the radar gun in a is aimed at a car travelling at 90 km/h along a straigt road, what will its reading be when it is aimed making an angle of 30 degrees with the road? So the car is travelling at 90 km/h says the text, but won't the radar be reading 90 km/h then? Or are those 90 km/h equal to ds/dt, because then I will be able to solve the task.
The radar gun can only measure the rate at which the distance between the gun and the car is increasing. In your notation, the radar gun measures $ds/dt$. The speed of the car, on the other hand, is represented by $dx/dt$ in your notation. So to setup your solution to part b, you'll enforce that $dx/dt = 90$ km/h. Also note that if the radar gun makes an angle of 30 degrees with the road, the relationship $x = k$ will no longer hold. Rather, you will find $k/x = \tan{30^{\circ}}$ and $k/s = \sin{30^{\circ}}$. With this information you can return to your rate relation and determine $ds/dt$, the reading on the radar gun, in terms of $k$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "derivatives" }
What are the possible eigenvalues of a linear transformation $T$ satifying $T = T^2$ Let $T$ be a linear transformation $T$ such that $T\colon V \to V$. Also, let $T = T^2$. What are the possible eigenvalues of $T$? I am not sure if the answer is only $1$, or $0$ and $1$. It holds that $T = T^2$, thus $T(T(x)) = T(x)$. Let's call $T(x) = v$, so $T(v) = v$. which means that $\lambda=1$. But I am not sure about this, while I have seen a solution that says that $0$ is possible as well. Thanks in advance !
Let $v\neq 0$ be an eigenvector of $T$ with eigenvalue $\lambda$, so $Tv=\lambda v$. Using $T=T^2$ we have $$ Tv = T^2 v = T(Tv) = T(\lambda v) = \lambda(Tv) = \lambda^2 v. $$ Hence, $\lambda v = \lambda^2 v$. Since $v\neq 0$ we conclude $\lambda = \lambda^2$. The only solutions to this equation are $0$ and $1$.
stackexchange-math
{ "answer_score": 8, "question_score": 5, "tags": "linear algebra, eigenvalues eigenvectors, linear transformations" }
Is it necessary to declare null variables manually in php? I am aware that PHP considers undefined variables as null. But despite this, when i want to use one undefined variable it throws an E_NOTICE error saying the variable is undefined. To prevent this, should I fix this E_NOTICE setting variables manually to null? For example: class Myclass{ private $var1; private $var2; public function __construct($settings){ $allowedKeys = array("var1","var2"); foreach($allowedKeys as $key => $value){ if(!isset($settings[$value])){ $settings[$value] = null; } } $this->var1 = $settings['var1']; $this->var2 = $settings['var2']; } }
You have four options to prevent E_NOTICE: One is to set the variable to either null, string, integer before you use the variable. I.e.: $variable = null; $variable = ''; $variable = 0; $variable = []; ... if(empty($variable)) { // do something with this situation } The other is to check if the variable exists. Like you did in one line: if(isset($variable)){ ... } Third one is to turn off E_NOTICE in your scipt: error_reporting(E_ALL & ~E_NOTICE); Forth one is to turn this off in you php.ini file (though i would not recommend this): error_reporting = E_ALL & ~E_NOTICE // you must find this line in your php.ini
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php" }
Editing Files In a Pods In Kubernetes I am trying to edit a file in my pod from my local machine using **kubectl exec** , but it is not working! Example: Suppose I am working on Ubuntu and having a pod named "Pod1", I want to edit a file named /lists inside Pod1. I am doing this **_kubectl exec Pod1 cat /lists >> "HELLO"_** but it is not working, please how to solve this kind of problem!
You can't `cat` a local file over. One way is to store the file in a BASH variable first before sending it over lists=$(cat /lists); kubectl exec Pod1 "echo $lists >> HELLO" But this isn't a great way either. Are you attempting to debug the app or to automate some process by writing to a file this way? If it's the latter, may I suggest using a ConfigMap instead?
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "ubuntu, containers, kubernetes" }
My array elements change value after I increment my counter I'm trying to read in a file to a character array, but whenever I increment my counter (for the array elements), my array elements seem to change value. In the following code, I'm printing out the array values before the counter is incremented and after the counter is incremented (to find out the problem). I'm not sure how to fix this (the code is in C)... char fileContents[rowNum * colNum]; rewind(file); int count = 0; while((ch = fgetc(file)) != EOF){ if(ch != '\n'){ fileContents[count] = ch; printf("%c ", fileContents[count]); count++; printf("%c %d\n", fileContents[count - 1], count - 1); } } These are the file contents" XXXX XXXX XX XXX XX X X X X X XX XX XXX XXXXXXXXX XXXXXXXXX XXXXXXXXX XXXXXXXXX
Try char fileContents[rowNum * colNum]; rewind(file); int count = 0; while((ch = fgetc(file)) != EOF){ if(ch != '\n'){ fileContents[count] = ch; printf("%c ", fileContents[count]); printf("%c %d\n", fileContents[count - 1], count); count++; } } I added the `count++` statement after the printf because there is the possibility that you increase `count` and `count = fileContents.size()`; this implies `fileContents[count]` is out of bounds
stackexchange-stackoverflow
{ "answer_score": -3, "question_score": -1, "tags": "c, arrays" }
Pasting text in vim. A tedious operation? I've been using vim for somewhat longer than a year now and during this time I have never feel really comfortable with the way vim works with yanking and pasting text (or maybe it is just me not using it in the most efficient way) For example, I have the word "World" yanked onto a register, and I want to paste it after "Hello". (Note that there are no spaces on either of the words). So, what I would do is Hello | Place cursor here, and press "p". Then, what I will end up with is HelloWorld So, in order to avoid this, I have always to swith into insert mode, insert a espace, and go back into normal mode (or either make sure that the yanked word has a space before it). Be as it may, this is quite annoying behaviour I can't think of a solution for... Am I missing something here? Suggestions will be appreciated. Thanks
**option zero** just live with what you have now. **option one** create a mapping for your workflow. for example nnoremap <leader>p i<space><esc>p **option two** :set ve=all then you could move your cursor to anywhere and paste **option three** you could in insert mode use `<c-o>` do normal mode stuff or `<c-r>` to get register values I recommend **option zero**
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "vim, insert, space, paste, yank" }
Append value in sql server I have written an c# foreach function that updates an column in the sql server. I have 2 values that i would like to append in the same column. In the foreach function, it updates the values in the column, but it overwrites the value on the next "loop". Example: string value = "Blue"; SqlCommand cmdUpdate = new SqlCommand("UPDATE Colors SET color=@value WHERE color_id = 11", connection); and then the next foreach loop the string value is "Red" string value = "Red"; SqlCommand cmdUpdate = new SqlCommand("UPDATE Colors SET color=@value WHERE color_id = 11", connection); How should i write my code to get both values in the sql column. "Blue, Red" Thanks in advance
Concat your string first and then update. string value = "Blue"; value += ", Red"; SqlCommand cmdUpdate = new SqlCommand("UPDATE Colors SET color=@value WHERE color_id = 11", connection); And of course do this in your foreach clause. Edit: You could also do this if you only want to use sql: SqlCommand cmdUpdate = new SqlCommand("UPDATE Colors SET color='' WHERE color_id = 11", connection); foreach(...) { value = "[Your Value]"; SqlCommand cmdUpdate = new SqlCommand("UPDATE Colors SET color= color + ', ' + @value WHERE color_id = 11", connection); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, sql server" }
Integrate WooCommerce and Woocommerce Bookings on one page custom theme I'm currently developing a one page website using Wordpress and a custom theme and I'm struggling to understand how I can integrate WooCommerce checkout (and WooCommerce Booking plugin) on my index page, which contains everything rather than using /shop/ etc. Is that even doable? The website can be seen here: < but the booking section is empty for now (it's live) Any insight deeply appreciated. Cheers. [edit] To be more specific, my question would be: How can I handle every step of the shop and checkout process on a single page? (that would be my index) [/edit]
Turns out that my main problem was wp_footer(); missing from the footer.php page on my Custom theme. That little thing wasn't trigging the WooCommerce functionalities (and more specifically the functionnalities linked to the Bookings Plugin) I've amended that and now it's working on my page. I still have a lot to figure out (like how can I do the checkout on that same page) but now I can work with that.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "php, wordpress, woocommerce, wordpress theming" }
How to print an Array on one line I've searched for answers but none have related directly or i haven't been able to adapt it to fix my problem How would I print the following in one line <?php $product_array = array("id"=>001, "description"=>"phones", "type"=>"iphone"); print "Print the product_array = "; print_r($product_array); ?> **Current result** Print the product_array =Array > ( > > [id] => 001 > > [description] => phones > > [type] => iphone > > ) **Wanted Result** > Print the product_array =Array ( [id] => 001 [description] => phones [type] => iphone )
$arrayString = print_r($array, true); echo str_replace("\n", "", $arrayString); The second value of print_r lets the function return the value instead of printing it out directly.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 6, "tags": "php, html, arrays" }
Using cscope to search for patterns with spaces I have the following problem. Consider this line: uint8_t status = 0x00; Now if I want to search for the occurence for the status, I will get LOADS of references (nearly every module uses some sort of status). :cs find s status Now, I thought that the best idea would be to search for: `extern uint8_t status` which will narrow down my search results (a little...) :cs find e extern uint8_t status Unfortunatelly `cscope` with `egrep` doesn't allow that. How should my call to `cs find e` look like, so that I will the occurence of `extern uint8_t status`? I have tried the following (omitting the obvious `extern uint8_t`...) :cs find e status = :cs find e status\s= :cs find e status[:space:]= :cs find e status[[:space:]]=
It seems, that the following works: :cs find e status[ ]=
stackexchange-vi
{ "answer_score": 1, "question_score": 1, "tags": "cscope" }
Is Mark 4:36-39 a fulfillment of Psalm 144:7? NIV | **Psalm 144:7** > "Reach down your hand from on high; deliver me and rescue me **from the mighty waters, from the hands of foreigners** " If hands of foreigners could pull on a boat like mighty waters (Psalm 144:7), then the does the miracle in Mark 4:36-39 simply demonstrate Jesus told the "other [foreigner] boats with them" to stop shouting / reaching for the disciples' boat? NIV | **Mark 4:36-39** > Leaving the crowd behind, they took him along, just as he was, in the boat. **[There were also other boats with him.]** A furious squall came up, and the waves broke over the boat, so that it was nearly swamped. Jesus was in the stern, sleeping on a cushion. The disciples woke him and said to him, “Teacher, don’t you care if we drown?” He got up, rebuked the wind and **said to the [foreigners] , “Quiet! Be still!”** Then the wind died down and it was completely calm. * Is Mark 4:36-39 a fulfillment of Psalm 144:7?
I don't think so. Psalms 144 is a psalm of David, for rescue and prosperity. To fulfill means > to bring to an end Are you asking if David was rescued then in Mark 4:36-39? That's not making much sense to me. Also, in Psalms 144:11 > Rescue me and save me from the hand of foreigners, (...) the image of the foreigns as floodwaters isn't present anymore. So what I extract from it is that the initial image was just to convey a certain degree of chaos - Proverbs 8:29 > When He set a boundary for the sea > > So that the water would not violate His command, > > When He marked out the foundations of the earth; The only relation I can see between the two passages is found in the comments on my KJV study bible about Mark 4:35-41 > Jesus is the Lord of nature as much as He is the Lord of individuals.
stackexchange-hermeneutics
{ "answer_score": 3, "question_score": 1, "tags": "psalms, mark, authorial intent" }
Would there be less load on a NAT firewall if some or all of the traffic were routed over IPV6 Instead of IPV4? Just curious.. I was thinking that, on a NAT firewall that is normally overloaded, offloading some or all of the IPV4 traffic to IPV6 might make a performance difference?
Yes. NAT can cause issues in a NAT firewall multiple ways. It would put a slightly lower load on the router CPU to ipv6 instead, although NAT is fairly lightweight and it likely don't make a big difference to the CPU. What is more relevant - and likely the cause of many issues is the size and number of entries.in the connection tracking table - is the mappings between lots of internal addresses and lots of external addresses. Especially in cases where you have.multiple internal sites hitting few external sites or using complex protocols. This is what tends to cause pain in NAT firewalls, and the ability to handle this at scale is the difference between regular NAT and Carrier Grade NAT. By moving to IPV6, you eliminate this issue.
stackexchange-serverfault
{ "answer_score": 2, "question_score": 0, "tags": "firewall, nat, ipv6" }
Specifying a range inside an if condition in C language I just want to know the difference between these C code segments. I used it in two different ways and final output was not same. if(120<=units<160){ total= total- total*(15.0/100); printf("Revenue : %.2f", total); } if(120<=units && units<160){ total= total- total*(15.0/100); printf("Revenue : %.2f", total); } Can't we use "120<=units<160" to specify a range in C language?
No, you can't test ranges in this way. What's happening here is the operators are evaluated left-to-right as per operator precedence. So this means: `(120 <= units) < 160` The value of `120 <= units` will be 0 if it is false or 1 if it is true In other words, the full expression will always be true, because both 0 and 1 are less than 160.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c, if statement, range" }
What word would be used to describe someone who has grown up with something? I'm looking for a word that could be used to describe someone as being comfortable with something (in this case technology) due to having grown up in a world with it. I know the term digital-native is thrown around a lot but am looking for something akin to this but in a single word. I've also thought along the lines of 'familiar' but didn't quite seem to fit. Anyone else got any better ideas?
I reckon there are more fitting words than these, but I'll carry on. Without a specific reference to having _grown up_ with something, you can be (or become) **_accustomed_** to [technology]. If [technology] pervaded your childhood to the extent that it is everywhere and all-around and is _second nature_ to you, it has become accepted and incorporated into life, you can be said to have been **_indoctrinated_** into technology. The word basically means "brainwashed" or "conditioned" - but can be toyed with. **_Conditioned_** might be worth a quick mention because it refers to "having a significant influence on or determine the manner or outcome of something."
stackexchange-english
{ "answer_score": 2, "question_score": 1, "tags": "single word requests" }
NSDateFormatter @"mmddyyy"? Helo, I'm trying the bunch of code and it is giving null. Is there any problem in this code? NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; // get NSDate from old string format [dateFormatter setDateFormat:@"mmddyyy"]; NSDate *date = [dateFormatter dateFromString:@"02012002"]; NSLog(@"%@",date); // get string in new date format [dateFormatter setDateFormat:@"dd-MMM-yyyy"]; NSString *strMyDate= [dateFormatter stringFromDate:date]; NSLog(@"%@\n\n********************************************************",strMyDate); the output is 2011-06-09 12:49:17.957 TestPrj[3054:207] (null) 2011-06-09 12:49:17.959 TestPrj[3054:207] (null) ********************************************************
You r missing one 'y' there in second line- it either should be - > dateFormatter setDateFormat:@"mmddyyyy"]; > > or dateFormatter setDateFormat:@"MMddyyyy"];
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "iphone, objective c, nsdateformatter" }
Static Equilibrium with 3 tensions ![enter image description here]( Hey guys, for the question that asks you to determine the tension in all 3 cables I am kinda confused. My teacher said the 2nd tension opposes gravity, so it is equal to gravity. then you can equate that to **Ft3sin60**. But if both **Ft2** and **Ft3sin60** are pointing upwards wouldn't they have to add to equal **Fg**? But that is not the case according to the answer that was provided.
If a straight rope is in tension, the forces acting on the two ends are in opposite directions, not in the same direction. The rope T2 is clearly pulling upwards on the mass m, therefore it is pulling _downwards_ on the point where the three ropes join. The vertical component of the force in T3 is pulling _upwards_ on the same point. You need to choose a part of the complete system, and then consider only the _external_ forces applied to that part. To find the force in T3, you can consider just the mass (the force FT3 is then an external force on the mass). To find FT2, you could consider the "mass + rope T3" taken together. The external forces on that system, in the vertical direction, are the weight of the mass, and the vertical component of FT2. Alternatively, you can consider just the "point" where the three ropes join. The vertical forces are then FT3 and the vertical component of FT2. Both methods give the same answer, of course.
stackexchange-physics
{ "answer_score": 1, "question_score": 0, "tags": "homework and exercises, forces, free body diagram, statics, equilibrium" }
Why is Kafka connect light weight? I have been working with kafka connect, Spark streaming , Nifi with kafka for streaming data. I am aware that unlike other technologies kafka connect is not a separate application and it is a tool of kafka. In case of distributed mode all technologies implement the parallelism by the underlying tasks or threads. What makes kafka connect to be efficient when dealing with kafka and why is it called light weight?
It's efficient and lightweight because it uses the built-in Kafka protocols and doesn't require an external system such as YARN. While it is arguably better/easier to deploy Connect in Mesos/Kubernetes/Docker, it is not required The connect API is also maintained by the core Kafka developers rather than people that just want a simple integration into another tool. For example, last time I checked, NiFi cannot access the Kafka message timestamps. And dealing with the Avro Schema Registry seems to be an after thought in the other tools as compared to using Confluent Certified Connectors
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "apache kafka, streaming, spark streaming, apache nifi, apache kafka connect" }
Random errors while downloading files from sharepoint I am using Sharepoint 2007 to host Excel 2007 files generated by my App, so that internal clients can download them. However, I sometimes (and it seems random) the bigger files fail to download (Internet Explorer and Firefox claim the download was successful, but the size of the file is smaller than expected and it is not usable). The files in Sharepoint are fine, because sometimes they download ok (so after trying a few times I can successfully download any file). Any ideas what causes it and if there are any workarounds available?
Can you post a snippet showing what's happening in code? There are numerous issues in file downloading capabilities of IIS because the whole process depends on multiple factors network failures etc Please refer link text
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "sharepoint, sharepoint 2007" }
Dynamic logical expression parsing/evaluation in C# or VB? What is the best was to evaluate an expression like the following: (A And B) Or (A And C) Or (Not B And C) or (A && B) || (A && C) || (!B && C) At runtime, I was planning on converting the above expressions to the following: (True And False) Or (True And False) Or (Not False And True) or (True && False) || (True && False) || (! False && True) Conditions: 1) The logical expression is not known until runtime. 2) The number variable and their values are not known until runtime. 3) Variable values are never null. I know I could create a simple assemble with a class and a method that I generate at runtime based on the inputs, but is there a better way. I have done this before. Use a string builder to write the code, then call the compiler. After that, you load the assembly and call the method. Suggestions? Thanks.
If you're using .NET3.5 then you can parse the text and create an abstract sytax tree using the Expression classes. Then create a suitable LambdaExpression instance and compile it into a delegate, which you can then execute. Constructing a parser and syntax tree builder for this kind of fairly simple grammer is quite an interesting exercise, and will execute somewhat faster than invoking the compiler (and it's neater in my view as well). If you're not using .NET3.5, then it's also not complicated to implement an interpreted abstract syntax tree yourself.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 10, "tags": "c#, vb.net, expression" }
Plasma 5.13 in Kubuntu 18.04? Plasma 5.13 is said to have better Kwin performance and many other improvements. Can it be installed and can it run in Kubuntu 18.04? The upgrade doesn't sound very abrupt, it should be from 5.12 to 5.13. Adding the Kubuntu Backports ppa only brought me 5.12.5. sudo add-apt-repository ppa:kubuntu-ppa/backports * * * ## NOTE JULY 2TH 2018: **I DO NOT RECOMMEND INSTALLING IT. AT THE DATE OF THE FIRST POST AND OF THIS EDIT 5.13 IS UNSTABLE ENOUGH FOR ME TO AVOID RECOMMENDING IT - AS I HAVE TESTED IT IN NEON ITSELF MEANWHILE.** At the date of this edit Neon is using Plasma 5.13 on an Ubuntu 16.04-base.
**From the Kubuntu forums** acheron: > ...we are waiting on the required new Qt version to be done for Ubuntu. > > Plasma 5.13 will get a 5.13.1 and 5.13.2 rapid bugfix update releases in the next 2 weeks, so even if we don't get the initial 5.13.0 done, that may not be a bad thing if we go straight to versions that have had a round or 2 of bugfixes. There is no such thing as the 'Neon ppa'. Your 'add-apt-repository ...' line is adding the Kubuntu ppa backport to your system. As the Kubuntu developer 'acheron' told the Plasma 5.13 will need at least the Qt 5.10. When the Ubuntu 18.10 has the newer Qt and the Plasma 5.13.X they will be backported to the Kubuntu backports ppa. The Neon has own KDE repositories: < . In the past the brave users have been mixing the Ubuntu and the Neon repositories: < . BUT ! as told you are doing it at your own risk. **“Kubuntu Package Archives” team** There are: < ![enter image description here]( Note the warnings !
stackexchange-askubuntu
{ "answer_score": 4, "question_score": 5, "tags": "kubuntu, 18.04, kde, versions, plasma 5" }
please how do I create this declaration page on latex, the major challenge is inserting the lines though ![image of the declaration page I intend to create with latex]( please I need assistance in inserting a line for signature/date in the declaration page of a research document using latex! assistance would greatly be appreciated
It looks like you want it at the bottom of the page. So, something like this: \documentclass{article} \begin{document} \leavevmode% \vfill\noindent \begin{center} \textbf{DECLARATION} \end{center} I declare that the work in this dissertation blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah blah b blah blah blah blah blah blah blah blah blah blah blah. \vspace*{4em}\noindent \hfill% \begin{tabular}[t]{c} \rule{10em}{0.4pt}\\ ETIM Emmanuel \end{tabular}% \hfill% \begin{tabular}[t]{c} \rule{10em}{0.4pt}\\ Date \end{tabular}% \hfill\strut \end{document} ![enter image description here](
stackexchange-tex
{ "answer_score": 4, "question_score": 0, "tags": "pdftex, line" }
Не работает lambda функция при печати случайной буквы из списка import random print(lambda upletters: (random.choice(['Q','W','E','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M']))) Возможно синтаксис не корректен. Помогите разобраться.
Если вы хотите **использовать** лямбду в точке объявления, именовать её не надо. Более того, код вида lambda upletters : ... объявляет лямбду с параметром `upletters`. Для использования лямбды "на месте" её нужно **вызвать** следующим образом: (lambda : ...)() Таким образом, корректный код в данном случае имеет следующий вид: import random print( (lambda : (random.choice(['Q','W']))) () ) (Массив сократил для улучшения понимания конструкции.)
stackexchange-ru_stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "python, случайные числа, lambda" }
Unable to pull data from API in python My code is below. I am trying to pull data from the COVID-19 API and want to store it in a dataframe to view it and then later use it for analytics purpose in Python. import pandas as pd import requests url = " r = requests.get(url) print(r.json) I get the following error: ValueError: Invalid file path or buffer object type: <class 'requests.models.Response'> What does this mean, and how can I fix it?
Make sure to _call_ the `json()` method: print(r.json()) # ^^ Right now you're getting a reference to the method itself.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python, json, api, data extraction" }
Zend Framework - How to implement partials which contain logic I have a layout which works fine. This layout contains several partials, which display adverts, a side column a slideshow, etc. All of these are likely to change depending on which page (module/controller/action) of the site you are on. What is the best way of doing this correctly? In the past I have assigned variables to my view inside my controllers, these are then passed to the partial which then displays the correct slideshow or advert. This seems ugly and not entirely correct for an MVC application. Does anyone have any other methods of doing this?
Partials are just another view scripts. My advice is: _newer put your logic into the view scripts_. Your may store the logic in: * models (remember, that you can create your own models, extending, or not extending the basic database models, eg. data hydrators) * view helpers (with parameters) * services (dependent on models, returning models) * combination of the above Then use view helper or pass the ready data (model) to different partials. Tip: Dependency injection is a good thing.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "zend framework, partial" }
Kicked out of Gnome desktop intermitently I am running Debian 8 (Jessie) using the default Gnome desktop and installation. Sometimes I will be logged off Gnome and brought back to the graphical login screen where I must enter my password. When I log back, all programs will have been closed and I am brought back to a fresh desktop. This is happening at irregular intervals. How can I diagnose this problem? Is there a file that would contain information to help me find the source of the error?
1 - I don't know fix your problem, but I would try log on tty1 with same user, and see if it logout too. If it logout you know it is not a problem with X, gnome... 2 - Some days ago I had a strange problem with X window, the programs crash and i couldn't logon again with normal user. I saw the logs in /var/log to find something, but I haven't found anything. The problem with me is /var/log too large (I guess, i couldn't fix my own problem!). 3 - Anyway the files in /var/log/ may help.
stackexchange-unix
{ "answer_score": 1, "question_score": 0, "tags": "debian, gnome" }
Joining points with nearest polygon using QGIS I have a points layer and polygons layer with attributes I want to join for each point. Not all points are exactly within a polygon, so I'm looking for a way to join attributes based on nearest polygon (so that if a point is located within a polygon it will just get its attributes). I've tried using the `NNJoin` plugin, but I've noticed that for lots of points that are located within a polygon, it will joing attributes of a different polygon.
Try splitting your point data in two. First part would be the points that fall within a polygon and the second part would be points falling outside polygons. For the first part, perform a regular spatial join, and for the second part, use the NNJoin plugin. You can later merge the two resulting point layers into one. This way you can avoid the plugin performing an incorrect join on some of the points that fall within a polygon. In order to select points that fall within the polygon layer, use the Spatial Query plugin (now a core QGIS plugin), then save the selection as a new layer. Invert the selection and save it as the second layer and perform the join using the NNJoin plugin. Note that I have never used the NNJoin plugin.
stackexchange-gis
{ "answer_score": 1, "question_score": 2, "tags": "qgis, spatial join, proximity" }
How do i take median of 5 grayscale frames? I am taking input from a video and I want to take the median value of the first 5 frames so that I can use it as background image for motion detection using deferential. Also, I want to use a time condition that, say if motion is not detected then calculate the background again, else wait t seconds. I am new to opencv and I don't know how to do it.. Please help Also, I want to take my video in 1 fps but this does not work. Here is the code I have: import cv2 BLUR_SIZE = 3 NOISE_CUTOFF = 12 cam = cv2.VideoCapture('gh10fps.mp4') cam.set(3, 640) cam.set(4, 480) cam.set(cv2.cv.CV_CAP_PROP_FPS, 1) fps=cam.get(cv2.cv.CV_CAP_PROP_FPS) print "Current FPS: ",fps
If you really want the median of the first 5 frames, then following should do what you are looking for: import numpy as np import cv2 cap = cv2.VideoCapture(0) frames = [] for _ in range(5): ret, frame = cap.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) frames.append(gray) median = np.median(frames, axis=0).astype(dtype=np.uint8) cv2.imshow('frame', median) cv2.waitKey(0) cap.release() cv2.destroyAllWindows() Note, this is just taking the source from a webcam as an example.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python, python 2.7, opencv" }
Sum of array using recursion! (Error: StackOverflowError) The main method calls sum and has to return the sum of the array.The program aims at finding sum of array without using any loop. Not able to detect the error. The code for Sum of array using recursion: import java.util.Scanner; public class X{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int l1,j,sum=0; try{ System.out.println("Enter length of array: "); l1= sc.nextInt(); int[] s1=new int[l1]; System.out.println("Enter array elements: "); for(j=0;j<l1;j++) s1[j]=sc.nextInt(); sum=sum(s1,0); System.out.println("Sum = "+sum); } finally{ sc.close();} } public static int sum(int[] a,int i){ if(i>=a.length) return 0; return a[i]+sum(a,i++); } }
i++ returns i before the increment, so you recursing with the same i. Replace i++ with ++i
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "java, arrays, recursion, out of memory, stack overflow" }
ASP.NET Data source controls I am learning ASP.NET. I noticed there are several types of ASP.NET data source controls available in Microsoft Visual studio, including SqlDataSource, AccessDataSource, ObjectDataSource, and XmlDataSource. Does anyone could explain the differences among SqlDataSource, AccessDataSource, ObjectDataSource, and XmlDataSource? Which one is more useful in the real world? Thank you.
go through this links, it helped me. Hope it will help you too. Data Source Controls and Connections ASP.NET Data Sources
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net" }
RSS link is broken for tagged questions After searching for < I got rss link which does not point to a valid rss feed.
Fun bug. For some reason if one of the tags doesn't exist (in your url, that'd be `urlib3`) then we 404 feeds. Now we'll chug along so long as at least one of the passed tags exist, which seems a lot more sensible. This fix will go out with the next build.
stackexchange-meta
{ "answer_score": 2, "question_score": 3, "tags": "bug, status completed, feed" }
Nested Transactions in ADO.NET First, is it possible to have n transactions levels over ADO.Net. Second, is this correct usage? var tx = cx.BeginTransaction(); cx.Execute("insert into atable(id) values(123123)"); var tx2=tx.BeginTransaction(); cx.Execute("insert into atable(id) values(123127)"); tx2.Commit(); tx.Commit(); ... etc.
You can nest transactions using `TransactionScope` \- however, they will only get committed once the most outer one gets committed. They will all be rolled back if any one of them will rollback. In terms of usage - you should wrap the transaction creation in `using` statements to ensure proper disposal. using(var tx1 = new TransactionScope()) { cx.Execute("insert into atable(id) values(123123)"); using(var tx2 = new TransactionScope()) { cx.Execute("insert into atable(id) values(123127)"); tx2.Complete(); } tx1.Complete() }
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "c#, .net" }
How to add opamp noise density in LTspice I have this circuit in LTSpice using the universalOpamp2: ![enter image description here]( The simulation gives me 30 nV/sqrt(Hz). If the opamp noise density is specified in the datasheet as 5 nV/sqrt(Hz), I understand I have to add 4 x 5 nV/sqrt(Hz) = 20 nV/sqrt(Hz) to my 30 nV/sqrt(Hz) to get my overall noise of 50 nV/sqrt(Hz). However, how do I do confirm this in LTSpice? I would like the 5 nV/sqrt(Hz) opamp noise density be part of the simulation.
The noise figures are added via the parameters En, Enk, In, Ink of universalOpamp2.
stackexchange-electronics
{ "answer_score": 1, "question_score": 0, "tags": "operational amplifier, noise, ltspice" }
Why doesn't PlusMinus[a]^2 simplify to a^2? So, I've been playing around with Mathematica lately, and I found an interesting (what I presume to be an) error. Trying to simplify `(PlusMinus[a])^2` does not give a result of `a^2`. However, it is a fact that $(\pm a)^2 == a^2$. Obviously, this is fairly easy to work around, but it does require splitting your work up into two (or more, depending on how many times you use `PlusMinus`) separate pieces. So, am I missing something, or is this an error on _Mathematica_ 's part?
From the documentation: > `PlusMinus[a]` displays as $\pm x$. I believe it is purely a formatting function. It is not literally interpreted as $\pm x$. However, per the documentation, you can _assign_ values to it. You can assign a rule that mimics the behavior you want by assigning an `UpValue` to `PlusMinus`: PlusMinus /: PlusMinus[a_]^2 := a^2 Then: UpValues@PlusMinus (* { HoldPattern[(\[PlusMinus]a_)^2] :> a^2 } *) and PlusMinus[5]^2 (* 25 *) * * * As pointed out by Lou in a comment, `PlusMinus` is one of the Operators without Built-in Meanings, which means that PlusMinus[x,y,[Ellipsis]] doesn't evaluate, it just displays.
stackexchange-mathematica
{ "answer_score": 25, "question_score": 10, "tags": "output formatting, formatting" }
Evaluation of a limit of a particular limit How to find the value of this limit? $$ \lim_{n\rightarrow \infty}\\{(1+1/n)(1+2/n)\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot(1+n/n)\\}^{1/n} $$ let $y=\\{(1+1/n)(1+2/n)\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot\cdot(1+n/n)\\}^{1/n}$ Then using $\ln$ on both sides I have ultimately reached the situation $\ln y= 1/n\\{\ln[(1+1/n)(1+2/n)\cdot\cdot\cdot\cdot+1+n/n)]\\}$. What to do next?
As $\ln(ab)=\ln a+\ln b\implies\ln(\prod a_i)=\sum \ln a_i,$ $$\lim_{n \to \infty} \frac1n\sum_{r=1}^n f\left(\frac rn\right)=\int_0^1f(x)dx$$ here $$\ln(y)=\lim_{n \to \infty} \frac1n\sum_{r=1}^n\ln\left(1+\frac rn\right)$$ Can you recognize $f(x)$ here?
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "calculus" }
mysql misses data entry Im trying to stress test mysql: for($i=0;$i<30000;$i++) { mysql_connect("localhost","admin","admin"); mysql_select_db("magic"); mysql_query(INSERT INTO Persons VALUES (4,'9999999999999999999999999999999999999999999999999999999999999999999999999999999999')); mysql_close(); } It only inserts 25985, not more. Table schema : id = primary int, content = long text Tt gives me `error cannot connect to mysql`, even though I increase the max connections. Any solution would be appreciated :)
"The amount of connection is damn to high !" Kidding ! The number of connection is provided by the number of RAM available on your computer. So if you have gygabites of RAM you can have like 10k connections, depend on your system, the RAM allowed to your connection etc. Check it here : MYSQL : too many connections > The maximum number of connections MySQL can support depends on the quality of the thread library on a given platform, the amount of RAM available, how much RAM is used for each connection, the workload from each connection, and the desired response time. Why do you need so much connections at the same time ? One connection and 30.000 insertions should be OK but not 30.000 connections at the same time. Hope it helps :)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "php, mysql, database" }
Перевод букв в цифры и обратно Помогите понять, в чем ошибка. Пример ниже это часть алгоритма, суть в том, что нужно найти код буквы (её порядковый номер в алфавите), изменить его и переприсвоить. В C++ делал так: // 012345678901234567890123456 string alpha{"abcdefghijklmnopqrstuvwxyz_"}; int N=alpha.size(); string msg="hello"; string cmsg(msg.size(),'_'); for (int i=0;...;...) cmsg.at(i)=alpha.at(alpha.find(msg.at(i)) //Сильно упрощено Попытался в QT: int N=alpha.size(); QString msg; msg=ui->text_msg->text().toLower(); QString cmsg(msg.size(),'_'); cmsg.at(2)=alpha.at(alpha.indexOf(msg.at(4))); //Упрощено Ошибка: ошибка: passing 'const QChar' as 'this' argument of 'QChar& QChar::operator=(const QChar&)' discards qualifiers [-fpermissive] cmsg.at(2)=alpha.at(alpha.indexOf(msg.at(4))); ^
`cmsg.at(2)`возвращает константное значение, попробуйте вместо этого `cmsg[2]` Если переписывать весь код не вариант, можно оставить код на c++, а в QLineEdit поместить полученную строку можно так: `ui->lineEdit->setText(QString::fromStdString(cmsg));`
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++, qt" }
Как отменить незакомиченные изменения? Мне нужно переключиться с ветки А на ветку Б, но не могу из-за незакоммиченых изменений в ветке А, эти изменения мне вносить в проект не нужно. Я хочу оставить все как было в предыдущем коммите. Т.е. по сути нужно отменить незакоммиченные изменения.
Можно положить в `stash`. `git stash push 'file_name_or_dir_goes_here'`. Таким образом вы и не удаляете свои изменения, но и не коммитите их. И можно спокойно переключиться на другую ветку. Я так понимаю, именно это вам и нужно. **UPD** Просто отменить незакомиченные изменения: `git reset --hard`
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "git, откат" }
Can I use PyFlink together with PyTorch/Tensorflow/ScikitLearn/Xgboost/LightGBM? I am exploring PyFlink and I wonder if it is possible to use PyFlink together with all these ML libs that ML engineers normally use: PyTorch, Tensorflow, Scikit Learn, Xgboost, LightGBM, etc. According to this SO thread, PySpark cannot use Scikit Learn directly inside UDF because Scikit Learn algorithms are not implemented to be distributed, while Spark runs distributedly. Given PyFlink is similar to PySpark, I guess the answer maybe "no". But I would love to double check, and to see what I need to do to make PyFlink able to define UDFs using these ML libs.
Thanks for the investigation of PyFlink together with all these ML libs. IMO, you could refer to the flink-ai-extended project that supports the Tensorflow on Flink, PyTorch on Flink etc, which repository url is < Flink AI Extended is a project extending Flink to various machine learning scenarios, which could be used together with PyFlink. You can also join the group by scanning the QR code involved in the README file.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "pyspark, apache flink, pyflink" }
Real Valued Function:finding number of solutions > If $f(x)$ is a real valued function satisfying $f(x+y)=f(x)+f(y)-xy-1$ for all real $x$ and $y$ such that $f(1)=1$ then how to find the number of solutions of $f(n)=n$ where $n \in \mathbb{N}$
It is rather immediate that $n=1$ is the only solution. Since $$f(2) = f(1+1) = f(1) + f(1) - 1- 1 = 0$$ you can use induction to prove that $f(n) \le 0$ for every $n \ge 2$ because $$f(n+1) = f(n) + f(1) - n \cdot 1 - 1 \le 1 - n - 1 = -n \le 0$$ provided that $f(n) \le 0$.
stackexchange-math
{ "answer_score": 5, "question_score": 1, "tags": "algebra precalculus, functions" }
Switching views creating memory leak I have been switching views with navigator.pushView over and over again but it seems to continually take up more memory. Any leads on what it could be? Am I changing views wrong?
DennisJaamann is correct in his comments - couldn't mark it as an answer since there wasn't anything to mark.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "actionscript 3, apache flex, mobile, air" }
How to slow all time measurements of a process? I'd like to make an application believe that time is going faster/slower than real time. I.e. I need to make all the time measurement APIs return `t0+dt*s` with user-defined `s` when `t0+dt` is real time. This would affect anything like `gettimeofday()` as well as `timer_gettime()` and all related functions and mechanisms (including actual trigger times of timers). I think of putting a hook somewhere which would change the visible time for the app. In a Linux system, what is the best place to put such a hook, so that I didn't have to create too many hooks? Is there any central place for this?
You can use the LD_PRELOAD trick described in this question. Libfaketime seams to do exactly what you need (see the README under "Advanced time specification options"). The following example shows time going 2x slower for "sleep": $ time FAKETIME="x0.5" LD_PRELOAD=/usr/lib/x86_64-linux-gnu/faketime/libfaketime.so.1 sleep 1 real 0m2.002s user 0m0.000s sys 0m0.000s (on a debian system, therefore /usr/lib/) If it doesn't actually do what you want, instead of rolling out your own solution, I'd suggest taking its source and implementing what you need from there. For completeness' sake, another possible starting point is datefudge.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 4, "tags": "linux, time, hook" }
Azure - Naming convention for resources What is the best way to name resources in Azure? I have seen some people name their resources with prefixing the resource group. Example: `grp-1-myfunctionapp`. Others add resource type, region and environment like `functionapp-westus-prod-fn1`. How should I go about it?
An effective naming convention assembles resource names by using important resource information as parts of a resource's name.A public IP resource for a production SharePoint workload is named like this: `pip-sharepoint-prod-westus-001` Straight From Microsoft Docs. Scroll down a little bit and you will find a whole bunch of great prefix to orginize your names. **Please notice** that changing resource names can be difficult. Establish a comprehensive naming convention before you begin any large cloud deployment.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "azure, naming conventions" }
Web API returns escaped JSON I have a POST method in a .NET core 2.0 web API project that needs to return a JSON (using newtonsoft). I have the following code at the end of the method: ObjectResult objRes = new ObjectResult(JsonConvert.SerializeObject(result, settings)); objRes.ContentTypes.Add(new MediaTypeHeaderValue("application/json")); return objRes When I test this using Postman I get a result like: "{\"name\":\"test\",\"value\":\"test\"}" As you can see, the JSON is still escaped in postman. When I test the exact same code in a .NET core 1.0 project, I get the following in Postman: { "name": "test", "value": "test" } How can I get the same result in my .NET core 2.0 project? I was thinking it might have been due to Newtonsoft but when I debug the deserialization into a string, the debugger shows exactly the same (escaped) value in both the .NET core 1.0 and 2.0 project.
You can just return result in the controller and it will be serialized by the framework. [HttpPost] public object Post() { var result = new MyObject { Name = "test", Value = "test" }; return result; } Or you can do: return new OkObjectResult(result); Or if you inherit from Controller: return Ok(result);
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "c#, json, asp.net core webapi" }
How to automatically delete records in sql server after a certain amount of time I have set up temporary user accounts on my sql database where the user names, passwords and date added of my websites users are stored. I was initially going to have these records delete programmatically but now im wondering if sql server 2008 has a built in function that allows records to be auto-deleted after lets say one day. This would resolve the issue of a user being able to stay logged into the system after their temporary account is closed thanks
You might be able to get what you want without actually deleting the records. You can add a computed column into the table to say whether the record is valid. IsValid as (case when getdate() - CreatedAt > 1 then 0 else 1 end) You can also do this for key fields in the record, so you cannot find them: _name varchar(255), name as (case when getdate() - CreatedAt < 1 then _name end) You can then use a view to access the table: create vw_Logins as select name, . . . from t where isValid = 1; Then, at your leisure, you can actually remove the rows if you need to for performance reasons. EDIT: You don't actually need a computed column, if you phrase the view as: create vw_Logins as select name, . . . from t where getdate() - CreatedAt < 1;
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 11, "tags": "c#, sql, asp.net, sql server, database" }
How to encourage people to use linebreaks and periods? I wonder why people do not use line breaks and periods. I see many long paragraphs and sentences using commas. Some posts are really hard to follow and require (lots of/some) post-editing to understand them. * How can we encourage people to use (shorter) sentences using periods and include line breaks? I know that this is included somewhere in the guidelines, such as how to ask, etc. but people are not following this simple advice to make their posts more readable.
If this makes the post _completely_ unreadable and you can't edit it to make it make sense, then downvoting is the best choice. If it's a question then vote to close. The problem is as old as time: people type the same way they speak, and in their head it's perfectly understandable, but to others it's not. It's complicated for someone using British English to explain to someone using Indian English, as an example, why their sentence structure isn't quite right. So instead of getting into that quagmire, just vote their post down and close the questions when appropriate. Then it's the system's responsibility to explain it to them.
stackexchange-meta_stackoverflow
{ "answer_score": 15, "question_score": 9, "tags": "discussion, low quality posts, new users, question quality, quality improvement" }
promise parameter from firestore set is undefined I am trying to create a new document and then do something inside the promise using the following way : firestore.collection('users').doc(uid).set({name: "testName"}) .then(res => { console.log("set data correctly with ", res); }).catch(err => { console.log('something went wrong '+ err) }); It indeed went into the `then` promise. However, the `res` is empty! I got: > set data correctly with undefined
Take a look at the API documentation for DocumentReference.set(). The method is defined like this: set(data: DocumentData, options?: SetOptions): Promise<void> Note that the method returns a Promise that contains `void`. That means set() doesn't yield any objects or data at all. So, if you use that promise, it will be delivered nothing. So it's working as expected.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, promise, google cloud firestore" }
What defines Google Chrome window location? In Google Chrome, when i want to open new window in incognito mode, i press CTRL+Shift+N. It opens new window in certain location. My question is: What defines coordinates of that location?? How can i define these coordinates?? i suspect, this question applies to any windows GUI application in general. Please, help me understand it.
For me it always opens a few pixels down and to the left of the current Chrome window. I'm assuming that it's hard coded in the application and that you won't be able to override them. The same will be true of any other application too. It will either be hardcoded to a specific location (not necessarily absolute values, but centred on the screen etc.), remember the location of the last time it was opened or will be random.
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "google chrome, gui, window, coordinates" }
Installing Yacc or Bison for Mac I'm having trouble finding a Yacc or Bison that doesn't require using darwinports for Mac. If anyone has experience in this category any information will be great
If you have a working C compiler, it should be pretty trivial to build byacc.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "macos, installation, yacc, bison" }