INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to keep each tab's panel height? There is a `TabbedPane` of two `Tabs` : tabClient.addTab("Fiche", cFicheClient); // cFicheClient is a Container tabClient.addTab("Crédits", cClientEtCredits); // cClientEtCredits is a Container On the first `Tab` there is only few fields to display , on the second `Tab` there is a `List` containing many records not all displayed on the screen. The problem is that there is a vertical `Scrollbar` at the right of the screen even when the selected `Tab` is the first one. Here are images : ![]( ![]( So how to make the first panel keep its own height so that there is no vertical `Scrollbar` ?
If I understand the question correctly just set the parent form to scrollable false.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -1, "tags": "lwuit" }
When is it equivalent to do a joint optimization over two variables in sequence over each variable? Say I have a function $f(x,y)$. When is $$\min_{x,y}f(x,y)=\min_x\min_y f(x,y)=\min_y\min_x f(x,y)$$ and what happens when there are constraints?
The below equation is always true, $$ \min_{x,y}f(x,y)=\min_x\min_y f(x,y)=\min_y\min_x f(x,y) $$ Let's take any point $x_0, y_0$. The following is always true by definition of $\min$, $$ f(x_0, y_0) \geq \ \min_y f(x_0, y) \geq \ \min_x\min_y f(x, y) $$ Note that the above holds for any point $x_0, y_0$. What if $x_0, y_0 = \arg\min_{x, y} f(x, y)$? $$ \implies \min_{x, y} f(x, y) \geq \ \min_x\min_y f(x, y) $$ Let's prove the reverse direction for any point $x_0, y_0$, $$ \min_{x, y} f(x, y) \leq f(x_0, y_0) $$ The above holds for any $y_0$, What if $y_0 = \arg\min_{y} f(x_0, y)$? $$ \min_{x, y} f(x, y) \leq \min_{y} f(x_0, y) $$ The above holds for any $x_0$, What if $x_0 = \arg\min_{x} \arg\min_{y}f(x, y)$? $$ \min_{x, y} f(x, y) \leq \min_x \min_{y} f(x, y) $$ Combining both eqns. We get the required result.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "optimization" }
Android Authentication with FingerPrint We have an app that every time asks user to enter PinCode before authenticate. Now we want to integrate authentication process with Google FingerPrint API. We have looked documentation. But in all this implementations we have one truble. So, we want to authenticate user if fingerPrint returns success . But authentication on our system have to go only with PinCode. So, Where i can save user PinCode securely so that, if FingerPrint returns success to read PinCode decrypt and sent to server? Take it into account that Shared Preferences is not secure enought.
Shared Preferences is an option for this. But please read up on Shared Preferences Security if you do go for this. For as noted by user Shuddh, there are a number of ways to gain access to the Shared Preferences. I think it is a good plan to encrypt it.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "android" }
Ubuntu desktop entry I have a *.desktop item in `/usr/share/applications` folder, but it's still is not available via search in Ubuntu `"Type to search"`results. What should I do to make concrete desktop item to be available in search?
Jetbrains appears not to install their `.desktop` files in the normal locations as I discovered. One would expect them to be found here `/usr/share/applicatiosn` but rather I found several locations where these files are stored. If you instruct `Jetbrains` software to install desktop for all users then the location is: /usr/local/share/applications If you instructed it to just install for you alone then the location is: /home/$USER/.local/share/applications Now I also found it here: /home/$USER/.gnome/apps That being said one can search for them using the command: sudo find / -type f -iname "jetbrains-*"
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 1, "tags": "14.04, .desktop" }
Convert Hashtable elements to List I have this hashtable has a key "ids" and its values are [1,2,3] List<long> ids= (List<long>)hashtable["ids"]; an error occurs when trying to cast. It says Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.List`1[System.Int64]'. I've been stuck for hours, any suggestions?
It would be helpful if you wrote in your question what are the values you expect to get and the definition of your hashtable. Assuming You are trying to get `[1,2,3]` and your 'Value' is an array of `long`, try: List<long> ids= hashtable["ids"].ToList();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, linq, list, casting, hashtable" }
Email injection in simple terms? Can someone explain why spammers use email injection? I am a victim and was wondering if there was any other malicious point besides annoying me and filling up my e-mail?
Email injection is a vulnerability of an application which allows a spammer to piggy-back on that application and send emails through it. There are several advantages of using this technique: * the application sends them = the spammer is anonymous * your antispam system may lower its "spam threshold" if the email comes from a reputable place Why do you think you were specifically a victim of that kind of spam? To answer your question: there are no more malicious points, except if the spammer used the application not only as the spam vector but also made the spam look as if it was coming from that particular system (adding some phishing to the email)
stackexchange-security
{ "answer_score": 2, "question_score": 4, "tags": "email, spam" }
matlab timer functions I want to call function A in a program. This function has a for loop inside and I'd like to shorten amount of iterations but not just changing the upper limit. How could I do it in this case? I was thinking if Matlab is capable of doing something like: one timer inside a function (or maybe inside a loop) and second in the main program that calls this function? But only rough idea, I'm a beginner. Please feed back if this is good idea and how could it be implemented? thank you!
It sounds like you're talking about having a maximum elapsed time condition in your loop, something along the lines of, MAX_T = 10; tic; for n=1:NMAX % Call your loop functions . . % Break if youve spent too much time in the loop if toc > MAX_T; break; end; end There are also ways of optimizing this, such as only checking the value of toc every N iterations.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "matlab" }
Remove brackets after installing rails-api (ruby on rails) I installed the rails-api gem. Then I made a new rails app, and set up an `index` action to print rows from the database using `@tasks = Task.all`. In the view I put `<%= @tasks.each do |task| %> <%= task.navn %> <% end %>` I get this symbol `[]` under the data I did get from the database. All the information I try to print out is in the symbols. Do anyone have a solution to remove the brackets? I have pushed my testapp to github so you can see whats in my application. <
<%= @tasks.each do |task| %> Should be <% @tasks.each do |task| %> notice the lack of `=` `<%=` means evaluate and execute the code and insert into the html `<%` means to simply evaluate and execute the code
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ruby on rails, ruby, ruby on rails 3, brackets, rails api" }
Second monitor stopped working after executing dist-upgrade I'm using a newly installed `Xubuntu 21.10` on my brand new `ASUS ROG Zephyrus G14 GA401QM-K2030T`. It has two video cards. One is the integrated on the AMD CPU `Ryzen™ 9 5900HX` and the second one is a discrete `NVIDIA GeForce RTX 3060`. I also using an external monitor alongside laptop one via the HDMI port. Initially, the setup was working fine, but after executing `sudo apt dist-upgrade` and restarting the external monitor has stopped working. Could someone give any suggestions on how to resolve this problem?
It seems that this is a problem with NVIDIA drivers. I logged in to a text terminal and type `sudo apt remove --purge nvidia*` and then reboot. Then I reinstalled the Nvidia drivers.
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 1, "tags": "drivers, nvidia, upgrade, multiple monitors, amdgpu" }
In UML, do you have to show the concrete implementation of an abstract method? I'm drawing some UML in which a concrete class inherits from an abstract class which defines a pure virtual method. Is it required to show this method in the concrete class as well? It's implied by inheriting from the abstract class.
Nope, you don't need to. in fact, in general, don't put any more in the UML than you _must_ have to clarify what you're saying, unless you're (god forbid) trying to generate code from it. The best guide I know of for UML is UML Distilled by Martin Fowler.
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 5, "tags": "uml, abstract, concrete" }
applescript does not run from terminal why doesn't my applescript run from terminal I can run it successfully from the editor I run command /usr/bin/osascript -e my_script.scpt I get error 0:12: syntax error: A unknown token can’t go after this identifier. (-2740) my script set volume 2 set x to 0 open location "spotify:user:wunspe:playlist:meininki" tell application "Spotify" set the sound volume to 0 play repeat 10 times if sound volume is less than 70 then set sound volume to (sound volume + 10) set x to (x + 9) set volume output volume x without output muted --100% delay 3 end if end repeat end tell
To run a compiled script (file) you have to omit the `-e` flag and pass the full path to the script /usr/bin/osascript /Users/myUser/path/to/my_script.scpt
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "macos, shell, terminal, applescript" }
Windows server 2012 Root Enterprise Certification Authority issue certificates only with 2 years validity I cannot make my Enterprise Root CA issue certificates with an expiration date more than 2 years. I've already set ValidityPeriodUnits and ValidityPeriod register keys with certutil.exe. I've already duplicated my template in order to encrease the validity period. My RootCA certificate expires on 2035 and is version 3.
strongline is right, I think. You should launch the certificate templates MMC snapin on your CA server and make a copy of the certificate template that you are using. Then, modify the copy to use the desired settings, such as the cert lifetime.
stackexchange-serverfault
{ "answer_score": 2, "question_score": 3, "tags": "windows server 2012, ssl certificate, certificate authority" }
How can I use Scala reflection to get only primary constructor parameters? I have a case class: case class Cow(breed: Breed, gender: Gender)(implicit grass: Pasture) { val hasSpots: Boolean } How can I use reflection at runtime to get back just the list (`breed`, `gender`)? Here's what doesn't work: def getConstructorParamsC = ct.runtimeClass.getDeclaredFields.map(_.getName) // returns (breed, gender, grass, hasSpots) def getConstructorParamsC = ct.runtimeClass.getConstructors.head.getParameters.map(_.getName) // returns (arg0, arg1, arg2) The first solution includes non-constructor fields (`hasSpots`), which is not what I want. The second solution loses the parameter names. Both methods also include the curried implicit `grass/arg2` argument, which I also don't want. Is there some way to get back just the (`breed`, `gender`) fields?
Assuming you're using the scala-reflect API (I tested it with 2.12 but it may work with other versions), you could do import scala.reflect.runtime.universe._ def getConstructorParams[T: TypeTag] = typeOf[T].decl(termNames.CONSTRUCTOR) .alternatives.head.asMethod // this is the primary constructor .paramLists.head.map(_.asTerm.name.toString) getConstructorParams[Cow] == List("breed", "gender")
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "scala, reflection" }
simpler way to parse using regex I have an input in the form of 'ABCD 3/1'. I need to parse the digit before '/', Also if the input does not match this pattern then return the original string itself. I am using below query, which works, but there would be a way to this in single regex I believe, any hints appreciated. select nvl(REGEXP_substr(REGEXP_substr('ABCD 3/1', '\d\/'), '\d'), 'ABCD 3/1') from dual;
What about this? I believe it meets your requirements. Add more test cases as you see fit to the with clause. SQL> with tbl(str) as ( select 'ABCD 3/1' from dual union select 'ABCD 332/1' from dual union select 'ABCD A/1' from dual union select 'ABCD EFS' from dual ) select regexp_replace(str, '.*\s(\d)/\d.*', '\1') digit_before_slash from tbl; DIGIT_BEFORE_SLASH ----------------------------------------------------------------------------- 3 ABCD 332/1 ABCD A/1 ABCD EFS SQL>
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "sql, regex, oracle" }
Inserting a column value with null in ruby on rails I want to customize the value inserted in the column in the controller and i want to insert a null value in it. In this way : @users.to = null
I believe you want: @user.to = nil You may have to run a migration to ensure the column allows NULL values: change_column :users, :to, :string, :null => true
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "ruby on rails, ruby on rails 3, null" }
Message sending Telegram bot (PHP) I know it's somehow weird to ask something like this, but I'm trying to program a telegram bot with PHP. The bot is in a channel (e.g. Channel A) and I'm going to send messages in that channel, so the bot will **copy** X number of messages to another channel (Channel B), Every Y minutes. Example: X = 5 Y = 60 Channel A = ID ..... Channel B = ID ..... **So it will COPY 5 messages from A to B every hour...** Can anybody write me a template please? I think I can configure the VPS and webhook stuff (SSL and etc).
If you need send message per minutes, and get message from Telegram callback, you need read about queue (zmq, redis, gearman or etc). 1. Create daemons. These are your bots. They can read messages from queue and send callbacks. 2. Write Controller to get callback from telegram. It can take message and push to queue. 3. Install Ev or Event extension on PHP. (You can use reactphp, it simple solution to create timer) 4. Bot1 create timer, and listen messages. If we have more 5 messages, timer can push message in queue for Bot2. You can use reactphp/zmq, nrk/predis-async to helpful your task P.S. **It is most simple solution.** But you can use pthreads (instead create daemon process) or use simple socket to send message in bot.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "php, bots, telegram" }
iOS large file llseek or lseek64 I can't find any information how to implement in C module of iOS Xcode project lseek() for large files: llseek() or lseek64() Compilation with: #define _LARGEFILE64_SOURCE #define _FILE_OFFSET_BITS 64 has no effect. How is this possible to do?
You need to use fseeko() and ftello() when seeking to specific 64bit offsets in a file. Pass the file offset as a off_t instead of int and it will work on both 32bit and 64bit systems.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ios, c, file" }
probability that 5 comes before 7 In the following question ![enter image description here]( What they have done after the line 'the probability of getting neither 5 nor 7'
Suppose that a $5$ came before a $7$. How could this have happened? Well... * The first roll could have been a $5$. * The second roll could have been a $5$. This means that the first roll must have been neither a $5$ nor a $7$. * The third roll could have been a $5$. This means that the previous two rolls must both have been neither a $5$ nor a $7$. * The fourth roll could have been a $5$. This means that the previous three rolls must each have been neither a $5$ nor a $7$. * ... * The $n$th roll could have been a $5$. This means that the previous $n - 1$ rolls must each have been neither a $5$ nor a $7$. Adding up each case's probability yields an infinite geometric series.
stackexchange-math
{ "answer_score": 1, "question_score": -2, "tags": "probability" }
Ruby system command is giving me an output This ruby 'system' gives me an output; on irb: system("sudo airodump-ng -w sidney wlan0") Airodump-ng is from the Airocrack-ng package. However, the ruby "system" should not give me a stdout. The thing is, that a "sh" processus is being created, which doesn't have an output. But the "sh" processus got a child processus, which gives me a output that I don't want at all to be displayed on my terminal. Second part of the question, how can I get the pid of that sub-processus, using threads and maybe a different way to call a shell command using ruby (and not displaying the output of that child processus) ?
If you don't care about the output, trash it: system("sudo airodump-ng -w sidney wlan0 >/dev/null 2>&1") I _think_ the child process will inherit the parent's file descriptors.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ruby, multithreading, shell, stdout" }
How to get rid of widget border? I have the following code: from Tkinter import * def gui(): root = Tk() root.configure(background = 'red') rightPanel = PanedWindow(borderwidth=0, bg='black') rightPanel.pack(side = 'right', fill=BOTH, expand=1) canvas1 = Canvas(rightPanel, bg='black') rightlabel = Label(canvas1, bg= 'grey') rightlabel.place(relx=0.5, rely=0.5, anchor=CENTER) canvas1.pack(fill=BOTH, expand=1) root.wm_attributes('-topmost', 1) mainloop() if __name__ =='__main__': gui() As you can see if you run it (especially in fullscreen mode), there is grey border near window edge. It looks like border of PanedWindow widget (you can see it, if you set its `fill=NONE` and expand window). Note that ts borderwidth is set to 0 How can I get rid of it or set it to some color?
What you are seeing is the highlight ring around the canvas -- something that changes color to show that the canvas has keyboard focus. Set it to zero with the `highlightthickness` attribute: canvas1 = Canvas(rightPanel, bg='black', highlightthickness=0) Note that it could also be the canvas border. You might want to set `borderwidth` to zero, too.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 4, "tags": "python, tkinter" }
Accordion Panel programmatically primefaces I want to make mega menu with accordion panel programmatically using primefaces, but how to do this?
To give an answer about your question try to use this I suppose that you have an entity that you call item and each item has a number of valuable informations ( the link title , xhtml path ...) <c:forEach var="item" items="#{cart.items}"> <p:panelMenu> <p:submenu label="#{item}" > <p:menuitem value="#{item.name}" outcome="/pages/" + #{item.pageName} + ".xhtml" icon="ui-icon-extlink" /> </p:submenu> </p:panelMenu> </c:forEach> Hope that helped you
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jsf, primefaces" }
Qt invoke method with QVariant I have the following function : class TestClass: public QObject { Q_OBJECT public: Q_INVOKABLE QString test() { return QString("test"); } }; And I want to invoke the test method, but get the return type as QVariant, not as QString. So I tried this : TestClass obj; QVariant returnedValue; bool rslt= QMetaObject::invokeMethod(&obj, "test", Qt::DirectConnection, Q_RETURN_ARG(QVariant, returnedValue) ); QString strVar = returnedValue.toString(); but it doesnot work, invoke returns false; If get the return type as QString it works, but unfortunately this will not be usable for me, cause I need to know the return type before calling the function. QString r; bool rslt= QMetaObject::invokeMethod(&obj, "test", Qt::DirectConnection, Q_RETURN_ARG(QString, r) );
You can inspect method return type via `QMetaMethod::returnType()`, and then construct the return value receptor using `QGenericReturnArgument`. Here is some code for inspiration
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c++, qt" }
Why does flushing a toilet or running a clothes washer sometimes change shower temperature? Admittedly, this isn't something that is happening to me but I'm curious: I've heard that in some houses, flushing toilets or running a clothes washer sometimes changes the water temperature for people taking showers at the same time in the same house. Why is this?
This happens because water is diverted away from the shower to the toilet or washing machine. What happens next will depend on the type of shower and it's age. Older, non thermostatic showers will be affected to a greater extent. For an electric shower the flow of water through the shower will be reduced which will have the effect of heating it up further - though the thermostat should keep the effect to a minimum. For a mixer shower it will depend on whether the cold water is reduced - in which case it will get hotter, or the hot water via the heater is reduced - in which case it will get colder. Again a thermostatic mixer should keep the effect to a minimum. In any case you'll get a much reduced flow through the shower. Power (pumped) showers shouldn't be so affected as the pump in the shower is controlling the flow rate.
stackexchange-diy
{ "answer_score": 8, "question_score": 7, "tags": "plumbing, interior, shower, temperature" }
Why does sed cause git to consider the entire file rewritten? Using Cygwin on Win7x32, when I use `sed` to replace some values in a file, `git` then considers the entire file to be completely rewritten (i.e., 500 insertions, 500 deletions). What's going on here? Only one line in the file is actually changed, and the replacement value is the same length as the original. I'd expect `git` to recognize only the lines that changed. The only thing that seems to have changed at all is the inode and time values as read from `stat some/file.txt`. Is there a way to tell `git` to ignore any relevant changed values for the duration of my `sed` calls, or to tell `sed` to not change any values that cause `git` to see a file with entirely new content?
I don't work with Windows much, but perhaps `sed` is changing your end-of-line markers. The `file` command will tell you which text encoding is being used. Also, you can run `cat -e` before and after you call `sed`; if the file is encoded for Windows each line will end with `^M`.
stackexchange-superuser
{ "answer_score": 7, "question_score": 4, "tags": "git, cygwin, sed" }
flutter migrate objective c project to swift project. Error when use swift plugin If you have an error like > ***-Swift.m doesn't exist in compile time, or you want to use swift module(plugin) in flutter you must enable swift project.( migrate from objective-c to swift project) in root folder of project backup ios folder, then delete folder. after that `flutter create -i swift .` and that's it.
in root folder of project backup ios folder, then delete folder. after that `flutter create -i swift .`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "swift, flutter" }
Why need bind in setInterval with method function? Here's working code sample: function Drum(){ this.noise = 'boom'; this.duration = 1000; this.goBoom = function(){console.log(this.noise)}; } var drum = new Drum(); setInterval(drum.goBoom.bind(drum), drum.duration); If I remove `.bind(drum)` part from this code instead of ' _boom_ ' I'll get ' _undefined_ ' in console. What's the reason of such behavior since `typeof drum.goBoom` returns ' _function_ ' ?
Taking a look at the documentation for bind. > The `bind()` method creates a new function that, when called, has its `this` keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. If you omit the `bind(drum)` then `this` within the call back will be something other than the `drum` object you want.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript" }
No R, Como calcular a média de uma coluna com base em critério em outra coluna? Tenho duas colunas (A e B) quero calcular a média da coluna A para os elementos correspondentes apenas para os que na coluna B forem maior que 10 por exemplo.
Quando é data.frame, e tenho de tirar médias de varias colunas, eu uso o código `colMeans` e dentro da função coloco tipo: `colMeans(dados[dados$coluna1=="A" & dados$coluna2=="0.01",])` normalmente ele irá obter as médias por colunas dos dados que atendam a este critério só ressalvo que na parte **,]** depois desta **virgula** você não está discriminando quais colunas entram no calculo por isso irá se realizar com todas, o problema é quando nas colunas tem caracteres ("A","NOME") pois o código costuma não realizar o calculo de médias com fatores, para isso voce pode simplesmente concatenar os respectivos números das colunas as quais você deseja os resultados. Ex: `nova.tabela.contendo.as.médias<-colMeans(dados[dados$coluna1=="A" & dados$coluna2=="0.01",c(4,1,3,2,5,7)])`,
stackexchange-pt_stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "r, static" }
Operator norm of $x^Tx$ comparable to $|x|^2$? If $x = (x_1,x_2, \dots, x_n) \in \mathbb{R}^n$, and $$ x^Tx = \begin{bmatrix} x_1^2 & x_1x_2 & x_1x_3 & \dots & x_1x_n \\\ x_2x_1 & x_2^2 & x_2x_3 & \dots & x_2x_n \\\ \vdots & & \vdots & & \vdots \\\ x_nx_1 & x_n x_2 & \dots & \dots & x_n^2\end{bmatrix}, $$ is it possible to show that $||x^Tx||$ is comparable to $|x|^2 = tr(x^Tx)$?
According to the notation I like to use ($x$ is a column vector and the matrix multiplication is on the left of the vector), the big matrix you wrote is $xx^T$ (while $x^Tx$ is the scalar $\lvert x\rvert^2$). I'll stick to mine because I don't want ot mess up, but it's basically the same thing up to transposition. If $x\ne0$, the matrix $xx^T$ is orthogonally diagonalisable. Per se, this is a consequence of spectral theorem, but for the purpose of the question we need to prove it manually anyways. In fact, $\ker xx^T=x^{\perp}$. Moreover $$(xx^T)x=x(x^Tx)=\lvert x\rvert^2x$$ So, if $$P=\left(x,b_1,\cdots,b_{n-1}\right)$$ where $b_1,\cdots,b_{n-1}$ is an orthonormal basis of $\ker xx^T=x^{\perp}$, the matrix $P$ is orthogonal and $P^{-1}xx^TP=\operatorname{diag}(\lvert x\rvert^2,0,\cdots,0)$. Since the operator norm is invariant under conjugation by an orthogonal matrix, you have that $$\lVert xx^T\rVert=\lvert x\rvert^2=\operatorname{tr}(xx^T)$$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "matrices, normed spaces" }
Passing a Hebrew file name as command line argument in Windows I have a small Python program. I use the the Windows registry to enable the opening of files using the right-click context menu. My registry entry: > C:\Users\me\projects\mynotepad\notepad.exe "%1" When I try and open a file with a Hebrew name using my right-click context menu, I get the file name as question marks, and I get an exception while trying to get the file size. Here is my code: file_name = sys.argv[1] file_size = os.path.getsize(unicode(file_name)) I have tried this: file_name = sys.argv[1].decode("cp1255").encode('utf-8') file_size = os.path.getsize(unicode(file_name)) But it didn't work. Any advice?
Turns out it's a problem. See here for the solution. You need to resort to Windows API to get the arguments.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, unicode, command line arguments, hebrew" }
GSON parsing without a lot of classes I have the following JSON and I'm only interested in getting the elements `"status"`, `"lat"` and `"lng"`. Using **Gson** , is it possible to parse this JSON to get those values without creating the whole classes structure representing the JSON content? JSON: { "result": { "geometry": { "location": { "lat": 45.80355369999999, "lng": 15.9363229 } } }, "status": "OK" }
You don't need to define any new classes, you can simply use the JSON objects that come with the Gson library. Heres a simple example: JsonParser parser = new JsonParser(); JsonObject rootObj = parser.parse(json).getAsJsonObject(); JsonObject locObj = rootObj.getAsJsonObject("result") .getAsJsonObject("geometry").getAsJsonObject("location"); String status = rootObj.get("status").getAsString(); String lat = locObj.get("lat").getAsString(); String lng = locObj.get("lng").getAsString(); System.out.printf("Status: %s, Latitude: %s, Longitude: %s\n", status, lat, lng); Plain and simple. If you find yourself repeating the same code over and over, then you can create classes to simplify the mapping and eliminate repetition.
stackexchange-stackoverflow
{ "answer_score": 60, "question_score": 36, "tags": "java, json, parsing, gson" }
I am not using web.xml as using servlet container version 3, in tomcat 7 with Spring mvc. But maven expects web/xml? this seems rather hacky if added to POM : <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration>
do you create web configuration class to implements `WebApplicationInitializer`if you have this class it should not ask about web.xml
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "maven, spring mvc, web.xml" }
Remove first and last dot from string if exists I want to remove dot from start and end of the string if exists without using `CASE` and `LIKE`. DECLARE @str1 varchar(max) = 'SQL Server.' DECLARE @str2 varchar(max) = 'SQL. Server' DECLARE @str3 varchar(max) = '.SQL Server.' DECLARE @str4 varchar(max) = '.SQL Server' Query: SELECT CASE WHEN @str1 like '%.' THEN left(@str1, len(@str1) - 1) ELSE @str1 END AS String1; Note: The reason behind not using `CASE` and `LIKE` is I am using multiple `replace` and `trim` function on `@str`. **Expected Result** : String1 String2 String3 String4 -------------------------------------------- SQL Server SQL. Server SQL Server SQL Server
This will remove the first and last dot: DECLARE @t table(strx varchar(max)) INSERT @t values('SQL Server.'),('SQL. Server'),('.SQL Server.'),('.SQL Server') SELECT STUFF( SUBSTRING(strx, 1, LEN(strx) -CASE WHEN strx LIKE '%.' THEN 1 ELSE 0 END), 1, CASE WHEN strx like '.%' THEN 1 ELSE 0 END, '' ) FROM @t
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "sql, sql server, string, sql server 2008 r2" }
Regex - mod_rewrite - Match string after characters and run as get vars I'm looking to find and capture the url by "/-" and run the resulting find as a single get var on the preceding page: would run as: I'm able to find the match with: RewriteCond %{REQUEST_URI} (\/-.*) RewriteRule ^(.*)$ ?get=$1 [L] But have been unsuccessful returning the proper get var. This yields: Any help would be much appreciated!
Ok, I found the issue to the redirect vs. rewrite I was having. Basically I need to make sure and put the file in `index.php`. RewriteCond %{REQUEST_URI} (\/-.*) RewriteRule ^(.*?)(\/-.*)$ $1/index.php?get=$2 [L] Thanks, Jason for your help!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "php, regex, .htaccess" }
406 Error with Mechanize I'm getting a 406 error with Mechanize when trying to open a URL: for url in urls: if " not in url: url = " + url print url try: page = mech.open("%s" % url) except urllib2.HTTPError, e: print "there was an error opening the URL, logging it" print e.code logfile = open ("log/urlopenlog.txt", "a") logfile.write(url + "," + "couldn't open this page" + "\n") continue else: print "opening this URL..." page = mech.open(url) Any idea what would cause a 406 error to occur? If I go to the URL in question I can open it in the browser.
Try adding headers to your request based on what your browser sends; start with adding an `Accept` header (406 normally means the server didn't like what you want to accept). See "Adding headers" in the documentation: req = mechanize.Request(url) req.add_header('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8') page = mechanize.urlopen(req) The `Accept` header value there is based on the header sent by Chrome.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "python, mechanize" }
If $p=\frac {dy}{dx}$ then solve the equation $p^3-p(x^2+xy+y^2)+x^2y+xy^2=0$ If $p=\frac {dy}{dx}$ then solve the equation $p^3-p(x^2+xy+y^2)+x^2y+xy^2=0$ My Attempt: $$p^3-p(x^2+xy+y^3)+x^2y+xy^2=0$$ $$p^3-p(x+y)^2+pxy+xy(x+y)=0$$ $$p(p^2-(x+y)^2)+xy(p+(x+y))=0$$ $$p\cdot (p+(x+y))\cdot (p-(x+y))+xy(p+(x+y))=0$$ $$(p+(x+y))\cdot (p(p-(x+y))+xy)=0$$ I don't get what to do after this.
$$(p+(x+y))\cdot (p(p-(x+y))+xy)=0$$ Solve the first DE: $$p+(x+y)=0$$ $$(ye^x)'=-xe^x$$ Integrate. $$ye^x=-xe^x+e^x+c$$ $$\implies y=-x+1+ce^{-x}$$ * * * The second DE can be factorized as: $$p^2-p(x+y)+xy=0$$ $$(p-x)(p-y)=0$$ You can easily solve both equations. $$y'=x \implies y=\dfrac {x^2}2+c_2 $$ $$y'=y \implies (ye^{-x})'=0 \implies y=c_1e^x$$
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "calculus, ordinary differential equations" }
how to handle long text in dropdownlist control in ASP.NET > **Possible Duplicate:** > Recommendations for dropdown menu items that are too wide? I have a drop down list which is populated by the database. Its value field contains the record's id, and its option field contains record's text. But the record's text entries are very long and make the drop down so wide that it totally changes the appearance of my webpage. When I cut down the width it also cuts down the text displayed. Is there any way I can make the web page look good and still allow the user to see the full text (like wrapping, scrolling, or something like that)? How can I handle this?
Try using CSS to add a fixed width to your dropdown, like: select {width: 150px} Whilst the dropdown itself will be of a fixed width and may not show all of the text, the option elements should expand to the width of the widest element. May not work in IE7 and below, in which case the this link may be of some use for those browsers:
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "asp.net, drop down menu, word wrap" }
CUPS gives 'Unable to open the initial device, quitting' when printing to network printer I am trying to print over Wi-Fi to an HP Photosmart D110 printer which is successfully recognized by CUPS. But I only get a sheet with the error message `Unable to open the initial device, quitting`. And in the CUPS interface it says `Filter failed`. At home I have an HP Photosmart C3100 that works correctly over USB, so I think CUPS is not the problem. I have tried to no avail: * reinstalling `cups`/`hplip` * `pacman -S avahi nss-mdns` (like proposed here) The full text of `/var/log/cups/error_log` is here. The same printer works correctly over USB, too. I'm running Arch Linux x86-64 with cups 1.6.1. What am I missing?
Solved by using the `hpcups` driver rather than the `hpijs` one (picked when configuring the printer).
stackexchange-unix
{ "answer_score": 6, "question_score": 4, "tags": "printing, cups" }
python2.7.10,OSX(10.11.2)でCarbon.Evt.EventAvailが見つからない。 python 2.7.10OSX(10.11.2) < OSXgetch() AttributeError: 'module' object has no attribute 'EventAvail' from Carbon import Evt class _Getch: def __init__(self): import Carbon,Carbon.Evt Carbon.Evt def __call__(self): import Carbon if Evt.EventAvail(0x0008)[0]==0: # 0x0008 is the keyDownMask return '' else: (what,msg,when,where,mod)=Carbon.Evt.GetNextEvent(0x0008)[1] return chr(msg & 0x000000FF) getch = _Getch()
< > Most of the OS X APIs that these modules use are deprecated or removed > in recent versions of OS X. select #!/usr/bin/env python import sys import select import tty import termios def main(): while True: print "hit ESC key" r, w, e = select.select([sys.stdin], [], [], 0) if r and r[0] is sys.stdin: if r[0].read(1) == '\x1b': break if __name__ == '__main__': term_settings = termios.tcgetattr(sys.stdin) try: tty.setcbreak(sys.stdin.fileno()) main() finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, term_settings)
stackexchange-ja_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python" }
hide meta tag, wrong syntax? My programmer isn't available at the moment and I need to make a change to the system. I have tried to copy what he has done before, but I keep getting errors. So what I want to do is to have the metatags hidden when a url stats with /id. He has done the same with the title tag like this: <?php if (!StartsWith($_SERVER['REQUEST_URI'], '/id/') echo "<title>$pagetitle</title>"; ?> Result: title is hidden when an url goes like www.site.com/id=15 Below is the metatag as it is: <?=isset($metatags) ? $metatags:"" ?> I tried to copy things and make it hide the meta with the code below: <?php if (!StartsWith($_SERVER['REQUEST_URI'], '/id/') isset($metatags) ? $metatags:"" ?> What am I doing wrong? Can anybody be so kind to provide me with the correct line? Thanks,
You can combine the existing "metatags" line with what your programmer has done previously to hide text based on the request URI, by saying: <?= (isset($metatags) && !StartsWith($_SERVER['REQUEST_URI'], '/id/')) ? $metatags : "" ?> OR <?php if (isset($metatags) && !StartsWith($_SERVER['REQUEST_URI'], '/id/')) echo $metatags; ?> They mean the same thing; you may use whichever you wish.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, syntax, meta tags" }
Do I need to dynamically allocate double arrays to pass them? Here's a simple compile error, I'm allocating double arrays like so: double mixmu[][1] = {{1},{-1}}; double mixvar[][1] = {{1},{1}}; double coef[] = {1,1}; can I not pass these as double** objects? error: no matching function for call to ‘MixtureModel::MixtureModel(int, int, double [2], double [2][1], double [2][1], Distribution*)’ ./problems/MixtureModel.h:25: note: candidates are: MixtureModel::MixtureModel(int, int, double*, double**, double**, Distribution*)
> **Do I need to dynamically allocate double arrays to pass them?** No you don't! Your misconception/doubt stems from the (Incorrect)fact that, Arrays are pointers **_No! Arrays are not pointers!!_** An array name decays sometime to an pointer to its first element in scenarios where array name is not valid. A two dimensional array does not decay to an double pointer. It decays to an pointer to array. Your declaration needs to be: MixtureModel::MixtureModel(int, int, double [2], double [2][1], double [2][1], Distribution*); or MixtureModel::MixtureModel(int, int, double *, double(*)[1], double (*)[1], Distribution*); * * * **Good Read:** How do I use arrays in C++?
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++" }
Notification in watchr I can't find an answer to a question. I would like to make a notification in watchr via autotest-notification, but I don't understand how to do it? In Watchr Install section talks about libev. And I tried to do this in my Ubuntu10.10 but after start watchr notification not appear.
Sorry. These issues I have been associated with bug on Ubuntu, when some program is running on full screen notify-send don't work.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails 3, testing, notifications" }
Workflow to capture the modified date when there is a change in Comments column I am new to SharePoint designer. Is it possible to create a workflow which captures the modified date in a new column only when there is a change/edit happened in comments column. This workflow should not trigger if the comments column untouched. Please help!!
Not possible directly with designer workflow . Alternative way is * Start work flow on item change * Store your old comment in a dummy field. * Then compare new comment with old comment * If both are same stop work flow else continue
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sharepoint, sharepoint designer" }
Find data attribute and insert it to database using ajax I need a correct script for iserting data attribute to database onclick using ajax. **HTML:** <li><a data-cat="random name">Button</a></li> **jQuery:** $('li a').click(function() { $(this).data('cat'); // Dont know how correctly use ajax here. }); **PHP:** $cat = HERE MUST BE DATA ATTRIBUTE; $timer = time(); $something = NULL; $stmt = $db->prepare("INSERT INTO table (cat, timer, something) VALUES(:cat, :timer, :something)"); $stmt->execute(array(':cat' => $cat, ':timer' => $timer, ':something' => $something,)); Sorry for bad english, and thanks for any answers.
More info at about jQuery.post() $('li a').click(function() { var category = $(this).data('cat'); $.ajax({ type: "POST", url: '/script.php', data: {'cat': category} }); }); PHP $cat = $_POST['cat'];
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "php, jquery, html, ajax" }
Visual Studio (C++) IntelliSense with parentheses If I have a vector toto, when I write **toto.s** , IntelliSense gives me **toto.size** but I would like **toto.size()**. How to force IntelliSense to give me parentheses?
I don't think that is possible using the visual studio's intellisense. However check out this very good third party tool which can do that: Visual Assist
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 4, "tags": "c++, visual studio, visual c++, visual studio 2015, intellisense" }
Loading shapefiles for reprojection using sf I'm trying to automate my workflow, but having trouble with one step. My data come as processed shapefiles saved in .RDA files; I load them to a PostGIS system, cleaning up little issues (`spTransform()` to a local CRS, `as.numeric()` on a key field, etc). When I simply `load(c:/data/regionX-yearY.rda)` they load as SpatialPolygonsDataFrame so I can simply `regionX-yearY_3035 <- spTransform(regionX-yearY, "+init=epsg:3035")` ... but for some reason looping over files from `list.files()` causes them to be loaded as characters, or their filehandle or something. The sf package errs with > "unable to find an inherited method for function ‘spTransform’ for signature ‘"character", "character"’" Ideas as to what's going on here? Obviously I took some sort of implicit shortcut by hand.
After I couldn't get @Spacedman's suggestion working I dropped it, feeling it was a bit out of hand; I later stumbled the simplest answer: I misunderstood `load()` and `get()`. After the `file <- load(c:/data/regionX-yearY.rda)` I had the filepath; this mislead me a bit as it's a ponderous load for these .rda files, actually "feels" like R has loaded something more than a char string, but `class(file)` confirms it's `[1] "character"`. One needs to simply `file <- get(file)` to do operations on the sp or sf object itself: now class(file) says: [1] "SpatialPolygonsDataFrame" attr(,"package") [1] "sp" May my mea culpa prove useful to others.
stackexchange-gis
{ "answer_score": 0, "question_score": 2, "tags": "r, sf, rgdal" }
Error opening MINC 2.0 images with SimpleITK 0.5.1 C# Windows I am trying to load an MINC 2.0 Image with SimpleITK 0.5.1 C# version I get the following error: System.ApplicationException : Exception thrown in SimpleITK ImageFileReader_Execute: ..\..\..\..\..\ITK\Modules\IO\HDF5\src\itkHDF5ImageIO.cxx:883: itk::ERROR: HDF5ImageIO(000000001DBE7AE0): H5Dopen2 failed My code is as follows: String fileName = @"d:\Temp\MRI\tst-convert.mnc"; ImageFileReader reader = new ImageFileReader(); reader.SetFileName(fileName); Image image = reader.Execute(); Do you have an suggestions what can cause such error? Should I install some additional libraries?
I got a response from ITK User group: Current version of SimpleITK and also ITK can not read MINC Images.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, itk, minc" }
How to obtain same results of plus operation in python and in math? In run the follow code: k = 0 while k <= 1: print(k) k += 0.1 And get result: 0 0.1 0.2 0.30000000000000004 0.4 0.5 0.6 0.7 0.7999999999999999 0.8999999999999999 0.9999999999999999 However, the expected output is 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 How to make the result of python output same as in math?
Just use `round` method with a precision of `1`: In [1217]: k = 0 ...: while k<=1: ...: print(round(k,1)) ...: k += 0.1 ...: 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, python 3.x, floating point" }
Find the number of terms in the arithmetic sequence $6 + 10 + 14 + \cdots + (4n-2)$ I am trying to understand how to find the numbers of terms in the arithmetic sequence below. > $6 + 10 + 14 + ... + (4n-2)$ I think it should be $(n-1)$ because $$\frac{(4n-2)-6}{4} = \frac{4n-8}{4}=n-2$$ and we add a $1$ to $n-2$ since we undercount the first number (example, if we just had the sequence $6+10+14$ and we want to find the number of integers we can subtract $6$ from 14 and divide by $4$ i.e.,$\frac{14-6}{4}=2$, but we undercounted by $1$ so the total number of integers in the example sequence is $3$), so it should $n-1$ terms in the above arithmetic sequence, but the book says $n-2$ and I don't know why that is.
You are right; the book is wrong. Your first term $6 = 4(2)-2$ Your final term is $4(n)-2$ The number of terms is the number of integers from $2$ to $n$ inclusive. Starting from $1$, that would be $n$, so here it's $n-1$.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "sequences and series, arithmetic progressions" }
How to understand "he realized a split second too late was also a mistake" > "It's not like that!" said Harry, and he was so relieved at finally understanding what she was annoyed about that he laughed, which he realized **a split second too late was also a mistake**. > > Harry Potter and the Order of the Phoenix It seems to me that " **a split second too late** " is the subject of the clause. But "a split second too late" doesn't look like a noun phrase, and hence it's not a legitimate subject in my opinion. Or we should parse it as "he realized [ **a split second** ] that too late was also a mistake"? How should we understand that phrase here?
No, the subject of **was also a mistake** is the act of laughing, he laughed. Laughing at that moment was a mistake. But he was aware of that just a split second **after** laughing, **too late** because he couldn't avoid it. **a split second too late** is a complement that determines **when** exactly he was aware of his mistake, when he realized that.
stackexchange-ell
{ "answer_score": 11, "question_score": 3, "tags": "phrase usage, sentence structure" }
Any good source of information on EU based postdoctoral/researcher funding opportunities I have read several posts on the forum but there seems no good information hub for EU based postdoctoral/researcher funding opportunities. I will be grateful if someone can give me a start. By the way, I have found this list myself.
I would suggest two options 1) applying for your own funding and/or 2) apply for a job where someone has aquired funding and is looking for a postdoc. Option #1 is far more desirable - though also more risky. For option 1) There are several EU funding options (many country specific). Not knowing your field, you might have a look the EU call; < For option 2) Academics post positions for postdocs all the time. Akadeus.com is a good starting point. < I hope that helps!
stackexchange-academia
{ "answer_score": 3, "question_score": 4, "tags": "research process, funding, postdocs, eu" }
Woo-Commerce : After Registration redirect to cart page If user is not logged in,there is a registration form on cart page,when submitting, it is redirecting to "my-account page". I want to redirect it to cart page. I have tried so many ways,but did not work.It is forcefully redirecting on my-account. Need Help !
Did you try this? function custom_registration_redirect() { global $woocommerce; $cart_url = $woocommerce->cart->get_cart_url(); wp_redirect($cart_url); exit(); } add_action('woocommerce_registration_redirect', 'custom_registration_redirect', 2);
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 0, "tags": "wordpress, plugins, woocommerce, redirect, registration" }
Refactor simple rails code for specifying active li on navigation I am trying to set an li class of active based on what page the user is on. I have 4 navigation elements and they all look something like this: <% if @activeLi == "home" %> <li class="active"> <% else %> <li> <% end %> <%= link_to :controller => "home" do %> <span>Home</span> <% end %> </li> and then in each controller I just set @activeLi like this: def index @activeLi = "about" end I know this is pretty basic stuff, but i'm just wondering if there is an easier way to do this?
Well I know one way you can simplify this and thats by getting rid of the need to use those nasty instance variables. <li class="<%= controller_name == "home" ? 'active': '' %>"> <%= link_to :controller => "home" do %> <span>Home</span> <% end %> </li>
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "ruby on rails" }
Show proportion with multiple conditions in R I have: > dataframe GENDER CITY NUMBER Male NY 1 Female Paris 2 Male Paris 1 Female NY Female NY 2 Male Paris 2 Male Paris Male Paris 1 Female NY 2 Female Paris 1 And I would like to return the proportion of Male and Female in bomb city (then in NY) who has 2 as a third column (The DF is way longer that my example), knowing that there are empty rows in NUMBER column. Technically speaking I want to show a proportion with two conditions (and more conditions in the future). I tried: prop.table(table(dataframe$GENDER, dataframe$CITY == 'NY' & dataframe$NUMBER == 2) But this gives me the wrong results. The xxpected output (or any that is close to this): NY Male 0 Female 20 Do you have any idea how I can get this? The best would be to have a column per city
Use the environment data.table, that makes your life much more easier. It uses SQL syntax and its superfast in case your data grows up. The code should be: library(data.table) df <- data.table(yourdataframe) df[, summary(GENDER), by = CITY] The output should give you the count of each value
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "r" }
which parts of asp.net website are shared between users? In asp.net website project, is pages and .cs files compile for each and every client ? how can I learn this sort of information is there any resource? which parts of website are shared between users?
Generally speaking, there is only one copy of the web site for all users. There is only one copy of any `static` (`Shared` in VB.NET) data, for all users, so be careful. Some developers assume that these values will magically be turned into per-session variables, but no. (I used to think that way, then learned). If using `Session` state, then each browser session will have one copy of `Session`. This is cookie-based, so the same user using IE and FireFox will have two sessions. Each request to a page creates a new instance of the `Page` class and any controls on that page.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net" }
Show that $x^2 + 1$ has an infinite number of roots in Q. **Let** $Q = (i,j,k)$ be the quaternion ring with multiplication defined by: $$ij = k, \quad jk = i, \quad i^2 = j^2 = k^2 = −1$$ and addition defined as a formal vector space over $\mathbb R$ with basis: $1, i, j, k.$ **Show that** $x^2 + 1$ has an infinite number of roots in Q. **My approach:** Let $a, b, c$ be real numbers satisfying $a^2 + b^2 + c^2 = 1$ and let $x = ai + bj + ck$. Then $$ x^2 = (ai + bj + ck)(ai + bj + ck) = -(a^2 + b^2 + c^2) = -1. $$ I'm not quite sure this approach is true in $\mathbb Q$, (I saw this approach was used when $x \in \mathbb H$)
Yes, it is correct, but, of course, you must explain why there are infinitely many elements $(a,b,c)\in\mathbb R^3$ such that $a^2+b^2+c^2=1$. And you should not write $\mathbb Q$ when you mean $Q$. Actually, I suppose that you mean $\mathbb H$ here.
stackexchange-math
{ "answer_score": 7, "question_score": 0, "tags": "abstract algebra, ring theory, quaternions" }
Can Thor fly in Norse mythology? In the Marvel Universe, flight is one of Thor's powers. (It's been a veeeeeeeery long time since I read the comics, but in the recent films he flies by holding onto Mjolnir's strap or handle, and is pulled along into the air by the hammer itself.) But my recollections of the Eddas are of Thor doing a lot of walking, and he even seems to slow down Odin and Loki, both expert shapeshifters, when they need Thor's companionship pending confrontations that can only be solved by exceptional feats of strength.
AFAIK, there is actually nothing that explicitly says that he can fly, even when he uses his chariot. _Þrymskviða_ , verse 21, describes how he goes to Jotunheim: > Then home the goats | to the hall were driven, > They wrenched at the halters, | swift were they to run; > The mountains burst, | earth burned with fire, > And Othin's son | sought Jotunheim. > This does not suggest flying. Furthermore, in Hárbarðsljóð, Thor is returning from Jotunheim in the east, and gets involved in a flyting with a ferryman who refuses to carry him across. It is strange to imagine why he would have to do so if he could have taken his goats instead. The only thing that comes close is how he is said to cause thunder, but there is no absolute need for that to come from free flight.
stackexchange-mythology
{ "answer_score": 9, "question_score": 7, "tags": "norse, thor" }
How to install Google Music on a non-US phone? I am trying to install Google Music on my phone from outside the US. After using Market Enabler Play Store correctly displays and even downloads the app, but then aborts with "this app cannot be installed in your country". It still doesn't work after rebooting my phone. Is there any way around this?
I had no trouble getting it myself, but that was a while ago. Have you tried using a US proxy or sideloading the app? Another option would be to switch to data or Wi-Fi for the download, whichever you weren't using, to see if it's just the particular network that the Play Store has a problem with.
stackexchange-android
{ "answer_score": 3, "question_score": 3, "tags": "google play store" }
Proper *pattern* for implementing graph algorithms? I have an `AdjacencyList` class and I want all graph **algorithms** to be seperated from it. Let's say all algorithms are **functors** and derive from `GraphAlgorithm` abstract base class. How do I make it work? I am currently thinking, class AdjacencyList { // ... friend class GraphAlgorithm; // ... }; But is it allowing **GraphAlgorithm's sub-classes** to access private members of **AdjacencyList**? Any other approaches are welcome.
> But is it allowing GraphAlgorithm's sub-classes to access private members of AdjacencyList? No, it does not. Friendship is not transitive. Regardless, whenever you need a `friend` declaration, you should regard it as a code smell and re-think your design. I would rather have getters in the `AdjacencyList` and so a `GraphAlgorithm` can operate on the members it has access to from the methods of `AdjacencyList`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c++, design patterns" }
Google maps and google location autocomplete clashing Am displaying a google map and below it have a text input where am using google's places autocomplete. I'm having problem where either the map is displayed or the autocomplete works, but am not able to get both working together :( jsfiddle here: < The map there works fine but the text box autocomplete ain't. < The location autocomplete works, but map ain't. I have a strong hunch am going wrong with the external Google Maps API JS source am including in the script section, but my brain is fried and am not able to fix this
Add: createMap(); to: $(document).ready(function() { } ...that fixed it for me.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "google maps, autocomplete, google maps api 3" }
Is motorcycle ABS necessary for newbie riders riding in India? ABS is now being installed and offered as an option on a few motorcycles in India. Most of them however, are only on the front-wheel. Rear wheels don't still have ABS, but apparently come with a wheel spin sensor. Considering the use-case of a 200cc, 20.5 bhp, 18.5 Nm (13.6 pound-feet) of torque, 150 kg motorcycle, on mostly city roads, and sometimes on highway roads - does one REALLY need ABS on a bike? Can one compensate for lack of ABS, by training one-self regularly? Please consider me a newbie in terms of motorcycling when considering an answer. Your response is much appreciated.
I don't have reputation so I cant comment. anyways, abs is a safety thing. it stops your wheel from locking when too much braking pressure is applied. Now, citing a scenario in the city when you are cruising at the main road nearing an intersection at a speed of 50kms when suddenly a car entered the intersection at high speed. you might be surprised of that car and suddenly squeezed the front brakes so hard that it pull locked your tyres and throw you off into the air. ABS prevents that kind of things happening
stackexchange-mechanics
{ "answer_score": 2, "question_score": 1, "tags": "motorcycle, abs, india" }
Passing class data on navigation to other page Windows Phone 8.1 I've a class class PTD { public string Player1 { get; set; } public string Player2 { get; set; } } And a Page1 have 2 text boxes and 1 button. The Button Click Method have following code: PTD ptd = new PTD(); ptd.Player1=textbox1.text.ToString(); ptd.Player2=textbox2.text.ToString(); NavigationService.Navigate(new Uri ("/Page2.xaml?msg=", UriKind.RelativeOrAbsolute)); On Page2 I have 2 text blocks where i want my class data to appear on navigation. What additional code should i write to perform this action?
In Windows Phone 8.0 and Windows Phone Silverlight 8.1, you can use NavigationService to do page navigations. You can pass strings as parameter of 'Navigation Uri'. NavigationService.Navigate(new Uri ( string.Format("/Page2.xaml?player1={0}&player2={1}", ptd.Player1, ptd.Player2), UriKind.RelativeOrAbsolute)); Then in Page2, you can receive the 2 params in OnNavigatedTo method like this: protected override void OnNavigatedTo(NavigationEventArgs e) { string player1; NavigationContext.QueryString.TryGetValue("player1", out player1); string player2; NavigationContext.QueryString.TryGetValue("player2", out player2); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, windows phone 8, windows phone 8.1, navigationservice" }
Eclipse: Project > Properties does not show all the options I have two work spaces, both for java projects. One shows all the options in project properties (such as Java Build Path). See the image below: !enter image description here Other project project properties in another workspace does NOT show all the options (Java Build Path in particular). See the Image below: !enter image description here Note: The second project is a maven project that i've checked out from an svn repository whereas, the first one is a java project (not checked-out). What is the reason for this?
The second project is not a Java project as far as Eclipse is concerned (technically it does not have the Java `nature` defined for the project in the `.project` file). Only Java projects have the property pages such as Java Build Path.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "eclipse, maven" }
Why is assignment operation still giving MemoryError for large arrays in Python? I have a large array `K` (29000 x 29000): K= numpy.random.random((29000, 29000)) I want to apply the following operation on K: output = K* (1.5 - 0.5 * K* K) To try preventing '`MemoryError`' , I am doing my computations as suggested on the answer from this thread. However, when I try to do the assignment operation on the large array as follows, I still get the `MemoryError`: K *= 1.5 - 0.5 * K * K Any help welcome. NOTE: this is not a duplicate post. There is a suggestion on this post using cython. But I am looking for alternative solutions which may not rely on Cython.
You can do assignment in blocks, say, of 1000 rows. The additional array this creates will be 1/29 of the size of your array, and having a for loop running 29 times shouldn't be much of a speed problem. Typical memory/speed tradeoff. block = 1000 # the size of row blocks to use K = np.random.random((29000, 29000)) for i in range(int(np.ceil(K.shape[0] / block))): K[i*block:(i+1)*block, :] *= 1.5 - 0.5 * K[i*block:(i+1)*block, :]**2 * * * Since there was some concern about the performance on smaller matrices, here is a test for those: block = 1000 K = np.arange(9).astype(np.float).reshape((3, 3)) print(1.5 * K - 0.5 * K**3) for i in range(int(np.ceil(K.shape[0] / block))): K[i*block:(i+1)*block_size, :] *= 1.5 - 0.5 * K[i*block:(i+1)*block_size, :]**2 print(K) This prints [[ 0. 1. -1.] [ -9. -26. -55.] [ -99. -161. -244.]] twice.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "python, numpy" }
iOS updateView called after viewDidAppear I have a `NavigationViewController` with a `UITableView` in it. Upon load, I make an asynchronous backend server call to get some data to populate the view. Upon return I would call `updateView`. I found that sometimes I would only see the Navigation Bar appear and no table view. From my debugging, this occurs when my `updateView` gets called **AFTER** `viewDidAppear`. I do have a `[self.taboleView reloadData]` at the end of my `updateView` but I guess that doesn't help when `viewDidAppear` has already fired? Bit confused about this. Anybody have any idea how to solve this timing issue? This is happening on an iPhone with iOS8. Thanks!
The answer is to reload/update the view on the main thread. So at the end of my `updateView` I changed my `[self.tableView reloadData]` to [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:TRUE]; And it fixed my bug!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ios, uitableview, uiviewcontroller, ios8" }
PHP Advance Job Queue I am making a script with 2000 jobs in a day using cron (means that is server side and automatically do all jobs.) but the job require to run simultaneously 10 (or specified no. of jobs ) jobs . like if u see IDM(internet download manager ) there is a queue function it run multiple jobs at a time and if any complete it start another . i want something like this .. how can i do this ?
You can either go ahead and write your own custom job queue handler. Spawn a separate process per job, and keep collecting the response in the parent process. Restart new jobs when previous one's have finished. Or alternately you can dig into using Gearman (specially if you have multiple boxes running jobs in parallel). Also do view solutions proposed here on asynchronous-processing-with-php-one-worker-per-job
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "php, cron, queue" }
Find the simple closed form of summation from $k=0$ to $N$ I am studying for my discrete mathematics class and I came across a question asking to find the simple closed form of the summation below. I know that $\binom{N}k = \frac{N!}{N!(N-k)!}$ but I am unsure how to use that to find the closed form. I cannot find a simple answer on what a simple closed form is. $$\sum_{k=0}^N (k^2-k) \binom{N}k $$ Thank you
1. Simple math show that $k\binom{N}{k}=N\binom{N-1}{k-1}$, so $$\sum_{k=1}^Nk\binom{N}{k}=N\sum_{k=1}^N\binom{N-1}{k-1}=N2^{N-1}$$ 2. Using the identity at 1. \begin{eqnarray} k^2\binom{N}{k}=Nk\binom{N-1}{k-1}&=&N(k-1)\binom{N-1}{k-1}+N\binom{N-1}{k-1}\\\ &=&N(N-1)\binom{N-2}{k-2}+N\binom{N-1}{k-1} \end{eqnarray} So taking sum over $k^2\binom{N}{k}$ we get $$\sum_{k=1}^Nk^2\binom{N}{k}=N(N-1)\sum_{k=2}^N\binom{N-2}{k-2}+N\sum_{k=1}^N\binom{N-1}{k-1}=2^{N-2}N(N+1)$$ Then the closed form is $2^{N-2}N(N-1)$
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "combinatorics, discrete mathematics" }
jQuery milliseconds timer? Is it possible to update in intervals similar to 10nths of milliseconds. I used window.setInterval(timeUpdate,20); Is this possible or does the browser's thread have some sort of minimum period? Thanks
Depending on the browser, it's version and if there's focus on the tab, the timer resolution may differ. For more detail please have a look at the following refrence, especially the Minimum delay and timeout nesting part.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "jquery" }
Can someone suggest a recent survey on product form Markov chains? I'm especially interested in their use in model checking applications. I have Open, Closed and Mixed Networks of Queues with Different Classes of Customers by Baskett et al. Any other suggestions for reading material? Thanks.
There is this unpublished book by Aldous and Fill, two experts in the field. You'll find walks on product of chains there.
stackexchange-cstheory
{ "answer_score": 7, "question_score": 11, "tags": "reference request, markov chains, queueing theory, model checking" }
Align items top and bottom without using flexbox There exist two items in a box and I'm trying to align the first item to the top of the box and the last item to the bottom of the box. I know I can do this easily with flexbox: .container { height: 150px; width: 100%; background-color: lime; display: flex; flex-direction: column; justify-content: space-between; } <div class="container"> <div>Top text</div> <div>Bottom text</div> </div> Unfortunately, the platform I'm using (some old html to pdf generator) doesn't support flexbox. Is there another way to do this without using flexbox?
You can use CSS positioning properties. .container { position: relative; height: 150px; width: 100%; background-color: lime; } .container > div { position: absolute; } .container > div:first-child { top: 0; /* optional */ } .container > div:last-child { bottom: 0; } <div class="container"> <div>Top text</div> <div>Bottom text</div> </div> **Just note** that absolutely positioned elements are removed from the document flow. This means they don't respect the space occupied by surrounding elements, which can result in overlapping.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "javascript, html, css, flexbox" }
jQuery select sort changing displayed option on page refresh. What's happening? I'm using the following jQuery to sort the select elements in a form: $('select.select-sortable').each(function () { var options = $(this).children(); var arr = options.map(function(_, o) { return { t: $(o).text(), v: o.value }; }).get(); arr.sort(function(o1, o2) { return o1.t > o2.t ? 1 : o1.t < o2.t ? -1 : 0; }); options.each(function(i, o) { o.value = arr[i].v; $(o).text(arr[i].t); }); }); The sorting works, but the displayed value changes on every page refresh. It changes in the order 1st option -> 3rd option -> 2nd option -> 1st option, no matter how many more options are present. I've added `$(this).children(":first").attr("selected", true);` to the loop, which locks the choice to the first option, but I still don't understand why the dsiplay was changing, and why in that order. Does anyone have any ideas?
It's happening because of browser cache. It stores information about which option (with what value) was selected before pressing reload. If you change option values on the fly, browser will reflect these changes on next reload, but your script will instantly modify the values again. It's playing catch-up with you :) Btw. you don't have to do constructs like this: `$(this).children(":first").attr("selected", true);` Simple `options[0].selected = true;` placed after `options.each` loop will suffice.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript, jquery, html" }
how to make UIAlertView with custom font , height and width? I want to show pop up of question with it's options. Each question have 3 options. Currently the text is not fitting in the UIAlertView. My UIalertView is in landscape mode. my questions are, 1) How to change the font and font size of UIAlertView message and Button? 2) How to increase the height and width of UIAlertView? OR please suggest me any other way , by which I implement the same pop up. Thanks .
A better idea might be to make a custom `UIView` (that you can design in Interface Builder) and have that "pop up" by adding/removing it as a subview from the current view.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "iphone, objective c, uialertview" }
Is there a word that means "to walk slowly"? The only word that comes to my mind is _tiptoe_. However, this word implies that you are walking stealthily or cautiously. Is there a word that just means _to walk slowly_? Example sentence: > Without knowing what I was doing, I _ toward her.
I would suggest **amble** : > _verb_ > > 1. to go at a slow, easy pace; stroll; saunter: > > > _noun_ > > 4. a slow, easy walk or gentle pace. > dictionary.com Your sentence would then be: > Without knowing what I was doing, I **ambled** toward her. As that definition suggests, **strolled** or **sauntered** may also work for you.
stackexchange-english
{ "answer_score": 132, "question_score": 34, "tags": "single word requests, verbs" }
Asp.net pagelifecycle page_loadComplete In my web application I load user controls in the page_loadComplete event. This works fine, however when a button is clicked in a user control, the click event is never fired. Does this has something to do with the page lifecycle? That button click (UI) events occur before the LoadComplete event?
You need to make sure the click event of the button is once again subscribed to, before event handlers fire. LoadComplete happens after control events. For a reference, the ASP.NET Page Life Cycle Overview gives a pretty nice summary. Snippet: * ... * Load * Control events * LoadComplete * PreRender * ... You also need to make sure that the controls that you dynamically load all end up in the same place, so viewstate and controlstate can be reapplied to the same hierarchy as before postback. Basically, you need to load all dynamic controls on each postback. Here's someone with the same problem, and solutions to some of them: ASP.NET dynamic controls
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "asp.net, page lifecycle" }
python re.sub, substitute a pattern only if it appears at the beginning of a string substitute a pattern only if it appears at the beginning of a string. for e.g. `str1 = "abab abadfadsf"` I only want to remove/replace the "ab" at the beginning of str1, i.e. I want to write an regex so that I can get `str2 = "ab abadfadsf"` from str1 by `re.sub` how do I do it?
You can use `re.sub('^ab', '', 'abab abadfadsf')` `^` stands for the beginning of the string.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python, regex" }
What is the difference between delete() and unlink() in PHP When I started searching for "How to delete a file in PHP" The solution I got almost everywhere is "unlink()" But in w3schools I met with another function named delete(). Here is that link delete() function w3schools And I started surfing about delete() but didn't get much answers.. This is the question similar to my question at stackoverflow.. DIfferent between unlink() and delete() on unix I really would like to know the difference and similarities between these two functions.. Why we are using unlink() instead of delete().
**`delete()` function doesn't exist** as the php docs says > This is a dummy manual entry to satisfy those people who are looking for unlink() or unset() in the wrong place. a dummy manual entry was created _to catch anyone that is looking for a function that they assume to exist but doesn't really exist_ then guide them to the right function <
stackexchange-stackoverflow
{ "answer_score": 16, "question_score": 18, "tags": "php, file io, unlink" }
Facebook SDK giving unused variable compile errors in Xcode 5.1 I'm getting a lot of unused variable errors after updating to the new version of and Xcode 5.1. Compiler is saying unused variables are errors, and checked the compiler settings that i didn't modify treating warning as errors. This only happened after I updated to Xcode 5.1
There seems to be indeed an issue with Facebook iOS SDK and compiling on Xcode 5.1 even if compiling it by itself. I opened a bug in the Facebook support system: < As a temporary workaround - you can fix it by turning off treating warnings as errors ( a very good practice by itself btw I use for our SDK) by: 1\. Open the Facebook proj file (or the project inside an existing project 2\. Go to build settings of the entire project 3\. Change the "Treat Warnings as Errors" field from YES to NO. This will let you compile it even with these warnings - but do be alert for an updated sdk in the coming days.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "ios, xcode, facebook, facebook graph api" }
HTML/CSS How to auto-adjust the width of my container in order to show several images horizontally displayed? I want to have a variable amount of images displayed horizontally in a web (which can be navigated with an horizontal scroll bar), but I can't get the images displayed beyond the 100% width of the browser. Since the amount of images will vary, I need to avoid setting a constant width to the container. Here's the code I'm trying right now. **HTML** : <div id="container-galeria"> <img src="galeria1/1.jpg"> <img src="galeria1/1.jpg"> <img src="galeria1/1.jpg"> <img src="galeria1/1.jpg"> <img src="galeria1/1.jpg"> </div> **CSS** : #container-galeria{width:auto;min-width:100%;height:auto;min-height:100%;} #container-galeria img{float:left} Hope I was clear and somebody can help me with this. Thanks in advance!
try this: <div id="container-galeria"> <ul><li> <img src="galeria1/1.jpg"></li> <li> <img src="galeria1/1.jpg"></li> <li><img src="galeria1/1.jpg"></li> <li><img src="galeria1/1.jpg"></li> <li><img src="galeria1/1.jpg"></li> </div> ul { list-style:none; white-space: nowrap; } li { float: left: /*overflow-x:scroll; /*optional*/ */ width:120px; display: inline; } <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "html, css, variable width" }
Reasonable phobia name for fear of alcohol evaporating before you can drink it I am curious as to what the phobia name would be for the fear of the alcohol in your drink evaporating before you can drink it. It appears most phobias are rooted in Greek and sometimes Latin. Some searching around turned up some names for a fear of alcohol: Alcohol Phobia- Methyphobia or Potophobia. Are there any language whizzes out there that can come up with this? Alcoholism will not be accepted as an answer.
Since the fear of alcohol is, in fact, _methyphobia_ , the fear of evaporating alcohol would be most precisely: **_methyexatmiphobia_** (since η is phonetically related to ἐ, some might prefer _methexatmiphobia_ ) or more simply: **_methyatmiphobia_** , or simplest of all: **_methatmiphobia_** : The Greek word for _wine_ is **μέθη** , while **ἐξάτμιση** is the Greek word for _evaporate_ , and **ἀτμίς** is the Greek word for _vapor_. * * * Also **_Soberphobia_** : If it evaporates before you can drink it you can't stay drunk. * * *
stackexchange-english
{ "answer_score": 4, "question_score": 0, "tags": "single word requests, word choice, terminology, phobias" }
Haskell pattern matching gone wrong I am learning some Haskell, and I am trying to get my head around how pattern matching works. In doing so, I have written a simple `nth` function. nth' :: Integer -> [a] -> a nth' n [] = error "Index out of bound" nth' n (x:xs) = if n == 0 then x else nth' (n - 1) xs This first implementation seem to work as expected. -- nth' 25 ['a'..'z'] -- 'z' -- nth' 26 ['a'..'z'] -- *** Exception: Index out of bound However, when I refactor it replacing the if statement with pattern matching, I end up getting the "Index out of bound" exception where I clearly should not. nth' :: Integer -> [a] -> a nth' _ [] = error "Index out of bound" nth' 0 (x:[]) = x nth' n (_:xs) = nth' (n - 1) xs -- nth' 2 ['a'..'z'] -- *** Exception: Index out of bound What am I doing wrong?
The problematic clause: nth' 0 (x:[]) = x It matches only one-element list. Try to change it with: nth' 0 (x:_) = x
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "list, haskell, pattern matching" }
Rails add column with default value with no affect on current entries I use rails 4 with postgreSQL I want to add a new column with default value add_column :users, :first_visit, :boolean, :default => true and have all new entries created with value true but need to have all the current entries not to be affected by default value but have a nil value on first_visit field.
`:default => true` in migration add `true` for all existing records. If you want `nil` for existing records and `true` default value then remove `:default => true` from migration and add below code in user model: class User < ActiveRecord::Base before_create :set_default def set_default self.first_visit = true unless self.first_visit end end
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ruby on rails, postgresql" }
Can I get the primary key of an inserted row, using ODBC? What is the best way to retrieve the primary key of an inserted row, when using ODBC objects in .NET? For example (VB): Dim command As OdbcCommand = gOdbcConn.CreateCommand() command.CommandText("INSERT INTO auhinode (node_key, node_desc) VALUES (0, 'New Node')") ... Dim result As Integer = command.ExecuteNonQuery() I've seen a couple of other suggestions here, but I'm wondering if there's solutions specific to the ODBC objects? **Edit:** The reason we're using ODBC, is because we support 3 different databases - SQL Server, Oracle, Informix.
You are not going to find ONE way that will work in all 3 db engines. They each have different ways of getting the ID of the row you just inserted. select scope_identity(); in sql server. In oracle you need to use a sequence and insert the value in the table yourself. Informix So in your code you are going to have to know what database is currently configured to use the required code. Another option is to have a stored procedure do the insert, get the ID an return to you. Then you don't need to make any changes in your code, the code calls a stored procedure that returns the ID but you have different versions of the stored procedure for each db engine, each with the same name, and include them in your scripts to create your database.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": ".net, sql, odbc" }
Wordpress install within another wordpress website (permalinks issue) I have a "/new" directory on an existing Wordpress install and the site itself works though going to any other page will return a 404 from the old website. ie: * website.com -> old website, works * website.com/new -> new website, works * website.com/new/about -> displays 404 from old website I've re-saved the permalinks settings in an attempt to make sure the htaccess file was correct, is there maybe a way in the old websites .htaccess file that I can ignore anything in the /new directory from it attempting to try and find a page in the old website?
Try adding an htaccess file in the `/new/` directory that does the appropriate routing. If there is no routing, then simply have: RewriteEngine On to essentially turn off all mod_rewrite activity when going into the `/new/` directory.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, wordpress, .htaccess" }
Why CUDA is unavailable for using with easyocr? According to Pytorch I used this command in cmd pip3 install torch torchvision torchaudio --extra-index-url ![enter image description here]( ![enter image description here]( But CUDA still unavailable. Could someone help me, please? import torch print(torch.cuda.is_available()) The output will be `False`
You have to update driver first: Here is a concept diagram from nvidia website ![enter image description here]( Here is another one: ![enter image description here]( More at CUDA Compatibility
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python 3.x, pytorch, cuda, easyocr" }
Show that: $\int_{0}^{\infty} \frac{\sin{x^{q}}}{x^{q}} dx = \frac{\Gamma{\frac{1}{q}}}{q-1}\cos{\frac{\pi}{2q}} \mbox{, q > 1}$ > How do you show that: $$ \int_{0}^{\infty} \frac{\sin{x^{q}}}{x^{q}} dx = \frac{\Gamma{\frac{1}{q}}}{q-1}\cos{\frac{\pi}{2q}} \mbox{, q > 1} $$ Without using Gamma function?
Yet another approach: applying Ramanujan's master theorem which states that the Mellin transform of a function that admits the expansion of the form $$f(x)=\sum_{n=0}^\infty \frac{(-1)^n x^n}{n!}\phi(n) $$ is given by$$\int_0^\infty x^{s-1}f(x)dx = \Gamma(s)\phi(-s) .$$ Since $$\sin(x)= \sum_{n=0}^\infty \frac{(-1)^n x^{2n+1}}{(2n+1)!}$$ we have $$\frac{\sin(\sqrt{x})}{\sqrt{x}}=\sum_{n=0}^\infty \frac{(-1)^nx^n}{n!}\frac{\Gamma(n+1)}{\Gamma(2n+2)}$$ and therefore, for $0<s<1$: $$\int_0^\infty x^{s-1}\frac{\sin(\sqrt{x})}{\sqrt{x}}dx=\frac{\Gamma(s)\Gamma(1-s)}{\Gamma(2-2s)}=\frac{\pi}{\sin(\pi s)\Gamma(2-2s)}$$ Substituting $t=\sqrt{x}$, $2s=\frac{1}{q}$ and multiplying by $\frac{1}{q}$ we get $$I=\frac{1}{q}\int_0^\infty x^{\frac{1}{q}-2}\sin(x)dx=\frac{\pi}{2q\sin(\frac{\pi}{2q})\Gamma(2-\frac{1}{q})}$$ Which you can match to your proposed form by multiplying by $$\frac{\Gamma(\frac{1}{q}-1)}{\Gamma(\frac{1}{q}-1)}\frac{(\frac{1}{q}-1)}{(\frac{1}{q}-1)}$$
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "calculus, integration, analysis, gamma function" }
gdb within emacs on Windows I'm running Emacs 22.3 in Windows. Earlier today I had gdb working within Emacs just fine. I was installing QT4 and during the installation it asked me to uninstall MSYS which I quickly clicked through not thinking about things. I think I had gdb installed with the MSYS package and Emacs was using that, but I'm not completely sure. Now when I run the following I get an error in the mini-buffer. M-x gdb "Searching for program: no such file or directory, gdb" I tried to add the path "`C:\cygwin\bin`" to the Emacs load-path with this code but I still get the same error. (message "Adding cygwin/bin to load path.") (add-to-list 'load-path "c:/cygwin/bin") Could someone tell me what I'm doing wrong? Thanks.
probably adjust your system path to point it where you have gdb installed.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "emacs, gdb, cygwin, dot emacs" }
Who are you to say otherwise? The following quote from Inception movie I'm trying to understand: > _Eames_ : They come here every day to sleep? > > _Elderly Bald Man_ : [towards Cobb] No. They come to be woken up. The dream has become their reality. **Who are you to say otherwise, son?** I emphasized a sentence I'd like to understand. What one means there?
The question _Who are you to VERB_ (or _Who {am I/are we/is X} to VERB_ ) is a challenge to produce credentials which demonstrate that you have the right or the authority to _VERB_. In practice it usuallly amounts to a denial that you have such right or authority and a demand that you desist from _VERB_ ing. In the present case, instance, the Elderly Bald Man expects the notion that dreams can serve as reality to be mocked, and he says this to prevent any such mockery.
stackexchange-ell
{ "answer_score": 3, "question_score": 3, "tags": "sentence meaning" }
Does Ruby 1.8 have an equivalent to 1.9's __callee__? I need to grab the name of the lexically enclosing method in Ruby 1.8; e.g. def foo this_method = __callee__ # => 'foo' end The above code is valid in Ruby 1.9, but fails in 1.8, since __callee__ was introduced in 1.9. Any suggestions for doing this in 1.8? _Kernel#caller_ looked promising, but seems to give me the call stack starting with the caller of the method, not the method itself. I guess I could throw an exception, catch it, and grab the first element in the _Exception#backtrace_ array, but my gut tells me that will be slow.
On Ruby 1.8.7 there is the `__method__`, not sure about 1.8.6. Anyway, You can monkey patch the `Kernel` module: module Kernel # Defined in ruby 1.9 unless defined?(__callee__) def __callee__ caller[0] =~ /`([^']*)'/ and $1 end end end
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "ruby, introspection" }
Random Bytes in TLS Handshake During the TLS handshake, there are random bytes sent from the server to the client and random bytes sent from the client to the server. Since these bytes are sent in clear text, what is the relevance of them being random? I thought randomness was mostly about lowering the likelihood that these numbers could be guessed. If they are passed around in clear text; whats the importance of the randomness? Also, what exactly are these random bytes used for?
> Since these bytes are sent in clear text, what is the relevance of them being random? They are a guarantee that the other party with whom you wish to communicate is actually interactively there and you're not just seeing a recorded session that is being replayed to you, potentially impersonating somebody else. The randomness helps in this to prevent attackers from simulating a bunch of sessions beforehand and then picking the the relevant one for you. > Also, what exactly are these random bytes used for? Their actual usage is limited to being additional input to the key based key derivation function that transforms the pre-master secret into the master secret (section 8.1 RFC 5246).
stackexchange-crypto
{ "answer_score": 8, "question_score": 7, "tags": "tls, key exchange, randomness" }
MS-Office Document Conversion to .PDF Format I am looking for a MS-Office document to .PDF 3rd party software that does not create the need for my code to manipulate the COM directly. I am looking for a package that is native to .net. I have already looked at the following: < < Are there any other SDK packages that you are aware of that can meet my needs? If the software package manipulates the COM on it's own, that is fine. I just don't want to perform any operations against the COM within my code. I would also prefer it to be C# based.
Have a look at ASPOSE.NET Total & TXTextControl .NET.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 4, "tags": "c#, pdf generation" }
How to get the names of the files stored in NSDocumentsDirectory? I have some files saved in my NSDocumentsDirectory, how do i get the names of those files and then display those names in a uitableview? I just want to retrieve the name of the objects as NSString, I am able to retrieve the files as objects but not their names. Here is the code for it: NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSError * error; objectsAtPathArray = (NSMutableArray*)[[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:&error]; [objectsAtPathArray removeObjectAtIndex:0]; Last line is to remove the .DS_Store file
adding a (for in) loop did the trick for me, for (NSString *fileName in self.objectsAtPathArray){ cell.textLabel.text = fileName; }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "iphone, ios, filenames, nsdocumentdirectory" }
select command in mysql returns an empty row even though the entry exist in table When I run the below query in phpmyadmin it returs 0 rows even the entry exists on the table SELECT * FROM `default_companyshare` WHERE `comp_symbol` = "ACEDBL"
Try this in case you have some space-padding in your database: SELECT * FROM `default_companyshare` WHERE `comp_symbol` like "%ACEDBL%" You can also try trimming your result: SELECT * FROM `default_companyshare` WHERE trim(`comp_symbol`) = "ACEDBL"
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "mysql" }
How to create a map without duplicate values from a map that contains duplicate values? I have a Map which contains the following entries: * <1, Developer> * <2, Admin> * <3, Manager> * <4, Admin> * <5, Developer> * <6, Sales> I need a new Map which shouldn't have the repeating values' entries, i.e it should look like : * <3,Manager> * <6,Sales> (As Developer and Admin was repeating, it shouldn't appear in the new map).
You would probably want to make two passes over the data. The first pass to find the non-duplicated values, and the second to make the new map. Here's what that would look like: Set<String> values = new Set<String>(), // Unique values dupValues = new Set<String>(); // Values that were duplicated for(String value: originalMap.values()) { // add returns false when Set was not modified; this would be a duplicate if(!values.add(value)) { dupValues.add(value); } } values.removeAll(dupValues); Map<Integer, String> remainingValueMap = new Map<Integer, String>(); for(Integer key: originalMap.keySet()) { // Check all key-value pairs. String value = originalMap.get(key); if(values.contains(value)) { // This value was unique remainingValueMap.put(key, value); } }
stackexchange-salesforce
{ "answer_score": 1, "question_score": -3, "tags": "apex, map, collection" }
Android make a first time use screen I want to implement a screen that appears when the user uses the app for the first time, like google does. Is there a special element to use? What would be the best method to check if the user opened the app for the first time?
I've implemented this feature in my app in quite a simple way. I've created a "Tutorial" Activity which shows up when the string (stored in Shared Prefs) "first_user" is equal to false (had problems with booleans...). It's a simple NoActionBar activity, with fragments for every "page". I've also used ViewPagerIndicator to put nice little dots at the bottom to indicate progress (see CirclePageIndicator or something of the sort...) Good luck if you want something more advanced :) ! EDIT : I guess Pablo also shares my opinion. It's a good sign.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "java, android, android intent, android activity, settings" }
Chef Apache2 web_app Configuration I am trying to provision a Apache using chef using the Opscode cookbook. I have configured my default attributes like this below. I have created a template file `/vagrant/sites-available/sof.conf` (and even `/vagrant/sites-available/sof.conf.erb` just to be sure). It never evaluates the template or enables the site. What is wrong? (Using chef-server if that changes anything) { "overrides": {}, "defaults": { "apache2": { "web_app": { "name": "sof", "server_name": "localhost", "server_aliases": [], "docroot": "/vagrant/web" }, "user": "www-data", "dir": "/vagrant", "log_dir": "/vagrant/logs/http" } } }
From the examples section in the doc it seems that you can declare `web_app`s only from within other cookbooks not via node attributes.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "chef infra, chef recipe" }
Core dump to a pipe is failing Tried this on MIPS platform: > uname -a Linux (none) 2.6.29 #2 Mon Jan 14 13:26:04 PST 2013 mips GNU/Linux > ulimit -c unlimited > which gzip /bin/gzip > echo "|/bin/gzip - > /home/core-%t-%s-%e.gz" > /proc/sys/kernel/core_pattern > ./fault hello there Segmentation fault (core dumped) > ls /home/core*.gz ls: /home/core*: No such file or directory i.e. piping to a program doesn't work. if I specify a file: > echo "/home/core-%t-%s-%e" > /proc/sys/kernel/core_pattern then it works. What did I miss?
Perhaps it fail because the kernel doesn't run any shell, but try to execute a program. Try to wrap the gzip invocation with the redirection in a script and use that script.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 2, "tags": "linux, pipe, mips, coredump" }
build-in extractColFromArray? Is there an equivalent **build-in** function to that one? (even without the _test_ capability) /** * extracts a column from a 2D associative array, with an optional selection over another column * * @param $aArray array to extract from * @param $aColName name of the column to extract, ex. 'O_NAME' * @param $aColTest (optional) name of the column to make the test on, ex. 'O_ID' * @param $aTest (optional) string for the test ex. ">= 10", "=='".$toto."'" * @return 1D array with only the extracted column * @access public */ function extractColFromArray($aArray, $aColName, $aColTest="", $aTest="") { $mRes = array(); foreach($aArray as $row) { if (($aColTest == "") || (eval("return " . $row[$aColTest] . $aTest . ";" )) ) { $mRes[] = $row[$aColName]; } } return $mRes; } // extractColFromArray Alex
I agree with VolkerK, but you can use something like this to extract a particular column from a 2D array // set up a small test environment $test_subject[] = array("a", "b", "c"); $test_subject[] = array("d", "e", "f"); //Select the column to extract(In this case the 1st column) $column=0; // do the actual work $result = array_map('array_slice', $test_subject, array_fill(0, count($test_subject), $column), array_fill(0, count($test_subject), 1) ); // and the end result print_r($result);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, arrays" }
Code works in PyCharm, but return syntaxerror when i call it by terminal There is a function: def change_BG_lin (path): os.system(f"gsettings set org.gnome.desktop.background picture-uri {path}") In PyCharm all works properly, but when i call it in terminal it returns this: os.system(f"gsettings set org.gnome.desktop.background picture-uri {path}") SyntaxError: invalid syntax ^
In ubuntu string "python" call to python2, which doesn`t have "f string".
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python 3.x, terminal, ubuntu 18.04" }
Equilibrium constant when given Ka and Kb of reactants !enter image description here The first problem has completely stumped me on even how to begin. I just need some sort of direction.
It should help to look at the form of the constants: $K_\mathrm{eq}=\ce{\frac{[NH4^+][CN^-]}{[HCN][NH3]}}$ For $\ce{HCN}$, $K_\mathrm{a}=\ce{\frac{[H^+][CN^-]}{[HCN]}}$ For $\ce{NH3}$, $K_\mathrm{b}=\ce{\frac{[OH^-][NH4^+]}{[NH3]}} = \frac{K_\mathrm{w} \cdot \ce{[NH4^+]}}{\ce{[NH3][H^+]}}$ where $K_\mathrm{w}=\ce{[H^+][OH^-]} = {1*10^{-14}}$ Is there anyway you can use some combination of $K_\mathrm{a}$ and $K_\mathrm{b}$ to get $K_\mathrm{eq}$?
stackexchange-chemistry
{ "answer_score": 0, "question_score": -1, "tags": "equilibrium" }
Managed C++ Error 2504 Error I'm new to managed c++ and I'm attempting to design a program for a presentation. I am attempting to have a class inherit from an ABC and I'm getting the Error C2504. The code in question is as follows: ref class Item : Auction //Error C2504 here { //More code for the class Auction is defined in a different .h file. Let me know if there are any other questions or if you need to see more of the code. Thanks
Fixed it... Forgot public before Auction so it was defaulting to private inheritance... Doh!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "managed c++" }
Firebase OTP only works in some devices - Swift 4 I am using firebase authentication in my device. I have followed every steps in firebase documentation. The OTP works in the devices that I used for testing purpose. But when I download the app from AppStore, It does not work. Please help me to get rid of this issue. Thanks in advance.
I got the answer. There were 2 things wrong with what I was done. 1. When I created SSL certificate (For push notification) from App Ids under 'Certificates, Identifiers & Profiles' tab in developer.apple.com, The certificate was not created for production. So I created one for production. ![enter image description here]( 2. I forgot to create APNs key. So I created APNs key from Keys under 'Certificates, Identifiers & Profiles' tab in developer.apple.com. Then I uploaded it in the firebase App (console.firebase.google.com). After you select your project, you can find a gear icon in the firebase website. Select project settings from there and click on the cloud messaging tab. And there you can find the option to upload APNs certificate.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "firebase, firebase authentication, swift4, one time password" }