INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Is $f(t-N t_0)=\sin(2\pi f_0t)\cos(2\pi f_1t)$ always true? Is it true that multiplying two sinusoidal functions, always result in some periodic waveform. i-e $$f(t-N t_0)=\sin(2\pi f_0t) \cos(2\pi f_1t)$$ If so, then how can we calculate the period ( $t_0$) of the resulting function, f(t) ? Moreover, is it correct to say that: $$\int_{-\infty}^{\infty}\sin(2 \pi f_1 t)\sin(2 \pi f_2 t)\ dt= \delta(f_1-f_2)$$ thanks
1. In general no, but it is often a yes. You have the following formula: $$ \sin(2\pi f_0 t + \phi) \sin(2\pi f_1 t) =\frac 12\left[ \cos(2\pi (f_0-f_1) t + \phi) + \cos(2\pi (f_0+f_1) t + \phi) \right] $$ It is not periodic if the ratio of frequencies of both signals is not a rational number. 2. The integral you talk about is not well defined from the mathematical point of view of Lebesgue integral. It may be true in terms of distributions, I need a more precise statement (you can't define a product of distributions, as far as I know).
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "fourier analysis, fourier series" }
Как переименовать копию проекта в Android Studio? На английском стэке задавали тот же вопрос, последовательность действий была примерно следующая: 1. Создать копию проекта используя файловый менеджер. 2. Refactor->Rename для проекта. 3. Изменить Gradle соответствующим образом. Мои проблемы: 1. Как и что нужно сделать в Gradle? 2. На этапе переименования через Refactor выводит в EventLog следующее: > 11:40:58 Unsupported Modules Detected: Compilation is not supported for following modules: H0001 Practise. Unfortunately you can't have non-Gradle Java modules and Android-Gradle modules in one project. > > 11:40:58 Gradle sync started > > 11:41:02 Gradle sync completed > > 11:41:02 Executing tasks: [:app:generateDebugSources, :app:generateDebugAndroidTestSources] > > 11:41:03 Gradle build finished in 1s 579ms > > 11:41:25 Throwable: Merged rootsChanged not allowed inside rootsChanged, rootsChanged level == 1
Чтобы переименовать проект в Android Studio нужно выполнить такие действия: 1. Идем в папку, где лежит проект и меняем имя этой папки на то, которое на необходимо. 2. Открываем Android Studio, в окне приглашения выбираем `Open an existing Android Studio project` и находим папку нашего нового проекта. 3. После открытия в `AndroidManifest.xml` мы видим в двух местах название старого проекта. Эта информация хранится в строковых ресурсах, поэтому переходим в `strings.xml` и меняем имя старого проекта на новое. 4. Имя нашего пакета все еще осталось старое. Идем в папку java, нажимаем на имя нашего пакета правой кнопкой мыши, выбираем Refactor, а потом Rename. После этого выбираем Rename directory и меняем имя нашего пакета. 5. Переходим в файл build.gradle, находим блок defaultConfig и строку applicationID, которая имеет значение нашего старого пакета. Меняем имя пакета и синхронизируем проект. Источник информации для ответа.
stackexchange-ru_stackoverflow
{ "answer_score": 12, "question_score": 3, "tags": "android studio, android" }
Integration involving beta and hypergeometric functions/ differential binomial So, hey, everybody! I have to integrate this $$ \int_0^2 \sqrt[3]{\frac{x^2}{2-x}} \, dx $$ and I've already figured out that due to Chebyshev's theorem it cannot be done in terms of elementary functions, since we can rewrite the task as $$ \int_0^2 x^{\frac{2}{3}}\left(2-x\right)^{-\frac{1}{3}} \, dx $$ and $$ \frac{2}{3}+1-\frac{1}{3}=\frac{4}{3}$$ which is, obviously, not an integer number. But, the point is that I'm not quite familiar with Beta-function and stuff like that, so, how do you write the answer to this problem? Mathematica show something like that $$\frac{\Gamma\left[\frac{1}{2} \right]\Gamma\left[\frac{2}{3} \right] }{\Gamma\left[\frac{7}{6} \right] } $$ The question is: "Hey, how did Mathematica do this?"
Here's a way to solve by using beta and gamma functions. Let $$I=\int_0^2 \frac{x^{2/3}}{(2-x)^{1/3}}\,dx$$ The above is equivalent to: $$I=\int_0^2 \frac{(2-x)^{2/3}}{x^{1/3}}\,dx$$ Add the two expressions for $I$ to obtain: $$2I=\int_0^2 \frac{2}{x^{1/3}(2-x)^{1/3}}\,dx \Rightarrow I=\int_0^2\frac{1}{x^{1/3}(2-x)^{1/3}}\,dx=2\int_0^1 \frac{dx}{x^{1/3}(2-x)^{1/3}}$$ $$\Rightarrow I=2\int_0^1 \frac{dx}{(1-x)^{1/3}(1+x)^{1/3}}=2\int_0^1 (1-x^2)^{-1/3}\,dx$$ Use the substitution $x^2=t \Rightarrow dx=\frac{1}{2}t^{-1/2}\,dt$ to get: $$I=\int_0^1 t^{-1/2}(1-t)^{-1/3}=B\left(\frac{1}{2},\frac{2}{3}\right)=\frac{\Gamma\left(\frac{1}{2}\right)\Gamma\left(\frac{2}{3}\right)}{\Gamma\left(\frac{7}{6}\right)}$$ You can even simplify it more by writing $\Gamma\left(\frac{1}{2}\right)=\sqrt{\pi}$ using Euler's reflection formula. In a similar way, you can prove the results presented by Claude Leibovici.
stackexchange-math
{ "answer_score": 4, "question_score": 2, "tags": "integration" }
os-prober Doesn't Detect Windows 10 in Archlinux I installed Arch recently (as in, yesterday). I was able to successfully install Grub in the EFI system Partition with `grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=grub --recheck`, `os-prober` and `grub-mkconfig -o /boot/grub/grub.cfg`. After booting, though, I had two issues: First, I wanted grub to boot linux and not linux-lts kernel by default and second, I wanted it to select Windows by default and a timeout of 1s. In the `/boot/grub/grub.cfg` file, I replaced three instances of linux-lts with linux in the first menuentry. In the `/etc/default/grub` file, I set `GRUB_DEFAULT` as '`Windows Boot Manager on (/dev/nvme0n1p1)`' and `GRUB_TIMEOUT` as `1`. When I ran `grub-mkconfig -o /boot/grub/grub.cfg`, it did not list Windows 10. Even when I ran `os-prober`, no results were shown. On rebooting, Windows entry was not shown but timeout was 1s. So, what should I do? Thank you!
Ok I installed ntfs-3g and ran o `os-prober`. It detected Windows.
stackexchange-unix
{ "answer_score": 3, "question_score": 0, "tags": "arch linux, grub2, uefi, grub2 mkconfig" }
Is it ok to use commas after a number written in digits? In Dog-eating an exaggerated myth > I categorically state that [eating dogs] is not at all a widespread Swiss habit and that the 3 per cent (that would make 130,000 Kiwis) are totally made up. the "Kiwis" is confusing - it looks as if the author meant there were 130,000 New Zealanders, or 130,000 Kiwi birds, whereas Kiwis are the people he's addressing, and I'd be tempted to put a comma in. However, I can't recall seeing a number written in digits with a comma after it. Is it ok to use a comma after a number written in digits?
There is no reason why a comma should not be placed after a number in such a situation. > We bought a pound of butter, a dozen eggs (that's 12, Mark) and a pint of milk. makes sense assuming, perhaps facetiously, Mark may not understand what a dozen means. However this is not what is meant in the phrase > that would make 130,000 Kiwis The reference is to 3% of the population of Switzerland eating dogs. This applies to Switzerland (although it may not be true). What the writer means is that if this 3% applied to New Zealand then it would be 130,000 New Zealanders. 3% of the population of New Zealand is about 130,000. Switzerland has more people. So what the writer means is that if the same proportion of Kiwis ate dogs, as it is suggested Swiss do, then that would be 130,000 New Zealanders. If you look at the populations of New Zealand and Switzerland this corroborates the meaning. It could have been written much more clearly.
stackexchange-english
{ "answer_score": 5, "question_score": 0, "tags": "commas, numbers" }
Objective C : calculate and display time to millisecond **Full Disclosure** : I am a mathematical moron int hours = totalSeconds / (60 * 60); int minutes = (totalSeconds / 60) % 60; int seconds = totalSeconds % 60; //int milliseconds ??? calculatedExposureTime.text = [NSString stringWithFormat:@"%02d:%02d:%02d:%02d", hours, minutes, seconds, milliseconds]; Say `totalSeconds` was a fraction of a second (0.000156), how do I calculate and display time down to the millisecond?
... double seconds = fmod(totalSeconds, 60.0); ... [NSString stringWithFormat:@"%02d:%02d:%06.3f", hours, minutes, seconds]; BTW, 0.000156 is less than one millisecond, so it will display as `0.000`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "objective c, math" }
how to duplicate an .xaml+cs file? What is the best method to duplicate an **.xaml+cs** file? I want to make a copy of that file but I'm afraid that there would be too many errors and that's why I've decided to ask you.
Try it but I am Assuming That You want as it is copy with different Name and using Visual Studio. 1) right click on your xml file in Project Explorer 2)choose copy 3)right click 4)choose past. it will appear as copy of yourxml file. 5) rename it as desired... hope this is help full.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "c#, xaml" }
How can I unjam a garbage disposal that the allen wrench doesn't fix? I have a jammed garbage disposal that makes the humming noise and trips the breaker if I leave it on too long. However, the manual unsticking method doesn't seem to help. I've done some research and haven't found much beyond "use the allen wrench and try to unstick whatever is jamming the disposal," however I have done so and it seems to turn somewhat freely. Every so often I can get it to spin by itself for a second, but then it immediately resumes humming. I can't see anything trapped, and as I mentioned it seems to turn fairly freely when I use the wrench. What else can I try, short of replacing the unit?
Based on your description, I don't think the problem is a jam. More likely the windings in the motor are bad or there is a bad contact in the motor. Because of the design of most domestic garbage disposals, you can't open the motor housing to fix these problems. Therefore your only option is to replace it.
stackexchange-diy
{ "answer_score": 5, "question_score": 6, "tags": "garbage disposal" }
Xpath: Igonore nodes with certain innertext how can you ignore nodes which have a certain innertext but you don't know the innertext of the other nodes: <row> <column>test</columm> </row> <row> <column>???</columm> </row> this is what I tried but didn't work * row/column[not(.='test')] * row/column[.!='test'] * row/column[not(text()='test')] * row/column[text()!='test'] * row[column[text()!='test']]/column
This will get you the rows where the first `<column>` is not `test`. //row[column[1][. != 'test']] See < (hit "Test!") to run it
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "xpath" }
Hadoop WordCount example - Implementing Sorting I'm a Hadoop newbie. I have been able to successfully run the WordCount example. I would like to modify this example such that my output is sorted in ascending order of count. I'm unable to figure out where I would need to make the necessary changes. It would be great if someone would give me some direction to implement sorting?
See `org.apache.hadoop.examples.Sort` This is not super-straightforward to do using map/reduce. It involves taking a histogram of your data and using the `TotalOrderPartitioner`. Alternatively, you can use Hive or Pig, which has built-in functions for sorting.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "hadoop" }
htaccess: Rewrite with several variables I want to redirect a page like `/topic/italian-page2.html` to `/index.php?s=italien$p=2` or `/topic/france-page4.html` to `/index.php?s=france$p=4` but also (without page number) `/topic/spain.html` to `/index.php?s=spain$p=1` Right now I use RewriteRule ^topic/([a-zA-Z0-9\-]+).html$ /index.php?s=$1&p=1 [L] RewriteRule ^topic/([a-zA-Z0-9\-]+)-page([0-9]+).html$ /index.php?s=$1&p=$2 [L] The first one (without page) works fine. The second one doesn't. It redirects to `/index.php?s=italian-page2&p=$2` What did I do wrong? Where is my mistake? Thank you!
Found a solution: RewriteRule ^topic/([a-zA-Z0-9]*)-page([0-9]*).html$ /?s=$1&p=$2 [L] RewriteRule ^topic/([a-zA-Z0-9\-]+).html$ /?s=$1&p=1 [L] That works!
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": ".htaccess, redirect" }
R 4.2.0: write.table() "clipboard-1024" copies only columns name I used `write.table(mat, "clipboard-1024", sep="\t", row.names=FALSE)` to copy from R to Excel in previous versions. After updating to 4.2.0 it copies columns names only to clipboard. Win 10 64 bit. Any ideas on how to fix it? Try this: mat = matrix(0, 2, 3) write.table(mat, "clipboard-1024", sep="\t", row.names=FALSE)
From Tomas Kalibera (Bugzilla) Thanks for the report and the nicely minimized example. Fixed in R-devel and will be ported to R-patched. The bug is in new clipboard code and affects any code doing subsequent writes to already opened clipboard connection. This is another repro for the same issue: con <- file("clipboard") open(con, "w") cat("A", file=con) cat("B", file=con) close(con) readLines("clipboard") # should be AB but instead A<garbage> It only affects Windows because R supports writing to clipboard only on Windows.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "r, write.table" }
How to tell if curl times out on the client or server? I'm connecting to a resource using curl and php (using GET to fetch some data). From time to time the operation fails. The error I see is ' _Operation timed out after 20001 milliseconds with 0 bytes received_ '. I understand that the operation timed out, but how can I check if that happens on the client or the server side? I think it might be possible that my server times out before we reach the destination. Here's the data from curl [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 20.001804 [namelookup_time] => 0.000198 [connect_time] => 0.016918 [pretransfer_time] => 0.059324 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => 0 [starttransfer_time] => 0 [redirect_time] => 0
If the server decides to time out it sends a response with status 408. See < If you don't received this response status, then it is the client who is tired of waiting.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, curl" }
Is there a version of jQuery somewhere that I can hotlink to without hosting the file? Just wondering if there's a website out there that allows you to hotlink to the latest version of jquery. Does Google code allow you, or does jQuery.com itself? What I'm _not_ looking for is a site that just happens to have jQuery that I can pinch. I want a site that says that you can hotlink to their jQuery.
Yes, it's available on Google's CDN. Everything you need is here: < You can link directly to the javascript file: < or use the `google.load` method * * * **Update** Its also available on Microsoft's CDN or the jQuery CDN
stackexchange-stackoverflow
{ "answer_score": 33, "question_score": 15, "tags": "jquery, cdn, google code, hotlinking" }
Windows 7 Dual boot licensing > **Possible Duplicate:** > Can I use my Windows 7 license in a dual-boot configuration? I have a single copy of Windows 7 Pro OEM. I would like dual boot Windows 7 on a single PC, one for games and one for applications. Am I allowed to do this, will Windows pop up a message telling me one of my installs is not valid or something? I really don't want to get to the point where I have to phone up to validate my copy of windows, because that's just rubbish. Thanks in advance
First of all: great idea :) The configuration you want will work fine. You won't have a problem with the registration as long as both copies are on the same hardware. The registration is done online before you finish the installation, or after OS installation if you don't happen to have internet at the time. This is why you can reinstall an OEM windows on the same machine countless times. Your hardware specs are sent to Microsoft upon online activation. HOWEVER: I am not sure if Microsoft allows this type of OS usage, you might be violating the EULA, so it might be illegal.
stackexchange-superuser
{ "answer_score": 3, "question_score": 4, "tags": "windows 7, windows" }
How to moveactivity in background in android? I have an App in which I am implemented **onBackPressed** but when I press onBack it will finish the activity by calling finish(), its ok it will work fine ,but when I press device home button it will also finish activity,what I want **onBcakpressed** it will finish activity and when press device home button it will move that activity in back stack .How can I do that **code is:-** private long lastPressTime = 1; @Override public void onBackPressed() { long currentTime = System.currentTimeMillis(); if ((currentTime - lastPressTime) < 2000) { finish(); } else { Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show(); lastPressTime = currentTime; } }
Try this First take a boolean > boolean mBacktwice = false; **On BackPressed** @Override public void onBackPressed() { if (mBacktwice) { super.onBackPressed(); return; } this.mBacktwice = true; Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { mBacktwice=false; } }, 2000); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android" }
CSV File header part is coming parsing by LINQ the below way i am parsing csv file by LINQ but i found header part is coming when i inspect user class data. what is wrong there in code. var csvlines = File.ReadAllLines(filename); // IEnumerable<string> var csvLinesData = csvlines.Select(l => l.Split(',').Skip(1).ToArray()); // IEnumerable<string[]> int flag = 0; var users = csvLinesData.Select(data => new User { CSRName = data[6], CallStart = data[0], CallDuration = data[1], RingDuration = data[2], Direction = data[3], IsInternal = data[4], Continuation = data[5], ParkTime = data[7] }).ToList();
You seem to be doing the `Skip(1)` in the wrong place: var csvLinesData = csvlines.Skip(1).Select(l => l.Split(',').ToArray()); // IEnumerable<string[]> As it stands you're skipping the first _column_ for each row, not the first _row_.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, linq, csv" }
checking a file starts with a name in ftp location using java Before downloading a file needs check whether the file(file name starts) exist or not: I had a ftp location, it will generate a file in response to hitting a service(API). I need to check whether file exits or not in ftp location using a starting characters of file name because it will append some data at end of file name. Can any one help on this using java code with commons.net package
Use `FTPFileFilter` try { String filePattern = "prefix"; FTPClient objFTPClient = new FTPClient(); //objFTPClient - set username, password, host, etc... FTPFileFilter ftpFileFilter = new FTPFileFilter() { @Override public boolean accept(FTPFile ftpFile) { return ftpFile.getName().toLowerCase().startsWith(filePattern.toLowerCase()); } }; /* List of file that starts with your given prefix */ FTPFile[] ftpFiles = objFTPClient.listFiles(remoteDirectory, ftpFileFilter); }catch(Exception ex){ ex.printStackTrace(); }finally{ //close connection, etc.... }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, ftp, filenames, apache commons net" }
How to completely remove ruby? I have installed multiple versions of Ruby that causes some problems. How do I remove it completey(all versions)? I use Linux(Fedora)
Use `rvm implode` to get rid of RVM installed Rubies and `yum` for uninstalling distriubtion packages if there are any. From the RVM docs: > implode - removes all ruby installations it manages, everything in ~/.rvm
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 4, "tags": "ruby, linux, rvm" }
What word(s) am I? I'm a 7-letter word. As a phrasal verb, I mean: 'begin to operate'. And if you read me palindromically, (contains multi-words e.g like crosswords does) I mean: keep mices? (3-4). Let's see who'll crack this word.
You are: > **START UP** Backwards, you are: > **PUT RATS**
stackexchange-puzzling
{ "answer_score": 12, "question_score": 7, "tags": "riddle" }
Query to View only top counts and counted by group I wanted to use this query =query(G2:I80,"select G,H,I where H=max(H) group by I",-1) * * * From this: Cdd Cts T NWH 4 A1 LBB 3 A1 MP 3 A1 DC 2 A1 AK 10 A10 CC 3 A10 SC 2 A11 JL 1 A11 VT 1 A11 * * * To This: T Cdd Cts A1 NWH 4 A10 AK 10 A11 SC 2 * * * Am I doing it right? Or I have to come up with something to manually count them?
Try =ArrayFormula(iferror(vlookup(unique(I2:I), sort({I2:I, G2:H},3,), {1,2,3},0))) and see if that works for you ? How does it work: 1: with sort() a new 'virtual' table is created with col I as the first column. That new table is sorted on col H (latest dates appear on top). 2: a list with the unique values is retrieved from col I (with the unique function) 3: that list is 'looked up' (with vlookup). When a match is found it retrieves the first 3 columns ({1, 2, 3} or: col I, G and H). Vlookup only returns the first match found: since our list is sorted, that will be the entry with the latest date. 4: if nothing is found an error is suppressed with the iferror().
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "google sheets, function query" }
How do I prevent update on wrong data? I have a scenario, like I want insert a record into a table, then I update same record by getting the last inserted row Id, so now my issue is if a another user inserts a new record before the first record gets updated, so according to my scenario I get the last inserted row Id , in this case update applied on the last row instead of the first one, any solution please.
This is for **SQL Server** if you have an Identity column in the Table, after inserting use the `@@IDENTITY` variable or `SCOPE_IDENTITY()` function to get the Identity value of the Row inserted and then while updating use the Identity Filed in the Where Clause. Something like this INSERT INTO MyTable(FullName) VALUES('My Name') SELECT @IdVal = SCOPE_IDENTITY() UPDATE MyTable SET Phone='1234' WHERE IdCol = @IdVal
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, sql server" }
Is the /snap/core folder needed? Ubuntu 16.04 - has a `/snap/core` folder with subfolders of revisions. Do I need the `/snap` folder at all? Can I just remove it (and how)?
Snap is package management tool which was Canonical's new package management tool. And this snap package management used by Ubuntu Software Center--I know this because I never use the snap tool but I have 13+ snap folders. That is the reason `/snap` folder exist, I guess. And tool name is snapd. So when you want to install or uninstall package, you should use command like this: sudo apt autoremove snapd or sudo apt autoremove --purge snapd If you are installing software package with `apt` command or synaptic package manager, you don't need snapd package. So you can remove it. Ubuntu Software Center will use 'snapd'--that's what happen to me. But after removed snapd, Software Center won't use snapd, it seems.
stackexchange-askubuntu
{ "answer_score": 15, "question_score": 20, "tags": "snap" }
Asking User to Input First Name & Last Name in 2DArray import java.util.Scanner; public class TwoDimensionalArray { public static void TwoDimensionalArray_M(){ Scanner input = new Scanner(System.in); String[][] newString = new String[3][2]; for (int i = 0; i < newString.length; i++) { for (int j = 0; j < newString[i].length; j++) { System.out.println(i +" "+ j); if ( i == j || j>=i) { System.out.println("First Name:"); }else { System.out.println("Last Name:"); } newString[i][j] = input.nextLine(); } } System.out.println("All Value are inputed"); } }
From what I can gather, you want the first dimension of this 2D array to reference a specific person, and the second dimension of this 2D array to reference the particular name (first or last depending on index) of the particular person. import java.util.Scanner; public class TwoDimensionalArray { public static void TwoDimensionalArray_M(){ Scanner input = new Scanner(System.in); int numNames=3; String[][] newString = new String[numNames][2]; for (int i=0; i<newString[numLastNames].Length; i++) { System.out.println("Input first name for index " + i + ":"); newString[i][0] = input.nextLine(); System.out.println("Input last name for index " + i + ":"); newString[i][1] = input.nextLine(); } System.out.println("All values have been inputted."); } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "java, multidimensional array" }
Why does Unicorn need to be deployed together with Nginx? I would like to know the difference between Nginx and Unicorn. As far as I understand, Nginx is a web server while Unicorn is a Ruby HTTP server. Since both Nginx and Unicorn can handle HTTP requests, what is the need to use the combination of Nginx and Unicorn for RoR applications?
**Nginx** !enter image description here **Unicorn** !enter image description here Refer to unicorn on github for more information.
stackexchange-stackoverflow
{ "answer_score": 60, "question_score": 145, "tags": "ruby on rails, nginx, webserver, unicorn" }
getAttributeRawValue gives an id I'm trying to compare an attribute value with a custom value. We use the `getAttributeRawValue` to get the product's attribute. That give's me the ID of the value. (If that makes sense). Currently I use this line: $col = Mage::getResourceModel('catalog/product')->getAttributeRawValue($simp, 'manufacturer_color', 0);` Attribute with code `manufacturer_color` is of **type Select** which outputs `1587`, I want it to output the 'label' value which in my case should be `blue`.
Try it using `getAttributeText()` function and **this function will only work with the attribute type`select`** $col=$simp->getAttributeText('manufacturer_color'); `getAttributeRawValue()` **returns the id of options** OR $col=$simp->getResource()->getAttribute('manufacturer_color')->getFrontend()->getValue($simp);
stackexchange-magento
{ "answer_score": 2, "question_score": 0, "tags": "magento 1.9, product attribute, dropdown attribute" }
How to use double buffer in this case? Let's say i have three control A, B, C. They are all inherited from CDialog, A is a main dialog , A contains B, and B contains C. and each time i use mouse mouse drag C, B and C will move together. This is a image:< We know this will cause B and C to redraw themselves. and it might cause flicker. And my question is whether not there is a method to double buffer these two dialogs B and C? I know that in XP and vista, there is a attribute WS_EX_COMPOSITED that will help, but i don't want to use this. someone might suggest me to use memDC, but my problem is how can i merge the actions in B's ondraw and C's ondraw function into a buffer ? Hope someone know what i said. Thanks in advance!
what helpes flickering a lot is to overload the erasebackground method. This method fills the entire background with a solid color. The paint than paints all items on it. By removing the erasebackground, the paint will just paint over stuff which is already there, thus removing flickering.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "c++, visual c++, mfc, doublebuffered" }
Route [cource] not definedin Laravel 5.7 I have the following link in my Blade file to link `cource.blade.php` in the view folder. <a href="{{ route('cource') }}" class="list-group-item"> <i class="fa fa-credit-card"></i> <span>Cource</span> </a> **Route** Route::get('/cource', function () { return view('cource'); }); I get the following error message, how can I fix this problem? > Route [cource] not defined. (View: D:\exam\curd\resources\views\sidebar\sidebar.blade.php) (View: D:\exam\curd\resources\views\sidebar\sidebar.blade.php)
You must provide the route alias/name: Route::get('/cource', ['as' => 'cource', function () { return view('cource'); }]); or Route::get('/cource', function () { return view('cource'); })->name('cource');
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php, laravel 5, laravel 5.7" }
How to know when to kill threads? I'm designing a thread library. So far I have a method that initializes the library, one that creates threads, and one that yields the current thread to the next one on a queue of ready threads. Before I move on to implementing semaphores for the threads, I figured I should probably kill the threads as soon as they are done and free up their allocated memory, but I'm having trouble figuring out how to do that. How do I tell when a thread has "finished"?
You don't just kill threads safely or reliably -- let them exit naturally (when their entry returns). Although the system provides a means to kill the thread, nearly any C++ program out there could expect undefined behavior if it were to continue. You could dream up cases where killing _could_ be accomplished without side effects (to the rest of the program), but that program does not at all resemble idiomatic C++. Such a program would be very exotic, with many unusual and severe restrictions. When you want to known when a thread has exited or not, you can add some cleanup before it exits in order to track its status. When you want the ability to request a thread exit (naturally), consider run loops and messages.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "c++, multithreading" }
Can Windows Server intercept SNMP and write to the event log? We have a software package that can speak SNMP when things go awry. Currently, we're using Tivoli to monitor SNMP and send out alerts as needed. We've been informed that our Tivoli installation is going away, and that all operations notifications will need to be SCOM monitoring Event Log entries. Unfortunately, modifying the software package to write to the event log is a pretty healthy undertaking, and the end result would be the service calling a command-line utility to write to the event log. Not a pretty solution at all. So, my question is this. . . Is there anything inherent within Windows Server 2003 that can monitor SNMP traps and write the appropriate data to the event log? Alternatively, can SCOM be configured to listen for SNMP traps.
For the first question, nothing that I'm aware of in Windows will run on ServerA, and listen for all SNMP traps that it tries to send and inserts them into the event viewer. Doing some quick reading however, SCOM will listen for SNMP traps. I don't know if it's easy or the best way, but it's the tool you've got.
stackexchange-serverfault
{ "answer_score": 0, "question_score": 0, "tags": "windows server 2003, snmp, system center, scom" }
Как сложить ячейки нескольких таблиц, расположенных на разных листах гугл таблиц (apps script)? подскажите скрипт для применения математических операций (например, сумма или среднее значение) к ячейкам нескольких таблиц из разных листов, чтобы на выходе получалась одна таблица, с результатом суммы ячеек A1, B1, C1 и т. д. Например: Лист 1 - значения в диапазоне A1:C1 - 1, 2, 3 Лист 2 - значения в диапазоне A2:C2 - 4, 5, 6 Лист 3 - значения в диапазоне A4:C4 - 7, 8, 9 Результат (Сумма) - 12, 15, 18. Спасибо.
Поставленная задача обычно решается "в лоб": в первую ячейку результата записывают формулу (следуя Вашему примеру): ='Лист1'!A1+'Лист2'!A2+'Лист3'!A4 которую затем копируют в следующие справа две колонки. Относительные ссылки при копировании преобразуются так, что получается требуемый результат. Но есть и более "продвинутый" способ решения, основанный на ARRAYFORMULA. В первую ячейку результата пишем **одну** формулу: =ArrayFormula('Лист1'!A1:C1+'Лист2'!A2:C2+'Лист3'!A4:C4) и нужный результат сразу появляется в трех ячейках.
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, массивы, google apps script" }
Address/Zip Code as NSString to CLLocation Is there a way to convert a zip code a user enters into a textbox and convert it into a CLLocation? I am trying to compare distance between their current location and either an address or zip code and this would be easy if I can make a CLLocation out of the NSString.
the procedure called _geocoding_ , and that is how it looks if you implement it: NString *_address = // any address or postcode CLGeocoder *_geocoder = [[CLGeocoder alloc] init]; [_geocoder geocodeAddressString:_address completionHandler:^(NSArray *placemarks, NSError *error) { if (placemarks.count > 0) { CLPlacemark *_placemark = [placemarks firstObject]; CLLocation *_location = _placemark.location; // ... do whaterver you want to do with the location } }]; _NOTE: the_ `CoreLocation.framework` _has to be added to your project properly. you may need to handle errors in your final completion-block, I have not added such part to my code above._
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "ios, cllocationmanager, cllocation" }
Would a full back up (from recovery) preserve all data including installed apps? I wonder if I create a full back up from recovery, would it preserve all my data? Including installed apps (along with their configs) and my contacts?
If you are talking about a Nandroid backup: Yes, it would. It creates images from the devices file systems -- so all that's stored there gets copied to those image files. You can then even extract single items using e.g. Titanium Backup.
stackexchange-android
{ "answer_score": 5, "question_score": 3, "tags": "backup, clockworkmod recovery, recovery mode" }
static_cast complex<short> to complex<double> in c++ I would like to use static_cast to convert complex< short > to complex< double >. Convert complex<int16_t> to complex<double> I am trying to do the same thing as in this post, but I need to use static_cast. The reason I cannot use that solution is because I am using Eigen which uses static_cast in its cast() function. Is there a way to extend the functionality of static_cast to convert in this way? Or is there a way to extend Eigen's cast() function to handle this conversion? This is basically what I am attempting: Eigen::Array<std::complex<short>, Eigen::Dynamic, 1> short_array; Eigen::Array<std::complex<double>, Eigen::Dynamic, 1> double_array; double_array = short_array.cast< std::complex<double> >();
The simplest is to specialize `Eigen::internal::cast`: template<> inline std::complex<double> cast(const std::complex<short>& x) { return std::complex<double>(std::real(x),std::imag(x)); } Demo here.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++, c++11, casting, eigen, static cast" }
How to zip and pass-through files to browser on-the-fly? I would like to implement feature like GMail's "get all attachments as zipped file". Is there a way to select multiple files on server, zip them and on-the-fly pass-through to browser? (something similar to PHP's function `readfile` used for attachments streaming) **[EDIT]** It seems you misunderstood my intentions, all given examples require to create **and close** archive **before** its being sent, I want to stream while archive is created. Something like unix command (from zip manual): `zip -r - . | dd of=/dev/nrst0 obs=16k` **[EDIT2]** I have tons of ~2MB files (> 100) to serve, waiting for creation of tmp zip file forces to implement queuing mechanisms and takes storage space... If it can be done through stream/pipe directly to browser, why I should write tmp zip in filesyetm?
Have a look at ZipStream-PHP library - it claims to do what you need.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, stream, zip" }
Item Description on a Feature Class Not Appearing on a Published Feature Access Service via ArcGIS Server? I have a feature class in an SDE where metadata has been loaded via the 'Load XML Recordset Document' option of the feature class. When viewing the item description of the feature class, the metadata appears (which is what I want), such as: ![enter image description here]( After I publish the feature class as a Feature Access Service via ArcGIS Server, then view the item description of the feature class from the service. The metadata does not appear, such as: ![enter image description here]( Any thoughts to have item description on the feature class appear on the Feature Access service? I am using ArcMap 10.3.1, ArcGIS Server 10.3.1, and a SQL Server SDE.
Contacted ESRI, this issue is a bug. BUG-000091609:Metadata from a Feature Class Does not Carry over to Feature Service
stackexchange-gis
{ "answer_score": 0, "question_score": 1, "tags": "arcgis server, enterprise geodatabase, arcgis 10.3, metadata" }
Using SSD as disk cache Is there software for Linux to use an SSD as disk cache? I believe that Sun does something like this with ZFS, though not sure. A quick search provides nothing suitable. The goal would be to put frequently requested files on the SSD on-the-fly. Since the SSD has more capacity than RAM for less money and better performance than hard disk, this should provide an efficient performance boost.
Facebook recently released a module for the Linux kernel called 'FlashCache' which can do exactly this: <
stackexchange-serverfault
{ "answer_score": 6, "question_score": 9, "tags": "linux, performance, filesystems, ssd" }
codeigniter : Commands out of sync; you can't run this command now I applied all the possible answers but still same problem. also tried $this->db->reconnect(); there is no problem in my query ![enter image description here]( MyCode: public function GetdistributorsDetails($username){ $sql = "SELECT u.FirstName, u.Email, u.Telephone, u.MobileNumber, u.AlternateMobileNumber, ud.Address1, ud.Pincode,ud.City,s.Statename FROM users u JOIN userdetails ud ON ud.UserId = u.UserId JOIN states s ON s.StateId = ud.StateId WHERE u.Username = ? "; $result = $this->db->query($sql,array($username)); return $result->result_array(); }
add following code into /system/database/drivers/mysqli/mysqli_result.php function next_result() { if (is_object($this->conn_id)) { return mysqli_next_result($this->conn_id); } } then in model when you call Stored Procedure $query = $this->db->query("CALL test()"); $res = $query->result(); //add this two line $query->next_result(); $query->free_result(); //end of new code return $res;
stackexchange-stackoverflow
{ "answer_score": 23, "question_score": 5, "tags": "codeigniter" }
Is there any application by Microsoft targeting the end user market and running on the .NET framework? It's all in the title. Inspired by < Edit: I am primarily thinking about desktop apps, not web apps.
I think you'll hardly find mainstream apps from Microsoft written in .NET, since most of their popular applications were built before .NET was released, re-writing them for .NET provides no benefit for them. But if you look at recent applications you might find .NET based ones: * Business Contact Manager (mentioned by Martin) * SQL Management Studio * Windows Live Essentials * Power Shell (and Exchange + all other management shells based on PS) * MMC in Windows (Vista,7,2008) I know that some are not consumer based, but it shows that recent investments were made on .NET
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 12, "tags": ".net" }
Loop over query in MySQL _Drupal 7 DB select_ **Here I am getting a array:** * * * Array ( [71] => adad [85] => erer ) * * * **How can I loop the above array in this query below?** function get values($array){ $q = db_select('node', 'n'); $q->join('ab', 'f', 'n.nid = f.entity_id'); $rooms_data = $q->condition('n.type', 'book'); if($room_selected!=null) { $rooms_data = $q->condition('n.nid', $array); **//assumption//** } $rooms_data = $q->fields('n', array('nid', 'title')) ->fields('f', array('feesid')) ->orderBy('n.title', 'ASC') ->execute(); } Assuming something like: ->wherein($array as $a) { $q->condition('n.nid',$a['value']); }
You could use `"IN"` as `$operator` of `SelectQuery::condition`, and use an array of scalar values as `$value`. To do this, you could use `array_column()` to extract these values: function get_values($array, $room_selected) { $q = db_select('node', 'n'); $q->join('ab', 'f', 'n.nid = f.entity_id'); $q->condition('n.type', 'book'); if ($room_selected != null) { $values = array_column($array, 'value') ; $q->condition('n.nid', $values, 'IN') ; } $rooms_data = $q->fields('n', array('nid', 'title')) ->fields('f', array('feesid')) ->orderBy('n.title', 'ASC') ->execute(); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php, mysql" }
Possible in Python to "import virus" I've searched the Google and on stackoverflow for this, so if it exists anywhere, my sincerest apologies. I'm (obviously) a newbie to Python, and one of my main concern with finding a new module that does whatever new programming project comes my way is this: What's preventing a module (once imported) from doing nefarious things, such as logging all keystrokes while the script is executing, then emailing that out? Am I being paranoid? Is this not possible in Python? Is there a website where modules have been code reviewed, and people can download / install them without needing to worry? Do I have to read the code of every module / sub-module every time I download it to ensure this exact thing isn't happening? I'm currently using Python 3.5.1 64-bit on Windows 8, but I doubt that's too relevant.
Nothing prevents it. That's one of the benefits of open-source software (in the strictest sense of "source code that I can view"): you can, in theory, examine it to see exactly what it does before actually running it. In practice, you usually just extend some level of trust to the source: 1. Is the module in wide use, such that others would have discovered or mentioned a problem in the first place? 2. Did I get the module from a reputable source? 3. Does the checksum of my copy match the checksum provided by my source? If the answer to all three is yes, you can assume that the module isn't doing anything shady without explicitly verifying it yourself.
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": -3, "tags": "python, virus" }
jQuery UI Sortable items in one line should have the same height I use jQuery UI Sortable to sort teasers. The problem ist, that sometimes the teasers include different amounts of text. (Red is text.) So if there is more than one line of teasers this happens: ![]( But what I want is this: ![]( The teasers should have the same height as the highest teaser in the line. It's no option to give them all the same height. The maximum count of teasers per line is always 3. Is there an easier way than measuring the height of the highest teaser per line and adjust the height of the other teasers with jQuery after each sort?
Based on DevIshOnes answer this is my solution: var heights = []; var tallest = []; $('.teaser:not(.ui-sortable-placeholder)').each(function () { $(this).height('auto'); heights.push($(this).height()); }); while (heights.length != 0) { var line = heights.splice(0,3); line.sort(function(a,b){return b-a}); tallest.push(line[0]); } $('.teaser').each(function (i) { $(this).height(tallest[Math.floor(i/3)]); }); To get the tallest teaser in each line I generate the `tallest` array and later I use `tallest[Math.floor(i/3)]` to get the correct height value for each teaser.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "css, jquery ui, css float, height, jquery ui sortable" }
How can I grab an element's attr data in angular with jqlite? How can I grab an element's attr data in angular with jqlite? html, <button ng-click="loadForm($event)" href="form.php">Load Directive Form</button> <div data-my-form></div> angular, app.directive('myForm', function() { return { controller:function($scope){ $scope.isLoaded = false; $scope.loadForm = function(e){ console.log(e.target.attr('href')); // error var form = e.target.attr('href'); // error $scope.isLoaded = true; } }, template: '<div><div ng-if="isLoaded" ng-include="'+ form +'" ></div></div>', link:function(scope, element) { } } }); I get this error, TypeError: e.target.attr is not a function any ideas?
`attr()` is method available on jqLite elements. `e.target` is a reference to a DOM element. You need to wrap the DOM element as a jqLite element first: var form = angular.element(e.target).attr('href');
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 4, "tags": "angularjs, angular directive, jqlite" }
Stop executables and built-ins from interpreting a string argument starting with - as a switch? Let's say I want to search a file for a string that begins with a dash, say `"-something"`: grep "-something" filename.txt This throws an error, however, because `grep` and other executables, as well as built-ins, all want to treat this as a command-line switch that they don't recognize. Is there a way to prevent this from happening?
For `grep` use `-e` to mark regex patterns: grep -e "-something" filename.txt For general built-ins use `--`, in many utilities it marks "end of options" (but not in GNU grep).
stackexchange-unix
{ "answer_score": 5, "question_score": -1, "tags": "shell, command line, arguments, escape characters, options" }
Pandas groupby summarize binary variable to indicate existence of an element? I currently have the following dataframe A B C 0 x 1 1 1 x 0 1 2 x 0 1 3 y 0 1 4 y 0 0 5 z 1 0 6 z 0 0 And i want A B C 0 x 1 1 1 y 0 1 2 z 1 0 Basically summatize to show that in each grouped class if that variable exists or not?
How about sorting the data as per order of higher to lower indicator value and then picking the first value for each group, In case any group lacks 1s on any row then we can use a filter condition by checking sum on each row should be greater than equal to 1. import pandas as pd df = pd.DataFrame({'x': ['x', 'x', 'x', 'y', 'y', 'z', 'z'], 'A': [1,0,0,0,0,1,0], 'B': [1,1,1,1,0,0,0]}) newdf = df.sort_values(['x', 'A', 'B'],ascending=[True, False, False]).groupby(['x']).first().reset_index() newdf.loc[newdf.sum(axis=1) > 0,:] **Output** : # x A B # 0 x 1 1 # 1 y 0 1 # 2 z 1 0
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "pandas" }
Derivative of implicit function with exponential functions of each other We have the equation: $$ x^y = y^x +y $$ Which defines an implicit function $y(x)$ at the point $(2,1)$. I'm asked to find the derivative at $y'(2)$. I saw the answer in Wolfram: $$ y'(x) = \frac{y (y x^y-x y^x \ln{y})}{x (-y x^y \ln{x}+x y^x+y)} $$ Which gives $y'(2)=\frac{-1}{\ln{4}-3}$. I don't understand how to get there. When I try to dervie, after taking $\ln$ from both sides I get: $$ y'\ln{x} + \frac{y}{x} = \frac{y^x\ln{x} + 1}{y^x+y}y' $$ $$ y'[\frac{1 - y\ln{x}}{y^x+y}] = \frac{y}{x} $$ $$ y' = \frac{y^{x+1}+y^2}{x - xy\ln{x}} $$
By the property of derivatives, if we find the derivative of all individually, then we can add them all and do the implicit differentiation. $x^y=t$ $y\log{x}=\log t$ $t(\frac{dy}{dx}\log x+\frac yx)=\frac{dt}{dx}$ For $y^x=u$ $x\log y=\log u$ $u(\log y+\frac{x}{y}\frac{dy}{dx})=\frac{du}{dx}$ So $\frac{dt}{dx}=\frac{du}{dx}+\frac{dy}{dx}$ $x^y(\frac{dy}{dx}\log x+\frac yx)=y^x(\log y+\frac{x}{y}\frac{dy}{dx})+\frac{dy}{dx}$ Substituting the point $2(\frac{dy}{dx}\log2+\frac12)=\log1+2\frac{dy}{dx}+\frac{dy}{dx}$ $2\log2\frac{dy}{dx}+1=3\frac{dy}{dx}$ $\frac{dy}{dx}(3-\log4)=1$ $\frac{-1}{\log4-3}=\frac{dy}{dx}$. Which is the required result.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "derivatives, implicit function theorem" }
I chopped through 1/3 of the width of the cord leading to my angle grinder - it still works should I replace the cord? I had an angle grinder setup in a chopsaw stand. Something similar to this: It was the first time using the setup and I didn't notice that the cord came into the area of the grinder disc. I cut through ~1/3 of the strands of copper in the cord. The grinder still seems to be working. I put electrical tape around the cut area. Do I need to replace the cord? If I don't replace the cord what are the downsides, the grinder is fairly cheap.
Yes, replace the cord. Seen too many damaged cords covered in unravelling sticky tape that then become dangerous - wet environment, spilled liquid etc etc Adding a cable joiner just adds a "catching" or "trapping" hazard. 2 or 3 metres (6 or 9 feet for some) of quality cable is cheap and safer. Also the length of cable is likely to be cheaper than a fancy repair plug...
stackexchange-diy
{ "answer_score": 20, "question_score": 6, "tags": "electrical" }
What does non-zero integer mean? The definition for the **Rational Number** is given as **Numbers that can be expressed as a fraction of an integer and a non-zero integer.** at < What does non-zero integer mean?
An integer is any whole number or its negative, e.g. ..., -2, -1, 0, 1, 2, ... A non-zero integer is any of these but 0. Your definition of a rational number is just a mathematically rigorous way of saying that a rational number is any fraction of whole numbers, possibly with negatives, and you can't have 0 in the denominator.
stackexchange-math
{ "answer_score": 5, "question_score": 4, "tags": "terminology" }
Current between batteries facing wire with same pole I have just started learning about electric circuits, so I hope you'll be patient :) I am trying to solve for the current \$I\$ in the problem below, but (after much googling and reading) I cannot figure out how the current behaves between \$E_1\$ and \$E_3\$. I discovered that \$-12+15i+25i+17+30i+10i-20+4i+6i=0 \implies i=0.17A\$, which is correct, but I cannot explain why \$30i\$ and \$10i\$ are positive. Could anyone explain this to me, please. ![enter image description here](
This is a simple circuit because all of the components are in series. This means that there is only one current path. So now you have to find the total voltage accumulated within the circuit as well as the total resistance. I'm not going to give you the answer but I'll give you a starting point: the battery voltages add together. Starting with the lower-left corner of the circuit, you have battery voltage of: (+20V ) + (+12V) + (-17V). Note carefully the polarity of the batteries. Given that: what is the total battery voltage?
stackexchange-electronics
{ "answer_score": 0, "question_score": 1, "tags": "circuit analysis" }
Gremlin union method throws exception using otherV method I ran these codes: 1. `g.V().has("name", "Jones").union(g.of().bothE("knows").inV()).values()` 2. `g.V().has("name", "Jones").union(g.of().bothE("knows").otherV()).values()` The first one returns correctly, but brings Jones too. The second one throws an exception, that is shown bellow: `Path tracking is not supported by this Traverser: class com.tinkerpop.gremlin.process.traversers.SimpleTraverser` Could anyone help me with this issue? Thanks, Celso
Huh. The short term fix is to `withPath()` after the V(). (assuming TP 3.0.0.M6).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "gremlin, tinkerpop" }
How to use Visual Studio to deploy a trigger to multiple databases? I have a trigger written in C# that is currently active on a production database. In order to test something things out, I want the trigger to be active on a test database as well. How do I make sure the trigger gets deployed to both the production and test databases? As far as I can tell, the way the trigger gets deployed right now is: * In Visual Studio, when I look at the properties of my code solution/project, there's a place for a database connection string. This string specifies the production database. * When I go to Build -> Deploy Solution in Visual Studio, this deploys the trigger to the production database specified in the connection string. So I guess another way of looking at the question is: is there some way of specifying multiple databases in the connection string?
I'm assuming you're using VS2010 database projects. Rather than using Visual Studio to deploy you could use the VSDBCMD utility. You can specify a connection string as a command line argument and then you could run the utility twice with different connection strings. Another option would be to set up multiple project configurations in Visual Studio with a different connection string for each. The Visual Studio Database Guide written by the Visual Studio ALM Rangers may be a useful resource.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, sql server, visual studio, triggers" }
TypeError in JQuery. Doesn't substring url I have Url: '< I need, that function return 'EventDetail.aspx?ids=1'. I have next function: function getFullPageName(url) { var index = url.lastIndexOf("/") + 1; var filenameWithExtension = url.substr(index); return filenameWithExtension; } But, when I call like this: var fullName=getFullPageName(window.location); I see in firebug error: TypeError: url.lastIndexOf is not a function var index = url.lastIndexOf("/") + 1; So. How its' fixed?
You need to use window.location is an object, not a string so the method `lastIndexOf` is not present in the `window.location` object. You can use the `href` property of `window.location` instead. var fullName=getFullPageName(window.location.href);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jquery" }
Barcode scanner and jquery ajax call? I am stuck with the following: I have a simple form on index.phpwith one input field. On button click the form makes a jquery ajax request to lookup.php which returns some data. This data is shown on index.php. So far nothing special and it works when i use the keyboard. Now when i use the barcode scanner it doesn't work, with some trial and error it looks like the barcode scanner uses the "submit" handler. But in my case the ajax request is handled by `$("#btnSubmit").on("click",` and button btnSubmit is of the type=button and not submit. How can i fix this so the barcode scanner is also making the ajax request? jquery submit with $.ajax doesn't seem to work
If you have a simple form like: <div id="status"></div> <form action=""> <input id="foo"/> <input type="submit" value="Submit"> </form> You can do: $("form").submit(function(e) { e.preventDefault(); $.ajax({ url: "lookup.php", type: "POST", // Can change this to get if required data: { foo: $("#foo").val(); }, success: function(data) { $("#status").html(data); }, error: function(jqXHR, textStatus, errorThrown) { $("#status").text(textStatus); } }); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ajax, jquery, ajax request" }
How to draw a bitmap file on a canvas in html? How to draw a .bmp file using a canvas tag in html. i found ways to draw a png and jpeg but not bmp files. Can someone suggest me the approaches and also does every browser and platform support bmp files? Please help.
Drawing .bmp file is not limited by the canvas but infact by the browser. Here is a link to the browser image file support list. Besides that if you are new to canvas I am going to point you here to a bunch of fantastic resources on using canvas specifically the section of images about half way down the page. Out of curiosity why are you drawing and image to canvas instead of using an img tag?
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, html, html5 canvas" }
What is beam coupling coefficient for linear beam klystron? What does beam coupling coefficient exactly tell? For eg. a voltage gain coefficient tells how much times the input was amplified. So what does beam coupling coefficient tell, like does it tell how much the beam is coupled with something?
In a linear beam two-cavity klystron acting as a microwave amplifier, the electrons are velocity modulated by the applied input RF signal at the input of the buncher cavity. The beam coupling coefficient describes the degree to which the electrons undergo the process of velocity modulation. It is quite similar to the modulation index which determines the degree to which the carrier is modulated with respect to the message signal.
stackexchange-electronics
{ "answer_score": 1, "question_score": 0, "tags": "rf, microwave, radar" }
Prove using set identities Let $A$,$B$,$C$ be sets. Draw a Venn diagram and color the region $(A−C) \cap (C−B)$. Prove that $(A−C)\cap (C−B)=∅$. Already done the first part, but the proving part I am stuck at. I have no clue on how to do this. Please show/guide me !Lorem ipsum.
We have $$\begin{align} x\in (A-C)\cap(C-B)&\iff (x\in A-C)\text{ and }(x\in C-B) \\\ &\iff (x\in A \text{ and }x\notin C) \text{ and }(x\in C\text{ and }x\notin B)\\\ &\iff \color{red}{(x\in C\text{ and }x\notin C)}\text{ and }(x\in A\text{ and }x\notin B), \end{align}$$ which is a $\color{red}{\text{contradiction}}$. Hence $(A-C)\cap(C-B)=\varnothing $.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "discrete mathematics, elementary set theory" }
Reproduce `Temporary failure in name resolution` How can I reproduce manually the `Temporary failure in name resolution` error, when doing `ping google.com` in linux? Probably, I can add a broken DNS server by my own and specify it in `/etc/resolv.conf`? I need this for testing my project.
You can try this in `/etc/nsswitch.conf`: hosts: files That is remove all traces of the `dns` service for the `hosts` case (a normal line is something more like `hosts: files dns` but have a look at yours before changing it). Then, if a name/IP is in `/etc/hosts` the name resolution works, if it is not, it does not work as the DNS is not consulted.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "linux, dns, dnsmasq, networkmanager" }
PedWait block in Anylogic assistance i am new in using Anylogic , and i see in the PedWait block , Delay end on free function call , what does that mean and what is the difference between choosing it and the on delay time expiry ? Thank you
the free function call is used in case you want to use something different than a time delay to allow the pedestrian to continue to the next block. For example, a pedestrian can wait until a resource is available... since you don't know if the resource is going to be available in an exact amount of time, you can't use a time delay, so you use a free function call. And when the resource becomes available, you can free the pedestrian by doing pedWait.free(ped)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "anylogic" }
The best practice for passing formatted string to methods Though it might be trivial for someone, I find it a little inconvenient when someone formats the string while passing it as a parameter to a method. For e.g. AddMessage( string.Format("{0} (" + Constants.Message1 + ")", Path.GetFileNameWithoutExtension(document.FileName)), string.Format("{0}" + FileExtensionPdf, Path.GetFileNameWithoutExtension(document.FileName))); I have taken a simple example here, but it could become a little messy sometimes. I prefer to not do this and instead format my string before I pass them to the method. For me, this reduces readability. I would like to know if there is a standard practice which goes against the above style. Since I am doing a code review, I am not sure if I should put it as a comment.
I would probably format your example code something like this: var fileName = Path.GetFileNameWithoutExtension(document.FileName); AddMessage( foo: string.Format("{0} ({1})", fileName, Constants.Message1), bar: string.Format("{0}{1}", fileName, FileExtensionPdf)); I think it's fine to format your input directly in the call as long as you do it in a readable way. Here I also use named arguments since it's two string arguments and I want to communicate clearly and avoid the stupid mistake of swapping those arguments. Using a temporary varible for the file name with no extension is both an optimization of code and readability.
stackexchange-softwareengineering
{ "answer_score": 6, "question_score": 2, "tags": "c#, coding standards" }
syntax error near unexpected token while executing a python file I was trying to execute a python file which is not saved in the python directory but in a different one in linux (fedora) terminal. What I tried was: $ exec(vsh1.py) which resulted an error: bash: syntax error near unexpected token 'vsh1.py' Could anybody find a solution please... Thanks in advance
Locate your python's source file find / -name vsh1.py and once located run python /path_you_found/vsh1.py if you want your script to be seen from any location for the interpreter you have to add it to PYTHONPATH: PYTHONPATH=$PYTHONPATH:/path_you_found/vsh1.py if your script in the same directory you can just run python ./vsh1.py
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "linux, python 2.7, terminal, fedora" }
Create dynamic object and JSON encode it I have the following code: while ($row = $psql - > fetch()) { for ($i = 0; $i < $psql - > columnCount(); $i++) { $col = $psql - > getColumnMeta($i); array_push($json, array($col['name'] = > $row[$i])); } } echo "var data = ".json_encode($json).";"; Which is producing this output: var data = [{"id":"3"},{"id2":"1"},{"sec":"1"},{"cat":"1"},{"term":"Teste"},{"sTerm":""}]; But in order to import that data I need the output to look like this: var data = [{id:"3",id2:"1",sec:"1",cat:"1",term:"Teste",sTerm:""}]; (Each data inside `{...}` is a row. Is there any way I could do this besides building the string manually? Thank you
You should do away with all that non-sense about reading column metadata. What you are ultimately after is an array of objects. So you can simplify that down to this: while ($row_obj = $psql->fetch_object()) { $json[] = $row_obj; } echo "var data = ".json_encode($json).";"; Here, `$row_obj` would be an object with column name for properties which store the associated values.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "php, json, pdo" }
MS ACCESS Запрос SQL SELECT выборка данных из четырех таблиц Есть четыре таблицы: 1. Main (ID (KEY), A1_ID, A2_ID, A3_ID); 2. A1 (A1_ID (KEY), NameA1); 3. A2 (A2_ID (KEY), NameA2); 4. A3 (A3_ID (KEY), NameA3); В таблице Main поля A1_ID, A2_ID, A3_ID могут быть пустыми = `NULL`. Мне необходим запрос SELECT, чтобы получилась следующая таблица: `Main.ID, A1.NameA1, A2.NameA2, A3.NameA3`, где Main.ID например = 12 Я написал запрос: SELECT Main.ID, A1.NameA1, A2.NameA2, A3.NameA3 FROM Main INNER JOIN A1 ON Main.A1_ID = A1.A1_ID INNER JOIN A2 ON Main.A2_ID = A2.A2_ID INNER JOIN A3 ON Main.A3_ID = A3.A3_ID WHERE Main.ID = 12 Но выдает ошибку: > Ошибка синтаксиса (пропущен оператор) Main.A1_ID = A1.A1_ID INNER JOIN A2 ON Main.A2_ID = A2.A2_ID INNER JOIN A3 ON Main.A3_ID = A3.A3_ID WHERE Main.ID = 12 Заранее спасибо за помощь!
Если я не ошибаюсь, MS Access требует скобки при соединении таблиц. Таким образом, запрос должен выглядеть как: SELECT Main.ID, A1.NameA1, A2.NameA2, A3.NameA3 FROM ((Main LEFT JOIN A1 ON Main.A1_ID = A1.A1_ID) LEFT JOIN A2 ON Main.A2_ID = A2.A2_ID) LEFT JOIN A3 ON Main.A3_ID = A3.A3_ID WHERE Main.ID = 12
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, ms access" }
How to highlight ivy candidates in the manner of hl-line? Coming from `helm`, I am giving `swiper` and `ivy-mode` a shot. I'm looking for a way to highlight candidates in the way `hl-line-mode` does: full width background. ![hl-line](
You probably want: (setq ivy-format-function 'ivy-format-function-line)
stackexchange-emacs
{ "answer_score": 2, "question_score": 4, "tags": "swiper, ivy" }
Can compression algorithm "learn" on set of files and compress them better? Is there compression library that support "learning" on some set of files or using some files as base for compressing other files? This can be useful if we want to compress many similar files retaining fast access to each of them. Something like: # compression: compressor.learn_on_data(standard_data); compressor.compresss(data, data_compressed); # decompression: decompressor.learn_on_data(the_same_standard_data); decompressor.decompress(data_compressed, data); How is it called (I think that "delta compression" is a bit other thing)? Are there implementations of this in popular compression libraries? I expect it to work by, for example, pre-filling dictionaries with standard data.
Yes it works. Although there are many techniques for this, the easiest one you'll find is called "dictionary pre-filling". In short, you are providing a file, from which the latest part is "digested" (up to the maximum window size, which can be anywhere from 4K to 64MB depending on your algorithm), and can therefore be used to better compress the next file. In practice, this is similar to "solid mode", when within an archive all files of identical type are grouped together, so that the previous file can be used as a dictionary for the next one, which improves compression ratio. Downside : the same dictionary must be provided for both the compressor and decompressor.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "compression" }
What characters does a new empty NSString contain? i created an NSMutableString with the method stringWithCapacity:5 How do i test if characterAtIndex:0 is empty
Empty string contains no characters, even if you created it with non-zero capacity. To check if string is empty simply check its length: if ([myString length] == 0){ // empty } Moreover, trying to access a character at index which is >= of string's length will result in `NSRangeException` exception.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "objective c, nsstring" }
mvc - file upload in external class Im using scott hanselmans file upload code: public ActionResult UploadFiles() { var r = new List(); foreach (string file in Request.Files) { HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase; if (hpf.ContentLength == 0) continue; string savedFileName = Path.Combine( AppDomain.CurrentDomain.BaseDirectory, Path.GetFileName(hpf.FileName)); hpf.SaveAs(savedFileName); r.Add(new ViewDataUploadFilesResult() { Name = savedFileName, Length = hpf.ContentLength }); } return View("UploadedFiles",r); } I dont want this to exist in the controller. rather call it as a static method in a utils.cs class is this possible?
Yes, but you'll need to pass your request object in to the function, as an outside library won't have access to it. public void UploadFile(HttpRequestBase request) { ... }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, asp.net mvc" }
is there any utf-8 input method under windows? I need this kind of IME on ocassions. For example, i'll need to test some programs which claim they support utf-8.
UTF-8 is only one type of encoding for storing Unicode code points (characters). You can easily enter Unicode text in Windows using your keyboard or using any standard IME. To make sure you use Unicode, just use another language that does not use Latin characters and is not your native system language. When a program claim to support UTF-8 it usually means that it can read or write data in this specific Unicode encoding. To test this kind of a program you will need to write UTF-8 data with another program and give it to the tested program as input. Windows notepad can write UTF-8 files. With all of the above said, there are certain cases when you will want to input a specific Unicode character in Windows using the keyboard. For this task an Unicode code points Input Method Editor will be very helpful. You can find what you have asked for at this address: < There are few other ways to directly enter Unicode code points in Windows, see following link from the same site: <
stackexchange-superuser
{ "answer_score": 2, "question_score": 2, "tags": "windows, ime" }
Honey bubbles taste question What do honey bubbles taste like? I'm asking because I've got almost no sense of smell or taste myself. The answer is probably obvious though.
Assuming you're asking about what's pictured in this question, they're basically just bubbles made out of honey, so they'll taste like honey - sweet, and maybe with some fragrance depending on what kind of honey it is.
stackexchange-cooking
{ "answer_score": 2, "question_score": 1, "tags": "honey, tasting" }
Insider Fast Ring fails to install since 15048, is there a log Since 15048, I can't upgrade to the latest insider fast ring. No changes to hardware / software, but it's a rather limited system: 2GB ram, old HP system, running 32-bit OS. Not sure what type of CPU. Is there an upgrade log that I can read to determine the cause of the failure?
The log files are located under `C:\$Windows.~BT\Sources\panther`. > The following log files are created when an upgrade fails, and the installation rollback is initiated: > > C:\$Windows.~BT\Sources\Rollback\setupact.log C:\$Windows.~BT\Sources\Rollback\setupact.err MS lists here all errors and possible fixes. So open the `C:\Windows\panther\setuperr.log` to see what is failed and look in the list what the error means and how you can solve it.
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "windows insider" }
How to open asp:HyperLink.NavigationUrl in a new tab Is there a way to open an asp:HyperLink.NavigateUrl in a new tab and not change location of the current?
use `<asp:HyperLink Target="_blank" />` actually depending on the users settings that may open a new window. This works for a new tab in FF and Chrome, doesn't seem to work in IE (8), but this may depend on the doctype.
stackexchange-stackoverflow
{ "answer_score": 70, "question_score": 37, "tags": "asp.net, hyperlink" }
Regex match if src or href not starting with slash I try to match if **src** or **href** starts without slash e.g. `src="images/ajax.gif"` I tried this: src="^(?!/\*).* But it does not match
You need to remove `^`, anywhere else then **_start of pattern or first character in character class_** it doesn't have a special meaning, it will be treated as literal `^` only src="(?!\/).* ![enter image description here]( `Regex Demo`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "php, regex" }
UTF8mb4 MariaDB 10.4 - Max key length is 767 bytes error I am running MariaDB 10.4. I am trying to setup symmetricDS for database syncing. Some of the tables it creates have fields that are are VARCHAR(255). I know UTF8mb4 can only support up to VARCHAR(191) I know I can setup my database to be UTF8 and this problem goes away. But it is my understanding that is not ideal solution. I can't change the tables/fields that symmetricDS is creating. I have read some other posts about this, since there are many. But haven't seen anything above MariaDB 10.2 which I believe I read that things have changed with the engines past 10.2. So I just want to see if it is all still relevant. Is there any way this can be resolved, while staying with UTF8mb4? Or does it even matter and just go to UTF8?
I'd keep the utf8mb4 as the default. You can use innodb_large_prefix=1 to get past the index length limitation. Its also quite possible that symmetricDS doesn't actually need 255 length character field and its just a length for arbitrary default reasons.
stackexchange-dba
{ "answer_score": 1, "question_score": 0, "tags": "mariadb, mariadb 10.4, symmetric ds" }
How to use dynamic types conforming to protocols I'm just trying to get a grasp as to why this isn't possible. Why can I not use a dynamic type with this setup. (I put this in playgrounds): protocol SomeProtocol { init() } class SomeClass : SomeProtocol { required init() { } } let x: SomeProtocol.Type = SomeClass.self x() When this runs, playgrounds will crash, and if you try to put code like this in Xcode it will throw a > Command failed due to signal: Segmentation fault: 11 If I, however, never call `x()`, I can print out x to be of the correct SomeClass.Type. I realize this is a weird setup, so I understand the confusion of "why would you ever want to do that?". But that aside; is it possible? not possible? Is it a bug? Am I not understanding how protocols really work?
It works fine. I tried your code in Xcode 7 and it compiles and runs. Of course, in real code you can't say `x()` at top level. And in Swift 2 you have to say `x.init()`, not `x()`. But when you do, it's fine. protocol SomeProtocol { init() } class SomeClass : SomeProtocol { required init() { } } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let x: SomeProtocol.Type = SomeClass.self x.init() } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, swift" }
How to pass a specific collection to an Info Collection node? In the official documentation on `Node Parts` it mentions about white colored socket inputs of the `Collection Input Node` (its official documentation also doesn't mention much, only says "Collection to get the properties from"). > Collection (white) > Used to pass a collection data-block. But I can't find any collection data-block based Nodes which can connect to this. How to pass a specific collection to an _Info Collection_ node in Blender 3.0.1? @Chris: Thanks for bringing this to my attention. But I need it to be inside the node editor so I can do some conditional stuff as well. ![enter image description here](
you can connect it to the group input node ;) ![enter image description here](
stackexchange-blender
{ "answer_score": 3, "question_score": 3, "tags": "node editor, geometry nodes, collections" }
React / Typescript - React.createElement I have an object which contains a reference to a FunctionalComponent however when I pass that reference into the `createElement` statement it is throwing a TS error. **Question:** why is this complaining? my interface excepts both `Component` and `FunctionalComponent`. ![error-message]( **Example:** const someFunctionalComponent: React.FC = () => { return <div></div> } const anotherFunctionalComponent: React.FC = () => { return <div></div> } const somePages = [someFunctionalComponent, anotherFunctionalComponent]; interface TabPage { active: number; content: React.Component | React.FC; } somePages.forEach(page => React.createElement(page))
You are getting confused between the component _instance_ and the component _class_. The name of a `class` like `React.Component` represents a the type for an instance of that class. `React.createElement` is looking for a constructor rather than an instance. The type for the class constructor is `React.ComponentClass`. You could use `content: React.ComponentClass | React.FC`. But there is actually a built-in helper for this union which is `React.ComponentType<Props>`. interface TabPage { active: number; content: React.ComponentType; } Typescript Playground Link
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 1, "tags": "reactjs, typescript" }
Identical classes casting? Suppose I have two classes A and B. Both are identical (same atributes, methods, etc), but they are named different. There's some safe way, in Java, to cast a B object as an A object?
No, you cannot cast one to the other if they belong in different class hierarchies. They are **not identical** , even if they _happen_ to share the same attributes and methods. Additionally, if they belong to the same class hierarchy, _but_ one is not a superclass of the other, you can't cast across the same class hierarchy either. There's only upcasting and downcasting within a hierarchy. However, you can pass objects of either class to a certain method if * They implement the same interface, or extend the same superclass, and * That method accepts a parameter that is of the interface's or superclass's type (And that's the basic premise of polymorphism.)
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 7, "tags": "java, class, casting" }
Where can I find all of the crafting patterns? Is there a help menu hidden away somewhere in the game that I haven't found which lists the various shapes needed to craft various kinds of weapons, glyphs, and talismans? I know that there were handy diagrams in the books that were used as part of the crafting tutorials at the Sheriff's Office and in the Fortune Tellers House, but is there any way I can pull those up for reference now, long after having done those quests? I can't even go back to those locations and look at the books anymore.
You can check out theses images in the journal (finished quest). For full information about crafting, shapes and much more i recommend this resource: <
stackexchange-gaming
{ "answer_score": 3, "question_score": 2, "tags": "the secret world" }
Retornar la segunda propiedad de un objeto si se cumple una condicion Tengo un arreglo que tiene tres objetos dentro, y necesito recorrerlo y si el type de uno de los objetos es "wikipedia" devolver solo su url y guardarla en otro objeto como un string... de esta forma: let movie = { "url": " } ////codigo let webs = [ { type: "imdb", url: " } { type: "wikipedia", url: " }, { type: "rottentomatoes", url: " } ] lo que hice fue usar el metodo find pero me devuelve el objeto entero con el type y no solo la url
el find efectivamente te devuelve el objeto entero, pero podrías hacer lo siguiente: let movie = webs.find(movie=>movie.type==="wikipedia").url Eso sería suficiente para devolver el value del segundo key. Sinó podrías para que quede más legible quizás y dejarlo en objeto como necesitas hacer algo como: searchedMovie = webs.find(movie=>movie.type==="wikipedia") let movie = {movie: searchedMovie.url} o directamente: searchedMovie = webs.find(movie=>movie.type==="wikipedia").url let movie = {movie: searchedMovie} Espero te ayude, buena jornada!
stackexchange-es_stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, objeto, ecmascript 6" }
How to attach image email on laravel 5.3 using Mail Facade? I got image on mail template but when i send it does not carry the image. what should i do. **Template HTML** <img src="/img/blahblah.jpg"> //this image does not display on receiver of mail **App\Mail\Subscribe** public function build() { return $this->view('mail.subscribe'); }
> To embed an inline image, use the embed method on the $message variable within your email template. Laravel automatically makes the $message variable available to all of your email templates, so you don't need to worry about passing it in manually <img src="{{ $message->embed($pathToFile) }}"> <
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 7, "tags": "laravel" }
What are the bennefits of prepareThreshold = 5 in pgjdbc? The `prepareThreshold` in pgjdbc have the following definition: > Determine the number of PreparedStatement executions required before switching over to use server side prepared statements. The default is five, meaning start using server side prepared statements on the fifth execution of the same PreparedStatement object. More information on server side prepared statements is available in the section called “Server Prepared Statements”. I wonder what benefit this actually brings us? Most webservers aren't restarted for months, so all database queries will be sent more than 5 times eventually, so give it a week or so and all prepared statements will be stored at the server, won't them? Is this only for benefiting desktop applications? Or am I missing something, like a "5 threshold over a period of time"?
I understand that you want to know why the JDBC driver waits at all before using a server side prepared statement. Without being in on the decision process, I'd say that the reason is that preparing a statement implies a certain overhead (send a Prepare, a Bind and an Execute call). It makes sense to do that only once you can be confident that the statement is going to be reused. Don't forget that there are other uses for prepared statements that saving the Parse step on multiple executions: it is the king's way to avoiding SQL injection. That alone justifies a prepared statement, even if it is executed only once.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "postgresql, jdbc, prepared statement, pg jdbc" }
Django : Cannot Import name xrange I am new to python and django. I had django running properly in my machine, till I installed django-haystack. I directly downloaded django-haystack.zip from github and executed 'python setup.py install' in haystack dir. After this whenever I run 'django-admin.py runserver' I am getting the following error : ImportError: cannot import name xrange. If I remove 'haystack' from INSTALLED_APPS the above command is working fine. I also cannot run 'python manage.py build_solr_schema' because of the same error. Let me know how I can resolve this issue.
Solved the issue. Deleted the haystack installation from /usr/local/.../dist-packages/ and used `pip install django-haystack` to install. That worked fine
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 6, "tags": "django, django haystack" }
How to merge two pandas dataframe using an OR condition I have two dataframe and I'd like to join based on a couple of columns. However, my join logic has an 'OR' in it, e.g. I want to join based on columns ['A','B','C'] OR ['A','B','D']. I have the following code to join based on one set of columns but how I can add the second set of columns? pd.merge(df1,df2, how='inner',left_on = ['A','B','C'], right_on = ['A','B','C'])
Try this, since `left_on` and `right_on` are the same just use `on`: d_1 = pd.merge(df1,df2, how='inner', on = ['A','B','C']) d_2 = pd.merge(df1,df2, how='inner', on = ['A','B','D']) d_3 = pd.concat([d_1,d_2]).drop_duplicates()
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, pandas" }
Silex with 404 page I create controller in controllers/Redirect/Myredierct.php There i have such code <?php namespace MyApp\Controllers\Redirect; use Silex\Application; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; abstract class errorController { public function errorAction(Application $app) { $app->error( function(\Exception $e) use ($app) { if($e instanceof NotFoundHttpException && $e->getStatusCode() == 404) { return $this->app['twig']->render('error.html.twig'); } } );} } My question is where i must include it? I can't understand how i can use my code. Please, help me to solve this problem.
There are two questions in your post : the 404 status and how to use your abstract controller. First, there is an error in the naming of you file / class : your class should be named like the file. Moreover, I do not know if it is mandatory or just good practice, but your file should always end with "Controller", so what I would do is rename your file to "ErrorController.php", and your class to "ErrorController". Now, you have an abstract class, which means it is meant to be used by another controller through inheritance. The way to use this would be to create a new controller like this one : <?php namespace MyApp\Controllers; class YourControllerName extends errorController { // Whatever you want public function whateverAction(Application $app) { // You can use you parent controller this way $this->errorAction($app); ... return $response; } } Hope this helps.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, silex" }
Debug Version of Flash Player for Google TV I was wondering if it is possible to obtain a Debug version of the Flash Player Chrome plugin for Google TV? I would like to remotely debug Flash applications running on a Google TV device, but as I understand it this requires a debug version of the player, and also a mechanism for entering the host name for the remote host where the debugger (e.g. Flash Builder) is running. I did find an article regarding Chrome on the Adobe web site, but there's no mention of Google TV. Thanks
It's not available. Google TV is based on Android - Flash support for android has been deprecated. As of this writing Google TV is based on Android 3.2 and continues to support Flash - Flash support is not expected for future versions.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "google tv, flashplayer debug" }
Inbuilt search and relationship field Does the inbuilt search search through the relationship fields? I am using `simple_form`
No, the Search module will _not_ look in any related entries when determining if your search terms match a particular entry.
stackexchange-expressionengine
{ "answer_score": 1, "question_score": 1, "tags": "relationships, search" }
Where is the log of pppd in ubuntu 13.10? I am trying to find the debug infromation of pppd on Ubuntu 13.10. I have tried to read the mannual, but I found that the location of the log is for older version Ubuntu. what I have input sudo pon dsl-provider debug
You can see pppd logs in /var/log/syslog less /var/log/syslog or tail -f /var/log/syslog or cat /var/log/syslog
stackexchange-askubuntu
{ "answer_score": 5, "question_score": 0, "tags": "13.10, log, pppoe, debug" }
References and auto_ptr If I have a auto_ptr I can pass it for a reference?Like: auto_ptr<MyClass>Class(new MyClass); void SetOponent(MyClass& oponent); //So I pass SetOponent(Class) And what is odd copy behavior of auto_ptrs?
No you can't, you would have to dereference it: SetOponent( * Class ) As for the copying behaviour, I recommend you read a good book on C++, such as Effective C++ by Scott Meyers. The copying behaviour of auto_ptr is extremely un-intuitive and possibly beyond the scope of an SO answer. However, nothing ventured... When an auto_ptr is copied, ownership is transferred from the original to the copy. For example: auto_ptr <Foo> p1( new Foo ); at this point p1 owns the pointer to the Foo object. auto_ptr <Foo> p2( p1 ); After the copy, p2 owns the pointer and **p1 is changed** so that it now holds a NULL pointer. This is important, because copying occurs in lots of places in C++. You should never, for example, pass auto_ptrs by value to functions, or attempt to store them in standard library containers.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c++, reference, auto ptr" }
In TBB, is there a way to find out if there is an existing task scheduler? In Threading Building Blocks (TBB), if I initialize 2 task schedulers within the same scope, the argument of the second initialization will be ignored unless the argument of the first initialization is deferred. In order to avoid any conflicts, I would like to find out if a task scheduler has been initialized earlier in my program. Is there a way to do it? If so, what was the argument to that?
You may want to consider `tbb::this_task_arena::current_thread_index()` and `tbb::this_task_arena::max_concurrency()` functions. The `tbb::this_task_arena::current_thread_index()` function returns "`tbb::task_arena::not_initialized` if the thread has not yet initialized the task scheduler." (documentation link). If the task scheduler is already initialized you can obtain the requested number of threads with the `tbb::this_task_arena::max_concurrency()` function. However, you cannot get the stack size used during the previous task scheduler initialization.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "initialization, scheduled tasks, intel, tbb" }
Webview shows image as a dot in Android (tabactivity) I am using a `webview` to load an image from an URL, but when the webview loads, it shows the image as dot in top corner. After a zoom in/zoom out operation, I get the image at its original size. This is my code: web = (WebView) findViewById(R.id.wvcalendar); progressBar = (ProgressBar) findViewById(R.id.progressBar1); web.setInitialScale(1); web.getSettings().setJavaScriptEnabled(true); web.getSettings().setSupportZoom(true); web.getSettings().setBuiltInZoomControls(true); web.getSettings().setDomStorageEnabled(true); web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); web.getSettings().setUseWideViewPort(false); web.loadUrl("
try this: web.setInitialScale(30); web.getSettings().setJavaScriptEnabled(true); web.getSettings().setSupportZoom(true); web.getSettings().setBuiltInZoomControls(true); web.getSettings().setDomStorageEnabled(true); web.getSettings().setLoadWithOverviewMode(true); web.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); web.setScrollbarFadingEnabled(true); web.getSettings().setUseWideViewPort(true); web.loadUrl("
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "android, webview" }
Password policy regex I've seen quite a few regular expressions regarding password policies, but none of them seem to be working for me. First, here are my requirements: 1. Minimum 8 characters 2. Maximum 40 characters 3. At least one number I've tried a couple different expressions (see below), and they both work for all my requirements except for #2. It seems no matter what, I can never get a regex that actually validates the max length. Here are the two expressions I have tried: 1. `^.*(?=.{8,40})(?=.*\d).*$` 2. `(?=.{8,40})(?=.*[0-9]).*` Any assistance would be much appreciated!
You're on the right track. Many ways to do it.. ^(?=.{8,40}$).*\d.*$
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "regex, validation" }
How to get GPS enabled device angle I am planning to buy a GPS enabled android phone and develop an Augmented Reality application (which will point the locations in front of camera). All i found about GPS is that it just tells the location of the device, how do i get the direction where camera is pointing, and height of device? how to make compass (2D, 3D) with GPS enabled phone? Is responsibility of phone to tell the direction? **(please correct, if i asked this question at wrong place)**
GPS by itself cannot tell you the direction. Most phones will also include a digital compass which can give you information about heading (north, south, east, west) and an accelerometer which can tell you information about angle (i.e. whether the phone is at 45o or horizontal, etc). For Android in particular, you'll want to look at the SensorManager class, which has a list of all the sensors that the phone has attached. SensorManager.getRotationMatrix() packages all the data from the sensors into an easy-to-use rotation matrix for your application.
stackexchange-softwareengineering
{ "answer_score": 2, "question_score": 4, "tags": "android" }
openssl_public_encrypt method doesn't encrypt beyond 118 chracters **I can encrypt small strings but when it exceeds 118 characters it doesn't seems to work ? any idea ?** private function encryptData($plaintext) { $plaintext = '{ "id":"1" "name":"Bottled Beer" "description":"" "parent_id":"111" "taxonomy":"SIMPLE_PLU" },{ "id":"2" "name":"Stout" }'; $publicKey = "../ssh_keys/coasts/public/pub.pem"; $fp=fopen($publicKey,"r"); $pub_key_string=fread($fp,8192); fclose($fp); $pubKey = openssl_pkey_get_public($pub_key_string); openssl_public_encrypt($plaintext, $encrypted, $pubKey); return $encrypted; }
The length of plain data used to encrypt depends on the length of your key, it must be not bigger than the number the length of key subtract 11. For example, if your use a 2048bit key, the maximum length is 2048/8 - 11 = 245. If you need to process data more than that limit, you could separate you plain data into blocks, encrypt them each and concatenate the cipher blocks(their lengths always equals the length of your key in byte). of course, you have to do the same while decrypting the concatenated cipher data.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 0, "tags": "php, encryption" }
MVC 4 solution structure Partial View Well since most of the tutorials and demos chooses to put the partial view in shared folder im asking for a better way to do this. My problem: I want to use partial views in order to create a dynamic interface with reusable views. As i can with usercontrols. Since there might be a lot of partial views i want to put them in a seperate folder than the shared folder. example: How it looks today: [View] * [View.Home] * index.cshtml * [View.Shared] * _layout.cshtml A better way [View] * [View.Home] * index.cshtml * [View.Shared] * _layout.cshtml * [View.Shared.Partial] * partial1.cshtml * etc Or should i rethink my approach enirely? if so how? if not what should i think about?
Here is an example of something I do, * Application Wide used partial views - I put them in my Shared directory. * Partial Views for a specific Controller - I put them in the Views/[ControllerName] Directory.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "asp.net mvc, asp.net mvc 4, directory structure, renderpartial, asp.net mvc partialview" }
application locked to launcher without icon I tried to drag and drop transmission to my launcher in Ubuntu 12.04, and this is what I got: !enter image description here As you can see - there is an icon shaped space where an icon ought to be. Transmission is locked to the launcher - but I only know this from right-clicking on the space (which gives me the option to unlock it, as well as start the application minimised or with all downloads paused). Left-clicking on the space does not launch transmission. Why don't I have a launchable icon of Transmission in my launcher?
I think that you can open a terminal and use this command: unity --replace & to restart unity without reboot or logout from the session. You can also use the shortcut ALT+F2 with the dash and use the same command.
stackexchange-askubuntu
{ "answer_score": 2, "question_score": 3, "tags": "unity, 12.04, launcher, transmission" }
Find number of triangles with integral sides and side lengths ≤ 2n Find number of triangles with integral sides and side lengths less than or equal to $2n$. I approached this method by recursion. Say $A_{2n}\ $is the number of triangles with integral sides and side lengths less than or equal to $2n$. $A_{2n-1}\ $ is the number of triangles with integral sides and side lengths less than or equal to $2n-1$ . So $A_{2n}=A_{2n-1}+\left( \text{number of triangles having at least one side equal to} 2n \right) .$ How to count the number of triangles having at least one side equal to $2n$? Also, is there any other better method to this other than generalization as well?
Number of triangles having at least one side equal to $2n$ is the number of couple $(a,b)$ with $a\ge b$ and $a+b > 2n$. That is, $$\begin{aligned} \sum^{2n}_{b=1}\sum^{2n}_{a = \max(b,2n + 1-b)} 1 &= \sum^{2n}_{b=1} (2n+1 - \max(b,2n+1-b))\\\ &=\sum^{2n}_{b=n+1} ((2n+1) - b) + \sum^{n}_{b=1} (2n+1 - (2n+1-b))\\\ &=\sum^{1}_{c=n}c + \sum^{n}_{b=1} b\hspace{5em}(\text{where } c = 2n+1-b)\\\ &= n(n+1) \end{aligned}$$ In order to argue recursively, you would need to compute $A_{2n-1}$ in similar fashion as well.
stackexchange-math
{ "answer_score": 1, "question_score": 2, "tags": "geometry, combinations, recursion" }
javascript array - separate values and values of values by single quotes I have an array that looks like this: var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"] I want to return the results like this: 'Rock Paper','Shoot','Dulce','Once','Apple Mic','Chairs' This is what I have done so far: includes = tagsI.map(tag => `'${tag}'`).join(',') But this only separates by commas and single quotes the values.. not the values of the values as well. How can I do this? Thank you
Join the items of the array to a single string with commas. Split the string by the comma separators, map the items to the required format, and join again with commas. const array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"] const result = array .join(',') .split(',') .map(tag => `'${tag}'`) .join(','); console.log(result);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, arrays" }
Word for feeling of closure or peace of a relationship (usually a bad one) As written in the title, there's a specific word that is not _too_ common in English that's used to describe the feeling you can get when you finally resolve your long-term disdain for someone, or reaching some sort of civility between you and them. I can't remember it but I would know it if I saw it. Example: > > He attained [a feeling of] ____ after talking to his estranged father after many years. I'm not looking for synonyms of peace or closure, and nothing on Thesaurus.com has helped me. It is a very specific, unique word. It's like closure, peace of mind, or inner peace, but I've only seen it used in the context of sunsetting a toxic, detached relationship. **Edit:** The _actual_ meaning of the word I was looking for was peace of mind for _any_ period of negativity. It's not necessarily unique to interpersonal relationships.
Perhaps, **catharsis** — M-W > 2b : a purification or purgation that brings about spiritual renewal or release from tension _" She has learned to have her catharsis, take a deep breath and move on. … she does not dwell on the negative anymore."_ —Selena Roberts, New York Times, 24 June 2001 Wikipedia explains in detail: > Stages of social catharsis: > > 1. Directly after emotional effects, the emotions are shared. Through sharing, there is a reciprocal stimulation of emotions and emotional communion. > > 2. This leads to social effects like social integration and strengthening of beliefs. > > 3. Finally, individuals experience a renewed trust in life, strength, and self-confidence > >
stackexchange-english
{ "answer_score": 5, "question_score": 7, "tags": "single word requests" }
Oracle need a query like what INFORMATION_SCHEMA provides for MySQL I'm in need of a single query that produces output similar to what INFORMATION_SCHEMA provides for MySQL. For instance, in MySQL, I have: SELECT TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, IS_NULLABLE, COLUMN_TYPE, DATA_TYPE, CHARACTER_MAXIMUM_LENGTH, COLUMN_KEY FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='person' AND TABLE_SCHEMA='test'; For Oracle, I'm having a hard time getting a column specifying whether or not the COLUMN_NAME is the primary key for the table. I have: SELECT utc.COLUMN_ID, utc.TABLE_NAME, utc.COLUMN_NAME, utc.DATA_TYPE, utc.DATA_LENGTH, utc.NULLABLE FROM USER_TAB_COLUMNS utc WHERE TABLE_NAME = 'PERSON'; Does anyone have a way of doing this by amending the query through a LEFT JOIN or similar? Thanks!
For future reference... SELECT utc.COLUMN_ID, utc.TABLE_NAME, utc.COLUMN_NAME, utc.DATA_TYPE, utc.DATA_LENGTH, utc.NULLABLE, (SELECT cons.status FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = 'PERSON' AND cols.column_name = utc.COLUMN_NAME AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner) AS IS_PRIMARY_KEY FROM USER_TAB_COLUMNS utc WHERE TABLE_NAME = 'PERSON';
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "mysql, sql, oracle" }
Drop down menu appearing behind images I can't for the life of me figure out why the drop down when hovering over the "about" menu item is appearing behind the images, see this link < (I hope it's OK to post the link). All search results suggest z-index, well the z-index for the images in there goes to 6, and I've set the menu to 100 and it still appears behind the images. On the server side this is generated by PHP. Thanks for your help.
Add **position: relative;** in your **#nav ul ul** #nav ul ul { z-index: 100; display: none; position: relative; }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "php, html, css" }
Remove tag if tag attribute class contain only that class in jquery I am trying to remove tag by its class attribute but the attribute should only contains that class only and not any other class. My code $("#click").on("click", function() { $(".text").remove(); }); <script src=" <div class="default text">One</div> <div class="text">Two</div> <button id="click"> Press </button> So when I press the button it should show the first div tag and remove other containing only that class. Is there any way I can achieve that? Thanks
You can use something like this: $("#click").on("click",function(){ $('[class="text"]').remove(); }); **Snippet** $("#click").on("click",function(){ $('[class="text"]').remove(); }); <script src=" <div class="default text">One</div> <div class="text">Two</div> <button id="click"> Press </button>
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "javascript, jquery, html" }