INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Adding File version Excel VBA I want to add and change file version in cell `P76` every time there is a change in file. I tried this function but it is showing Excel version and it is not changing. Function ExcelVersion() ExcelVersion = Application.Version End Function and in cell `P76` (Sheet2) =ExcelVersion() I want it to show like `VERSION 001` and every time (sheet2) update of change it change to next eg `VERSION 001` to `VERSION 002` and so on and in cell `P77` (Sheet2) Dates and time of update. I also try to add this Private Sub submit_Click() Dim i As Integer i = 1 Cells(P76).value = "VERSION 00" & i + 1 End Sub but not working
Place this in "ThisWorkbook". It will add the version number without the "Version" string. I would recommend adding "Version" in an adjacent cell in order to keep it simple. Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Sheets("Sheet2").Range("P76").Value = Sheets("Sheet2").Range("P76").Value + 1 Sheets("Sheet2").Range("P77").Value = Now End Sub If you need "version" to be in the same cell as the number itself, comment and I will edit my response to reflect that functionality. Also, this will not prevent users from editing the version number, time etc. just so you are aware.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "excel, vba, version" }
When applying to a company again some years later, would it look bad still using the same covering letter? I'm planning to apply to a company almost 2 years after I previously applied to them. They declined the last time by reasoning that they don't see me as experienced enough. Now 2 years later (after working for 2 years in that field where they have their business), I'm going to reapply. I would like to use the same covering letter as I did 2 years ago, as it's just my experience and qualifications that have improved. But the reasons why I like what the company is producing, why I think I would be a good fit to them by my personal characteristics, and how I got to know about them (AFAIK this are the things written into a covering letter here in Germany), didn't change in the last 2 years, and I still perceive this as being the best fit. So should I rewrite it so just that it isn't the same wording? Or would it be okay to use the same covering letter again?
A cover letter is your sales pitch. Last time they did not buy, but now you have improved and you are a way better deal. Why would you want to hide this messages back in your CV. Why would you have them make a diff between the new and the old one to see that? _Tell them_. Tell them about your good experience last time with them in the interview, tell them how you got more experience and what you did at the other company that could benefit them. You _could_ send the same cover letter and it might not be seen as negative. But that's not what you want. You don't want the same result as last time. You want _positive_. So go and craft a cover letter that tells them how much you improved and how good an idea it would be to hire you _now_ even if they did not last time.
stackexchange-workplace
{ "answer_score": 8, "question_score": 2, "tags": "applications, germany" }
Bootstrap - when use rows I could do <div class="row"> <div class="col-md-12"><h1>Title</h1></div> </div> <div class="row"> <div class="col-md-6">content</div> <div class="col-md-6">content</div> </div> <div class="row"> <div class="col-md-12">content</div> </div> <div class="row"> <div class="col-md-12"><p>Some Text</p></div> </div> ... or <div class="row"> <h1>Title</h1> <div class="col-md-6">content</div> <div class="col-md-6">content</div> <div class="col-md-12">content</div> <p>Some Text</p> </div> It would both result in the same output. When do I need to use rows? It it just "ugly" or for any reason wrong and not recommended?
You just need the `row` div around the `col-6` columns. The other items (e.g the h1) will all go full width (if they are outside the `row` div), so no need for the `col-md-12` div. <h1>Title</h1> <div class="row"> <div class="col-md-6">content</div> <div class="col-md-6">content</div> </div> <div>content</div> <p>Some Text</p>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "twitter bootstrap, twitter bootstrap 3, bootstrap 4, twitter bootstrap 2" }
Saving data to file or database I'm starting to work on a new Java desktop app that should help me and my colleagues learn vocabulary. It will contain around 700 words, some texts (that point to the words contained in them) and maybe some images (not sure about that part yet). The data will **never** change and I want the program to be able to run offline. The question is: Should I use database, text file or serialize the data into file? Or perhaps if there is any other option I don't know about? If you could explain your choice in detail I would be glad.
If the data never changes and is only 700 words it would probably be easiest to use a file. If your data was a bit more complex and had many fields and was being constantly updated, a database would be more preferable but a csv file could still be used.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "java, persistent storage" }
How can I increase my Athletics DC? If I want to create an efficient grappler, I need to increase my Athletics DC, so Escape is harder. Unfortunately, I could only find items that improve checks, like Armbands of Athleticism. Can I buy something, or is increasing proficiency in Athletics my only option?
## Item bonuses work for increasing your skill DCs The rules for skill dcs are the following: (emphasis mine) > When someone or something tests your skill, they attempt a check against your skill DC, which is equal to 10 **plus your skill modifier** And a skill modifier is defined as follows: > Skill modifier = modifier of the skill’s key ability score + proficiency bonus + **other bonuses** \+ penalties Armbands of Athleticism provide an item bonus to AC, which falls under the "other bonuses" category and increases your skill modifier. And because that modifier is included in your Athletics DC, the armbands will increase that DC by 2.
stackexchange-rpg
{ "answer_score": 9, "question_score": 4, "tags": "magic items, skills, pathfinder 2e" }
Qt resize widgets in linear layout with mouse I have a linear layout which has 2 widgets, like this, ![enter image description here]( The black square is the linear layout, and the blue squares are 2 widgets, `Widget0` and `Widget1`. What I want to implement is while dragging the right edge of `Widget0` or the left edge of `Widget1`, both widgets can be resized with mouse. Does anyone have some simple ways to make it?
You are looking for QSplitter. See < Example, three resizable text edit (or widget): QTextEdit *editor1 = new QTextEdit; QTextEdit *editor2 = new QTextEdit; QTextEdit *editor3 = new QTextEdit; QSplitter* splitter = new QSplitter(Qt::Horizontal); splitter->addWidget(editor1); splitter->addWidget(editor2); splitter->addWidget(editor3); setCentralWidget(splitter); Results: ![enter image description here]( ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 1, "tags": "c++, qt" }
Batch insert/update using stored procedure Can anyone give me a sample script for batch insert/update of records in table using stored procedure in SQL Server?
I've done something like this in the past: CREATE PROCEDURE InsertProductIds(@ProductIds xml) AS INSERT INTO Product (ID) SELECT ParamValues.ID.value('.', 'VARCHAR(20)') FROM @ProductIds.nodes('/Products/id') as ParamValues(ID) END Obviously this is just a single-column table, but the XML approach applies for multi-column tables as well. You then do this: EXEC InsertProductIds @ProductIds='<Products><id>3</id><id>6</id></Products>'
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 5, "tags": "sql, sql server" }
JQuery live submit event not call? **The code:** $("#pitch_image_path_browseiser").live("change",function(){ $("#pitch_image_path_form").live("submit",function(e){ alert("sdfdsf"); this.submit(); }); }); Now change event is called but then not call the form submit event. The live submit event is not being called.
dear renishkhunt please try this code. this is help fully for me. $("#pitch_image_path_browseiser").live("change",function(){ $("#pitch_image_path_form").ajaxSubmit({ success: function(){ alert("sdfdsf"); } }); }); please check this link this is tutorial.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery" }
How to convert map keys from strings to atoms in Elixir What is the way to convert `%{"foo" => "bar"}` to `%{foo: "bar"}` in Elixir?
Use Comprehensions: iex(1)> string_key_map = %{"foo" => "bar", "hello" => "world"} %{"foo" => "bar", "hello" => "world"} iex(2)> for {key, val} <- string_key_map, into: %{}, do: {String.to_atom(key), val} %{foo: "bar", hello: "world"}
stackexchange-stackoverflow
{ "answer_score": 104, "question_score": 93, "tags": "elixir" }
PHP Get value from JSON Let's say I have this JSON: { "achievement": [ { "title": "Ready for Work", "description": "Sign up and get validated", "xp": 50, "difficulty": 1, "level_req": 1 }, { "title": "All Around Submitter", "description": "Get one piece of textual content approved in all five areas.", "xp": 500, "difficulty": 2, "level_req": 1 } } and I am trying this thru PHP: $string = file_get_contents("achievements.json"); $json_a=json_decode($string,true); $getit = $json_a->achievement['title'][1]; I'm trying to get the first "id" of the achievement.. which would be `READY FOR WORK`. How do I fix this?
When you set the second parameter of `json_decode` to `true`, it will return an array. $json_a=json_decode($string,true); returns an array. $getit = $json_a['achievement'][1]['title'];
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 3, "tags": "php, json" }
How to use ' and " when using HTML and Python together I am using Javascript, Python and HTML to make a web app. The problem I am facing is this: print("<p id='" + arr14.index(eachP) + "'>" + eachP + "</p>" + "<br />") I am trying to assign each paragraph a different id using normal HTML and Python syntax (btw it's a .py file) but I can't. I know it's the issue with my `'` and `"` but, I really can't figure it out. This is usually my only blunder as I couldn't figure it out how the quotes(`'` and `"`) work in HTML with variables from programming languages like Python or Javascript etc. Please guide me how this thing actually works as this is the second time I am stuck with this problem.
You could just switch the `'` and `"` to achieve your goal: print('<p id="' + arr14.index(eachP) + '">' + eachP + '</p>' + '<br />') However, a more readable way for you would be this: print('<p id="{}">{}</p><br />'.format(arr14.index(eachP), eachP)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, python" }
PHP Based for Search Engine Framework? I'm looking for PHP based search engine framework, that similiar to Compass < But it should free and open source. Any help is really appreciated. Thanks Ivan
No being funny but a simple google query and an hour of research will teach you much more than having the answer handed to you on a plate.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "php, frameworks, search engine" }
NetBeans EE includes Java EE? I'm fairly new to Java and I've been working on Java SE JDK 7 + Eclipse for Java. If I install NetBeans for Java EE, do I have to install Java EE 7 SDK?
According to this link, JEE7 is partially supported and it will be feature complete with Netbeans 8. Also, I have tried myself to setup Tomcat 8.0(partial support for JEE7) to work with Netbeans 7.3.1, it doesn't work out of the box.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "java, jakarta ee, sdk, java 7" }
add event listener + do not allow form submit I have got simple registration form with submit button: <input type="submit" value="" class="loginInput" id="submitReg" /> and javascript function to meassure time in miliseconds between page load and form submit: (function () { var element = document.getElementById('submitReg'), start, end; window.onload = function (event) { start = +event.timeStamp; }; element.onclick = function (event) { end = +event.timeStamp; var diff = end - start; // time difference in milliseconds //alert(diff); }; })(); How to do it, to allow form submitting only if `diff>3000`? I guess I should add something like `return true` / `return false`, but I do not know how. Thanks for answers!!!
In your case, to submit form on condition - adjust your `element.onclick` event as shown below: ... element.onclick = function (event) { end = +event.timeStamp; var diff = end - start; // time difference in milliseconds return (diff > 3000)? true : false; }; ...
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "javascript" }
Render HTML to QImage/QPicture using QWebFrame I am trying to render html data to qimage or qpicture using QWebPage/QWebFrame without QWebView: #include <QtWebKitWidgets> auto htmlData = R"( <!DOCTYPE html> <html> <body> <p>A quick brown fox jumps over the lazy dog.</p> </body> </html> )"; int main(int argc, char *argv[]) { QApplication a(argc, argv); QWebPage page; auto frame = page.mainFrame(); frame->setContent(htmlData, "text/html"); QImage img(500, 500, QImage::Format_ARGB32); QPainter p(&img); frame->render(&p); p.end(); img.save("html.png"); return 0; } The result image is blank. QWebFrame::print does produce correct PDF file though. What do I need to do to make the html render properly?
OK. I finally figure it out. I need to call `QWebPage::setViewportSize()`. I guess it's automatically set if the page is part of QWebView.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "qt, qt5, qtwebkit, qwebpage" }
If $f(x)\rightarrow 0$ as $x\rightarrow c$, what can we say about the convergence of $\sqrt{f(x)\,}$? There is a standard problem that I have been going through: Let $f(x)\rightarrow L$ as $x\rightarrow a$ for some $L>0$. Prove that $\sqrt{f(x)\,}\rightarrow \sqrt{L\,}$ as $x\rightarrow c$. I have done this and am more than happy with my answer, but I wondered about the strict inequality on $L$: can this be changed to a weak one? What I have so far is: Since $f(x)\rightarrow 0$ as $x\rightarrow c$ then there must exist $\delta>0$ such that for any $\epsilon>0$: $$|x-c|\,\leq\,\delta \quad\Longrightarrow\quad 0\,\leq\,|f(x)|\,\leq\,\ \epsilon^{2} \quad\Longrightarrow\quad \sqrt{|f(x)|\,} \,\leq\, \epsilon.$$ But I don't know how to remove the $|\cdot|$ from around $f(x)$ under the square root (notice I am not restricting $f$ to be a positive function). Any help/thoughts would be appreciated.
There's no guarantee that $\sqrt{f(x)}$ is even defined in a neighborhood of $c$. Consider for instance $f(x)=x\sin(\frac{1}{x})$ and $c=0$.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "real analysis, proof writing" }
How to show the first 5 character in text value and rest of them in ***** in visualforce page I have a requirement to show the first 5 character in text value and rest of them in *****. Example:- HelloSalesforce would be Hello**********
Here is an example of working with strings. string str = 'HelloSalesforce'; string subStr = str.subString(0,5); string encryptedString = str.subString(5, str.length()).replaceAll('[a-zA-Z]', '*'); string finalStr = subStr + encryptedString; This will give you the answer you are looking for. A regex is being used here to find the characters from position 5 onwards in your original string. Once found, it will replace those characters with an asterix value. Hope this helps. You can also look at the apex String Class.
stackexchange-salesforce
{ "answer_score": 1, "question_score": -1, "tags": "visualforce" }
How To Use @InjectMocks For A Dependency For Another Class To Be Mocked? Say I have a class : public class Boy { @Inject @Named("birthDay") BirthDay bday; } And I want to mock it, but the problem is the BirthDay class itself uses a dependency which I want to mock and control as well, I cannot use both @InjectMocks and @Mock on the same class, how do you go about achieving the same?
Why do you need to inject something in the mock? You need to have two test classes for testing `Boy` and `BirthDay` classes. Here you sould test logic of a `Boy` class public class BoyTest{ @Mock private BirthDay brithday; @InjectMock private Boy boy; } And logic of a `BirthDay` should have it's own Test class. public class BirthDayTest { @Mock private Dependency dependency ; @InjectMock private BirthDay brithday; } So, you should assume that your mock returns some data that you need. And check that your Unit under test works as expected with given data.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, spring, dependency injection, mockito, spring test" }
SELECT from database where 2 items in row aren't a specific value I've got a table which contains the following columns: ID, Condition 1, Condition 2. I'd like to select all rows where condition 1 AND condition 2 is not a specific word. let's say the word is "no". So, I want to select all rows where condition 1 and condition 2 are not "no" and all rows where there is a "no" but only in one of the conditions. Any help is appreciated.
to get rows where both conditions are NOT 'no' SELECT ID, Condition1, Condition2 FROM Conditions WHERE Condition1 != 'no' AND Condition2 != 'no'; to get rows where either one condition or the other (but not both) is NOT 'no' SELECT ID, Condition1, Condition2 FROM Conditions WHERE Condition1 != 'no' XOR Condition2 != 'no'; To do both sets at the same time: SELECT ID, Condition1, Condition2 FROM Conditions WHERE Condition1 != 'no' OR Condition2 != 'no'; ETA extension of query returns the row with id=1 IF that row does NOT have 'no' in Condition1 or 2: SELECT ID, Condition1, Condition2 FROM Conditions WHERE Conditions.ID=1 AND (Condition1 != 'no' AND Condition2 != 'no');
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "mysql" }
In finding a logarithmic fit for some data (of the form a*Log[b*x]), WolframAlpha succeeds where Mathematica 7.0 fails, why? I would like to fit a function of the form: $a \log(b x)$ to a set of data: data = {{10, 10/153}, {100, 100/1833}, {200, 200/3814}, {300, 300/5847}, {500, 500/10006}, {625, 625/12649}} The input string to WolframAlpha: [`"log fit {{10, N[10/153,16]},{100,N[100/1833,16]},{200,N[200/3814,16]},{300,N[300/5847,16]},{500,N[500/10006,16]},{625,N[625/12649,16]}}"`]( produces a nice logarithmic fit of this data. However, using `FindFit` with my copy of _Mathematica_ 7.0 produces nonsensical values for $(a,b)$ and/or complex functions. How did WolframAlpha produce this fit, and how might I find this fit using my copy of _Mathematica_?
I'm using 8.0.4 and I get reasonable results (notice the constraint `c>0`) : nlm = NonlinearModelFit[data, {a + b Log[c x], c > 0}, {a, b, c}, x] ; nlm // Normal (* 0.0740508 - 0.00391526 Log[1.0714 x] *) FindFit[data, {a + b Log[c x], c > 0}, {a, b, c}, x] (* {a -> 0.0740508, b -> -0.00391526, c -> 1.0714} *) Show[Plot[nlm[x], {x, 10, 625}, PlotRange -> All], ListPlot[data, PlotStyle -> Directive[Red, PointSize[0.02]]]] !plot The fit without an additive constant looks much worse : nlm2 = NonlinearModelFit[data, {b Log[c x], c > 0}, {b, c}, x] ; nlm2 // Normal (* 0.0094653 Log[1.07146 x] *) FindFit[data, {b Log[c x], c > 0}, {b, c}, x] (* {b -> 0.0094653, c -> 1.07146} *) Show[Plot[nlm2[x], {x, 10, 625}, PlotRange -> All], ListPlot[data, PlotStyle -> Directive[Red, PointSize[0.02]]]] !plot2
stackexchange-mathematica
{ "answer_score": 9, "question_score": 6, "tags": "fitting, wolfram alpha queries" }
How do I fill an allocated 2D array with data from a file? I have the following piece of code in C: #define LINES 40 int i,j,k = 0; char **c; char tmp; // allocate key array memory if( (c = malloc(LINES*sizeof(char*))) == NULL) printf("Error allocating memory\n"); for(i=0;i<LINES;i++){ c[i] = malloc(10*sizeof(char)); } I also have a file with data like this: AsfAGHM5om ~sHd0jDv6X uI^EYm8s=| .... How can I fill the array allocated above with data from that file (for example using `fgets` or `fgetc`)?
If you've got constant length of the strings, like in your example, then you could define a macro with the `BUFSIZ` as the max length of the word. **Beware: don't forget to count also the** `'\0'` **character at the end of each string.** In that case, the solution would look like this: // create an array of strings char ** array = (char **)calloc(LINES, sizeof(char *)); for (size_t i = 0; i < LINES; i++) { // allocate space for each string array[i] = (char *)calloc(1, BUFSIZ); // get the input fgets(array[i], BUFSIZ, stdin); // remove the '\n' character // from the end of the string array[i][strlen(array[i]) - 1] = '\0'; }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c, multidimensional array" }
Why is end parenthesis not closing my %nrstr function? My goal is to pass percent symbols into a string. There is no result to the %put when I run: %let foo = %nrstr(bar%x%); %put foo is &foo; If run again, I get errors, the first one is > WARNING: The quoted string currently being processed has become more than 262 bytes long. You might have unbalanced quotation marks." In Enterprise Guide, the parenthesis matcher doesn't detect the close parenthesis. Adding another close parenthesis: %let foo = %nrstr(bar%x%)); results: > foo is bar%x) %nrstr will pass unbalanced parenthesis into the result, so this isn't surprising. This would seem to imply that the snippet with just the open and close parenthesis are balanced.
The percent symbol before the close parenthesis was causing the unexpected behavior. Per SAS(R) 9.2 Macro Language: Reference: > percent sign before a parenthesis - for example, %( or %) two percent signs (%%): EXAMPLE: %let x=%str(20%%); making the correct code: %let foo = %nrstr(bar%x%%); %put foo is &foo; resulting in: > foo is bar%x%
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "sas, sas macro" }
regex back-reference not working in PHP PCRE I want to match matching tags like `<tag>...</tag>`. I tried the regex ~<([^>]+)>.*?</\1>~ but this fails. The expression worked when I used the exact text inside the angle brackets, i.e, ~<(tag)>.*?</tag>~ works, but even ~<(tag)>.*?</\1>~ fails. I'm assuming that the back reference is not working here. Can someone help me out please. Thanks PS: I'm not using this to parse HTML. I know I shouldn't.
You didn't show your PHP code, but I surmise you have your regex in double quotes. If so then the backreference `\1` actually is converted into an ASCII character `` before it reaches PCRE. (All `\123` sequences are interpreted as C-string octal escapes there.)
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 2, "tags": "php, regex, pcre" }
Class constructor issue C# I Have a class with this constructor , apperantly it doesn't seem to work. And before it was but I just forgot the syntax , could you remind me how to do it , please? public class Excerscise { Excerscise(int t, double w, DateTime d) : tries(t), weight(w), date(d) {} int tries; double weight; DateTime date; }
Something like that: public class Excerscise { int tries; double weight; DateTime date; // it seems, that the constructor should be public public Excerscise(int t, double w, DateTime d) { tries = t; weight = w; date = d; } }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -4, "tags": "c#, class, syntax" }
File location, not the same as folder path. Video file do not play. Using Windows 10 * Edition Windows 10 Pro * Version 21H2 * Installed on ‎6/‎15/‎2022 * OS build 19044.2006 * Experience Windows Feature Experience Pack 120.2212.4180.0 * Secondary hard drive "D:" the one with the issue. **Issue:** Due to the video file location being incorrect, video files are not playing. **Example:** When looking at the properties of bad files. Location: `\\?\D:\Other Games\123.mp4` ← The extra slash are causing issues. Folder path: `D:\Other Games\ 123.mp4` **Request:** Is there any way to modify the location to be the same as the folder path? I have over 250 GB of these files. Below are the images of the same file: !Properties image of Location !Properties image of Folder Path !More Info
In the text of your question, you only show a single backslash; the screenshot shows a **double** backslash, as in Microsoft's implementation of the UNC path convention, "A server or host name, which is prefaced by \\\\." For some reason Windows considers the D: drive to be on a remote server. Where are these files actually located? On a drive in the PC? On a remote server or NAS? If on a remote device, try making a shortcut to the device, e.g. \MY_NAS, or \MY_NAS"Other Games". Another possibility is that the space in the folder _Other Games_ is causing issues on the server. Try changing the folder to _OtherGames_ to avoid need for quotes. _Footnote:_ Questioner has determined it _is_ a folder name issue, due to _length_ of total file path; and the hint to remove space helped resolve issue by showing some files were visible in shortened path. Kudos to questioner for letting others know.
stackexchange-superuser
{ "answer_score": 0, "question_score": 1, "tags": "windows 10, files folders" }
Adding Alt Text Automatically to all images without JS How can i set the alt atribute = the filename of an image tag in asp.net automatically without using javascript? <img src="/a/b/c/xxx.jpg" /> to <img src="/a/b/c/xxx.jpg" alt="xxx.jpg" /> I tought maybe something like a rewrite module on IIS? Or maybe somehow change the base Image class to emit different html? Any ideias? Thanks
If you're willing to add the `runat="server"` attribute to your img tags, then in your code behind you can loop through the list of controls on your page and for all the `img` tags, update the `alt` attribute. I wrote this without testing so there may be some minor tweaks required. private void UpdateImgTags<T>(ControlCollection controlCollection) where T : Control { foreach (Control control in controlCollection) { if (control is T) { string filename = (T)control.Attributes["src"]; filename = IO.Path.GetFileName(filename); (T)control.Attributes.Add("alt",filename); } } } To call the method: UpdateImgTags<HtmlImage>(Page.Controls)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "asp.net, iis 7" }
Mysterious error with jQuery validate and IE7 I have this little code: alert(1); $('input[name^="Quantity_"]').each(function () { alert(2); $(this).rules("add", { required: true, digits: true }); alert(3); }); alert(4); In Chrome or Firefox, I see the alert 1, 2, 3 and 4, but with IE7, I see only the alert 1 & 2\. Why the script failed on rules()? **IE7 doesn't report an error in the page** **EDIT 1:** The javascript failed on the line **$.data(element.form, 'validator').settings;** in jquery.validation.js script. `Element.form` is not null, but `$.data(element.form, 'validator')` is undefined. Thank you
Be sure you call `$("#YourForm").validate()` before using the `rules` method, as per the documentation: < In your case, I'd use that call before `alert(1)` or wherever you want to initialize your code. Replace `#YourForm` with whatever selector you want.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jquery, jquery validate" }
How to remove control characters in ruby I used Open3 to get result of a command like this: Open3.popen3(service_command) do |stdin, stdout, stderr| result = stdout.read.delete(' ').split("\n") end In the string returned in `stdout.read` I found there are control characters like `\e[2K`, how can I remove those and get "clean" strings? Thanks
Seems like these are CSI sequences (< You could remove them like this: REGEXP = /\e\[[^\x40-\x7E]*[\x40-\x7E]/ input = ["\e[mstring1", "\e[2Kstring2", "string3", "\e[2Kstrin4"] def remove_csi(line) line.gsub(REGEXP, "") end output = input.map do |line| remove_csi(line) end p input p output # => ["\e[mstring1", "\e[2Kstring2", "string3", "\e[2Kstrin4"] # => ["string1", "string2", "string3", "strin4"] The regexp is a simplified version that matches from the start of the string up to the "final byte" in the sequence.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "ruby, linux" }
How to set a pointer to zero'th location? As per my knowledge, all occurrences of NULL in code are replaced by a 0 during the preprocessing stage. Then during compilation, all occurrences of 0 in pointer context are replaced by an appropriate value which represents NULL on that machine. Thus the compiler has to know that NULL value for that particular machine. Now, this means that whenever I use 0 in pointer context, it is replaced by the appropriate value representing NULL on that machine, which may or may not be 0. So, how can I tell the compiler that I actually mean 0 and not NULL, when I use 0 in pointer context? Sorry for the long description. Correct me if I am wrong
One way is to store all-bits-zero into your pointer: void* zero; memset(&zero, 0, sizeof(zero));
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 3, "tags": "c" }
Possible to over-knead dough? It will be my first attempt to bake with yeast this weekend and I'm interested to know how you know when you have kneaded dough enough. Is it possible to over-knead dough? If it makes a difference I'll be making croissants. Thank you :)
Cookbooks describe the state as "smooth and elastic" I think this is a reasonable description. When the dough is first mixed it is very wet and sticky. As it is mixed you can see a lot of clumps and heterogeneous textures. As the proteins in the flour mix with water they form gluten and the kneading folds the elastic gluten over itself again and again making sheets. The dough becomes less sticky and wet and more springy. The texture becomes completely homogeneous. Kneading by hand it is impossible to over knead this type of dough. I have read that it is possible to over knead in a machine. In this case, supposedly, the protein sheets eventually rip up enough that you lost what you created and the dough reverts. I have kneaded in a machine for a long time and never personally seen this effect.
stackexchange-cooking
{ "answer_score": 12, "question_score": 7, "tags": "baking, dough, kneading" }
Enforce subclass to declare a enum Can I enforce child classes to create a enum in them? class Document<T extends Enum<T>>{ Map<T, String> fields; } class TextDocument extends Document<TextDocument.Field>{ public enum Field{ ... } } How can I enforce any implementation of Document to have an enum named Field within it? In the above example, TextDocument can extend Document with some other enum (say GraphDocument.Field) as well which shouldn't be allowed. How can I create this restriction? I need to enforce this rule to subclasses - "You must have your own enum". Is this even possible? By some hacky way? Any ideas?
In short, you can't. However, you can force it to return an array of the values of a particular enumeration. You can also force the enumeration to implement an interface. public interface SomeInterface { // any methods you want to be able to perform on the enums } public abstract class SomeSuperClass<T extends SomeInterface> { abstract T[] getSome(); } public class SomeSubclass extends SomeSuperClass<SomeInterface> { public enum SomeEnum implements SomeInterface { testEnum { // interface implementation } } public SomeInterface[] getSome() { return SomeEnum.values(); } } This is a pretty awkward solution, but it works.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "java, generics, enums, subclass" }
How to replace numbers inside of a string using Regular Expression I am quite new in regular expression so I am having confusion in replacing numbers inside an string. a="12ab34cde56" I want to replace it by `12abXXcde56` b="abc1235ef" I want to replace it by `abcXXXXef` c="1ab12cd" I want to replace it by `1abXXcd` I am trying those in python and in php, but with no luck. This is what I had in my mind: ^([0-9]+)([a-z]+)(.*)([a-z]+)([0-9]+)$
You can use this regex to capture all digits that is not leading or trailing: (?<!^|\d)\d+(?!$|\d) Then in Python, you can supply a function that replace the match with corresponding number of `X`. For PHP, you can enable PREG_OFFSET_CAPTURE to know the position of the match, and loop through the list of matches and process them. Note that with the regex above `" 5 ddds"` will be changed into `" X ddds"`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "php, python, regex, string" }
How to find what **options parameters are? I am using tkinter. When I want to learn more about the methods I go into their library. > i.e. from tkinter import filedialog One of the methods I am looking at is this: def askdirectory (**options): "Ask for a directory, and return the file name" return Directory(**options).show() I know the the `**options` parameter means it accepts an arbitrary number of arguments and/or keyword arguments. I don't understand how to find the parameters for `options` for that method. I tried looking in deeper into the method classes but I get lost to where to look. I want to be able to find what the parameters can be by reading the library code so I can apply that to reading and understanding other python libraries quicker.
You aren't going to have a lot of luck getting the options from the code itself. Tkinter is a wrapper around a tcl/tk interpreter, and a lot of the options are simply passed through tkinter to the underlying tcl interpreter. The definitive source of documentation for the available options can be found in the tcl/tk man pages: <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, python 3.x, tkinter, pycharm" }
hover over li to change color in twitter bootstrap I am trying to make the inner text turn green when I hover over. However it is not doing so and I am not sure why. I am using Twitter bootstrap !enter image description here Here is my code: CSS: #nav_pills li:hover { color: green; } HTML: <nav class="navbar navbar-default"> <ul id="nav_pills" class="nav nav-pills" role="tablist"> <li role="presentation"><a href="#about">About</a></li> <li role="presentation"><a href="#services">Services</a></li> <li role="presentation"><a href="#portfolio">Portfolio</a></li> <li role="presentation"><a href="#contact">Contact</a></li> </ul> </nav>
Add the `a`selector to your CSS #nav_pills li:hover a{ color: green; }
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 1, "tags": "html, css, twitter bootstrap" }
Mosfet Regulator heating issue Guys i trying to step down voltage using mosfet. Application: * Input battery supply 40 to 50 volt * Output voltage is 12 volt not more than 500 ma. ![enter image description here]( _Mosfet heating issue due to..._ Since the mosfet is dropping voltage **37 volt** (50v-13v), if output load consume **500ma**. Then power dissipation will be 37*0.5= **18.5 watts**. For this reason my mosfet getting too hot. Can anyone suggest how to reduce the heat or what is the option for stepping down 50v to 12v without using buck converter.
Heat is not the problem. According to other things I've been told on this site, MOSFETs suffer a thermal runaway problem (hot spots on the silicon) when they are used as voltage controlled resistors. Is it okay to use a MOSFET in its resistive region with a heat sink? If you use a linear regulator which is made for the purpose, you will avoid the hotspot problem, but will still need a heat sink. However, in my cursory search, I couldn't find anything that could handle 50 V in and which would provide 500 mA output. The LM317 or LM217 might be able to handle it. If you have your heart set on making a transistor controlled circuit using feedback, you can use a BJT (Darlington?) instead of MOSFET, however I am hesitant to give more specific advice since I'm a little out of the electronics game these days. You will need a heat sink for sure.
stackexchange-electronics
{ "answer_score": 2, "question_score": 0, "tags": "mosfet, voltage regulator, linear regulator, step down, regulations" }
Using R dplyr to summarize data I have this df where there are 3 colums: year, treatment/control group, and double variable. year T/C Var <int> <int> <dbl> 1992 0 15.5 1992 0 0.0 1993 0 17.5 1993 0 20.5 1992 1 40.5 1992 1 2.0 1993 1 27.0 1993 1 19.5 What can I do to make a table similar to this where the columns are the treatment/control, rows are the years, and the cells are populated by the mean of var for that group? 0 1 1992 mean(var(0, 1992)) mean(var(1, 1992)) 1993 mean(var(0, 1993)) mean(var(1, 1993)) I tried group_by and summarise like this but I don't know how to make the T/C the columns. df %>% group_by(year, T/C) %>% summarise(across(everything(), list(mean)))
You can use `pivot_wider` to get data in wide format and apply function `mean` to each group of value in the data. library(tidyr) result <- pivot_wider(df, names_from = T.C, values_from = Var, values_fn = mean) result # year `0` `1` # <int> <dbl> <dbl> #1 1992 7.75 21.2 #2 1993 19 23.2 In `data.table` you could use `dcast`. library(data.table) dcast(setDT(df), year~T.C, value.var = 'Var', fun.aggregate = mean) **data** df <- structure(list(year = c(1992L, 1992L, 1993L, 1993L, 1992L, 1992L, 1993L, 1993L), T.C = c(0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L), Var = c(15.5, 0, 17.5, 20.5, 40.5, 2, 27, 19.5)), class = "data.frame", row.names = c(NA, -8L))
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "r, dplyr" }
Is there a way to increase the attachment file size on Azure Devops Services Wiki I have tried finding a setting but can't find an option to increase the attachment size from 18 MB.
I am afraid that there is no method could increase the attachment size from 18 MB. You could refer to this doc: File naming conventions Restriction type Restriction File size Must not exceed the maximum of 18 MB Attachment file size Must not exceed the maximum of 19 MB This is a limitation of Azure DevOps, so there is no method to increase it for the time being. But the requirement makes sense, you could refer to the following suggestion ticket in Our UserVoice Site: File size limits for wiki are restricting You can also create a new suggestion ticket based on your requirement.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "azure, azure devops, devops, wiki, azure devops wiki" }
Ограниченный доступ на сайт <? $admin = '111.222.333.44'; if($_SERVER['REMOTE_ADDR']!=$admin) {echo 'Доступ запрещен';exit;}; // и завершается выполнение скрипта ?> Вот дан скрипт. Он будет пускать на страницу только тех, у кого IP-Адрес 111.222.333.44. Вопрос, как пускать на страницу `site.com/test.php` только тех, кто перешел отсюда `site.com/index.php` \- знаю, что это через REFERER. Это вообще возможно или нет?
<? if (empty($_SERVER['HTTP_REFERER']) || ($_SERVER['HTTP_REFERER'] != ' die('Access denied.'); ?>
stackexchange-ru_stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "php" }
craft.fields.getFieldByHandle() has been deprecated I'm querying a dropdown field to loop through all of the options and followed best practice (so I thought) in the twig template. Does anyone know how to update for the deprecation below? Deprecation message: > craft.fields.getFieldByHandle() has been deprecated. Use craft.app.fields.getFieldByHandle() instead. Code line: `{% set siteOptions = craft.fields.getFieldbyHandle('siteSelector').settings.options %}`
You should replace `craft.fields.getFieldbyHandle()` with `craft.app.fields.getFieldByHandle()` (note the additional `.app` in there).
stackexchange-craftcms
{ "answer_score": 2, "question_score": 1, "tags": "deprecation" }
Wordpress некорректно загружает медиа (изображения) При добавлении изображений в медиабиблиотеку Wordpress некоторые изображения отображаются некорректно. В данном случае 4 изображения созданных в фотошопе. Менял разрешение, менял расширение, ничего не изменяется. При этом, самое первое созданное изображение отобразилось _(№6)_. Также занимательно что они открываются во встроенном редакторе wordpress (правда проходит много времени до окончательной прогрузки). При помещении на страницу также работают некорректно. ![Со 2 по 5 изображение](
Решение оказалось довольно банальным. Все дело было в том, что названия изображений были написаны на кириллице. После переименования все стало работать.
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "wordpress" }
Finding in which vector does the element belong to suppose I have 3 vectors: a = c("A", "B", "C") b = c("D", "E", "F") c = c("G", "H", "I") then I have an element: element = "E" I want to find which list does my element belongs to. In this case, list b. It will be appreciated if the solution to this problem is more general because my real data set have more than a hundred lists.
element = "E" names(our_lists)[sapply(our_lists, `%in%`, x = element)] # [1] "b" Data our_lists <- list( a = c("A", "B", "C"), b = c("D", "E", "F"), c = c("G", "H", "I") )
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -1, "tags": "r" }
Using implicit differentiation on trigonometric fraction and logarithm I am supposed to solve the following using implicit differentiation. $$\sin\left(\frac{x}{y}\right)+\ln(y)=xy$$ This is what I have so far: $$\cos\left(\frac{x}{y}\right)\frac{d}{dx}\left(\frac{x}{y}\right)+\frac{d}{dx}\big(\ln(y)\big)=y+x\frac{dy}{dx}$$ My problem here is differentiating the fraction as well as the $\ln y$, especially since $\ln y$ does not contain $x$ to differentiate towards. Thanks for your help in understanding this.
Keep doing what you did on the right-hand side to get $$\cos\left(\frac{x}{y}\right)\frac{d}{dx}\left(\frac{x}{y}\right)+\frac{d}{dx}\big(\ln(y)\big)=y+x\frac{dy}{dx}\;.\tag{1}$$ You have $$\frac{d}{dx}\left(\frac{x}y\right)=\frac{y\cdot1-x\frac{dy}{dx}}{y^2}=\frac1y-\frac{x}{y^2}\frac{dy}{dx}$$ and $$\frac{d}{dx}\ln y=\frac1y\frac{dy}{dx}\;;$$ both of these are just applications of the chain rule (together with the quotient rule and the rule for differentiating the natural log). Now for convenience I’ll write $y'$ for $dy/dx$; then $(1)$ becomes $$\cos\left(\frac{x}y\right)\left(\frac1y-\frac{x}{y^2}y'\right)+\frac{y'}y=y+xy'\;,$$ and all that remains is to solve for $y'$.
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "ordinary differential equations, implicit differentiation" }
How to adjust table cell with depend on longest one with Flexbox I am implementing table layout with flexbox but I got a problem. If I use `table` tag for it, it is easy to adjust cell width but with Flexbox, it is not easy. Please tell me how to adjust cell width depends on longest one and should I use `table` tag instead of flexbox ? Table: | id | text | | ----- | ----------- | | 3 | lorem lorem | | 43432 | lorem lorem | Flexbox: | id | text | | -- | ----------- | | 3 | lorem lorem | | 43432 | lorem lorem | Thanks in advance.
From your question I understand you are displaying tabular data. In this case, you have two options 1. Responsive layout? Use `divs` with `display:table|table-row|table-cell`. 2. Same table for all devices? Use the classic `<table>`, `<tr>`, `<td>`'s... Flexbox is for layout-ing. It's supposed to flex depending on "cell" contents. It's for fluid, linear content.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "css, flexbox" }
wp8 c sharp community create tables in sqlite Anyone knows if it's possible to dynamically create tables for sqlite using c#. I'm using the c sharp community class for sqlite. I can't find any documents on it.
This will create a table called Task. Schema of table task should be defined as a class in C#. // The database path. public static string DB_PATH =Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "sample.sqlite")); // The sqlite connection. private SQLiteConnection dbConn = new SQLiteConnection(DB_PATH); dbConn.CreateTable<Task>(); Here is a complete tutorial on SQLite For Windows Phone App.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, .net, windows phone 8, sqlite" }
Windows 2008 R2 File Server Cluster vs. DFS We're currently using 2 Windows 2008 R2 with DFS but discovered some issues with: * replication of permissions (permissions are not replicated across DFS members) * replication of quota (quota is disk-based) Do these problems exist in clusters? Meaning, if we set the permission/quota on a folder in a member cluster, will all members of that cluster inherit the permission/quota? We will have a dedicated servers (HP P4300 Lefthand) and we plan to use it for the file servers as well. So, our choices are: DFS or fail-over cluster.
< anaswers your question on quota behaviour on cluster nodes. Note this is for FSRM quotas. FSRM and NTFS quotas are apparently different. See < Which do you have? Also see < Without wanting to sound like marketing I'd like to say DFS and clustering are complementary technologies. Clustering is for those that want quick recovery from server (node) failure. DFSR is for keeping multiple copies in several places in sync. This is why DFSR is supported on clusters starting with 2008 R2. See < . What are the issues you have with replicating permissions? Did you pre-seed content in supported ways before creating RG/RF? I wonder if a robocopy usage issue is the cause fo your permissions issue. See <
stackexchange-serverfault
{ "answer_score": 7, "question_score": 4, "tags": "windows server 2008 r2, cluster, dfs, file server" }
Can we generate a link to downlaod a document in SharePoint without login? I'm implementing an application to store and fetch some company wide documents in a SharePoint site. And only use this application to manage those. I created an admin account to the site and got client id and secret to access the site using Graph API. I'm trying to use client credentials we got to upload and download these documents. But the generated download url for the document still need to login to the site with a valid account. Is there a way to create/generate a url from the data we could fetch from Graph API to download documents without needing to login.
You need to implement Get access without a user. Add the one of the required **Application permissions** : `Files.Read.All, Files.ReadWrite.All, Sites.Read.All, Sites.ReadWrite.All` into your Azure AD app. ![enter image description here]( Call this API: Download the contents of a DriveItem to get the download link. It won't require you to sign in.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "sharepoint, microsoft graph api, sharepoint online" }
Asymptotic distribution of $\mathbb E_{\hat{P}_n}[Z]^T\operatorname{Cov}_{\hat{P}_n}[Z]^{-1}\mathbb E_{\hat{P}_n}[Z]$ Under very general conditions on the random $p$-dimensional vector $Z$, what can be said about the asymptotic distribution of the (random) scalar quantity $R_n := \mathbb E_{\hat{P}_n}[Z]^T\operatorname{Cov}_{\hat{P}_n}[Z]^{-1}\mathbb E_{\hat{P}_n}[Z]$ ? Here, $\mathbb E_{\hat{P}_n}[Z] = (1/n)\sum_{i=1}^nz_i \in \mathbb R^p$ is the empirical mean of $Z$ from an i.i.d sample $z_1,\ldots,z_n$, and $\operatorname{Cov}_{\hat{P}_n}[Z] \in \mathbb R^{p \times p}$ is the empirical covariance matrix. # Notes My ultimate goal is to understand the rate of growth of $R_n$ as a function of $n$. # Observations My wild guess is that $R_n$ should be "concentrated" around $\mu^T\Sigma^{-1}\mu$ where $\mu \in \mathbb R^p$ is the mean of $Z$ and $\Sigma \in \mathbb R^{p \times p}$ is its covariance matrix.
If $\mu\ne0$, then the distribution of $R_n$ is asymptotically normal with asymptotic mean $\mu^T\Sigma^{-1}\mu$ and an explicit asymptotic variance $\tilde\sigma^2/n$; see e.g. Theorem 3.9, page 1018, where a bound on the rate of convergence is also given. More specifically, \begin{equation} \tilde\sigma^2=EL(V)^2=E(2\xi-\xi^2+\mu^T\Sigma^{-1}\mu)^2, \end{equation} where \begin{equation} V:=(Y-EY,(Y-EY)(Y-EY)^T-I),\quad Y:=\Sigma^{-1/2}z_1, \end{equation} \begin{equation} L(x_1,x_2):=2x_1^T\,EY-EY^T\,x_2\,EY, \end{equation} \begin{equation} \xi:=EY^T\,(Y-EY)=\mu^T\Sigma^{-1}(z_1-\mu). \end{equation} If $\mu=0$, then the distribution of properly normalized $R_n$ is asymptotically chi-squared; see e.g. Theorem 3, page 48.
stackexchange-mathoverflow_net_7z
{ "answer_score": 1, "question_score": 1, "tags": "st.statistics, probability distributions, asymptotics, limits and convergence" }
How to get same domain invisible IFRAME content in to main page when iframe finishes its process? i Wonder how i can create an invisible iframe and get its final content in to main page too not only inside the iframe? (Note. My invisible iframe url is in same domain and is written in php and i can modify it for my requirement). <iframe id ='myframe' src=' My goal is to show user some sort of loading animation while invisible iframe finishes its process (usually it takes 10 seconds to finish ) and then show the final output in main page and removes the loading animation. My invisible iframe redirects to another php url(also in same domain) and outputs some data but i want to show this data inside my main page also not only inside invisible iframe. Could you guys tell me how this can done ?
This what you looking for? Otherwise I could only think to use `ajax` for this.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "php, javascript, html, iframe" }
Installing an ssl certificate in order to serve a local web application? I need to install a local SSL certificate so that the browser trusts it. This tutorial has instructions for OS X and Windows, but not Ubuntu. < For example these are the instructions for OS X: Double click on the certificate (server.crt) Select your desired keychain (login should suffice) Add the certificate Open Keychain Access if it isn’t already open Select the keychain you chose earlier You should see the certificate localhost Double click on the certificate Expand Trust Select the option Always Trust in When using this certificate Close the certificate window The certificate is now installed. What would the equivalent be for Ubuntu?
**you** can search With => 'How To create SSL certificate By Let's Encrypt in Ubuntu Linux' in **Google** and **Keep Learning** This should do the trick though: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "angular, ubuntu, ssl, https, angular cli" }
Anyone know of an ASP.NET equivalent to the Rails auto_link helper? A fast function for scanning text for urls and turning them into html hyperlinks would be very nice... I'd write one but I feel like the odds of someone already having written one are high... Thanks! Tom
how about this: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, asp.net, hyperlink" }
Magento : Check if two conditions are true (category view) I am trying to check if two conditions are true in the Magento category view file. Specifically if parent id = 1 and if category name = Nike. Can someone please suggest how I can update the code below to get this working? <?php if ($_category->getParentCategory()->getId() == 1) && ($_category->getName() == 'Nike'): ?> <p>Then show this</p> <?php endif; ?>
Your if condition syntax is wrong. You use if ($_category->getParentCategory()->getId() == 1) && ($_category->getName() == 'Nike'): In this code, your if statement parenthesis ends before && operator. The correct syntax is : if ($_category->getParentCategory()->getId() == 1 && $_category->getName() == 'Nike'):
stackexchange-magento
{ "answer_score": 1, "question_score": 0, "tags": "magento 1.9, if, category view" }
window.open won't work in Phonegap 1.7.0 I'm working with Phonegap on a mobile device. And its issues and bugs are too much to solve. One of them is: window.open('new_window.html','well','width=300,height=200'); > (I have already created a new_window.html under assets/www/.) it appears a full screen window, and of course. If I set scroll bar option is true, it's still no use. The system is like a dummy. I have searched the solution for several days, trying use iframe/frame to replace it. But they are not appropriate or no use. In my development environment, I just want to let the user press a button and a small window pops out. I can set the tile, location, size... Any alternatives or suggestions? Thanks.
You could try setting the size on the actual page that is popping up and try window.open() again, if that does not work try: window.location.href = "newindow.html"; If that does not work either and you could try using a jQuery Dailog box (need to import the jQuery Library found here jQuery) as the popup, code would be something like this: $(document).ready(function() { $('#buttonID').click(function() { $help.dialog('open'); return false; }); var $help = $('<div></div>') .html('Your HTML copy goes here!') .dialog ({ autoOpen: false, height:200, width: 300, title: 'Window Title' }); });
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, android, jquery ui, cordova, phonegap plugins" }
Lazyloading like googlenewstand app I am currently doing a project which needs to load images in a listView with some text from web.I am using **universal image loader library** ,every thing work fine images are loading perfectly without any problem, but my requirement is that if there is no image in a specfic url, i dont want to show that image view in the listview row.which is similer to the news stand app of google. !enter image description here in the above screen of the newsstand app if there is no image the imageview is not shown and the text will fill to the total width of the cell or row in the listview.How can i achieve this requirement.i have goggled but did not get any right solution or clue to fix this issue,can any one give any snippet or any idea to sort out this issue. Thank you
In your adapter, when you call the library to display the image, if there is no image url just set the visibility of your ImageView to GONE (and VISIBLE again when there is an url). If you want to wait that the image is completely loaded to make the ImageView visible, you'll need to register a loading listener. See here.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "android, listview, imageview, lazy loading, android lazyloading" }
Mobile or phone number validation in javascript I need to validate phone or mobile number in javascript. It should match the following types: `+91-9198387083` `9198387083` `09198387083` It is a 10 digit number with one of these four prefixes `'+91-'`, `'+91'`, `'0'` or `''` Can someone suggest me a regex expression in javascript which matches all the three types.
I'd using something like this: /^(\+91-|\+91|0)?\d{10}$/ This is very specific about one of your three allowable prefixes (or no prefix) followed by exactly 10 digits and no extra characters on the beginning of end of the string. Test app with both valid and invalid phone numbers here: <
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 1, "tags": "javascript, regex, validation" }
Restrictions on an asset level in Content hub Can we apply a restriction on an asset level to disable or remove the " **create rendition button** ", " **download user renditions** " and " **Public link option** "? I know we can do that on the user group level but the ask is to do it on particular assets.
I was able to achieve this by applying rules on user group policy(Each user is assigned with some user groups with some permissions on it to access the asset). I have used OOTB Content Hub taxonomy field "M.DRM.Restricted"(You can create your own new taxonomy)to add a rule on a user group which was assigned to the users that client was using and deselect the permissions which I don't want for the asset. If "M.DRM.Restricted" field on an assets is "yes" then these restrictions will be applied else it won't. See screenshot for reference: ![enter image description here](
stackexchange-sitecore
{ "answer_score": 0, "question_score": 0, "tags": "content hub" }
Detect String doesn't include number I need to detect user number should never include character. I know this method: public boolean haveDigit(String str) { for (int i = 0; i < str.length(); i++) { if (Character.isDigit(str.charAt(i))) return true; } return false; } Is there any other better and easy solution?
Using Pattern class and regular expressions. This method is equals to your method. public boolean haveDigit(String str) { Pattern p = Pattern.compile(".*[0-9].*"); Matcher m = p.matcher(str); return m.matches(); } test haveDigit("d9h"); //true haveDigit("d9agh6"); //true haveDigit("hello"); //false Next method checks what you ask public boolean isNumeric(String str) { Pattern p = Pattern.compile("[0-9]+"); Matcher m = p.matcher(str); return m.matches(); } test isNumeric("r5t"); // false isNumeric("100"); // true isNumeric("0.5"); // false
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "java" }
DataGridView, How to use if statement for a cell that starts with a string I would like to be able to use an if statement to determine the colour of a DGV cell that starts with a string "Manual". I know how to change the cell's colour if (Convert.ToString(DGV_Points.Rows[x].Cells[2].Value.StartsWith) == "Manual") { } Also is it possible to disable the restoration of the cell's default colours when a header is clicked?
if (DGV_Points.Rows[x].Cells[2].Value.ToString().StartsWith("Manual")) { } Is this what you were looking for?
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, datagridview, background color, cells" }
How to add elements to an array in Bash on each iteration of a loop? I have this `depends` file in my `$PATH`: #!/bin/bash k=0 for i in "$@" do DP[k]="nodejs-$i" k=$((k+1)) done echo $DP I ran `depends js kd` and it returned: nodejs-js this surprised me as I thought that the result I would get would be: nodejs-js nodejs-kd as the loop was meant to be adding new elements to the `DP` array of form `nodejs-$i` where `$i` is the input I provided to the `depends` script when I ran it. I have tried using this depends script instead: #!/bin/bash DP=() for i in "$@" do DP+=("nodejs-$i") done echo $DP but it returned the exact same result, with the `js kd` inputs (i.e., the output was `nodejs-js`).
Your script is correctly adding elements into the array, check how to read the DP array below. Give this a try: #!/bin/bash k=0 for i do DP[k]="nodejs-$i" k=$((k+1)) done printf "DP array size is %d\n" "${#DP[@]}" printf "%s " "${DP[@]}" printf "\n" \--edited-- Note that new applications are encouraged to use printf instead of echo. _Funny =>_ By default the **for** statement loops over the script's arguments. The test: $ ./depends js kd DP array size is 2 nodejs-js nodejs-kd
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "arrays, bash" }
ms sql error :Incorrect syntax near the keyword 'on' select * from other table inner join ( select Count(*), F1,F2,F3 from Table group by F1,F2,F3 ) on F1 = OtherF Incorrect syntax near the keyword 'on'.
Your subselect needs to be aliased: select * from other AS o inner join ( select Count(*), F1,F2,F3 from Table group by F1,F2,F3 ) AS x on F1 = o.OtherF
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "sql server, syntax" }
How to get Current Year and Previous Year values as Columns Can any body please tell me about below case. I have fact table which has datekey, I have bridge table which has `Datekey` and `PYdatekey`( PYDatekey represents last year value). When I want current year value, I am joining with `FactTable.DateKey = BridgeTable.DateKey`, for Last year values `FactTable.DateKey=BridgeTable.PYDateKey`. I am writing two separate queries doing union all to get these values as rows. But now I need to get these values as columns. Please suggest how to achieve this.
You can join to FactTable twice to get the previous and current data separately. Use LEFT JOIN in case Datekey and/or PYdatekey is not required in BridgeTable. --Sample data CREATE TABLE BridgeTable (Datekey int, PYdatekey int) CREATE TABLE FactTable (datekey int, SomeField varchar(100)) INSERT INTO FactTable VALUES (1, 'A') INSERT INTO FactTable VALUES (2, 'B') INSERT INTO BridgeTable VALUES (1, 2) INSERT INTO BridgeTable VALUES (1, null) INSERT INTO BridgeTable VALUES (null, 2) --Query SELECT PreviousFacts.SomeField AS Previous_SomeField, CurrentFacts.SomeField AS Current_SomeField --Or whatever columns you need FROM BridgeTable LEFT JOIN FactTable PreviousFacts ON BridgeTable.PYdatekey = PreviousFacts.DateKey LEFT JOIN FactTable CurrentFacts ON BridgeTable.Datekey = CurrentFacts.DateKey
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "sql server" }
Modules on the same layer in layered architecture In theory in layered architecture you can have multiple modules on the same layer. Can this modules cross reference to each other? Is is possible technically, eg. using .NET?
It is certainly possible to do so, just be careful not to introduce any cyclic dependencies between modules. In general, modules at a given layer should only depend on other modules from the same layer or from the layers below it. Modules should not be aware of the layers above them. If you want to make this even stricter, then you can also limit dependencies to other modules from the same or other layers immediately below the current one. Keeping the exposed interface to a minimum, e.g. exposing only a core set of public interfaces, value objects, and exceptions is always a good idea. You can use the language's access control features (i.e. private/package/public) to limit visibility of module internals from spilling into other layers.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "architecture, layered" }
filter and send a contact database I have a script that sends emails to a contact list. I would like to filter the large list each time I send and wondered what would be the best way to store the temporary list? I was thinking of creating a temporary table which contained the filtered results and then dropping it at the end of the script. Is there an easier way to store the results? The contact list is in the the thousands. Thanks for any advice.
I would agree with the use of a temporary table, but would also suggest independent views. If you frequently filter your tables and need to create many temporary tables, why not create multiple views, which would contain results only for the criteria you wish, and sending mail based on that. This would prevent the need for creating and dropping tables, but would only benefit you if you use the same filter many times.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, mysql, database, email" }
How to properly use querySelectorAll with addEventListener What's the proper way to use the querySelectorAll method? I'm just trying to add a click event to each div with class '.box', but it's not working. I've found that this works fine if I replace the method with 'getElementById' and just test the kitchen box. document.querySelectorAll('.box').addEventListener('click', test); function test() { console.log('hi'); } <section class="main"> <div class="box" id="kitchen"></div> <div class="box" id="laundry"></div> <div class="box" id="bedroom"></div> </section>
It's really simple, you just loop over every element and add an event listener. document.querySelectorAll('.box').forEach(item => { item.addEventListener('click', event => { // Handle the click event here }) })
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, dom" }
Get local file inside the extension folder in Chrome I know that I can't get a local file from within the extension directory. It is possible to get a file that is _inside_ the extension directory itself?
You can use chrome.runtime.getURL to get a fully-qualified URL to a resource. // Outputs path to the file regardless if it exits > chrome.runtime.getURL('assets/extension-icon.png'); "chrome-extension://kfcphocilcidmjolfgicbchdfjjlfkmh/assets/extension-icon.png" The _`chrome-extension`_ protocol plus the extension id, will be the address for the extension's root directory. If you need something more powerful, you might also use HTML5's FileSystem API which can create, read, write and list files from a sandbox in the current user's local file system.
stackexchange-stackoverflow
{ "answer_score": 38, "question_score": 28, "tags": "google chrome extension" }
Help with a circuit I am trying to figure what is wrong in this circuit. There is an ultrasonic module that creates mist from water. I measured the tapped inductor and it seems to be fine. Also the resistor is fine. I measured the capacitor and it is 1000pf (I removed it from the board.) I am not sure if the capacitor is faulty but I don't know what it should be. When I measure with my multimeter A - B I get 5V. Also when I measure A-C I also get 5V. When I measure +Module and -Module (I missplaced the + and - on the picture, there are opposite) I get 0V. Question. Should I be able to read something with a multimeter? The white lines are how they are connected. I am not 100% sure that the module is working. My guess is that since it doesn't get any voltage it shouldn't work. I also show you the other side. ![Circuit]( ![Other side](
Lack of voltage may be because it is high frequency AC. Soldering or wires (original) is terrible. Check that plated through holes to wires from tracks is complete - this MAY have been marginal and failed. Trace tracks from pin X to pin Y or solder points and then use ohm-meter to check there is continuity. eg connection to 47k that jsotola mentioned. If it was working and now isn't then failure of the piezo element seems most likely, and next the IC itself. Check that the wires are continuous from PCBA to piezo contacts. ABC is (probably) a transistor - FET or bipolar. C is gate/base. B is source / emitter. A is drain / collector. There should be AC drive to C (and, as you report, DC feed of power supply to A via inductor.) Ab and AC = 5V is close enough to right).
stackexchange-electronics
{ "answer_score": 0, "question_score": 0, "tags": "circuit analysis" }
pl sql error PLS-00103 I have a table(customer) and is has attributes of c_Id, fname, lname, age the table is populated with the following values 1|Ann|Smiths|23 2|Chris|Gates|21 3|Janes|Jobs|24 I am very new to pl/sql and I wrote a simple select statement DECLEAR name varchar2(50); BEGIN SELECT fname into name FROM customer WHERE fname= 'Ann'; END; When I execute the script my from my textfile(doselect) on sqlplus using the following command EXECUTE doselect however it gives me the following error ERROR at line 1: ORA-06550: line 1, column 8: PLS-00103: Encountered the symbol ":" when expecting one of the following: := . ( @ % ; Please help.
Apart from the typo (DECLEAR instead of DECLARE), your script looks fine. To get output from SQL/Plus, I'd also add a `DBMS_OUTPUT` statement: DECLARE name varchar2(50); BEGIN SELECT fname into name FROM customer WHERE fname= 'Ann'; -- print it dbms_output.put_line(name); END; However, to execute a file from SQL/Plus, don't use the `EXECUTE` command - rather use `@` : SQL> set serveroutput on SQL> @doselect 10 / Ann SQL/Plus is not very friendly to new users - you might want to use another client to get started (e.g. Oracle SQL/Developer \- it's free and comes with a nice GUI).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "plsql, sqlplus" }
Computing $\frac{d^k}{dx^k}\left(f(x)^k\right)$ where $k$ is a positive integer Does anyone know a formula for the derivative $$\frac{d^k}{dx^k}\left(f(x)^k\right)$$ where $k$ is some positive integer? I started trying to work it out but it got messy.
Apply Faà di Bruno's formula to get $$\frac{d^n}{dx^n}(g(x)^n)=\sum \frac{n!^2}{m_1!\dots m_n!(n-\sum_{j=1}^nm_j)!}g(x)^{n-\sum_{j=1}^nm_j}\prod_{j=1}^n\left(\frac{g^{(j)}(x)}{j!}\right)^{m_j},$$ where the sum is taken over the $n$-uples $(m_1,\dots,m_n)$ of integer satisfying $\sum_{k=1}^nkm_k=n$. (I changed the notations to be conform with the link)
stackexchange-math
{ "answer_score": 7, "question_score": 10, "tags": "calculus, derivatives" }
Rails 3 problem with second, third ActiveRecord methods Last week this worked but now, for some reason I can only use Model.first. Model.second and Model.third, etc no longer work. Did something change in Rails? I keep getting a NoMethodError.
`Model.second` never worked, I don't think. `second` and `third` work on arrays, however. Maybe you used something along the lines of `User.all.third` the first time.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "ruby on rails, activerecord, ruby on rails 3" }
Помогите с View Я создал свой класс View и назвал LetterView . В layout файле это очень просто добавляется в RelativeLayout Но проблема в том, что я должен добавить в java с нужным размером, которое зависит от размера экрана используя addView по умолчанию марджины 0dp . Я попробовал изменить марджины в методах `onCreate()`, `onStart()`, но когда вызываю `getWidth()` , `getMeasuredWidth()` возвращает 0 . Позже попробовал в методе `onWindowFocusChanged()`, казалось бы все ок, но результат не удовлетворительный.Очень заметно как View изменяет марджины от 0 к нужному месту. Если не понятно. Я создаю игру эрудит. И буквы должны находится в низу в от доски и каждая буква это View класс. Я прошу у вас совета в каком методе расположить margin LetterView так, чтобы я знал длину и ширину экрана и расположил в нужном месте сразу же. Я почитал разные документации, но не могу добиться своего. Я почти закончил игру, но это калякса просто ужас. Спасибо
У `View` есть метод `onMeasure(int, int)`, в нем ты можешь получить ширину и высоту методами `getMeasuredWidth()` и `getMeasuredHeight()`
stackexchange-ru_stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android" }
What is the meaning of "spend it living" in this sentence? > Sam: My mom left when I was little. My dad raised me and he died last year. > > Cathy: Oh, my. So you cared for him as well? > > Sam: I would have. I just thought I had more time. > > Cathy: You think too much about the time you have left. you don't **spend it living.** I don't get it, what Cathy is speaking here about it?
I'll rephrase Cathy's line: > You think too much about the time you have left. You don't spend **that time living life to the fullest**. Cathy is saying not to brood too much about how short life is. Instead, live your life as though the time is precious. Don't just think -- live. _Carpe diem_.
stackexchange-ell
{ "answer_score": 2, "question_score": 2, "tags": "meaning in context" }
How to convert time format into milliseconds and back in Python? The reason is because I'm making a script to work with ffmpeg and I need to be able to add/subtract time in the format 00:00:00[.000] The last 3 digits are optional and they mean milliseconds. A time string could look like any of the following 4:34.234 5.000 2:99:34 4:14 This would be easier if a lot of the digits weren't optional. But since they are, I'm thinking I have to use some sort of regex to parse it?
From string to milliseconds: s = "4:34.234" hours, minutes, seconds = (["0", "0"] + s.split(":"))[-3:] hours = int(hours) minutes = int(minutes) seconds = float(seconds) miliseconds = int(3600000 * hours + 60000 * minutes + 1000 * seconds) From milliseonds to string: hours, milliseconds = divmod(miliseconds, 3600000) minutes, milliseconds = divmod(miliseconds, 60000) seconds = float(milliseconds) / 1000 s = "%i:%02i:%06.3f" % (hours, minutes, seconds)
stackexchange-stackoverflow
{ "answer_score": 18, "question_score": 7, "tags": "python, datetime" }
Controllers that are not Gamepads in LWJGL I'm having troubles with Gamepad Support. try // to create the Controllers { Controllers.create(); } catch(Exception exep) {} int allControllers=0; allControllers=Controllers.getControllerCount(); //finding out how much //of it do we have It says that I have 3 Controllers. But the Gamepad is the Controller number 0. Because when I poll n1 or n2 Controller -- game just crashes. Does anyone knows hot to automatically pick working gamepad from this list and evade the Crash?
Looks like nobody else can do it. I've been working on it for good, and there is only one solution so far. Here it is: for(int co=0;co<allControllers;co++) { gamepad = Controllers.getController(co); GamePadName=gamepad.getName(); if(GamePadName.charAt(0)!='H' && GamePadName.charAt(0)!='U') Keys=checkGamepad(Keys); } There are two controllers that can't be polled. On some PC's they are called "HID something", on other they are called "USB Keybord", "USB Mouse". Maybe on other PC's they will be called in other way. So we are not polling these Controllers, and game is not crashing... seems to be a bad solution, but I see no better.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 4, "tags": "java, controller, lwjgl" }
per blog metadata for plugin I wish to have my plugin store metadata for each blog in a network (or just one if single site install). Most of the Google results are for post_meta and user_meta but I really need site_meta which does not appear to be the same (only a get method). The data is generally going to be of the form: $metadata['this']['foo'] = 'something'; $metadata['this']['bar'] = 'one thing'; $metadata['that']['foo'] = 'mum'; $metadata['that']['bar'] = 'dad'; What is the best way to store this?
Options are site specific, so you just need to use `update_option()` and `get_option()`. The network-wide equivalents are `update_network_option()` and `get_network_option()`. Note that `update_site_option()` is just a wrapper for `update_network_option()`, and is an older name from when a multisite network was (confusingly) called a 'site'. The same applies for `get_site_option()`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugin development, custom field" }
Help with smart contract Hello i have these smart contracts: contract CarFactory { Car[] deployedCars; function createCar() public { Car newCar=new Car(this); deployedCars.push(newCar); } function getDeployedCars() public view returns (Car[] memory) { return deployedCars; } function getDeployedCarsWhereTrue() public view returns (Car[] memory) { return deployedCars ///where bool made is true; } } contract Car { CarFactory factory; bool made; constructor(CarFactory _factory) { factory=_factory; } function makeTrue() { made=true; } } And i need the function getDeployedCarsWhereTrue to return only the addresses where the bool in the smart contract is true.Is that possible?
You need to check every element inside the array, I added the `getCount` function to be able to declare a size for the dynamic array: function getDeployedCarsWhereTrue() public view returns (Car[] memory) { uint count = getCount(); Car[] memory result = new Car[](count);; for(uint i = 0; i < deployedCars.length; i ++){ if(deployedCars[i].made){ result.push(deployedCars[i]); } } return result; } function getCount() internal view returns (uint) { uint count; for (uint i = 0; i < deployedCars.length; i++) { if(deployedCars[i].made){ count++; } } return count; } Neededless to say this is going to be very expensive in gas, I recommend having a separate array to save the made Cars.
stackexchange-ethereum
{ "answer_score": 1, "question_score": 0, "tags": "solidity" }
get the count (integer) of cells in a specific column that have a value, with google apps script Is there a way to get the count of cells that have values in a specific column? I need it for 2 reasons. First off I want to read that number back to the user in a dialog box. secondly I'm running a function multiple times with the `forEach` method. I don't want to run it more times than the amount of cells with values, but can't seem to set the range according to the values count. keep in mind this column's data is dynamic. It's not the same amount every time it depends on the user's input. Note: calling `getDataRange()` or `getLastRow()` don't help because they return the entire sheet's count which can be more than the column I need.
function getCount() { let a=SpreadsheetApp.getActive().getActiveSheet().getDataRange().getValues().map(function(r){return r[0];}).filter(function(e){return e;}); SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(a.length), "count") }
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "google apps script" }
Mate Panel Completely Gone I installed MATE on my Antergos Desktop and right clicked on the panel → reset panel. Since then it has disappeared completely. I have tried pretty much every `mate-panel` command combinations such as * \--layout default.layout * \--reset * \--replace and also tried `pacman -Rn mate mate-extra` and then reinstalling. Now when I run `mate-panel` I get this warning : ** (mate-panel:2502): WARNING **: 11:14:32.089: Cant find the layout file! Where should this layout file be for `mate-panel` to find it?
Unsolved: how it happened. Solution: Open a terminal (right click on the desktop background). Enter user command: `mate-panel --replace` Tests icons and mate panel menu bar. If you get the menu bar back, then open another terminal. Enter user command: `mate-session-properties` This GUI edits the startup programs. Click the icon ADD. Enter this text: `mate-panel --replace` Save the edit. Close the GUI. Reboot. The result: The session will start with mate-panel populated. The Dec 18, 2018 suggestion to install mate-tweak might help. Start `mate-tweak` and select Windows ==> Display Manager ==> Marco. This is the default on a fresh install of Linux Mint 19.1.
stackexchange-superuser
{ "answer_score": 5, "question_score": 5, "tags": "linux, arch linux, mate" }
Find the number of common normals to both these curves. Find the number of common normals to the curves $ x^2 + (y-1)^2 =1 $ and $y^2=4x$. My take : I formed a cubic in $m$ i.e. slope, so there'll be 3 normals. Please help.
Your first curve is a circle of radius 1, centered at $(0,1)$. Its normals are the lines through its center, that is, the lines $$y=mx+1$$ for arbitrary $m$ (this leaves out the vertical normal, but that's obviously not normal to the other curve). So now you just have to work out the values of $m$ for which the graph of $y=mx+1$ is normal to the graph of $y^2=4x$. Can you do that? I guess not, so here goes. From $y^2=4x$ we get $2yy'=4$, so $y'=2/y$. If $(a,b)$ is a point on the graph of $y^2=4x$, then 1\. the slope of the normal to the curve at that point is $-b/2$, and 2\. $b^2=4a$. So the equation of the normal is $$y-b=-(b/2)(x-a)$$ which we can write as $$y=-(b/2)x+(1/2)ab+b$$ But we want the normal to be $y=mx+1$, so $$(1/2)ab+b=1$$ Now combining that with $b^2=4a$, we get, after a little algebra, $$b^3+8b-8=0$$ and it's easy to show that equation has exactly one real zero, so there is exactly one common normal.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "algebra precalculus, coordinate systems" }
Best way to find out distinct item in the big list I have a following collection, it has more than 500000 items in it. List<Item> MyCollection = new List<Item>(); and type: class Item { public string Name { get; set; } public string Description { get; set; } } I want to return a list of items having distinct Name. i.e. to find out distinct item based on name. What are the possible ways & which would be best in terms of time & memory. Although both are important however less time has more priority over memory.
You can sort your list an then delete all repeated items, But seems that storing all data in a `Dictionary<string, string>` would be better for this task. Or maybe even put all the list in a `HashSet`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "c#, .net, list, c# 4.0, collections" }
How do you get the latest version/master of a package in bower? I had the problem with backbone-forms, where I needed to draw from master branch (because of a fix that was not yet tagged). I was trying all kinds of combinations. ` { 'backbone-forms': ? } `
All you have to do is say: ``` { 'package-name': 'master' }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "backbone.js, bower, backbone forms" }
Portenta pinouts for ADC I wanted to have your comments about one of my questions. I am currently working on the sketch for the Arduino Portenta H7. However, due to my poor electrical background, I would like to ask your opinion about the pinouts. Below you can find the pinout diagram from the document page 1 available at the below link. < I am a bit confused about the analog pins. As the diagram and color-coding show ADC A0 ( available on the high-density connector) and analog pin A0 both separately. What can be the difference between them ? or maybe I am interpreting wrong. Because, on an ordinary Arduino board ( as far as I found), we have the Analog pins which are used for the ADC too. However, here in the Portenta pinout diagram, we have ADC A0 and analog A0 separate? I thank you for your time and opinion![pinouts of portenta h7]( ![High density connectors at bottom of portenta](
The "high density" connectors expose every pin of the MCU. The pins around the edge of the board duplicate just the immediately useful ones. Every pin that is on the edge of the board is also on the high density connectors somewhere. Why have the pin on both connectors? Simple: if you want to use it in a breadboard or with jumper wires then you want the useful pins on the edge. If you want to use a plug-in board then you don't want to have to connect to both the high density connectors _and_ the breadboard connectors, that would just be really awkward (since both have completely different height profiles). So everything is on the high density connectors for plug-in boards, and the useful ones are also on the breadboard headers. A0 is the Arduino name for the pin. ADC is the function of the pin. The A of ADC stands for Analog. It's a pin that Converts Analog to Digital. It's an Analog to Digital Conversion pin - ADC.
stackexchange-arduino
{ "answer_score": 1, "question_score": 0, "tags": "arduino ide, pins, adc, analog sampling, arduino portenta h7" }
Apply fadein effect to tooltip? I have this code, which shows the tooltip within a box with the id of "tooltip-container" - currently it just pops in...how can I make it fade nicely and fade out on roll-off? Current code: $(document).ready(function(){ $('.tippytrip').hover(function(){ var offset = $(this).offset(); console.log(offset) var width = $(this).outerWidth(); var tooltipId = $(this).attr("rel"); $('#tooltip-container').empty().load('tooltips.html ' + tooltipId).show(); $('#tooltip-container').css({top:offset.top, left:offset.left + width + 10}).show(); }, function(){ $('#tooltip-container').hide(); }); });
instead of `.show()` use `.fadeIn(timeInMS)` Same for `.fadeOut()`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery" }
Tone of 和 in 暖和 For words like and , we can pronounce either with full tones as yi¹fu² and peng²you³, or with neutralized tones of the second syllable like yi¹fu⁰ and peng²you⁰. Then comes which confuses me. In the Taiwanese dictionaries that otherwise show full tones, this word is still spelled as nuan³huo⁰. What would be the tone of if it was not neutralized? Or is this maybe a wrong question; does this syllable huo⁰ only exist in neutral tone?
read huo has four pronunciations: * huō * huó * huò * huo _Liang’an_ defines neutral huo as: > and gives the following example words: > > > > > The definitions of the other pronunciations of huo certainly don’t fit. Why? Well because: * huō can only be found in the word which means stupid. * huó basically only means: to mix with water. * huò means to mix or to blend. But this answer isn’t very satisfying. Knowing that the in is the same as the one in then we can look back at an entry in _ABC_ : > The given Pinyin for this word is: > ruǎnhuóhuàr Here is marked huó. It fits the idea that sometimes these words are also pronounced he and hé. For instance _MOE_ has the entry: > written as: > nuǎn hé hé Again: it’s second tone. So if you want an answer with a tone & not just with a neutral tone, the second tone is your best bet.
stackexchange-chinese
{ "answer_score": 3, "question_score": 2, "tags": "tones" }
x3d - what blend modes to use What blend modes and attributes must I use to achieve following effect: First texture is a tileable grass texture and second texture is the opacity mask for that texture. <MultiTexture mode='"MODULATE" "?"'> <ImageTexture repeatS="true" repeatT="true" url='"grass.jpg"' /> <ImageTexture url='"grass_opacity.png"' /> <MultiTextureTransform> <TextureTransform scale="8 8"/> <TextureTransform/> </MultiTextureTransform> </MultiTexture> Using: `"SELECTARG2, SELECTARG1"` seems only to work with hard masks, either 0 or 100% opacity. Using Bs Contact player.
Correct blending is: <MultiTexture mode='"SELECTARG2,SELECTARG1" "BLENDCURRENTALPHA,DIFFUSE_SELECTARG2"'> but Bs Contact player does not supports it in x3d file format. With vml its no problem.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "3d, x3d" }
This video has been removed by the user - add a redirect link I deleted a video with the intent of replacing it with a newer version. Now, preexisting links are broken. Is there a way to redirect? Alternatively, is there a way to have a link to the new video, instead of just displaying this: > This video has been removed by the user.
Unfortunately there's no possible way of redirecting a removed video. Once it's deleted, there's nothing we can do. However if you haven't deleted the video, you could create a "replacing video" and create an annotation on the old one, letting people know that there's a new version of that video, like the example on this video: <
stackexchange-webapps
{ "answer_score": 1, "question_score": 1, "tags": "youtube" }
Java api for calculating Interquartile range Is there any java api for calculating interquartile range? I was wondering apache commons math library contains all the stats function like mean, median, mode but i could not find any thing for IQR.
I'm not sure, but maybe you can use getPercentile from DescriptiveStatistics class of Apache Commons Math, like in the following code sample. double[] data = // obtain data here DescriptiveStatistics da = new DescriptiveStatistics(data); double iqr = da.getPercentile(75) - da.getPercentile(25);
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 5, "tags": "java" }
What are the pros and cons of Solr & ElasticSearch? Both Solr and ElasticSearch are built upon Lucene. How do they compare to each other in terms of: * Features (facet & multi-language support in particular) * Performance * Scalability * Stability * Manageability Any experiences you have with either software that you can share? Thanks.
Well, to make is short and simple: * Use **SOLR** if you want to be able to fine tune your performance(by fiddling with the internals), want more control and also a huge community. * Use **elastic search** if you want faster deployment, ready to live with a lesser grain of control(there are advanced options though) and get the actual output(during development) that you want to get during deployment. Both are known to be **scalable** and **stable** and offer **great performance**. PS: I have read about a person 'getting stuck' with some minor problems/bugs in **elastic search**. However, there are plenty that are satisfied. :D
stackexchange-stackoverflow
{ "answer_score": 8, "question_score": 7, "tags": "lucene, full text search, solr, search engine, elasticsearch" }
Android - get children inside a View? Given a View how can I get the child views inside it? So I have a custom View and debugger shows that under `mChildren` there are 7 other views. I need a way to access these views but it doesn't seem like there is a public API to do this. any suggestions? **EDIT:** My custom view inherits from `AdapterView`
for(int index = 0; index < ((ViewGroup) viewGroup).getChildCount(); index++) { View nextChild = ((ViewGroup) viewGroup).getChildAt(index); } Will that do?
stackexchange-stackoverflow
{ "answer_score": 341, "question_score": 188, "tags": "android, view" }
8bit panels and hdr I'm looking into buying an Asus pg65uq when it's available, but I noticed something strange - it claims to support HDR10 while at the same time only supporting 8bit color. Doesn't those two contradict each other?
An 8-bit display can use FRC to expand its perceived color range. It essentially dithers a pixel between two colors in time rather than with neighboring pixels. Many monitors do this, in fact a lot of displays that support "16.7 Million Colors" (24-bit Color) are actually 6-bit panels using FRC. If you are trying to decide between monitors, I wouldn't let this detail become a deciding factor. You are very likely looking at a monitor right now that uses FRC and you may not have noticed. It would be hard for most people to notice the quality improvement of a true 10-bit panel _without_ FRC vs 8-bit with FRC.
stackexchange-hardwarerecs
{ "answer_score": 0, "question_score": 0, "tags": "displays" }
LFTP Reconnect infinite loop When I try to connect to the host that is dwon I get the following message: cd `sftp://example.com/tmp' [Delaying before reconnect: 30] After each attempt delay sis increasing. I found the following command that should help me: repeat -d 10 -c 1 which should delay by only 10 seconds (instead of default 30) and repeat th ecommand only once. But still I get Delaying reconnect in endless loop.
ok found it: lftp -e "set net:max-retries 2;set net:reconnect-interval-base 5;set net:reconnect-interval-multiplier 1 ;mirror -v --just-print '/tmp/md1/' '/tmp/m2'" sftp://example.com
stackexchange-stackoverflow
{ "answer_score": 13, "question_score": 5, "tags": "reconnect, lftp" }
Invalid value for 'Event'-Property (XAML Eventsetter) I'm using Visual Studio 2015 Community and I get the following error message: > Invalid value for 'Event'-Property: Microsoft.VisualStudio.DesignTools.Xaml.LanguageService.Semantics.XmlValue. Here's the code behind: <Style x:Key="TextBoxStyle1" BasedOn="{x:Null}" TargetType="{x:Type TextBox}"> <EventSetter Event="MouseEnter" Handler="Check_MouseEnter" /> <EventSetter Event="MouseLeave" Handler="Check_MouseLeave" /> <EventSetter Event="GotFocus" Handler="Check_GotFocus" /> I've tried `UIElement.MouseEnter`, `Mouse.MouseEnter`, `TextBox.MouseEnter`. If I compile the handler works just fine, but the error message is still there. Any suggestions?
This seems a bug in the WPF designer, as already reported here on Microsoft Connect. It seems that the designer falsely gives an warning or error, but eventually the code is okay, so it compiles and works. Nothing you should worry about now, since the product isn't released yet.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 11, "tags": "c#, wpf, xaml" }
Mysql query efficiency We have a table called product with productID as primary key. Then we have table called productProcess where store the productID and processID. So now we want to search all productID which does not have an instance in the productProcess table. Currently we run two query first all the product and second is the productID from productProcess and those does not exist is selected. Is there any other mechanism for this?
Yes, there is. Use `LEFT JOIN` SELECT a.* // this will get all columns from product table. FROM product a LEFT JOIN productProcess b ON a.productID = b.productID WHERE b.productID IS NULL * SQLFiddle Demo To further gain more knowledge about joins, kindly visit the link below: * Visual Representation of SQL Joins Another tip to make if faster is to set `productID` of table `productProcess` a foreign key.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": -3, "tags": "php, mysql, sql, join" }
Does NLog raise an event when something is logged? I want to be able to catch this event in order to not only log the message but to insert this message into a ListView simultaneously. Is there such an event?
The comments are right, but to elaborate: In NLog log-events aren't event-driven (there are no event handlers), but route-driven. So every event is matched to the defined routes (the `<rules>` in your nlog.config). With the routes you can send the log-events so 0, 1 or multiple targets and create fallbacks, filtering etc. So if you need the logevents in a ListView, you need to search for a target to use or write a custom one. Full list of targets are here: < Writing a custom target is explained here: < Happy logging :)
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 7, "tags": "c#, logging, nlog" }
What is difference between __va() and phys_to_virt()? What is difference between __va() and phys_to_virt() ,what is need of these two separate implementation for same purpose, any difference between these two?
phys_to_virt and __va are preprocessor macros. phys_to_virt: #if !defined(CONFIG_MMU) #define virt_to_phys(address) ((unsigned long)(address)) #define phys_to_virt(address) ((void *)(address)) #else #define virt_to_phys(address) (__pa(address)) #define phys_to_virt(address) (__va(address)) #endif And __va #define __va(x) ((void *)((unsigned long) (x))) If CONFIG_MMU is not defined then are equals.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 5, "tags": "linux, memory management, linux kernel" }
Does each computer/smart phone use electromagnetic wave with different frequency to communicate when they're connected to a WLAN? I read some papers about WLAN and Wi-Fi. They say that modern WLAN/Wi-Fi uses a kind of technology called "OFDM(Orthogonal Frequency Division Multiplexing)". My understanding is: ODFM means that each host(PC, laptop, smart phone, etc.) uses electromagnetic wave with different frequency to communicate with the wireless router(or hotspot)?
> My understanding is: ODFM means that each host(PC, laptop, smart phone, etc.) uses electromagnetic wave with different frequency to communicate with the wireless router(or hotspot)? What OFDM does is split a single data stream to multiple frequencies. A host will use a range of frequencies to communicate to the WAP. Multiple hosts must share the frequency range, and only one host at a time uses that frequency range. Wi-Fi forces the hosts to take turns to share the frequency range.
stackexchange-networkengineering
{ "answer_score": 2, "question_score": 1, "tags": "router, wireless, ieee 802.11, cisco wireless" }
Unhandled exception System.OverflowException Value is either too large or too small for Int32 I have this `C#` code here, and what I'm trying to do is that when I put a number with many digits the application crashes and I want it to not crash but I don't know what to do, I tried changing the `.Parse` command but Idk which command to use instead. An example is that when I run the application I want to put a number like `564984894897987878` and I want the application to not crash, can someone help me, in this case, please? If you find a solution post it here including your code and my code too please and thank you?! int num; Console.Write("Please type your number here:"); num = Int32.Parse(Console.ReadLine()); if (num < 0) Console.WriteLine("This is a negative number!"); if (num > 0) Console.WriteLine("This number is a positive number");
You can use TryParse: Console.Write("Please type your number here:"); if(!Int32.TryParse(Console.ReadLine(), out num)) Console.WriteLine("Invalid number"); if (num < 0) Console.WriteLine("This is a negative number!"); if (num > 0) Console.WriteLine("This number is a positive number");
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#" }
When to use in-place layers in Caffe? By setting the bottom and the top blob to be the same we can tell Caffe to do "in-place" computation to preserve memory consumption. Currently I know I can safely use in-place `"BatchNorm"`, `"Scale"` and `"ReLU"` layers (please let me know if I'm wrong). While it seems to have some issues for other layers (this issue seems to be an example). When to use in-place layers in Caffe? How does it work with back-propagation?
As you well noted, in-place layers don't usually work "out of the box". For some layers, it is quite trivial (`"ReLU"` and other neuron activation layers). However, for others it requires special handling in code. For example, the implementation of `"PReLU"` layer has specific cache `bottom_memory_` member variable that stores information needed for backprop. You can see similar code for other layers that specifically test for `if (top[0] == bottom[0])` to see if the layer is used in an "in-place" case. Moreover, it makes little sense to have an in-place layer for which the input and output are of different shapes, thus layers such as `"Convolution"`, `"InnerProduct"`, `"Pool"` are not considered as candidates for "in-place" layers.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 23, "tags": "machine learning, neural network, deep learning, caffe, backpropagation" }
CAST as TIMESTAMP not working for some string formats I have a field in a BigQuery table that is a STRING but is actually a timestamp, of the format "2019-06-14T11:31:07". So I am using CAST(sign_up_date AS TIMESTAMP) to convert to a usable TIMESTAMP. This works perfectly in Legacy SQL, however, in Standard SQL, it brings up errors when the STRING is of the format "2019-06-14T09:09" (on the exact minute, missing ":00") or "2019-05-25T05:31:22.7263555" (as sometimes they come through with decimal seconds). Any idea on how I can get it to work in Standard SQL? Obviously I could just use Legacy SQL, but I want to write in Standard as there are other functionns that work better in that one. Thanks, Benji
Below is example for BigQuery Standard SQL #standardSQL WITH `project.dataset.table` AS ( SELECT "2019-06-14T11:31:07" sign_up_date UNION ALL SELECT "2019-05-25T05:31:22.7263555" UNION ALL SELECT "2019-06-14T09:09" ) SELECT sign_up_date, COALESCE( SAFE.PARSE_TIMESTAMP('%FT%R', sign_up_date), SAFE.PARSE_TIMESTAMP('%FT%R:%E*S', sign_up_date) ) AS sign_up_date_as_timestamp FROM `project.dataset.table` with result Row sign_up_date sign_up_date_as_timestamp 1 2019-06-14T11:31:07 2019-06-14 11:31:07 UTC 2 2019-05-25T05:31:22.7263555 2019-05-25 05:31:22.726355 UTC 3 2019-06-14T09:09 2019-06-14 09:09:00 UTC As you can see this will cover all three patters you presented in your question. If you will find more - you can add respective SAFE.PARSE_TIMESTAMP inside COALESCE
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "sql, google bigquery" }
How to build a kernel module I am trying to compile a hello world module given over here I have followed the following step. 1. Downloaded Linux kernel 2.6.35-rc5 2. extracted to directory /general/source/linux 3. Complied the entire kernel. 4. created a dir test in the linux folder. 5. Created and complied a hello world module as mentioned there. when I run the insmod command, I get this error insmod: error inserting 'hello.ko': -1 Invalid module format How do I sort out this error? Regards,
Ok the mistake that you are making is the kernel version. First try uname -r You would get the kernel version. The downloaded version mostly likely won't be the kernel version of your system. So change the make file to ifeq ($(KERNELRELEASE),) KERNELDIR ?= /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) .PHONY: build clean build: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules clean: rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c else $(info Building with KERNELRELEASE = ${KERNELRELEASE}) obj-m := hello.o endif Make sure the tabs are in the order as mentioned in the above script.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "linux kernel, linux device driver" }
Why does scrolling a UIWebView *feel* so much different than scrolling any other UIScrollView? I'm building an app that loads in a _small_ amount of simple HTML (locally) into a single full-screen UIWebView. I'm noticing that scrolling this web view _feels_ significantly different than scrolling any other UIScrollView. This does not appear to be a performance or a responsiveness issue, per se... It's just a matter of how the momentum plays out as you drag and flick the web view up and down. It just doesn't feel very "native" (for lack of a better word). It's like scrolling through molasses or pudding... kinda "sticky" and not as "slick" as you would like it to feel. Does anyone know what causes this? Is there any way to fix it, or at the very least make scrolling a UIWebView feel more "native"?
I have the same perception. It must have to do with the webView's scrollView deceleration rate. Just ran this test, and 1) it confirms our suspicion and 2) suggests a fix. I added a scrollView and a webView to my UI then logged the following: NSLog(@"my scroll view's decel rate is %f", self.scrollView.decelerationRate); NSLog(@"my web view's decel rate is %f", self.webView.scrollView.decelerationRate); NSLog(@"normal is %f, fast is %f", UIScrollViewDecelerationRateNormal, UIScrollViewDecelerationRateFast); The output confirms the guess about webView being more frictional: my scroll view's decel rate is 0.998000 my web view's decel rate is 0.989324 normal is 0.998000, fast is 0.990000 And suggests a fix: self.webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
stackexchange-stackoverflow
{ "answer_score": 55, "question_score": 33, "tags": "ios, cocoa touch, uiwebview, uiscrollview" }
Multiplying elements in two different lists then summing up the nested loop So I have two sets of nested lists: l = [[3,4,4],[1,2,1]] w = [[2,4,1],[3,1,3]] I want look at each nested list, multiply the two values of l and w (for example in first nested loop 3*2) then add them all up to make sure each nested list has a total area of less than 40. In the case of the first pair of lists `3*2 + 4*4 + 4*1 + 1*3 + 2*1 + 1*3` is 34 which is less than 40.
If I understand correctly, this should work just fine: summ = 0 for l_sub_list,w_sub_list in zip(l,w): #zip will join each element of l with w #element on the same index. for l_sub_val,w_sub_val in zip(l_sub_list,w_sub_list): print(f"{l_sub_val} * {w_sub_val}") summ += l_sub_val*w_sub_val print(summ) You can also go for shorter solution: flat_l = [x for sublist in l for x in sublist] #Creating flat list, with no sub lists. flat_w = [x for sublist in w for x in sublist] result = sum([l_number * w_number for l_number,w_number in zip(flat_l,flat_w)]) #Using comprehensive lists, to multiply elements from flat_l list by flat_w list elmeents. Then, summing it with sum function/ print(result)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "python, nested lists" }