INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Why is the first bullet of my list larger than the rest? In the environment \documentclass{article} \usepackage{enumitem} \usepackage{tabularx} \newcommand{\resumeItemListStart}{\begin{description}} \newcommand{\resumeItem}[2]{\item[$-$]\small{{#1}}} \newcommand{\resumeItemListEnd}{\end{description}\vspace{-5pt}} \begin{document} \resumeItemListStart \resumeItem{A} \resumeItem{B} \resumeItem{C} \resumeItem{D} \resumeItemListEnd \end{document} Why is the first bullet `-` of item A longer than the rest? Screenshot attached below. ![enter image description here](
Removing `\small` from `\newcommand{\resumeItem}[2]{\item[$-$]\small{{#1}}}` did the trick!
stackexchange-tex
{ "answer_score": 1, "question_score": 3, "tags": "lists, itemize" }
what are protocols used during accessing email via web browsers? All I know is smpt, pop3 and imap are used for email transactions . But when I access my email (gmail or hotmail) via web browsers , we use http or https. (whereas Smpt is used in email client like outlook, thunder bird,etc..) can anyone tell me how this is working ?
HTTP/HTTPS is for presentation. Email is still using SMTP for sending mail, and either POP3 or IMAP for receiving/fetching from the email server. Whatever language in between -- PHP, Java, .NET, etc -- has libraries to handle the information appropriately.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "email" }
How to display response message after redirecting to otherpage? I am using ASP.NET and C#.In register page after click on submit i am storing all the details in database and redirecting to login page.So in login page i need to display message like successfully registered. Can someone tell me is it possible? Thanks.
You may use Session, QueryString, Cookie for this purpose. But I would suggest show you message on same Register page. And put continue button on page, that will redirect user to Home or other page. Why I`m saying show message on same page, because one thing is fixed you are going to redirect user if registration was successful, if not you will show the errors. Session, QueryString will be easy and handy option for this: Session["RegisterMessage"] = "Hello User, You have successfully registered"; Or Response.Redirect("Home.aspx?msg=Hello User, You have successfully registered"); You may show this value on label on the page.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, javascript, asp.net" }
Can I use my sonarqube server for any git repository? I am working on a online-school where student projects are decentralized on git repositories. When a student wishes to correct a project: * The student must specify his git-repo-url + private key in order to pull it on the correction-server * Then several tasks are applied on the project (compilation check, output checks). I'd like to check the code quality and return a feedback for each user. I guess sonarqube would be a good choice since it supports 28+ languages. I am familiar with sonarqube used with a continous integration, but I can't find in their documentation how to call sonarqube for my use case. I'd need something like a rest api for requesting a code analysis by giving the git url & its key and get a response with the code quality output. Would it be possible?
I think there is a misunderstanding, between SonarQube Server and SonarQube Scanner, this is already well explained in < So to do an analysis, you actually need to run a SonarQube scanner with some specificaitons, which is pretty well documented. When you have successfully set up the scanner, you can easily retrieve reports, status, quality gate via REST API.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "rest, sonarqube" }
custom validations with custom control I have a custom web control which has two html select field and buttons i use them to make associated and available list box.But in few situations i have to Validate that Associated field must have at least 1 entity. I implemented a client side custom validator to confirm that. and its working great but issue is i am unable to fire Validate at the time List box is made empty it fires when i click save button and similarly when i have moved a few entries in associated List. validation Message is stile there and removes only when i click save button. So i want to know how can i fire validator when i need using javascript...
To fire a validator from javascript we may use `ValidatorValidate(document.getElementById('validator clientID'))` for more details see <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, asp.net, validation, custom controls" }
Can APC recognise duplicate source files? I have a webserver with lots of sites which are all based on Drupal. The sites share a vast majority of identical code, and it'd be great if APC could take advantage of this and not 're-cache' the same files x times over. Is there any theoretical problem with this idea? Do any PHP opcode caches take advantage of this that you know of?
Seems the answer's no, at least as things currently stand.
stackexchange-serverfault
{ "answer_score": 2, "question_score": 1, "tags": "php, cache" }
Rails - html img tag error: 404 not found Inside my rails project: if i use the image_tag <%=image_tag 'sqlite.png'%> the image shows up, if however, i use the raw html img tag like so: <img src="/assets/images/sqlite.png"> I also tried <img src="/images/sqlite.png"> ![](/images/sqlite.png) I still get the 404 - not found error. How do I use raw html image tags inside rails ? For my specific use case, I need to use html img tag . Help!
Be sure you add your images in app/assets/images/ and your code `<%= image_tag 'sqlite.png' %>` should be fine. Your images: `app/assets/images/sqlite.png` In your code: <%= image_tag 'sqlite.png' %> HTML: `<img src="/assets/sqlite.png" >` <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, ruby on rails, image, http status code 404, asset pipeline" }
How to authenticate to Bluemix S3 Lite? I'm trying to use S3 API with Bluemix object storage using the following code: import boto3, pprint, sys; s3 = boto3.Session().client( service_name="s3", region_name="us-geo", endpoint_url=" aws_access_key_id="auto-generated-apikey-<redacted>", aws_secret_access_key="<redacted>"); pprint.pprint(s3.list_buckets()); but keep getting AccessDenied error: <Error> <Code>AccessDenied</Code> <Message>Access Denied</Message> <Resource></Resource> <RequestId><redacted></RequestId> <httpStatusCode>403</httpStatusCode> </Error> I took aws_access_key_id and aws_secret_access_key from the "Service Credentials" tab. I used similar code for AWS S3, and it worked. What am I missing?
The IAM-enabled cos uses a slightly different syntax for client creation that is supported by a fork of the boto3 library. Here’s an example in the docs: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ibm cloud, object storage" }
Convert String to Date Object in Java I need to parse the following string into a date object in java: String time = "Jul 24 2012 05:19:34"; DateFormat df = new SimpleDateFormat("MM dd yyyy HH:mm:ss"); Date date = df.parse(time); The code throws this exception: Unparseable date: "Jul 24 2012 05:19:34" Does anyone know how to fix this?
Make it DateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss"); Note: `MMM`
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 3, "tags": "java, date" }
Como fazer for loop em SQL SERVER? BEGIN <<LOOP_EXTERNO>> FOR V_EXTERNO IN 1..20 LOOP DBMS_OUTPUT.PUT_LINE('Contador externo: ' || V_EXTERNO); <<LOOP_INTERNO>> FOR V_INTERNO IN 1..5 LOOP DBMS_OUTPUT.PUT_LINE('Contador interno: ' || V_INTERNO); IF V_EXTERNO = 10 THEN EXIT LOOP_EXTERNO; END IF; END LOOP INTERNO; END LOOP EXTERNO; END; / Esse comando é no `PL/SQL`, e eu não entendo como faze-lo no `SQL server`, não sei se é a mesma coisa ou algo muda. Alguém poderia me ajudar?
O sql server não tem o `FOR LOOP`, em vez disso ele usar o WHILE , para isso você tem que criar variáveis como contador. Seu código ficar assim. declare @V_EXTERNO int = 1 declare @V_INTERNO int = 1 BEGIN WHILE @V_EXTERNO < 21 BEGIN print 'Contador externo: ' + cast(@V_EXTERNO as varchar(10)); WHILE @V_INTERNO < 6 BEGIN print 'Contador interno: ' + cast(@V_INTERNO as varchar(10)); SET @V_INTERNO = @V_INTERNO + 1; END; SET @V_EXTERNO = @V_EXTERNO + 1; SET @V_INTERNO = 1; END; END;
stackexchange-pt_stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "sql server, oracle, pl sql" }
Finding the equivalent Resistance of acircuit !schematic simulate this circuit - Schematic created using CircuitLab I am a little confused on how to find R equivalent of this circuit because of the wire. Right now I have the following expression:Req= (R1//R2) +(R3//R4) Is this correct?
Redrawing the circuit should hopefully make the solution obvious: !schematic simulate this circuit - Schematic created using CircuitLab So yes, you are correct.
stackexchange-electronics
{ "answer_score": 6, "question_score": 0, "tags": "circuit analysis, resistance" }
Extjs 3.4 automatic reload grid after save new records in database Using Extjs 3.4 I call the `save()` method in the `store` to save new records. The `save()` method works fine: I see the new record in the database. The problem is the `save()` method doesn't automatically reload the grid after save. gridStore.save(); //Ok it works but grid is not reloaded.
When the server insert the data in DB he must return the new records just creates. The response must be entire new records not just the new ids. With this solution extjs parse the server response and automatically reload the grid.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, extjs, store" }
XML фигуры в Android Добрый день, Есть ли альтернативные программы для создания xml-фигур (кнопок, рамок и тд), кроме редактора в Eclipse? Получается в нем, пишем xml - смотрим, а хотелось бы рисовать, а файл генерится сам. Уважаемые обитатели hashcode, подскажите, какие способы, примочки и программы вы используете для кнопок и тд.? Photoshop + res/drawable/ ? NinePatch? XML? alternative?
Intellij IDEA там есть встроенный редактор, который генерит XML'ки Правда, я лично, предпочитаю все равно врукопашную... Ни один редактор не может заменить т.н. WYSIWYG верстку. **Update** Открываете xml файл лейаута и шлепаете на таб "Design". Выглядит как то так... !JetBrains designer
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "xml, android" }
In Views, how do I get a link directly to an image file (not the node containing the image file)? I have a view that displays nodes in _fields_ format. I have a _Global text_ field in which I want to display the URL of images contained in nodes; however, I can't find how to get the URL of the images. What I've tried: * I added the Image field and chose "Content" as the option for "Link to." This is the link I want, but this prints out the image too (I don't need the image) and I can't use this field as a replacement pattern. * I added a link to the content itself, but then this gives me a link to a node, not the image. In Views, how do I get a link directly to an image file (not the node containing the image file)?
An option that doesn't require installing a new module: * Create a Relationship to the image for which you want to create a link * Add a field File:Path * Exclude from display * Rewrite Results - output this field as a link * Add the replacement pattern to your global text
stackexchange-drupal
{ "answer_score": 3, "question_score": 1, "tags": "views, media" }
Should I declare function prototype for every function? In Obj-C, what's the best practice for function prototype ? Should I include them for every function in my class or just the one that's needed (i.e a function call happens before a function implementation)
Generally speaking, there is no need to forward declare private functions and methods unless the compiler requires it. I can think of no practical benefit to forward declaring proactively. Even for internal documentation purposes, it is better to put the documentation close to the function rather than all at the top of the file. Of course you have to declare public methods and functions in the header, and you should document them there as well. But that's a separate issue.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "objective c, ios, function" }
create threads but don't run it immediately in linux I am trying to execute my program in threads, I use `pthread_create()`, but it runs the threads immediately. I would like to allow the user to change thread priorities before running. How it is possible to resolve? for(int i = 0; i < threads; i++) { pthread_create(data->threads+i,NULL,SelectionSort,data); sleep(1); print(data->array); }
Set the priority as you create the thread. Replace errno = pthread_create(..., NULL, ...); if (errno) { ... } with pthread_attr_t attr; errno = pthread_attr_init(&attr); if (errno) { ... } { struct sched_param sp; errno = pthread_attr_getschedparam(&attr, &sp); if (errno) { ... } sp.sched_priority = ...; errno = pthread_attr_setschedparam(&attr, &sp); if (errno) { ... } } /* So our scheduling priority gets used. */ errno = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); if (errno) { ... } errno = pthread_create(..., &attr, ...); if (errno) { ... } errno = pthread_attr_destroy(&attr); if (errno) { ... }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c++, linux, multithreading, unix, pthreads" }
Where does Firebase fit in? This is a conceptual and rather basic question. So I know HTML, CSS, JS and now AngularJS. And I was wondering how I could build functional web apps without knowledge of server side programming languages - and chanced upon Firebase. Could someone please explain to me how I could use Firebase to build web apps - with my limited knowledge in mind?
Building a full-featured web application without any server-side logic and input validation does not make much sense. If you are unwilling to learn a server-side language and a proper framework, take a look at NodeJS. It allows you to write server-side code in JavaScript, so if you catch up on security principles you should do OK. Good luck!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "php, database, html, firebase realtime database" }
How close automatically a PrimeFaces dialog after three seconds I want to show a dialog only three seconds and after close it automatically and redirect an other faces page. How can I do it? Thanks in Advance. The dialog: <p:dialog id="dialog" header="Message" widgetVar="dlg1"> <h:outputText value="your account is being blocked......" /> </p:dialog>
Dialog has two attributes `onShow` and `onHide`(you can reference in Primefaces doc), and you can use timeout to do it, you can try: <p:dialog widgetVar="dlg1" onShow="myFunction();" onHide="myStopFunction();"> </p:dialog> <script> var myVar; function myFunction() { myVar=setTimeout(function(){ dlg1.hide()},3000); } function myStopFunction() { clearTimeout(myVar); } </script>
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "jsf 2, primefaces" }
when does product of maps being zero implies acyclicity Suppose $R$ is a polynomial ring and $R^n\xrightarrow{\phi_1}R^m\xrightarrow{\phi_2} R^s$ be such that $\phi_2\circ\phi_1=0$. Let the rank of $\phi_1$ and $\phi_2$ be $r_1,r_2$ respectively. Then does $\operatorname{grade} I_{r_1}(\phi_1)\geq 1$ and $\operatorname{grade} I_{r_2}(\phi_2)\geq 2$ imply the above complex is exact? It has bearing on the theorem of Buchsbaum-Eisenbud. They show that for a complex of free modules $0\rightarrow F_n\xrightarrow{\phi_n} \cdots F_2\rightarrow F_1\xrightarrow{\phi_1} F_0\rightarrow 0$ such that the rank of $\phi_i=r_i$. Then the complex is acyclic if and only if $\operatorname{grade} I_{r_i}(\phi_i)\geq i$ for every $i$.
Consider $R=k[x,y,z]$ with $\phi_1=(y,-x,0), \phi_2=(x,y,z)^T$. Then $r_i=1$, $\phi_2\circ\phi_1=0$, grade conditions are satisfied, but it is not exact. Am I missing something here?
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "commutative algebra" }
MySQL limit range SELECT name FROM mydb ORDER BY score DESC LIMIT 10; The query above will return the first 10 ranks. How to modify the `LIMIT`, or maybe is there another syntax to query the 10th rank through the 20th rank?
You should use: SELECT name FROM mydb ORDER BY score DESC LIMIT 10,10; < The two arguments 10,10 are (Offset, Limit) so this will retrieve rows 11-20. 9,11 Would be required to grab the 10th - 20th rank.
stackexchange-stackoverflow
{ "answer_score": 64, "question_score": 27, "tags": "mysql, sql, sql limit" }
Are outer joists a different distance in "on center" floor framing? I've watched some videos and talked to a contractor buddy about how to do floor framing. "16 inches on center" is the phrase I keep hearing, and I understand that that will ensure a layout divisible by 4 feet. However, if they were really all 16 inches on center, there would be an extra width of 1 1/2 inches (assuming 2-by framing material) because the outer joists would be a factor of 16 inches in distance on center. Based on reading and watching the proper method, it appears that the outer joists are actually 15 1/4 inches on center from the second joists since they start the second joist at 16 inches on center from the end of the rim joist. Is that correct? By the way, this is just a tiny shed and I'm not messing around with double joists. But my current best guess it that the outer joists are simply ignored in the _N_ -on-center scheme.
You are correct. Framing a wall or floor the two outer studs or joists are moved in to compensate for the end of the interval. If you are going for an exact dimension divisible by 4'. This makes placing 4'x8' sheets of OSB come out nice and even with no waste. Good luck!
stackexchange-diy
{ "answer_score": 1, "question_score": 1, "tags": "framing, joists" }
"What went wrong?" Vs. "What did go wrong?" I came across the phrase " **What went wrong?** " and I doubt if it has a correct form " **What did go wrong**?" or it would be already not idiomatic in this way. Is it idiomatic to use "What did go wrong?"?
The second form is idiomatic with one caveat. When we say it, we emphasize _did_. This means that we would also emphasize it in writing: > What _did_ go wrong? It doesn't sound right if we don't emphasize _did_. Without the emphasis, we would revert back to the simpler _What went wrong?_ When we do emphasize it, we are generally comparing it to something that _didn't_ go wrong: > "It all went wrong." > "You mean the food didn't get there?" > "No, actually that part was fine." > "Okay, so _what **did** go wrong_?"
stackexchange-ell
{ "answer_score": 2, "question_score": 1, "tags": "idiomatic language, emphatic polarity" }
How does family of curves formula exactly work? I am familiar with the following equations $$S_1 + \lambda S_2=0$$ for two circles $$L_1 + \lambda L_2=0$$ for two lines $$L_1 + \lambda S_1=0$$ for circle and line But I never really understood how they worked. Now this is a sample questions > A circles touches the parabola $y^2=2x$ at P $(\frac 12, 1)$ and cuts parabola at vertex V. If centre of circle is a Q, find the radius of circle The formula used here was $$(x-\frac 12)^2 + (y-1)^2 +\lambda (2x-2y+1)=0$$ Now it’s easy to see that equation is basically hinting at a curve passing through $(1/2, 1)$ and tangent to $(2x-2y+1)$, but how exactly was the form mat determined? How can we tell if this will us gives a circle? Why was the distance formula used in the first part of the equation? Basically I want to know the process of writing such equations .
$C_1:\left(x-\frac 12\right)^2 + (y-1)^2 =0$ is the equation of the circle having centre in $P\left(\frac12,1\right)$ and radius $r=0$ and $C_2:2x-2y+1=0$ is the equation of the line tangent to the parabola $\mathcal{C}:y^2=2x$ at $P$ A linear combination of the two $C_1+\lambda C_2=0$ represents all circles tangent to the parabola $\mathcal{C}$ at $P$ (see image (2) below) $$\left(x-\frac 12\right)^2 + (y-1)^2+\lambda(2x-2y+1)=0\tag{1}$$ If the circle passes through the origin, the vertex of $\mathcal{C}$, then substitute $(0,0)$ in $(1)$ to get $\lambda=-5/4$. The circle we are looking for has equation $$\left(x-\frac{1}{2}\right)^2+(y-1)^2-\frac{5}{4} (2 x-2 y+1)=0$$ simplify $$2 x^2+2 y^2-7 x+y=0$$ center is $\left(\frac74,-\frac14\right)$ and radius $r=\frac{5\sqrt 2}{4}$ * * * $$...$$ ![enter image description here]( ![enter image description here](
stackexchange-math
{ "answer_score": 2, "question_score": 2, "tags": "conic sections" }
$K$ compact $\implies K^{\epsilon}:=\{x: d(x,K)\le\epsilon\}$ compact? Let $(X,d)$ be a metric space. I was wondering under what condition on the space do we have that for any $K\subset X$ compact we have that $K^{\epsilon}:=\\{x: d(x,K)\le\epsilon\\}$ is also compact. Should the space be locally compact?
This is equivalent to the Heine-Borel-property. If $X$ satisfies the Heine-Borel-property (i.e. closed + bounded implies compact), then clearly $K^\varepsilon$ is closed and bounded for a compact $K \subseteq X$, therefore compact. If $X$ satisfies your property, then any closed and bounded set $X \supseteq A\neq \emptyset$ is contained in one $ \\{a\\}^\varepsilon$, for some $a \in A$, $\varepsilon$ sufficiently large. Since $\\{a\\}$ clearly is compact, so is $ \\{a\\}^\varepsilon$ and therefore $A$, being a closed subset of a compact set.
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "general topology" }
Who is the woman of a similar age to Wit? In _Words of Radiance_ , chapter 55, after Shallan hugs Wit (aka Hoid), Adolin jealously tells Wit: > Stick to women your own age. To which Wit cryptically replies: > Well, that might be a little harder. I think there's only one of those around these parts, and she and I never did get along. Are there any hints as to whom he might be referring to?
Hoid is said to have been at the shattering of Adonalsium (this is obviously not said in the books where precious few know that event, but has been confirmed by the author to various fans, and is backed up by the fact that he knows most of the Shardholders by their original names). That event was millenia ago. So basically, the only woman his age that would be around would be a Shardholder holding one of the god-powers from that event. **Which basically means he's probably referring to the bearer of Cultivation,** whose real name I don't believe is known at this point, but who is believed to be female, and is anyway the only Shardholder that isn't either dead or utterly evil in the area.
stackexchange-scifi
{ "answer_score": 11, "question_score": 5, "tags": "cosmere, stormlight archive" }
Why does R notebook display truncated lines in "html_notebook" output? I have a R notebook named "test.Rmd" with the following content: --- title: "R Notebook" output: html_notebook --- ```{sh} faToTwoBit dmel-all-chromosome-r6.04.fasta dmel-all-chromosome-r6.04.2bit ``` Then rstudio will create "test.nb.html" automatically. However, the code chunks are wrongly displayed in the html: ![enter image description here]( It only displayed `bit`, instead of the entire line (`faToTwoBit dmel-all-chromosome-r6.04.fasta dmel-all-chromosome-r6.04.2bit`). Is there something wrong with my .Rmd?
I'm not familiar with the shell command you are running, however, it seems that the language engine is getting confused with the way to display it. Given that the form is meant to be `faToTwoBit in.fa [in2.fa in3.fa ...] out.2bit`, I recommend explicitly stating the engine. --- title: "R Notebook" output: html_notebook --- ```{test1, engine="sh"} faToTwoBit dmel-all-chromosome-r6.04.fasta dmel-all-chromosome-r6.04.2bit ``` ![enter image description here]( You could also lodge an issue on github, where they may be able to provide a more permanent solution.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "r, rstudio, knitr, r markdown, rnotebook" }
When are $n$ and $2n$ both sums of two squares? Given a natural number $n$, can we completely characterize when $n$ and $2n$ are each a sum of two squares? For example: $446,382,709=(13010)^{2}+(16647)^{2}$ and $892,765,418=2(446,382,709)=(3637)^{2}+(29657)^{2}$ Do these imply, perhaps, that 446,782,709 is the hypotenuse of a primitive pythagorean triple? (I found this question on a slip of paper while cleaning my office. It turns out that a trivial algebraic identity resolves the question...beyond Euler's characterization of when a natural number is the sum of two squares. Is the question nontrivial if we replace $2n$ by $3n$ above?) EDIT: The modification is trivial, too. This is my fault, as I didn't think about my question before posting it. (This was a problem found on a slip of paper in my office. I posted it because it looked like a fun problem for students. This is certainly not the best forum for such things!!!)
A natural is the sum of two squares iff every prime of the form $\rm\:4\:k+3$ occurs to even power in its prime factorization (iff the same is true for $\rm\:2\:n\:$). Note $\rm\ n = x^2 + y^2\ \Rightarrow\ 2\:n = (x+y)^2 + (x-y)^2$ which arises by compositions of forms, or, in linear form, with the norm $\rm\ N(a+b\ i)\ =\ a^2 + b^2 $ $$\rm 2\ (x^2+y^2)\ =\ N(1+i)\ N(x-y\ i)\ =\ N((1+i)\ (x-y\ i))\ =\ N(x+y + (x-y)\ i) $$
stackexchange-math
{ "answer_score": 19, "question_score": 9, "tags": "number theory" }
Python not able to get iotop output I am working on a python script which needs to read the output of iotop. But stdout appears to be blank. The goal is to have the output of iotop stored as a string which I can then later search and use. This is running on Ubuntu 16.04 w/ python 3.6. I am calling the script with "sudo python3.6 script.py" as iotop requires admin rights. p = subprocess.Popen(['iotop','-b','-n','1','-a','-k'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) try: outs, errs = p.communicate(timeout=15) except subprocess.TimeoutExpired: p.kill() outs, errs = p.communicate() returncode=p.returncode print(outs.decode('UTF-8')) Running this command in the bash terminal gives me the expected output. What am I doing wrong? sudo iotop -b -n 1 -a -k
Removing `shell=True` made the code work the way I wanted to. p = subprocess.Popen(['iotop','-b','-n','1','-a','-k'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, monitoring" }
Velocity factor in coax cables I mainly see the term "velocity factor" used when referring to the velocity of propagation of an electromagnetic wave front in coax cables. This velocity seems strongly dependent on the properties of the cable's dielectric. Would coax cables stripped of their tubular shielding (but not their dielectric) have the same velocity factor as a normal coax line? Or is the velocity affected by electromagnetic coupling between the core and shield?
Well, in vacuum the velocity of a wave is $c_0=3\cdot10^8$m/s. The speed in a medium is $\frac{e_0}{n}$ where $n$ is the refractive index of the material .The relationship between the refractive index and dielectric constant is $n=\sqrt{\epsilon_r\mu_r}$ where $\epsilon_r$ and $\mu_r$ is the relative permitivitty (dielectric constant) and relative permeability of the material. Thus the velocity of the wave is $\frac{c_0}{\sqrt{\epsilon_r\mu_r}}$ Stripped cable should show the same speed for the wave still confined in the dielectric. You can however, if you want to, dig deeper into group and phase velocity and try to see where that math takes you.
stackexchange-physics
{ "answer_score": 1, "question_score": 0, "tags": "electricity, electric circuits, electric fields, dielectric" }
will Opera's DragonFly and Extentions still exist in Webkit world? I just saw that Opera will stop using Presto, and switches to WebKit, so will DragonFly still exists, or this will be replaced by Chrome Inspector? And what about Extensions too!
There will be no Dragonfly in Opera with WebKit (Blink): <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 4, "tags": "webkit, opera, blink, opera dragonfly" }
How to rollback the appcfg in Google App Engine? Unable to update app: Error posting to URL: 409 Conflict Another transaction by user suganya.karthik is already in progress for app: s~ethereal-zodiac-803, version: 1. That user can undo the transaction with "appcfg rollback". See the deployment console for more details Unable to update app: Error posting to URL: 409 Conflict Another transaction by user suganya.karthik is already in progress for app: s~ethereal-zodiac-803, version: 1. That user can undo the transaction with "appcfg rollback".
Just as the message says, you need to use `rollback` command to undo the previous update that failed to complete. Just replace the word `update` with the word `rollback` (everything else stays the same) and run the command. You can run it in the terminal window (command prompt) on your computer by running appcfg program. * Python: < * Java: <
stackexchange-stackoverflow
{ "answer_score": 25, "question_score": 11, "tags": "google app engine" }
Bug configuring Cloud SQL instance? Error encountered while trying tutorial I'm following the tutorial at < and hit an issue with the section "Configure the new Cloud SQL instance". Basically, I can't click "Save" successfully when entering the "0.0.0.0/0" network configuration. Chrome's Javascript Console shows an error "Custom HTML/JavaScript blocked. See go/13687728." What's going on? I tried continuing with the tutorial but hit an issue at the "npm run-script init-cloudsql" step. Thanks for the help / fix!
I found a work around that might get you moving: Click Add Item, Enter details, then click Save. Do not add another until the done message appears.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "google cloud sql" }
removing a repo from a group in gitolite I've a gitolite setup, my gitolite.conf file looks like, @myrepos = test @myrepos = proj1 proj2 repo @myrepos RW+ = user1 user2 user3 user4 Now, I'd like to give access to a new user "user5" to "proj2" alone. Is there a way to do it in gitolite without removing the repo from the group? If I were to remove the repo "proj2" from the group to place it separately, would that break something?
You could define another rule just for user5 and proj2, which means you don't have to modify `myrepos` group. repo @myrepos RW+ = user1 user2 user3 user4 repo proj2 RW+ = user5
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "git, gitolite" }
How to create method to use "_changed?" on combined fields Suppose I have a method that combines several address fields like so: def address "#{street_address}, #{city}, #{state}, #{postal_code}, #{country}" end How would I extend the method to allow for the checking if any of the fields have changed? Basically, I'd like to be able to do the following: after_validation :geocode, :if => :address.changed? My model is as follows: class Place < ActiveRecord::Base attr_accessible :street_address, :city, :state, :postal_code, :country, :latitude, :longitude, :geocode_type geocoded_by :address after_validation :geocode#, :if => :address.changed? def address "#{street_address}, #{city}, #{state}, #{postal_code}, #{country}" end end Or is there a better way to do this all together?
def address_changed? attrs = %w(street_address city state postal_code country) attrs.any?{|a| send "#{a}_changed?"} end
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "ruby on rails, ruby on rails 3" }
Map NumPy integer list values to lists according to lambda function How can I map each value of an integer NumPy array to a list according to a lambda function? I have the following code: x = [0, 1, 2, 0, 0, 2, 1, 1] colours = [[0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0, 255]] coloured = lambda v: colours[int(v)] vcoloured = np.vectorize(coloured) x_color = vcoloured(x) # throws ValueError: setting an array element with a sequence. # would like to get x_color = [[0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0, 0], [0, 0, 0], [0, 255, 0], [255, 0, 0], [255, 0, 0]]
Don't bother with lists at all. If you have numpy arrays, it's much faster to use the power of numpy: >>> x = np.array([0, 1, 2, 0, 0, 2, 1, 1]) >>> colors = np.array([[0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0, 255]]) >>> x_color = colors[x] >>> x_color array([[ 0, 0, 0], [255, 0, 0], [ 0, 255, 0], [ 0, 0, 0], [ 0, 0, 0], [ 0, 255, 0], [255, 0, 0], [255, 0, 0]]) Yeah, I went ahead and Americanized your spelling, but functionally, the array `x_colored` will behave just like a list for all practical purposes. If you absolutely need a list, just call `tolist` on the result: x_color = colors[x].tolist()
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "python, arrays, numpy" }
Reading double-precision floating point numbers from a file? My problem is pretty simple; I have text file filled with double precision floating point numbers which I need to read in and store in a matrix. I know how to open the file but from there I'm not sure how to parse out the data and convert it. The numbers are separated by spaces and newlines and each is preceded by a sign (either '+' or '-'). I'm not sure which function (scanf, fgetc, etc.) I should use to read in the data. I'm not new to programming though this is my first time working extensively with C. Detailed explanations are welcome as I'd like to get more familiar with how tasks like this are handled. Thanks! Edit: Should have clarified that the file is generated by code so no need to worry about users messing with it. Also From reading the docs it seems like I could just use fread to load all of the contents of the file into a string and then use atof to parse out each double. Is this correct?
double d; scanf("%lf", &d); scanf will skip the white space chars and let you read all values in a simple loop. If you are reading from a file then fscanf should be your choice. scanf documentation and fscanf documentation
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "c, string, file, double" }
How to export a table with header to Excel with table2excel I'm using table2excel to export a datatable powered by jQuery DataTables to Excel. I am able to export the data to excel but i am not able to export table with the heading. Here is my code $('#btn-export').on('click', function () { $('<table>').append(table.$('tr').clone()).table2excel({ exclude: "", name: "EmailTracking", filename: "EmailTracking" //do not include extension }); }); Here is my HTML: <table id="userGrid" class="table table-striped table-bordered dt-responsive nowrap " cellspacing="0" width="100%"> <thead> <tr> <th>User</th> <th>Subject</th> <th>Sent On</th> <th>To</th> <th>Cc</th> <th>Bcc</th> </tr> </thead> <tbody> </tbody> </table>
Use the code below: $('<table>') .append($(table.table().header()).clone()) .append(table.$('tr').clone()) .table2excel({ exclude: "", name: "EmailTracking", filename: "EmailTracking" //do not include extension }); See this example for code and demonstration.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "javascript, jquery, html, excel, datatables" }
Google Apps Script Popup to maintain widgets when re-opened I'm working on a script using Google Apps Script with UiApp and I need to maintain the widgets in a popup after reopen it. e.g. Open a popup, create some listboxes, close the popup and on reopen the same listboxes should be there. Any sugestion?
When you close and reopen a UI you get a new instance of it so that the widgets will have forgotten everything they knew ;-) You'll have to take care of it yourself and store every data somewhere so that you can restore the previous state when the new Ui shows up. The place to store and the way to do it are your choice and depend mainly on the context in which you use that Ui.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "google apps script" }
Is it possible to find Dittos by catching some rare Pokémon? Sometimes I am thinking if I encounter a Dragonite or Lapras, will it turn into a Ditto? It is requiring the possibility to catch dittos from rare Pokémon. Hope no Dittos from those rare Pokémon.
So far, only common Pokémon like Zubat and Magicarp have been shown to potentially be a Ditto in disguise. So it is most likely not possible unless proven otherwise.
stackexchange-gaming
{ "answer_score": 1, "question_score": -3, "tags": "pokemon go" }
MATLAB interop server (automation server) is available with Runtime libraries? I am trying to figure out whether it is possible to use the MATLAB COM server (automation server) without installing the whole MATLAB package (but only the runtime libraries).
I will assume that MATLAB COM server is Matlab engine and runtime libraries are MCR. And the answer is: **No** , because `MCR` is available to re-distribute freely whereas `Matlab` requires a license. This is taken directly from here: > You must use an installed version of MATLAB; you cannot run the MATLAB engine on a machine that only has the MATLAB Compiler Runtime (MCR).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "matlab, com server" }
Need to know webclient download method run in UI thread I have used the web client method to download images using a background worker in my wp7 app. I came to know the webclient method usually run in the UI thread by default. So now there is a confusion that wheather the webclient run in the backround thread or UI thread in the app even if it is mention inside the background worker class
The execution of a `WebClient` request will run on the thread it is called on, unless it has a Async suffix at the end of it's method name. (For example `DownloadData(Uri)` will run on the same thread as the call. `DownloadDataAsync(Uri)` will run on a new background thread) If you're using a `BackgroundWorker` to call your WebClient requests it will not be executed on the UI thread (Both using the `Download` and `DownloadAsync` methods), because `BackgroundWorker` already runs it's code in a background thread in the first place. EDIT: Looking at your tags, it should be noted that Silverlight (and thereby Windows Phone 7) only supports the Async versions of the `WebClient` calls.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "wpf, silverlight, windows phone 7, windows phone 7.1" }
Homeomorphism of closed manifold Suppose that we have two closed n-manifold $M$ and $N$ such that the topological group of homeomorphisms $Homeo(M)$ is homotopy equivalent to $Homeo(N)$ (maybe as topological groups if needed), can we deduce that $M$ is homotopy equivalent (or even homeomorphic ) to $N$ ? Is there an easy counterexample ?
It is a result of Whittaker (1963), and Rubin (1990, in greater generality with a better proof) that $Homeo(M)$ (viewed as a group) determines $M$ up to homeomorphism (see this question). I doubt that the homotopy type is enough: Gabai had shown that for closed hyperbolic 3-manifolds, the inclusion of $Isom(M)$ into $Diff(M)$ is a homotopy equivalence. $Isom(M)$ is a finite group, so its homotopy type is given by its order. I don't think it is hard to find two hyperbolic manifolds with the same cardinality of isometry group (in fact, I assume that order is usually equal to $1.$)
stackexchange-mathoverflow_net_7z
{ "answer_score": 11, "question_score": 6, "tags": "at.algebraic topology, gt.geometric topology, manifolds" }
Why will my friend have to grow his beard out? _Knowledge required for this riddle: English-language proverbs._ My friend Leonard came to me with a problem the other day. He said, “Tanner, I want to have a clean-shaven face. But every time I use a razor, I end up with this nasty painful rash.” “Razor burn,” I said. “Yeah, that's right,” said Leonard. “Do you have any advice for me?” “Unfortunately, there's no good solution,” I told him. “You're going to have to either grow your beard out, or just cope with those painful rashes.” **Why will Leonard have to grow his beard out?**
Maybe it is because > A Lenny shaved is a Lenny burned. > (A penny saved is a penny earned.)
stackexchange-puzzling
{ "answer_score": 29, "question_score": 20, "tags": "wordplay, english" }
How to read this advanced return statement? > **Possible Duplicate:** > Reference - What does this symbol mean in PHP? When I use a function I use standard return statements. I mean by that that I usually either return `true` or `false` or a variable. Nevertheless I am currently following a tutorial which I understand pretty well beside the return of the here below function. I do not get how to read the question mark the two dots.... public function someFunction() { return null === $this->anAttribute ? null : $this->aFunction(); }
Return `null` if `$this->anAttribute` is `null` else return `$this->aFunction()` `?:` called ternary operator Writing `null` in first place is used for avoiding wrong assignments typo, like `if ($a = null)`. If you get used to writing functions and constants firts this will lead to error `if(null = $a)` `===` can be read in article used above and called **Identical**. `$a === $b` `TRUE` if `$a` is equal to `$b`, and they are of the same type.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, return" }
Binary Programming with nonlinear constraints i have the following type of problem i'm interested to solve: Minimize the objective function: $f(x_1,\ldots, x_8) = \sum_{i=1}^8 a_i x_i$ with $a_i \in [0, \infty)$ and $x_i \in \\{0,1\\}$ and given constraints:$\\\ \begin{align} x_1+x_2+x_3+x_4 &= 1\\\ x_5+x_6+x_7+x_8 &= 1\\\ x_1x_5 + x_2x_6 + x_4x_8 + x_4x_7 &= 1 \end{align}$ Later i want to solve this type of problem with say 200 variables. Is there a matlab implementation to this? I only know yet the _binintprog_ function to solve _linear_ binary programming. Also I think, that this could be computationally extremly hard to solve.
I've just noticed (thanks to @Macavity) that $x \in \\{0,1\\}$, not $x \in [0,1]$. Then, your system as it is, is trivial. The first equation says: exactly one of $x_i$ for $i \in \\{1,2,3,4\\}$ equals 1, and the second implies the same for $i \in \\{5,6,7,8\\}$. The third ensures that exactly one pair must be "enabled", so you need to find minimum of $a_i+a_j$ such that $x_ix_j$ term belongs to the third formula, that's it. This easily extends to solutions with more variables and _the same form_. On the other hand, it might be very hard to find a solution for a general problem, the issue being you can easily embed any logical formula into it, particularly the SAT problem. Finally, there is a hope for _some_ formulas, including those that can be converted to 2-SAT, for example, it is alright as long as your constraints mention at most _two_ variables at a time. I hope this helps ;-)
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "binary, integer programming" }
Why is the interaction energy of the electrons in an atom positive? Consider a simple Hamiltonian for the Helium atom (where $e'^2 = e^2/4\pi \epsilon_0)$: $H=\frac{P_1^2}{2\mu}+\frac{P_2^2}{2\mu}-\frac{Ze'^2}{R_1}-\frac{Ze'^2}{R_2}+\frac{e'^2}{|\vec{R}_1-\vec{R}_2|}$ I understand the first two kinetic terms are positive because they contribute to the ionization; the second two are negative because they correspond to the _attractive_ potential of the nucleus. But is the third term positive? If I calculate the ground state energy ($-\frac{\mu Z^2e'^4}{2\hbar^2}\sim-Z^2$Ry) without electron interactions, I obtain $\sim-4$ Ry, whereas the experimental value is $\sim-5,8$ Ry, which leads me to conclude that to correct this value the interaction term must be _attractive_ (in order to "attract" the system towards its center), so it should have a minus sign. However, intuitively, I know the interaction between electrons should be repulsive, and have a positive sign!
Your intuition is correct. The error is in your calculation of the ground state energy without interactions. There are _two_ electrons, each with energy $-4\,{\rm Ry}$, for a total of $-8\,{\rm Ry}$. The repulsion raises the energy to the experimental value.
stackexchange-physics
{ "answer_score": 2, "question_score": 2, "tags": "quantum mechanics, atomic physics" }
URL Scheme not trigger application:openURL:options I just setup my URL Scheme In `plist.info`file. When I use the assoicated web page I have two different cases : 1 - If the app is lunched and in the background : The URL form the web page open the app and trigger `application:openURL:options` and the parameters parsed and the flow continue smoothly. 2 - If the app isn't lunched : The URL from the web page open the app but **NOT** trigger `application:openURL:options` so the application stop on the first screen. Why the second scenario happened ? I'm on iOS 9.0 as a deployment target and iOS 9.3.5 as a testing device version.
The behaviour of `application:openURL:options:` depends on the result of `application:willFinishLaunchingWithOptions:` and `application:didFinishLaunchingWithOptions:` methods, because you can handle the incoming urls always inside of these methods. Take a look into the discussion section in the docs for `UIApplicationDelegate` (< for more details.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, deep linking, url scheme" }
Objective-C memory management: if I release a string stored in an array, it only releases this reference or it releases the object in the array? If I have this: NSString *lastPushed = (NSString *)[tagStack objectAtIndex:[tagStack count]-1]; .//do something with the last pushed element locally .//do more cstuff here .//after doing all the stuff needed in the function [lastPushed release]; where tagStack is an NSMutableArray If I release lastPushed, since it was not copied, or inited, will it only release this reference or will it actually release the object in the mutableArray?
You didn't `alloc`, `new`, or `copy` or `mutableCopy` `lastPushed`, so why are you releasing it? Since `lastPushed` is a pointer to the object in the array, you are releasing that. This _could_ lead to a problem when your array thinks that it has a valid pointer to an object but you've released it and it's been `dealloc`ed.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "objective c, memory management" }
I have to tables I want to join them and also want to use group by clause using lambda expression The below is the SQL query, for this i want to write lambda expression. the entity model for the Enrollment_Policy and Enrollment_MemberPolicy tables is MCEntities. select mp.PolicyId, p.PolicyNo from Enrollment_Policy p inner join Enrollment_MemberPolicy mp on mp.PolicyId=p.ID where mp.UHID=123 group by mp.PolicyId, p.policyNO I got stuck at how to write group by clause. Please some one help me.
This is how you can achieve this. Let's say you have Foo and Bar classes: public class Foo { public int Id { get; set; } public string Prop1 { get; set; } public int BarId { get; set; } } public class Bar { public int Id { get; set; } public string Prop2 { get; set; } } Then you can operate them like this: var arr = new List<Foo>() {new Foo(){Id=1, Prop1 = "test"}}; var arr2 = new List<Bar>() {new Bar(){Id=1, Prop2 = "test"}}; var arr3 = arr.Join(arr2, foo => foo.BarId, bar => bar.Id, (foo, bar) => new {foo, bar}) .Where(t=>t.foo.Prop1=="test") .GroupBy(t => new {t.foo.Prop1, t.bar.Prop2});
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, sql server, lambda, asp.net mvc 5" }
Правильний ужиток слів «те» і «то» Я часто чую «те» у спілкуванні українською. Наприклад, «те, що я сказав». Але також мені незвично говорити, наприклад, «що те таке?». Тут чомусь мені здається, що більше підходить «то». Як насправді правильно використовувати ці слова?
Ви маєте рацію: казати «що те таке?» і «то, що я сказав» не слід. Але, боюся, конкретно для цих прикладів пояснення банальне: * Конструкція «те, що» (приблизний відповідник англ. «that which») є сталою і не допускає заміни «те» на «то». Якби хтось сказав «то, що», я би поправив людину, уточнивши, що це русизм. * Вираз «що то таке?» також є в кращому випадку сталим, а в гіршому — ще й не зовсім нормативним (більш звично було б — залежно від значення — «що це таке?» або «що ото таке?»). Якби хтось сказав «що те таке?», я би перепитав «що те _що_ яке?», бо «те» звучить тут на слово в ролі прикметника. Робити ж узагальнення, на жаль, важко, бо і слово «те», і слово «то» мають в українській по кілька різних значень із різними особливостями вжитку кожне.
stackexchange-ukrainian
{ "answer_score": 3, "question_score": 3, "tags": "вибір слова, різниця між словами" }
Generation of random capital letters in C# while checking to generate only one pair from each Hi I'm trying to code basic console Pexeso game in C#. And I'm wondering how to generate one and only one pair of capital letters. So far my code can genereate string with random capital letters but I don't know how to control it to generate only two and only two from each one. string chars = "AABBCCDDEEFFGGHHIIJJKKLL"; var stringChars = new char[24]; Random random = new Random(); for (int i = 0; i < stringChars.Length; i++) { stringChars[i] = chars[random.Next(chars.Length)]; } string finalString = new String(stringChars); Console.WriteLine(finalString); Thank you very much for your help.
You start off well by defining all items you want in your final sequence. What you want to do next is not take items from that list (in a way that you can take them more than once) as you do now, instead you actually want to _shuffle_ your list. Imagine your letters are playing cards, and you take two full sets. You shuffle them, and you have a sequence of playing cards, in which every card appears exactly twice. To shuffle your set of letters, or any given sequence, you can use the Fisher-Yates shuffle. Something like this should do the trick: for (int i = chars.Length - 1; i > 0; i--) { char j = random.Next(i + 1); int temp = chars[i]; chars[i] = chars[j]; chars[j] = temp; } Now your `finalString` is no longer needed: the result you want is in your `chars` array.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c#, random, generator" }
Get matching route from URL How do you retrieve the matching route for a URL (in string format)? Basically something like... Routes.GetMatchingRoute(" Without having a HttpContext. Basically I would like to RedirectToAction using a referring URL.
You _could_ just return Redirect(url); instead of RedirectToAction(); I recall seeing someone ask that on SO before, but I can't find the question. Edit: here it is (note the edit by the OP), there was no answer there either.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, asp.net mvc" }
Find the count of all Brzozowski's derivatives of a given language Given the language L = {$a^nb^n: n\in \mathbb{N}$} I have to find the number of derivatives I can produce from it. I wrote down some of them and I feel like the number of them must be infinite, is that correct? For every n there will be for example $(a^n)^{-1} L$, but also ($a^{n-1})^{-1} L$ etc... Can someone tell me if my reasoning is right?
You’re right, but you can make it much clearer by actually identifying the derivatives: for each $n\in\Bbb N$ $$(a^n)^{-1}L=\\{a^kb^{k+n}:k\in\Bbb N\\}\,,$$ and these are clearly all distinct languages.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "formal languages, automata" }
How to find the timestamp of the last lock? I want to determine which process locks my table TABLE1, and the timestamp when it was locked. I suppose that I should use tables like `dba_locks` and `gv$session`, but I'm new on Oracle and I don't know much about system tables. Can anybody help me with this query?
Use this query to find the last time a session was blocked waiting for access to a specific table: select max(sample_time) last_block_time from gv$active_session_history --Or use this table for further back. --from dba_hist_active_sess_history where blocking_session is not null and current_obj# = ( select object_id from dba_objects where owner = 'JHELLER' --Enter the object owner here. and object_name = 'TEST1' --Enter the object name here. ); This is not necessarily the same thing as "when was the last time the table was locked". It's possible the table, or a row in the table, was locked but no sessions waited on it. And it's possible that a session did wait on it but not during the sample. However, if something does not happen often enough to appear in the session history tables then it's usually not important enough to worry about.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "sql, oracle, locking" }
rails の migration の仕様について rails Active Record MigrationFile () Migration File file name alphabetical order ( file name datetime prefix ) 1. MigrationFile () 2. db:setup schema.rb MigrationFile db/migrations rails migration # * rails `db:migrate`, `db:reset`, `db:setup`, `db:migrate:reset` ? * ?
schema_migration (YYYYMMDDHHMMSS) db/migrate 1. MigrationFile () DB 2. MigrationFile db/migrations > db:migrate, db:reset, db:setup, db:migrate:reset ? schema.rb **db:migrate** DB **db:migrate:reset** schema.rb **db:reset** schema.rb schema.rb **db:setup** DB schema.rb setup db:migrate * * * < db:migrate:reset = db:drop + db:migrate db:reset = db:drop + db:setup db:setup = db:create + db:schema:load + db:seed < db:schema:load force:true drop and create create already exist db:migrate
stackexchange-ja_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ruby on rails" }
PHP - How do you get the values of a dropdown from SQL Say I've got a dropdown list on my site like this: <select> <option value="test">Volvo</option> <option value="icles">Saab</option> <option value="lol">Mercedes</option> <option value="hax">Audi</option> </select> But I don't want the above values, what if I want to get the values from an SQL table, how would I do this? Obviously this would be PHP but could someone give me an example?
you will have to do it like this: first select the values: `$result = "SELECT * from table";` then you will have to `foreach()` those values and create your selectbox like this: echo '<select>'; foreach($result as $res) { echo '<option value="'.$res['somevalue'].'">' . $res['car_name'] . '</option>'; } echo '</select>'; and you're done :D
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -3, "tags": "php, html, mysql" }
Celebrate title after red card If a player receives a red card during the final of a football tournament and leaves the pitch, can he goes back and celebrate the title, if his team wins? Do you remember such a case?
Yes; the French player Marcel Desailly got sent off during the 1998 World Cup final against Brasil but there are many pictures of him celebrating, like the one below (he's the one in the blue shirt with number 8): ![enter image description here]( (source: ABC News, Getty Images, Lutz Bongarts)
stackexchange-sports
{ "answer_score": 8, "question_score": 8, "tags": "football" }
Regex to remove word from XSLT I need help writing regex to remove a word using XSLT. I need to change the output of my XML file's "detailpath" from: /events/262/26207 ...to simply: 262/26207 The XSL is: <xsl:value-of select="detailpath"/> How can I remove "/events/"? Thanks in advance.
The regex pattern would simply be `'/events/'` You can use it in an XSLT 2.0 replace() function call: <xsl:value-of select="replace(detailpath,'/events/','')"/> > function returns the xs:string that is obtained by replacing each non-overlapping substring of $input that matches the given $pattern with an occurrence of the $replacement string. You can optionally specify flags > > fn:replace( $input as xs:string?, > $pattern as xs:string, > $replacement as xs:string) as xs:string > > fn:replace( $input as xs:string?, > $pattern as xs:string, > $replacement as xs:string, > $flags as xs:string) as xs:string >
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "regex, xslt" }
Add Assemblies to Visual Studio 2015 ASP.NET 5 I want to add "Stimulsoft.Report.dll" as an assembly in my Visual Studio 2015 ASP.Net 5 project. But the reference manager does not contain the assemblies section with the extentions area(as it is in VS 2013), where i could select "Stimulsoft.Report" and add this to my references. Is there any solution adding these reference to my ASP.NET 5 project?
you can add the assembly if it available in GAC like below code "frameworks": { "aspnet50": { "frameworkAssemblies": { "Stimulsoft.Report": "" } } } in the second part, you can give the version and type of the assembly
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "assemblies, asp.net core, visual studio 2015, asp.net core mvc" }
Why is mapping over Optional Array different from non-optionalArray let optionalArray : [Int]? = [1,2,3] optionalArray.map({ print("beforeEach element"); print($0); }) let nonOptionalArray = [1,2,3] nonOptionalArray.map({ print("beforeEach element"); print($0); }) The output: > beforeEach element > [1, 2, 3] > beforeEach element > 1 > beforeEach element > 2 > beforeEach element > 3 I was using an OptionalArray and the `$0` was **returning the entire array**. Why? Am I not looping over it?!
You are running the map on an `Optional<[Int]>`, which also supports map. You want `optionalArray?.map` to run the map on the array the optional might be wrapping.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "arrays, swift, option type, enumeration" }
Getting FerrersDiagram to work I am trying to generate FerrersDiagram (see < any clues to getting it to work? I get error message for the following: << Combinatorica` FerrersDiagram[10] (* combinatorica Graph and Permutations functionality has been superseded by preloaded functionality. The package now being loaded may conflict with this. Please see the Compatibility Guide for details.*)
Argument should be a partition: FerrersDiagram[{1, 1, 2, 2, 4}] !enter image description here
stackexchange-mathematica
{ "answer_score": 3, "question_score": 0, "tags": "plotting, graphics, combinatorics" }
Guarantee for closest random point on a sphere Let $v \in \mathbb{S}^{d-1}$ be a fixed point on a sphere, and $X_1, X_2, \cdots, X_n \sim Unif(\mathbb{S}^{d-1})$ which are i.i.d. How large $n$ can guarantee that, with probability $1-\delta$, $\exists i$ such that $\|v-X_i \|\leq \epsilon$? I think sufficiently many samples could do this, but I don't know how to calculate. What about the case when $X_1, X_2, \cdots, X_n \sim N(0,1)$?
Note that if $d(u,x)$ is the distance between $u$ and $x$, then $$ \mathsf{P}\\!\left(\bigcap_{i=1}^n\\{d(u,X_i)>\epsilon\\}\right)=[\mathsf{P}(d(u,X_1)>\epsilon)]^n=\left[\frac{|\\{x\in \mathbb{S}^{d-1}:d(u,x)>\epsilon\\}|}{|\mathbb{S}^{d-1}|}\right]^n. $$ (Here $|\cdot|$ denotes area.)
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "probability, uniform distribution, spheres" }
Properties of nonsummable sequence Let $\\{\alpha_k\\}\subset \mathbb{R}$ be a positive sequence satisfying $$ \lim_{k\rightarrow\infty}\alpha_k=0, \quad \sum_{k=0}^{\infty}\alpha_k=+\infty. $$ Put $\displaystyle S_k=\prod_{i=0}^{k}(1-\alpha_i)$. Find the limits (if exist) * $\displaystyle\lim_{k\rightarrow\infty}S_k.$ * $\displaystyle\lim_{k\rightarrow\infty}\sqrt[k]{S_k}.$
I will assume that $\alpha_i\in(0,1)$. * * * Note that $$0\le\prod_{i=0}^k (1-\alpha_i) \le \prod_{i=0}^k \frac1{1+\alpha_i} = \frac1{\prod_{i=0}^k(1+\alpha_i)} \le \frac 1{1+\sum_{i=0}^k \alpha_i}$$ For $k\to \infty$ the RHS tends to zero, so you get $\lim\limits_{k\to\infty} S_k=0$. We have used $1-x\le \frac1{1+x}$, which follows from $(1-x)(1+x)=1-x^2\le 1$. * * * For the second part, let us try to use this result: $$\liminf_{n\to\infty}\frac{c_{n+1}}{c_n}\leq\liminf_{n\to\infty}\sqrt[n]{c_n} \le \limsup_{n\to\infty}\sqrt[n]{c_n}\leq\limsup_{n\to\infty}\frac{c_{n+1}}{c_n}$$ which is true for any positive sequence $(c_n)$, see e.g. this answer and this question. If we apply this to the sequence $(S_k)$, we get $$\liminf_{k\to\infty} (1-\alpha_{k+1}) \le \liminf_{k\to\infty} \sqrt[k]{S_k} \le \limsup_{k\to\infty} \sqrt[k]{S_k} \le \limsup_{k\to\infty} (1-\alpha_{k+1}),$$ which implies $\lim\limits_{k\to\infty} \sqrt[k]{S_k}=1$.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "sequences and series" }
Best Practice for temporary query result storage in Google App Engine I have a query that takes a bit of time (it involves some computations and accessing a third-party). Currently, the user makes an HTTP request to initiate the query (it returns immediately). GAE puts the task in a queue and executes it. After execution, the task stores the results in a static object. The user makes another HTTP request later to retrieve the results. Is there a best practice way to implement something like this? Would the results be better stored in the DataStore?
> the task stores the results in a static object How are you making sure that the subsequent request from same user hits the same instance so that it can access the static object? A better way to do it would certainly be either storing it in memcache (prone to hit or miss) and/or datastore. Keep in mind, with the new pricing model, datastore operations are going to cost more.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "google app engine" }
How to rotate the screen to landscape (or portrait) by programmable way? How to rotate the screen to landscape (or portrait) by programmable way? I am trying to make it independent when user rotates the screen. Is it possible thing ? Thanks in advance.
You can try with the sample below... if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { // You can set the value initially by // ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED. Once set it // retains it's value. The View will be rendered in the specified // orientation using the code below. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); }
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 7, "tags": "android" }
Plugins: Time/Date specific functions Other than setting up a cron job, does Craft include any functionality for plugins to run a function at a specific time and/or date? Some actions could include: * Bulk activate/deactivate entries * Messaging all users every monday (or once a week) * Hitting an API (account update, eCommerce, data updating etc.) Let me know if a question like this already exists. I searched and couldn't find any related information.
Not really, and it'd be pretty difficult for PHP to truly emulate a cron service since, by nature, it requires something to execute it before it can run (in Craft's case, a browser request). The closest thing in Craft would be its "Tasks" (completely undocumented). Tasks are usually meant for things that might take a long time for PHP to complete and it's not critical that they happen right away. But you can't schedule, them... if there is a task in a "pending" state in the craft_tasks table, the next request to the control panel is going to trigger it. I suppose we could add something like a "runDate" property to tasks where you could be at least guaranteed they wouldn't run until the first control panel request was made after that given date.
stackexchange-craftcms
{ "answer_score": 4, "question_score": 3, "tags": "plugin development, datetime, date" }
Need clarification about constant expressions K&R c 2nd edition(section 2.3) mentions > A constant expression is an expression that involves only constants. Such expressions may be evaluated at during compilation rather than run-time, and accordingly may be used in any place that a constant can occur however, I have several doubts regarding it: 1. Will this expression be considered as constant expression? const int x=5; const int y=6; int z=x+y; i.e using `const` keyword is considered constant expression or not? 2. Is there any technique by which we can check whether an expression was evaluated during compilation or during run-time? 3. Are there any cases where compile time evaluation produces different result than run-time evaluation? 4. Should I even care about it? (maybe I use it to optimize my programs)
1. Perhaps. A compiler can _add_ more forms of constant expressions, so if it can prove to itself that the variable references are constant enough it can compute the expression at compile-time. 2. You can (of course) disassemble the code and see what the compiler did. 3. Not if the compiler is standards-compliant, no. The standard says "The semantic rules for the evaluation of a constant expression are the same as for nonconstant expressions" (§6.6 11 in the C11 draft). 4. Not very much, no. :) But do use `const` for code like that anyway!
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "c, constant expression" }
How can I call a method when data binding gridview to edit data before displaying it? <asp:Label ID="RespiteDay" runat="server" Text='<%# Eval("StepRespiteDay")%>' </asp:Label> i want to call below method and edit "StepRespiteDay" PersianDateTime persianDate1 = new PersianDateTime("StepRespiteDay"); persianDate1.ToString("dddd dd MMMM yyyy"); then i want to display persianDate1 instead of "StepRespiteDay" what should i do? thank you very much.
Just create a method in your code-behind that returns a `string`, like this: protected string DisplayRespiteDate(object stepRespiteDay) { DateTime theDate; // Attempt to cast object to DateTime try { theDate = (DateTime)stepRespiteDay; } catch (Exception) { // Do something with failed conversion here, throw for example throw; } return theDate.ToString("dddd dd MMMM yyyy"); } Now in your markup you can call the method, like this: <asp:Label ID="RespiteDay" runat="server" Text='<%# DisplayRespiteDate(Eval("StepRespiteDay"))%>' </asp:Label>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, asp.net, gridview, data binding, edit" }
Finding the number of ways to tile a rectangular board In how many ways can a 2 × n rectangular board be tiled using 1 × 2 and 2 × 2 pieces? What i tried I used to inclusion exclusion principle where no of ways the 2 × n rectangular board can be tiled using 1 × 2 AND 2 × 2 pieces =the no of ways the 2 × n rectangular board can be tiled using 1 × 2 pieces + no of ways the 2 × n rectangular board can be tiled using 2 × 2 pieces - no of ways the 2 × n rectangular board can be tiled using 1 × 2 OR 2 × 2 pieces Then solving each of the three parts indivually no of ways the 2 × n rectangular board can be tiled using 1 × 2 pieces=$(n/2*2)=n$ ways no of ways the 2 × n rectangular board can be tiled using 2 × 2 pieces =$(n/2)$ ways no of ways the 2 × n rectangular board can be tiled using 1 × 2 OR 2 × 2 pieces=$(3*n/2)$ ways Im unsure of my answers. Could anyone please explain. Thanks
You have several problems. The question is intended to allow you to mix $1 \times 2$ and $2 \times 2$ pieces. You have assumed that a given tiling only allows one type to be used. Given your assumption, there is only one way to tile using $2 \times 2$ pieces, and that only if $n$ is even. For $1 \times 2$, there are at least as many tilings as if you tile it with $2 \times 2$ blocks, then cut each block in half. As you can cut each block either horizontally or vertically, this accounts for $2^{\frac n2}$ tilings and there are many more. The intended solution is by a recurrence relation. A tiling of a $2 \times n$ board can either end with a $2 \times 2$ block on the right, a pair of horizontal $1 \times 2$ blocks on the right, or a vertical $1 \times 2$ block on the right. Let $A(n)$ be the number of ways to tile a $2 \times n$ rectangle. Can you write the recurrence based on the first sentence?
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "combinatorics, discrete mathematics" }
Bash relative date (x days ago) I have a date string that I am able to parse and format with the `date` command from a bash script. But how can I determine how many days ago this date was from my script? I would like to end up with a number.
You can do some date arithmetics: DATE=01/02/2010 echo $(( ( $(date +%s) - $(date -d "$DATE" +%s) ) /(24 * 60 * 60 ) ))
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 15, "tags": "linux, bash, date" }
Hand over FBConnect Session from iPhone >> Backend Server? Good afternoon, I have a quick 'top level' question regarding the usage of Facebook Connect in an iPhone app which is in fact powered by my own backend. Is it possible that the user does authenticate him/herself with fbconnect on the iphone and the app hands over the session identifier to my server in order to perform whatever I need to do? So basically use FB primarily as authentication & profile storage / retrieval, and everything beyond is actually done / stored by my own backend? So basically it would look something like this: iPhone > (authentication) > Facebook and then iPhone < (hands over session/token) > My Backend < (uses that token) > Facebook ? Is that doable? Cheers and thanks, -Joerg
Sure, as long as you have the session keys and token you should be able to pick up the session anywhere as long as it doesnt expire.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "iphone, session, facebook" }
Rails redirect to iOS custom url Say I create some custom iOS url: customurl In my rails controller redirect_to "customurl://" produces at runtime: ERROR URI::InvalidURIError: bad URI(absolute but no path): customurl:// When I append some arbitrary path the redirect is successful. redirect_to "customurl://w" (User must now accept the page load, as opposed to a seamless redirect, which is undesirable). Anyone have a solution to redirect to a custom url without some arbitrary path? Thanks.
`custom://` is not a URI. You _must_ have something after that or otherwise it's not saying to go anywhere. Try going to ` That work? No, it's not a URI. Same principle here. EDIT: Apple does some strange stuff so you have to do something with JavaScript. That is not actually a valid URI, Safari just detects it and launches the app.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ios, ruby on rails, redirect" }
How can I load two grunt tasks with the same name? Im using yeoman for a project. Basically it's working fine, but during the build process I want to move my images folder to somewhere else. So I loaded the `grunt-contrib-copy` task which would let me do that. But unfortunately this conflicts with the yeoman built-in copy task. Is there any way to alias the `grunt-contrib-copy` in my `Gruntfile.js` so I can use both of them? grunt.loadNpmTasks('grunt-contrib-copy'); //Here I need to use "copy" again but not referencing the yeoman task but the grunt-contrib-copy task. grunt.registerTask('build','intro clean coffee compass mkdirs concat css min replace copy time');
grunt.renameTask() will probably help you here. Try this: // temporarily rename yeoman's copy task grunt.renameTask('copy', 'yeomanCopy'); // load 'copy' from grunt-contrib-copy grunt.loadNpmTasks('grunt-contrib-copy'); // rename it to something other than 'copy' grunt.renameTask('copy', 'myCopy'); // rename yeoman's task back to its original name so nothing breaks grunt.renameTask('yeomanCopy', 'copy'); // now use 'myCopy' for your purposes // ...
stackexchange-stackoverflow
{ "answer_score": 33, "question_score": 17, "tags": "gruntjs, yeoman" }
Image Get Requests with AngularJS I am storing the the source string of an image to be rendered in HTML in the AngularJS controller, however it yields a 404 before the Angular controller is initialized. Here is the HTML: <div ng-controller="Cont"> <img src="{{imageSource}}"> </div> Angular controller: var Cont = function($scope) { $scope.imageSource = '/tests.png'; } And the error I get (`%7D%7D` corresponds to the `{{` in the template). GET 404 (Not Found) How can I prevent this from happening? That is, only load the image when the Angular controller has been initialized?
Try replacing your src with ng-src for more info see the documentation: > Using Angular markup like {{hash}} in a src attribute doesn't work right: The browser will fetch from the URL with the literal text {{hash}} until Angular replaces the expression inside {{hash}}. The ngSrc directive solves this problem. <div ng-controller="Cont"> <img ng-src="{{imageSource}}"> </div>
stackexchange-stackoverflow
{ "answer_score": 230, "question_score": 106, "tags": "javascript, http status code 404, angularjs" }
Firebase authentication tokens expiration duration I just upgraded to the new version of Firebase and I can't find where I can set the expiration duration of my Firebase authentication tokens. It used to be under the authentication section in Firebase's old layout (I had it set for 1 year). Does Firebase still have this?
If you keep using the Firebase 2.x SDK, your expiration period will be the same as before. You cannot change the value anymore though. If you upgrade your code to use the 3.x SDK, it'll switch to user a never-expiring ID token and a quickly expiring access token. See this answer for more on that: Firebase authentication duration is too persistent
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "ios, firebase, firebase authentication" }
If $\sum_{n=1}^{\infty} a_{n}$ converges, then$\sum_{n=1}^{\infty} \sin(a_{n})$ also converges If series $\sum_{n=1}^{\infty} a_{n}$ converges, prove series $\sum_{n=1}^{\infty} \sin(a_{n})$ converges too. Is this a series function problem or something related to? I tried this: If $a_{n} \ge 0 $ for all $n$, then $| \sin (a_{n})| \le a_{n}$, on the other hand $\sin(x)$ is continuous function in $[0,x]$ and differentiable in $(0,x)$ then exist $c \in (0,x)$ and $$(x-0)\cos (c)= \sin(x)-\sin(0)$$ then $$x\cos(c)= \sin(x)$$ but, $|\sin(x)|=|x\cos(c)|= |x| |\cos(c)| \le |x|$, thus $|\sin (x)| \le |x|$. We know, $|\sin (a_{n})| \le |a_{n}| $ and $\sum_{n=1}^{\infty} a_{n}$ converges, then $\sum_{n=1}^{\infty} |\sin(a_{n})|$ converges. Therefore $\sum_{n=1}^{\infty} \sin(a_{n})$ converges. But this proof use ${a_{n}}$ positive and in the original problem I don't have this hypotesis.
This is a "Community Wiki" answer recording a comment by Daniel Fischer under the question. The comment provides a link The set of functions which map convergent series to convergent series to a proof that the result in question is false in general, though certainly true when the $a_n$ are non-negative. My reason for writing this answer is that comments can vanish more easily than answers and can probably also be more easily overlooked.
stackexchange-math
{ "answer_score": 7, "question_score": 10, "tags": "real analysis, calculus, sequences and series, limits, convergence divergence" }
How to restrict number of hits to S3 bucket via presigned URL? I Want to restrict the number of S3 operation via pre-signed URL. Currently I can have expiry time. Same way can we specify number of hits? I am using below node JS code to get pre-signed URL. I am geting the signed URL const url = s3.getSignedUrl('putObject', { Bucket: myBucket, Key: myKey, Expires: signedUrlExpireSeconds })
No, currently there is no way to restrict number of hits on a presigned URL. You can change the expiry time. You should contact AWS support and request this feature though, it does sound useful.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "amazon s3, aws sdk, pre signed url" }
What is the difference between `str` and `object` data types in `pandas.read_csv`? According to the pandas documentation, `pandas.read_csv` allows me to specify a `dtype` for the columns in the CSV file. > **dtype** : Type name or dict of column -> type, default None Data type for data or columns. E.g. {‘a’: np.float64, ‘b’: np.int32} (Unsupported with engine=’python’). Use _str_ or _object_ to preserve and not interpret dtype. To treat every column as text data, I can use either df = pandas.read_csv(... , dtype=str) or df = pandas.read_csv(..., dtype=object) As far as I know, these two methods always behave exactly the same. Are there any situations in which these two methods behave differently? If so, what are the differences?
These _had_ a subtle difference, until release 0.11.1 ( _see issue #3795_ ). Every element in a numpy array must have the same size in bytes. The issue with strings is that their size in bytes is not fixed, hence the `object` dtype allows pointers to strings which _do_ have a fixed byte size. So in short, `str` has a special fixed width for each item, whereas `object` allows variable string length, or really any object. In any case, since release 0.11.1 there is an auto-conversion from `dtype=str` to `dtype=object` whenever it is seen, so it does not matter what you use, although I would advise avoiding `str` altogether and just use `dtype=object`.
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 7, "tags": "python, python 3.x, pandas" }
Mercurial repository URL equivalent of SVN info If I do `hg clone <MY_URL> <MY_DIR>` then `cd MY_DIR`, I want a command to retrieve 'MY_URL'. In SVN there was an easy `svn info` command which would give me the whole URL (among other things), which is exactly what I want.
Use $ hg paths default to get the default pull URL, that is, the URL that will be used if you run `hg pull`. _Note:_ This URL can be changed by the user (by editing `.hg/hgrc`). The URL wont always point back to the server where the repository came from: $ hg clone $ hg clone project project2 Inside the `project2` clone, the default path will be `../project`. Please see my other answer if you're trying to use the default path to determine the "identity" of a repository.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 3, "tags": "version control, mercurial" }
How to find a html tag by class in python using beautifulsoup I am working on a simple dictionary and can't figure out the way to print a specific html tag in this example span with the class of "ind". Here is my code: import requests from bs4 import BeautifulSoup print("Please enter your word:") word = input("") url = " + str(word) print(url) info = "" r = requests.get(url) soup = BeautifulSoup(r.text) for span in soup.find_all('spanclass: ind}'): print(span.text) info += span.text
How about: span_tags = soup.find_all('span', class_="ind") for span in span_tags: print(span.text)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python" }
regex expression needed javascript How to achieve the following using regex in javascript: convert --> "thisIsTheFunniestStuff" to --> "this-Is-The-Funniest-Stuff" I used the following regex: /\B[A-Z]/g My understanding was that I needed to target the position just before an uppercase letter to insert a hypen at that location I also tried - `/[a-z]\B[A-Z]/` **PS. I also don't understand when people write $1 $2 at the end after finishing the expression. $ is for end of input but why not include it in the expression itself.**
Use `String#replace` method and within the replace string you can use matched string by using Specifying a string as a parameter option. var str = "thisIsTheFunniestStuff"; console.log( str.replace(/\B[A-Z]/g, '-$&') ) // with positive look-ahead assertion console.log( str.replace(/(?=\B[A-Z])/g, '-') )
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "javascript, regex" }
How does DKfindout.com (website) annotate the image? Here is An example in DKfindout. I'm wondering how to make **predefined annotation** (not user-defined annotation, e.g. drag a box and add comment) on images. ![A screenshot of the example]( I have no idea how to locate the place where I want to add an explanation. Is there any javascript library can do this job? Or I have to find the relative position of the annotation of the image (e.g. left:10%, top:10%), then add all annotations one by one? Or any other solutions?
I strongly believe they're using <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, html, css, image, annotations" }
Asymptotic expansion of Riemann's prime counting function Riemann's prime counting function is given as $$J(n)=\sum_{k=1}^{\infty}\frac{\mu(k)}{k}\operatorname{li}(n^{1/k})$$ the approximations \begin{align} \operatorname{li}(n)\sim J(n)\tag{1}\\\ \operatorname{li}(n)-\sqrt{n}/\log n\sim J(n)\tag{2}\\\ (1-\sqrt{n}/\log n)\operatorname{li}(n+\sqrt{n}\log n)\sim J(n)\tag{3}\\\ \end{align} get increasingly closer. Could these be the first few terms of an asymptotic expansion of $J(n),$ or can $(3)$ not be taken any further?
To make it clear $\sum_{k \ge 1} \frac{\mu(k)}{k} li(x^{1/k})$ is **not** a prime counting function. The prime counting functions are $$\psi(x) = \sum_{p^k \le x} \log p, \quad J(x) = \sum_{p^k \le x} \frac{1}{k} = \int_{2-\epsilon}^x \frac{\psi'(y)}{\log y} dy = \sum_{k \ge 1} \frac{\pi(x^{1/k})}{k}, \quad \pi(x) = \sum_{p \le x} 1$$ Whose Mellin transforms are $\frac{-1}{s}\frac{\zeta'(s)}{\zeta(s)},\frac{1}{s}\log \zeta(s),\frac{1}{s}P(s) $. The (Riemann) explicit formulas are $$\psi(x) = x - \sum_\rho \frac{x^\rho}{\rho} - \sum_{m\ge 1} \frac{x^{-2m}}{-2m}-\log 2 \pi, \\\J(x) = \text{Li}(x)- \sum_\rho \text{Li}(x^\rho) - \sum_{m\ge 1} \text{Li}(x^{-2m})-A, \\\\\pi(x) = R(x) - \sum_\rho R(x^\rho) - \sum_{m\ge 1} R(x^{-2m})-B,\\\ \text{Li}(x) = \int_2^x \frac{dy}{\log y}, \qquad R(x ) = \sum_{k \ge 1} \frac{\mu(k)}{k} \text{Li}(x^{1/k})$$
stackexchange-mathoverflow_net_7z
{ "answer_score": 1, "question_score": 0, "tags": "nt.number theory, asymptotics" }
How to put HTML (specifically a link) into a radio-button text I want to put a link in the text by the radio-button. Is there any way of doing this? The radio button inherits from TextView so there should be. I have managed to use Html.fromHtml() to get the text into the radio button, but the link is neither underlined nor clickable. final RadioButton sButton = (RadioButton)findViewById( R.id.radiobutton ); sButton.setText( Html.fromHtml( "1 månad (99:-) <a href='banan.html'>info</a>" ), BufferType.SPANNABLE ); sButton.setLinksClickable( true ); sButton.setMovementMethod( LinkMovementMethod.getInstance() ); Info should appear as a link and be clickable.
Turns out my example code above works! The problem was that I had used `android:autoLink` for the radio button, which somehow negated any code I added. So without the `autoLink`, the code above works. The `setLinksClickable` is not necessary.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "android, html, radio button, hyperlink" }
Can we integrate, the indefinite integral $\int 2aye^{ay^2}dy$ by parts? Can we integrate, the indefinite integral $\int 2aye^{ay^2}dy$ by parts ? If we let, $ay^2= t$, we have $(2ay)dy=dt$ and the integral can be integrated. This process is known as integration by substitution.
Yes, but you're not going to like it. Let $u=1$, $dv=2aye^{ay^2}\,dy$. Then $du=0dy$, and (by the substitution technique that you already know about) $v=e^{ay^2}$. So $$\int2aye^{ay^2}\,dy=\int u\,dv=uv-\int v\,du=e^{ay^2}-\int0dy=e^{ay^2}$$
stackexchange-math
{ "answer_score": 4, "question_score": 0, "tags": "calculus" }
How to encrypt http response using RSA encryption I am developing a web service for which I am using RSA encryption to encrypt request-response. I have shared the public key with the client and I am able to decrypt the incoming request using my private key. Now my question is how can I encrypt the response which is to be returned to the client. I have two options for this: (1) Use my private key to encrypt the response and client will decrypt it using already shared public key. (2) Ask clients to provide their public key and encrypt the response with that public key. Kindly suggest which strategy to use for encrypting response?
You cannot encrypt with the private key, as the public key is supposed to be public. Encryption with the private key is inherently unsafe and programming API's generally disallow the use of it. So (2) is really the only option: have the clients public key and let them decrypt with the private key. However that's not all of the story: 1. the public keys need to be trusted, and you may need to setup a full PKI to trust the keys; 2. larger messages cannot be easily encrypted with RSA, so you may need hybrid encryption (encryption of a random AES key and encrypting the messages with that); 3. padding oracle attacks are very real, and do apply to RSA, so just performing RSA is pretty dangerous. This is why it is generally advisable to rely on TLS (only). TLS is not always secure, but it is almost always more secure than a self-made scheme.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, http, encryption, rsa" }
What does "$\cdots$" mean in $\frac{n(n-1)(n-2)\cdots(n-r+2)}{(r-1)!}a^{n-r+1}b^{r-1}$? In the formula, $$\frac{n(n-1)(n-2)\cdots(n-r+2)}{(r-1)!}a^{n-r+1}b^{r-1}$$ what does the "$\cdots$" mean?
It means: "There are too many terms to write, but follow the obvious pattern to fill them in". In your example, you subtract $1$ from a factor to get the next factor. I might read that aloud as "$n$ times $n-1$ times $n-2$ all the way down to $n-r+2$". As another example, $$ 3 + 6 + 9 + \cdots + 3n $$ would indicate the sum of all positive multiples of $3$ less than or equal to $3n$.
stackexchange-math
{ "answer_score": 14, "question_score": 7, "tags": "algebra precalculus, notation" }
PHP MySQL select two random rows but not with rand() I need to select 2 random rows but it's known that rand() is too slow. So I tryed a code from a website and it is: SELECT * FROM bilder AS r1 JOIN (SELECT (RAND() * (SELECT MAX(id) FROM bilder)) AS id) AS r2 WHERE r1.id >= r2.id ORDER BY r1.id ASC LIMIT 2 But this way I get same 2 rows multiple times and parsing is also not correct, so this is complete useless. Is there a working solution which is better that rand()? The table name is `bilder` the fields are: `id`, `userid`, `nickname`. `id` is primary and auto increment. Some rows are also deleted so it's not 1 2 3 4 5 but 1 2 4 5 6... so the solution to generate random numbers and select them won't work
There are multiple solutions to this problem, but something like the following often has good enough performance: SELECT b.* FROM bilder b CROSS JOIN (SELECT COUNT(*) as cnt FROM bilder) v WHERE rand() <= 100 / cnt ORDER BY rand() LIMIT 2; The subquery selects about 100 rows. Sorting such a small number of rows is usually pretty fast. It then chooses two of them.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, mysql, random" }
many belongs_to and has_many in single line Hi I am working on one application which has so many relations on the model. Now I am thinking to reduce line of code and I find so many relations like `has_many` and `belongs_to`. Can we have singe line where we can write something like `belongs_to [:comment, :rating, :indication], dependent: :destroy` `belongs_to :travels, foreign_key: travel_item_id`
Unfortunately, not. AFAIK this is not possible and even the documentation doesn't seems to allow this. What you can do, is to define a metaprogramming method that iterate over an array and create this associations. But not sure if it worth it. **EDIT** Just an example of what I mean by `metaprogramming method` Create a file `app/models/concerns/associate.rb` module Associate extend ActiveSupport::Concern module ClassMethods def associate(ass_type, names = [], params = {}) names.each do |n| send ass_type, n, params end end end end Then, in your model, to do the multiple `belongs_to`, just do include Associate associate :belongs_to, [:comment, :rating, :indication], dependent: :destroy
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "ruby on rails, ruby on rails 4.1" }
Get token from activation url sended from server I'm newbie to coding login systems and now I'm coding an account activation logic after registration. I'm sending an email to the registered user with an url like this: 127.0.0.1:3000/activate/(token here) And I'm handling it on server side when user access to that url on this way: app.get('/activate', ( req, res) => { res.sendFile( __dirname + '/public/activation.html') }) But of course there's not a handler for every unique token so I need a way to access to enter on that app.get... /activate but kinda ignoring the second part where the token is so the file is served but keeping this token in a variable to operate with it later on it's inside logic. How can achieve it? Am I totally wrong on my approach? Thanks in advance.
You can use dynamic link app.get("/activation/:token",(req,res,next)=>{ const token = req.params.token; //don't use token directly in sql database });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "node.js, sendgrid, nodemailer" }
org.json.JSONArray cannot convert list of maps correctly in Android 4.2.1 Android 4.2.1. List<Map<String, String>> printers = new ArrayList<Map<String, String>>(); Map<String, String> printerInfo = new HashMap<String, String>(); printerInfo.put("name", "prn1"); printerInfo.put("address", "addr1"); printers.add(printerInfo); printerInfo = new HashMap<String, String>(); printerInfo.put("name", "prn2"); printerInfo.put("address", "addr2"); printers.add(printerInfo2); org.json.JSONArray arrBTPrinters = new org.json.JSONArray(printers); System.out.println(arrBTPrinters.toString()); This code prints [ "{address=addr1, name=prn1}", "{address=addr2, name=prn2}" ] But correct JSON array should look like [ {"address":"addr1", "name":"prn1"}, {"address":"addr2", "name":"prn2"} ] Is it a bug in Android 4.2.1 or I should use different Java structure?
//build objects JSONObject printer1 = new JSONObject(printerInfo); JSONObject printer2 = new JSONObject(printerInfo2); //build array org.json.JSONArray arrBTPrinters = new org.json.JSONArray(); arrBTPrinters.put(printer1); arrBTPrinters.put(printer2); //print System.out.println(arrBTPrinters.toString());
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "android, json" }
Update config file for script via svn checkout I need to write a script that is able to logon to an svn repository and checkout a config file for a script I am running on a lot of servers. Perl is the only scripting language that I can use but I'm a complete novice in perl. Could someone point me in the right direction and maybe give me some links with examples and/or documentation. UPDATE:I can't install svn on the remote servers. Is it impossible to do without installing svn? Gísli
Use LWP::Simple and fetch it over HTTP: #!/usr/bin/perl use LWP::Simple; my $config = get(" or just use wget to fetch it before launching your script.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "perl, svn" }
How to have fixtures for certain models and REST for everything else? I have an Ember app using an API which has most of the models implemented, but some of them not, and for those I would like to provide fixtures. App.ApplicationAdapter = DS.RESTAdapter.extend({ host: ' }); App.Post = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.attr() }); // ... this.store.find('post', 1); // // ... App.Tag = DS.Model.extend({ hashtag: DS.attr(), color: DS.attr() }); App.Tag.FIXTURES = [ { hashtag: 'foo', color: '#000' }, { hashtag: 'bar', color: '#fff' } ] // ... this.store.find('tag', 1) // searches among fixtures Is this possible?
You can make adapters specific to models by doing this: App.TagAdapter = DS.FixtureAdapter.extend();
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ember.js, ember data" }
XOM analogue for Scala? Is there an XML processing library for Scala "that strives for correctness, simplicity, and performance, _in that order_ " like does XOM for Java? (Scala XML API is not an option)
The only alternative XML library for Scala as far as I know is anti-xml, which is an effort started not two weeks ago. It is not really useful for anything right now, but you can at least try to influence its development if you find it worthy.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "xml, scala, xom" }
How do I use GitLab pajamas? Gitlab pajamas is a front-end framework that specifies all of the components (e.g. buttons) used by Gitlab: < Does anyone know how I can use the Pajamas framework, as I would Bootstrap? I cannot find a setup guide.
It doesn't appear that you are meant to pajamas to write your own site (as you would something like bootstrap or prime-ng). As you say, they don't publish any information on how to get started, they publish nothing in their npm repository, and there is no publish step in their CI/CD pipeline. This is likely because the project is heavily insinuated to be a design/UX documentation repository as opposed to code for the components itself. Instead, they do offer GitLab UI as a set of pre-built components that you can use within your projects. You can see a gallery of what's available here.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, gitlab" }
SQLite: readers not waiting for writers I have around 200 tables in an SQLite database with hundreds to millions rows. These tables are queried by many concurrent processes of an OLTP application. Each table needs to be occasionally updated by a full refresh -- delete all rows and then insert different ones, all within a transaction. For largest tables this takes almost one minute, but such refresh only happens few times a day for a table. I need to make sure that the readers do not need to wait for the refresh to finish -- should use old version of table data until the transaction completes, then use the new version. Any waits, if need be, should be in terms of milliseconds rather than seconds or minutes. Can this be achieved, i.e. avoid any database locks or table locks blocking the readers? I am not concerned about writers, they can wait and serialize. It is a Python application with pysqlite.
Use WAL mode: > WAL provides more concurrency as readers do not block writers and a writer does not block readers. Reading and writing can proceed concurrently.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sqlite, locking, pysqlite" }
How to reference a column by its index and see if any of them have a certain value r I have the following dataframe, and this is just a sample. I have 530 columns but I know the index of the columns that I need to check whether they contain certain values. I want to check whether column a, b, c, d contain the value 1. If they do then "YES", if not, then "NO". I ONLY want to reference the columns by their position not name. df=data.frame(row_number=c(1,2,3,4),a=c(1,0,0,0),b=c(1,1,1,0),c=c(1,1,0,0),d=c(1,1,0,0)) I have tried this but it's not working, any suggestions? df%>%mutate(check=ifelse(any(colnames(df[,c(2:5)])==1), "YES","NO"))
Assuming that: * columns a, b, c and d contain **only** 1 or 0 * you want to check if **any** column contains 1 then one approach is to check that the row sum over those columns is > 0. library(dplyr) df %>% mutate(check = ifelse(rowSums(.[, 2:5]) > 0, "YES", "NO")) Result: row_number a b c d check 1 1 1 1 1 1 YES 2 2 0 1 1 1 YES 3 3 0 1 0 0 YES 4 4 0 0 0 0 NO
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "r, indexing, dplyr" }
Why don't HTTP headers include device resolution, pixel density, etc.? I'm currently developing a responsive website with CSS media queries. It would be much easier if the server returned a different HTML/CSS for each viewport. I was wondering why couldn't the client include its viewport information when requesting an HTML file. This behavior is already common for returning websites in the correct language using the `Accept-Language` header.
**In short, that was not how the Wild Wild Web was designed to work.** The original design was simply that the HTML gave the browser hints about the document. Which bits to emphasise, where to go to get image files. Decisions about the font (as well as what size) was the job of the browser and local configuration settings. Yes, I know the world has moved on, and now web designers expect to control every pixel our eyes get to see. In the bygone past, that was the desktop theme's job to do that.
stackexchange-softwareengineering
{ "answer_score": 19, "question_score": 12, "tags": "http" }
Can not unlock sleep screen of windows 2016 virtualBox in Windows 10 i am using windows 10 but i have to install windows 2016 in Oracle VM Virtual Machine to finish my midterm assginment, i have installed it successfully when it come to unlock sleep screen it tell me to hit `Ctrl + Alt + Del` to unlock ![enter image description here]( But my windows 10 OS it execute this command and function it concurrently and it take over all the screen side, ![enter image description here]( how can i deal with it? Thank you so much and have a good day
You are looking for `Input > Keyboard > Insert Ctrl-Alt-Del`. ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -2, "tags": "windows, windows 10, virtual machine, screen" }
What is a good free / open source cross platform mobile application development framework I am looking for a good cross platform mobile application development framework that at least supports the big 4: iOS,Android,Windows Phone and Blackberry. Can you please also let me know what is the best points of the framework you recommend?
PhoneGap is an HTML5 app platform that allows you to author native applications with web technologies and get access to APIs and app stores" Check about the supported features by OS here * You can use your javascript , HTML, CSS skills to create native apps. avoiding the burden of Java (Android), ObjectiveC (iOS) etc. * Free! This is another strong contender.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 5, "tags": "android, ios, mobile, cross platform, windows phone" }