INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Is it possible to "escape" a method name in PHP, to be able to have a method name that clashes with a reserved keyword? I'm doing MVC in PHP, and i'd like to have a list() method inside my Controller, to have the URL /entity/list/parent_id, to show all the "x" that belong to that parent. However, I can't have a method called list(), since it's a PHP reserved keyword. In VB.Net, for example, if I need to have something with a name that clashes with a reserved keyword, I can wrap it in [reserved_name]. In SQL, you can do the same thing. In MySQL, you use the backtick ` Is there some syntax in PHP that specifies "treat this as an identifier, not as a keyword"? (NOTE: I know I can use routes to do this without having a list() method. I can also simply call the action something else. The question is whether PHP provides this kind of escaping)
With variable names you can use the bracket signs: ${'array'} = "test"; echo ${'array'}; But PHP does not provide a method for escaping function names. If you want a 'user-defined' way of getting around this, check out this comment: <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 4, "tags": "php, escaping, keyword, identifier, reserved words" }
How to exit text files/logs when viewing them in Putty I'm new to putty. Connected to a linux server to view/read some files. So, I opened a text log file that is constantly being updated, so I'm getting new lines every second. Is there a shortcut/command to exit/close the file when viewing in putty? Thanks in advance. Edit: It was not "vim", but "tail -f" that I was talking about. Sorry for the confusion.
Found it. Ctrl+C is the shortcut.
stackexchange-superuser
{ "answer_score": 2, "question_score": 1, "tags": "putty, tail, logfiles" }
How do I show P(Z = z) if Z = X+Y, both random discrete variables. If Z = X+Y, and both are random discrete variables. How do I show ![enter image description here](
This needs just two steps: 1. split up into cases according to the possible values of $X$. (Whenever the goal formula involves a sum indexed by the values of $X$, you can guess this is probably involved.) 2. then notice that the condition “$X = x$ and $Z = x$” is equivalent to “$X = x$ and $Y = z-x$”. $$ \begin{align*} P(Z=z) & = \sum_x P(X=x\ \text{and}\ Z=z) \\\ &= \sum_x P(X = x\ \text{and}\ Y = z-x) \end{align*} $$
stackexchange-math
{ "answer_score": 2, "question_score": 0, "tags": "probability" }
How to prove 2-EXP != EXP I am guessing that this is correct for `3-EXP`, `4-EXP` etc... Basically I should find a problem in `2-EXP` that is not in `EXP`. Any examples ?
It is a direct consequence of the time hierarchy theorem: **Time Hierarchy Theorem** : if f and g are time-constructible functions and $f(n) \log f(n) = o(g(n))$ (e.g. $f(n) = n^2, g(n) = n^3$), then $DTIME(f(n)) \subsetneq DTIME(g(n))$
stackexchange-cs
{ "answer_score": 13, "question_score": 5, "tags": "complexity theory" }
How to get the web page to redirect? The thing is that is not working is that the page does not redirect to another page, weather if it is wrong or right. I want the page to redirect to another page if the user guesses the generated word right.
you just need to preventDefault the form submission, use this code to prevent it document.querySelector('form').addEventListener('submit', (e) => { e.preventDefault(); })
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "javascript, html" }
calculate age from database $day, $month, $year I'm trying to calculate age. I'm using this code and it works great for the sample birthdate, but I can't figure out how to get $birthDate to equal my three separate variables $day, $month, $year that are stored in my database for each user. How would I do this so $birthDate = $day/$month/$year and works with the age calculator below? <?php $birthDate = "12/17/1983"; $birthDate = explode("/", $birthDate); $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])-1):(date("Y")-$birthDate[2])); echo "Age is:".$age; ?>
this is tried and tested in my registration system //date in mm/dd/yyyy format; or it can be in other formats as well $birthDate = $_POST['month']."/".$_POST['date']."/".$_POST['year']; //explode the date to get month, day and year $birthDate = explode("/", $birthDate); //get age from date or birthdate $age = (date("md", date("U", mktime(0, 0, 0, $birthDate[0], $birthDate[1], $birthDate[2]))) > date("md") ? ((date("Y")-$birthDate[2])-1):(date("Y")-$birthDate[2])); use date time picker or validate the values being submitted via javascript to allow only valid dates
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "php" }
Given orthogonal basis what is the orthogonal complement? The question states: > Let $q_1,q_2,\dots,q_n$ be an orthogonal basis of $\Bbb R^n$ and let $S = \operatorname{span}\\{q_1,q_2,\dots,q_k\\}$, where $1 \le k \le n-1$. Show that $S^\perp = \operatorname{span}\\{q_{k+1},\dots,q_n\\}$. I am not sure what the answer should really be. I know that if $S=\operatorname{span}\\{q_1,\dots,q_k\\}$ then $S^\perp$ must be the span of vectors that are orthogonal to each vector in $S$. Other than using this logic I am not sure how to prove $S^\perp = \operatorname{span}\\{q_{k+1},\dots,q_n\\}$. Should I show that if $S$ is a subset of $\Bbb R^n$ then the union of $S$ and $S^\perp$ creates the basis in $\Bbb R^n$?
HINTS: 1. Is it true that every vector in $\operatorname{span}\\{q_{k+1},\dots,q_n\\}$ is orthogonal to every vector in $S$? If so, then you know that $\operatorname{span}\\{q_{k+1},\dots,q_n\\}\subseteq S^\perp$. 2. Suppose that $v\in\Bbb R^n\setminus\operatorname{span}\\{q_{k+1},\dots,q_n\\}$. Write $v=a_1q_1+\dots+a_nq_n$ for some scalars $a_1,\dots,a_n$. There must be some non-zero $a_i$ with $i\le k$; why? That implies that $v\notin S^\perp$; why? Finally, why does this imply that $S^\perp\subseteq\operatorname{span}\\{q_{k+1},\dots,q_n\\}$? Now put (1) and (2) together to conclude that $\operatorname{span}\\{q_{k+1},\dots,q_n\\}=S^\perp$.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "numerical methods, numerical linear algebra" }
Why is Rails generating incorrect SQL for an order by clause? Why is Rails 3.2.14 generating an incorrect order by clause for this relationship? What is going on here? > 2.0.0p247 :306 > u.comments.order(created_at: :desc) > > Refinery::Groups::Comment Load (0.3ms) SELECT `refinery_groups_comments`.* FROM `refinery_groups_comments` WHERE `refinery_groups_comments`.`user_id` = 56 ORDER BY '---\n:created_at: :desc\n'
In Rails 3.2 and older, `order` expects a string: u.comments.order("created_at desc") The `order(created_at: :desc)` style was added in 4.0.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql, ruby on rails, ruby on rails 3" }
Visual Studio not supporting XSLT 2.0 i am using visual studio 2010 . when running xslt2.0 in that getting below errors > xsl:value-of/* ** is not yet implemented. > > 'xsl:result-document'** is not yet implemented. can any one help me to reslove the above issues
If you want to use XSLT 2.0 you need to switch from XslCompiledTransform to an XSLT 2.0 processor like the .NET version of Saxon 9 or like AltovaXML or like XmlPrime. Microsoft's XslCompiledTransform is an XSLT 1.0 processor, even in .NET 4.5/VS 2012. However the named XSLT processors mainly allow you to write code using XSLT 2.0, I don't think they integrate in VS 2010.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "c#, c# 4.0, xslt, c# 3.0, xslt 2.0" }
Vim - editor and shell side by side Is there a way to have a text file open in Vim, and have the shell open next to it in the same window? I find myself opening a script for editing, making changes, closing Vim, running the script to test it, then opening Vim again, over and over. I suppose I could have two separate windows with a shell in one and Vim in the other but that somehow feels clunky (I guess I'm too used to IDEs). The real problem, however, is that I am using SSH to connect to a remote machine, and having two separate windows with two separate SSH sessions seems not just clunky but actually Wrong. Is there a better way or am I stuck with two windows/SSH sessions?
I'd say the tool you're looking for is tmux. tmux will allow you to have 2 (or many more) sessions running at once, either in splits on your screen or in sessions that you can easily switch between. So yes, you can have vim on the left and the shell on the right and easily switch between them. This is all extremely handy, but the best feature when working remotely over ssh is that the sessions continue if you lose your connection - you just reconnect, then `tmux a` to reopen your existing session, containing vim, long running install or build scripts, whatever. A quick and easy guide to using tmux
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 3, "tags": "linux, shell, vim, ssh, tabs" }
Reading in SVM files in R (libsvm) The data files from < are in 'svm' format. I am trying to read this in to sparse matrix representation in R. Is there an easy/efficient way to do this? Here is what I am doing now: read in file line by line (800,000 lines), for each line separate classes, values, and cols. Store the classes as a list and the features as a .csr sparse matrix (1 row), then rbind the feature row with all previous rows. This is terribly inefficient and basically won't finish (12 minutes for 1000 lines). I think it comes from rbinding the sparse matrices once the number of rows starts to get large. Note: the matrix (800000*48000) is too big to build and then convert to sparse format. Thanks!
The `e1071` package has a means for exporting to the libsvm "svm" format in the `write.svm` function. But to the best of my knowledge, there is no `read.svm` function.
stackexchange-stats
{ "answer_score": 4, "question_score": 7, "tags": "svm, matrix, dataset" }
How to use Inf with lubridate and dplyr case_when I want to build a custom function which returns a date x years ago, or in the case the x supplied is infinite, reverts to a special date. I'm using `dplyr` and `lubridate`. Here is a trivial example: foo <- function(years_ago) { case_when( years_ago == Inf ~ as.Date("1800-01-01"), TRUE ~ Sys.Date() - years(years_ago) ) } `foo(1)` duly returns the date 1 year ago. However, `foo(Inf)` gives me the error: `argument is not interpretable as logical`. It seems that R jumps to evaluate the TRUE line of the case_when statement, even when the first condition is met. Is there any way I can get these tidyverse functions to play nicely, or do I need to find a workaround in base R?
`case_when` always evaluates both conditions. So while it would be intuitive to assume that if your value is `Inf`, the case when would not evaluate the second line, it actually does. And then the problem is that the `years` function can't handle infinite values. What you could do in the case_when, is to simply add an ifelse command that makes sure the years function is only run on values that are not infinite. foo <- function(years_ago) { case_when( years_ago == Inf ~ as.Date("1800-01-01"), TRUE ~ Sys.Date() - years(ifelse(is.infinite(years_ago), 0, years_ago)) ) } Some examples: foo(1) [1] "2021-06-24" foo(Inf) [1] "1800-01-01" foo(0) [1] "2022-06-24"
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "r, dplyr, lubridate" }
how do i solve the deprecation warning while compiling what does this warning mean and how to resolve it. Is it something I should worry about. I've tried reading the webpack's documentation. ![Compilation warning message](
You don't actually have to worry about deprecation warnings, from time to time some or the other library will adapt to something new and deprecate the previous (it will work fine though) for various reasons like security loopholes, performance or something better. Your warning appears to be related to html-webpack-plugin In your webpack.config add the stats property like below to suppress warnings module.exports = { entry: './index.js', stats: { warnings:false } } Also, try uninstalling your html-webpack-plugin and install latest || upgrade to fix it `node --trace-deprecation ./node_modules/.bin/the_library_name_here` will list all deprecations You could do `npm outdated` to check the latest versions. or simply `npm update --force` as well to update.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "javascript, node.js, webpack" }
Cakephp default index action and paginator By default the 'index' action in my EventsController (or any Controller) returns the full set of entries and I want to display only the events created by the currently logged in user (the associations are well defined and my events table has a foreign key `user_id`). here is the default index action as generated from the cake bake console command: class EventsController extends AppController { public function index() { $this->Event->recursive = 0; $this->set('events', $this->paginate()); } .... } There might be something with the `$this->paginate()` that I don't understand, 'cause already I tried to retrieve the entries I need using `$events = $this->find('all',$options)` and it didn't do anything. Is there a way to specify my conditions as to which entries will be returned to the view?
The way to set conditions to the pagination is in the docs. Basically, if you have the user id in a variable `$userID` and the events have a `user_id` column, you could do what you ask like this $this->set('events', $this->paginate('Event', array('user_id'=>$userID)));
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "cakephp, cakephp 2.0, cakephp 2.1" }
Search for lines that contain anything but alphabetic characters, dots and hyphens I'm struggling to create a RegEx pattern to match lines that contain anything but `a-zA-Z` , `.` and `-` So I don't want to match `hello-world.txt` , but I would like to match `hello-world123.txt` or `hello-world(copy).txt`
Just need match full string with: * `/^[a-zA-Z.-]+$/` * `[a-zA-Z.-]` \- match any of those characters * `+` \- repeat one or more * `^`, `$` \- anchor to start and end of the string
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "regex" }
How does an RMI respond when tuned to a VOT station? I know that a VOT station for testing VORs broadcasts a 360 radial signal, so on a VOR, the indication would be 360 with a 'FROM' or 180 with a 'TO' indication, but how does an RMI respond if tuned to a VOT station? Would the RMI simply home to the station because it points to the _direction signal is coming from_ , or would it point at the 180 position because it detects that it is on a 360 radial 'FROM' the station?
Yes, it will point at the 180 position VOR Test > A VOT differs from a VOR in that it replaces the variable directional signal with another omnidirectional signal, in a sense transmitting a 360° radial in all direction VOR Receiver Check > With the Course Deviation Indicator (CDI) centered, the omni−bear- ing selector should read 0 degrees with the to/from indication showing “from” or the omni−bearing selector should read 180 degrees with the to/from indication showing “to.” **Should the VOR receiver operate an RMI (Radio Magnetic Indicator), it will indicate 180 degrees on any omni−bearing selector (OBS) setting.**
stackexchange-aviation
{ "answer_score": 2, "question_score": 1, "tags": "rmi" }
How to efficiently determine if a string starts with a number and then get all following numbers up until the first non-numeric character? I have a requirement to sort some strings that contain data like this: var strings = new List<string>{"2009 Arrears","2008 Arrears","2008 Arrears Interest","2009 Arrears Interest"}; And they want the results ordered like this: 1. "2009 Arrears" 2. "2009 Arrears Interest" 3. "2008 Arrears" 4. "2008 Arrears Interest" It seems like I need to create a function to see if the string starts with a number. If so, the function will get all numbers up until the first character and sort the numeric result descending and then sort the remaining characters ascending. I am having trouble trying to write a method that gets all starting numbers in a string. What would be an efficient way to do that?
public int GetLeadingNumber(string input) { char[] chars = input.ToCharArray(); int lastValid = -1; for(int i = 0; i < chars.Length; i++) { if(Char.IsDigit(chars[i])) { lastValid = i; } else { break; } } if(lastValid >= 0) { return int.Parse(new string(chars, 0, lastValid + 1)); } else { return -1; } } Though this would strictly be the most efficient, the regular expression solutions offered by other posters is obviously more concise and could be clearer, depending on how much processing you'll do on the string.
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 7, "tags": "c#, string" }
php array_unique combined with array_filter, incorrect output In a database table are multiple entries related to a customer. Each entry will have time_1, time_2, time_3, time_4, time_5 and time_6 fields. I have looped through the entries and used this to combine these times to create a round cycle for a day: while($row=mysql_fetch_assoc($script_check)) { $prerounds = array_filter($row); $rounds = array_unique(array_merge($prerounds)); } This works however if one entry has times 1-4 set and the second entry has times 1-3 set the fourth time will be totally removed thus only times 1-3 are put into the array. How can I combine these fields without losing data when some are blank? This strategy so far has been to strip the $row of all blanks then merge it together to create one set of round times related to that customer for that day. Thanks.
As the OP requested: Basically, your main problem is you're re-initializing `$rounds` on each iteration, you're not merging any existing array with a new one. $rounds = array(); while($row = $pdo->fetch(PDO::FETCH_ASSOC)) { $rounds = array_merge($rounds, array_unique(array_filter($row))); } Hmz... apart from `mysql_*` being deprecated (that's why I used PDO in my snippet), you should really check your logic... perhaps a decent query might be more suitable, or a simple set of `if`'s. It's even likely to be faster that way
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, arrays" }
how single irq line is shared at physical hardware among multiple devices I want to know how one single irq line is shared among multiple devices, i mean how they are physically connected at hardware level, do they use multiple APIC controllers for this, or what other methods are used.
The most basic way to connect multiple devices to a single interrupt request line, so that every device can activate a request, is to use open collector. When the request is granted, the acknowledge signal may be forwarded from device to device using a daisy chain#Computer_hardware).
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "hardware, interrupt, pci, irq, apic" }
Thymeleaf code in Spring Boot attribute model is it possible to sent thymeleaf code via attributeModel to View, to be treated like standard code? I would like to load a piece of code(thymeleaf fragments) in different places only when it is needed. But when I try this: Spring Boot Controller: model.addAttribute("fragment", "<th:block th:include=\"fragments/header :: body\"></th:block>"); View: <div th:text="${fragment}"></div> In WebBrowser as a TEXT I have: <th:block th:include="fragments/header :: body"></th:block> Can I force re-render? And how can I do that? But if it is not possible, what can I do in replace?
Every thing that `th:text` parse, set to `innerHTML` and not rerendered. You can set parameter in your `controller` and then check in `Thymeleaf` if that set, then include or replace your fragment. like this: **Controller** model.addAttribute("isFragmentBodyShow", true); **View** <th:block th:if="${isFragmentBodyShow}" th:include="fragments/header :: body"></th:block> You can also send fragment name from `contoller` to `Thymeleaf` and use it in `th:include` for dynamic template include.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "spring, spring boot, thymeleaf" }
Make it possible for guests to add entries via "template-generated" form in expression engine? I'm trying to figure out how if it is possible to provide guests (regular visitors) to my site with a form via the regular templates and let this form submission create an entry to a specified channel. In essence, I would like to make a channel entry using a simple http-request and render a "frontend" response-page i suppose. Does anyone know about any neat solutions for this?
EE doesn't support this out of the box - all users must be logged in order to allow them to modify channels/weblogs There's a few plugins - < is one of them that allow "fake" users being logged in Mix that up with SAEF and you might achieve what you want
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "codeigniter, expressionengine" }
JavaScript как построить пирамиду из чисел без повторения Всем доброго времени суток! Прошу помощи так как просидел слишком много часов и никак не найду решения. Нужно построить пирамиду из чисел таким образом: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 И так далее. Суть в том, что сколько цифр в текущей строке столько раз ее повторить но без повторения чисел. Вот что у меня есть(но работает не совсем так как я хочу) var n = prompt("Введите число"); for (var i = 1; i <= n; i++) { for (var j = 1; j <= i; j++) document.write(' ' + j + ' '); document.write('<br>'); } Заранее благодарен!
Алгоритм то вроде не сложен. Вам надо выводить 2 строки по 2, 3 строки по 3, 4 по 4 и так далее. Значит, надо считать выводимые строки. И когда счетчик такой станет равен длине строки, длину увеличить, а счетчик сбросить. Вот собственно и все. В данном решении `n` \- максимальное число. Вернее сказать, данный алгоритм выводит всю строку, содержащую это число. `i` это сами выводимые значения, `len` \- текущая длина строки, а `c` это текущий счетчик строк такой длины. var n = 100, i = 1, len = 1, c = 0 ; while(i < n){ if(c == len){ len++; c = 0; } let row = []; for(let k = 0; k < len; k++, i++) row.push(i); c++; console.log( c + '/' + len + '| ' + row.join(',') ); }
stackexchange-ru_stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "javascript" }
May accounts use ed25519 Is it possible to use ed25519 for account key pairs on a substrate based blockchain instead of the default?
Sure, it's totally possible. This is how moonbeam did to use ECDSA. < < Basically, you just need to define the `Ed25519Signature` and implement those traits. And let the `<<Ed25519Signature as Verify>::Signer as IdentifyAccount>::AccountId;` as your `AccountId`.
stackexchange-substrate
{ "answer_score": 1, "question_score": 0, "tags": "cryptography, key" }
How to configure a calendar to accept only a limited number of items Can anyone advise if it's possible to configure a SharePoint 2007 list so that only accepts a specific number of entries on a specific date? I have a calendar that has been set-up as a seminar self booking facility. Each seminar has a specific number of seats. I'd like to know if it's possible to hide or bar submissions for entries on a specific day once the seating limit has been reached. I don't have access to Visual Studio but I can use SPD, JQuery and so on.
On the NewItem form and with jQuery and/or SPServices, query the list on date selection, and set validation against posting the new item. Just have an event fire whenever the date changes to query the calendar, then if it pulls back a bool of items.count > value, set validation, and display validation text, and disable the Save button. Here's the SPServices library and function that I would start with, GetListItems:<
stackexchange-sharepoint
{ "answer_score": 1, "question_score": 0, "tags": "2007, calendar" }
How to insert a value to a particular row in a DataTable C# Please help me with a code snippet to insert a value to a particular row which already exists in my DataTable . DataRow myrow; for (i = 1; i <= cnt2+1; i++) { myrow = finalRprt.NewRow(); for (j = 1; j <= lstSubName.Count + 4; j++) { myrow[j] = "-"; } finalRprt.Rows.Add(myrow); } Now I want to add a value to the particular row depending on a condition. How can I do
This question is quite vague. But you can for example use the `DataRow.SetField` extension methid to set a field of a `DataRow`. You can either use the indexer to get a row of a `DataTable` or use `Linq-To-DataTable` to find the rows you're searching for. DataRow row = table.AsEnumerable() .Where(r => r.Field<int>("ID")==ID) .Single(); row.SetField("Name", newName); Generic Field and SetField Methods (LINQ to DataSet) Now you need a `DataAdapter` to update your database (if you want).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, ado.net" }
iPhone app user review request from code Can I request the user of my iPhone app to submit a review about the application?
Yes. Lots of apps do this. If you are going to ask for a review, make sure you include a link to the app store.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "objective c, iphone" }
Включение файлов С++ Как исключить круговое включение файлов в C++ и C при использовании директивы #include?
Существует два стандартных способа решения этой проблемы. Первый, непортируемый, - использование директивы `#pragma once` в начале `.h` файла. Второй - использование деректив `#ifndef #define #endif`. Например, если мы имеем .h файл с именем `SomeClass.h`, то его следует оформить следующим образом: #ifndef _SOME_CLASS_H_ #define _SOME_CLASS_H_ // all SomeClass.h content #endif /* _SOME_CLASS_H_ */
stackexchange-ru_stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "c, include, c++" }
converting office documents to html5 I am working on a project, and I need something like office web app , I don't know if I can make it myself , how to read office file formats and convert it to html5.
It's a very significant project to convert arbitrary Office documents to HTML 5. Office itself can generally save in HTML format. You can most likely use the Interop libraries provided by the various Office products to save as HTML. Look at: < If you want to do this from scratch (without using an existing implementation or the Interop libraries), you can look at the Open XML format <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "html, ms office" }
Random Int IllegualArgumentException I am using this code to using a Random generator to generate random positions. But i keep getting this error 11-06 21:33:07.364: ERROR/AndroidRuntime(12796): java.lang.IllegalArgumentException 11-06 21:33:07.364: ERROR/AndroidRuntime(12796): at java.util.Random.nextInt(Random.java:186) Here is the code i am using. private void addFace() { Random rand = new Random(); float x = (int) roof.getHeight() + mBallTextureRegion.getWidth(); float minY = mBallTextureRegion.getHeight(); float maxY = (int)(roof.getHeight() - mBallTextureRegion.getHeight()); float rangeY = maxY - minY; //The error points here float y = rand.nextInt((int)rangeY) + minY;
That means that rangeY is negative. Check the logic that you're using to assign that value.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "android" }
vuejs 3 version for this main.js Below code is in Vue 2 version. Can someone tell me what is the Vue 3 version for this main.js please. sorry if my english is bad. i want to change my tutorial project to Vue 3 because Vue 2 has so many errors in console that i can't solved. import Vue from 'vue' import App from './App.vue' import './registerServiceWorker' import router from './router' import store from './store' import axios from 'axios' import VueAxios from 'vue-axios' Vue.config.productionTip = false Vue.use(VueAxios, axios) new Vue({ router, store, render: h => h(App) }).$mount('#app')
This option is possible import { createApp } from 'vue' import App from './App.vue' import './registerServiceWorker' import router from './router' import store from './store' import axios from 'axios' import VueAxios from 'vue-axios' const app = createApp(App) app.use(VueAxios,axios) app.use(store) app.use(router) app.mount('#app')
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "vue.js" }
Xcode 12 failed to build cocoa pods - generate umbrella header When updating to XCode 12, the project stopped working. Not able to build the project. Number of errors occurred stating failed to build cocoa pods generate umbrella header
To solve this issue, follow the below steps 1. Go to pods ![enter image description here]( 2. Select build settings 3. Search **quoted** 4. Set value of **Quoted include in Framework Header** to **No** ![enter image description here]( 5. Clean and Run the project.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "swift, firebase, cocoapods, ios14, xcode12" }
Quote all fields in CSV output @out = File.open("#{File.expand_path("CSV")}/#{file_name}.csv", "w") CSV::Writer.generate(@out) do |csv| csv << ["01", "02", "test"] end @out.close When i run above code it stores the values in CSV as 01, 02. test I want them to store as "01", "02", "test"
Change CSV::Writer.generate(@out)do |csv| to CSV::Writer.generate(@out, {:force_quotes=>true}) do |csv|
stackexchange-stackoverflow
{ "answer_score": 24, "question_score": 14, "tags": "ruby, csv" }
hindi font slug convert <script type="text/javascript"> $("#title").keyup(function () { var str = $(this).val(); var trimmed=$.trim(str) var slug=trimmed.replace(/[^a-z0-9-]/gi, '-'). replace(/-+/g, '-'). replace(/^-|-$/g, ''); var check =slug.toLowerCase(); $("#slug").val(slug.toLowerCase()); }); </script> I am able to convert english alphanumberic . BUt not able to convert hindi fonts like : > अत्याधुनिक प्रविधि भित्र्याइँदै
Now its work for me . I can convert Hindi and English text to slug. <script type="text/javascript"> $("#title").keyup(function () { var str = $(this).val(); str.replace(/[`~!@#$%^&*()_\-+=\[\]{};:'"\\|\/,.<>?\s]/g, ' ').toLowerCase(); str.replace(/^\s+|\s+$/gm,''); var slug=str.replace(/\s+/g, '-'); var trimmed=$.trim(str) var check =slug.toLowerCase(); $("#slug").val(slug.toLowerCase()); }); </script>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 3, "tags": "javascript" }
Using IF ELSE CONDITION inside SELECT STATEMENT in Stored Procedure I am a beginner in STORED PROCEDURE, So I am curious about IF ELSE Condition Inside the Select Statement, Can I Use this Condition Inside it or Not? example: `SELECT FName from USER IF LNAME = 'SAMPLE'`. `A man who asks is a fool for five minutes. A man who never asks is a fool for life. - Chinese Proverb`
What you have mentioned in the question goes in the `where` clause of the select statement. Basic select statement would look something like this: SELECT <COLUMN NAMES YOU WANT TO RETURN IN RESULT> FROM <TABLE FROM WHERE THE DATA SHOULD COME> WHERE <SOME CONDITION YOU WANT TO LIMIT DATA BY> So your query becomes, SELECT FName from USER WHERE LNAME = 'SAMPLE' There are plenty of resources where you can start learning. MSDN would be the first place to look at basics and then you can go to advanced concepts elsewhere.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "stored procedures" }
Is it possible to automatically return to my app after setting a social account for Social.framework? In my app I'm using the Social framework to share status updates on Facebook and Twitter through an SLComposeViewController. If the user doesn't have an account set up, he receives an alert that lets him go to the settings page. Is there a way to automatically return to my app after setting up the account?
Simply put: no. There is no call of action to navigate the user from settings to your app. You have to have faith the user will navigate to your app
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, facebook, twitter, social framework" }
Get difference between date returns zero I have a date time in 'Y-m-d H:i:s', and i tried to substract the now date with the defined date +1 day to get remaining time in hours, minutes and seconds: $time = '2017-10-05 14:54:03'; $now = date('Y-m-d H:i:s'); $endTransaction = date('Y-m-d H:i:s', strtotime($time. ' + 1 day')); $dteDiff = $endTransaction - $now; echo $dteDiff; but i always get 0 as the result
You are doing it wrong. The `date` function returns string so PHP is not able to compare anything. Try with the DateTime class instead. Its diff method returns the DateInterval object with some public properties, like the `days` property among others, which is the positive integer number (rounded down) of days between two dates: $now = new \DateTime(); $endTransaction = (new \DateTime('2017-12-05 14:54:03'))->modify('+1 day'); $diff = $endTransaction->diff($now); printf( 'Difference in days: %d, hours: %d, minutes: %d, seconds: %d', $diff->days, $diff->h, $diff->m, $diff->s );
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, datetime" }
putting d3.js elements on the slider Please first take a look on this picture : < Now i want to make something like that but i want to put d3.js elements on a slider like that instead of images like a rectange, circle, square, triangle so that user can move them with arrow buttons shown in the image. I just wanted to know if it is possible with d3.js and if Yes, please tell me how or from where to start?
You could make something like that using D3. One way you could do it is to draw the tiles as rectangles using SVG and then have a clip path that hides the tiles that are outside of the frame of what you want to see. The left and right arrows would update the xScale domain which would slide the tiles left and right. And, you can register click events on the rect elements to create links on the tiles. See this for some ideas on how to start: < If you aren't already somewhat familiar with d3, you should probably start with a basic tutorial like: < before you dive into the deep end.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, html, css, d3.js" }
Click and Drag using jQuery I'm trying to make an element respond when the user clicks **and** drags the mouse. I need the response to happen every `mousemove` while the single `mousedown` event is happening. I'm using jQuery, but I'm open to a pure JS implementation as well. Here is what I've tried: $('.element').on('mousedown', function (e) { $('.element').on('mousemove', function (e) { console.log("response"); }); $('.element').off('mousedown'); }); This works, but it will work after I clicked once, even if I don't keep doing the `mousedown`.
Hook into the `mouseup` event and unbind the `mousemove` there: $('.element').on('mousedown', function (e) { $('.element').on('mousemove', function (e) { console.log("response"); }); }).on("mouseup", function(e) { $('.element').off('mousemove'); });
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javascript, jquery" }
Using NSComboboxCell with NSTableView I'm struggling to get a `NSComboboxCell` to display the options I'm expecting when loading from a `NSArray`. - (IBAction)addProjector:(id)sender { Projector *p = [[Projector alloc]init]; [p setIpAddress:[_ipAddressTextField stringValue]]; NSComboBoxCell *n = [[NSComboBoxCell alloc]init]; [n addItemsWithObjectValues:wuAvailable]; [p setGType:n]; [_list addObject:p]; [_tableView reloadData]; } `wuAvailable` is an `NSArray` of `NSStrings`. When the App's loaded I'm not seeing my strings as options just get "Field" an no other options. Image below shows the problem. Any help would be gratefully recieved. ![](
Unless you’ve done something magic to make the cell ’n’ you create appear in the tableView, it’s not going to. So, it doesn’t matter what array you assign it. If you’ve already set up the tableView with the tableColumn that has an NSComboBoxCell in it, then you can modify that cell in your code by getting the ‘tableColumn.dataCell’ and setting properties on it. You can get the tableColumn by its identifier from the tableView—your controller should have an IBOutlet onto the tableView.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "objective c, cocoa, xcode5" }
Logic - How to say "Not only but also". I am trying to translate an English sentence into propositional logic. "To limit the loss of our company, not only the economical and statistical researches are necessary, but also a change in our spending patterns." L: Limiting the loss of our company E: Economical researches S: Statistical researches C: Change in our spending patterns $ (E \land S \land C ) \Rightarrow L$ I think that this conveys the meaning that we need to do all 3 to be able to limit the loss, but I am not sure it conveys the meaning that only E and S won't be enough. Do I have to find a way to include them into the formula, and if so how could I do that?
It is in fact the other way around. If you want to say "$\psi$ is necessary for $\varphi$", then this translates to $\varphi \rightarrow \psi$ (see < for the distinction between the terms "necessary" and "sufficient"). This means that your answer is almost correct, but you need to change the order of implication: $$L\rightarrow (E \land S \land C)$$ Edit: One way to see it in this example is to use the following interpretation of implication: $\varphi \rightarrow \psi$ means that "either $\varphi$ does not hold or $\psi$ holds". In your example, this translates to the following: "Either we do not limit the loss of our company, or we perform economical and statistical researches, and change our spending patterns." This is equivalent to the English sentence you started with because "not only but also" is equivalent to "and".
stackexchange-math
{ "answer_score": 20, "question_score": 11, "tags": "logic, propositional calculus" }
How to backup and restore localDb 2012 Database? I try to backup my localDB file using `file.Copy()` method but it throws the following `IOException`: > The process cannot access the file '.\DB.mdf' because it is being used by another process. And when I try to do backup with the following script: @"BACKUP DATABASE " + DatabaseName + " TO DISK = N'" + BackUpLocation + @"\" + BackUpFileName + @"'" it throws the following `SqlException`: > Database 'DB' does not exist. Make sure that the name is entered correctly. My connection string is: Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\DB.mdf;Integrated Security=True;Connect Timeout=30 What is the best way to do backup in this situation?
Use the full path od your mdf (e.g. `C:\DATA\DB.MDF`) as the database name in your `BACKUP DATABASE` command.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "c#, database, visual studio, backup" }
split string into the string and digits I'm trying to split this string (`incoming_string`) to digits and string to the next view (`result`): `incoming_string = '02, 102, 702New York' # Also possible incoming strings: '06, 25Jerusalem' or '34Saint Luise'` `result = {'New York': ['02', '102', '702']}` I'm found this approcach, but I think this is not a best way: import re digits = re.findall('\d+', incoming_string) # ['02', '102', '702'] strings = re.findall('[a-z, A-Z]+', incoming_string)[-1] # 'New York' By best way I mean a most concise, understandable and pythonic way, preferable without imports. All symbols are the same encoding (ascii)
The trouble is finding the index where the list stops and the key value starts. We can make a function that helps us find the first "non-list character". Then it's a matter of splitting the string in two using that index, after which we can split the first part into a list using the `", "` delimiter. def get_first_non_list_char_index(incoming_string): for i, c in enumerate(incoming_string): if c not in "1234567890, ": return i incoming_string = "02, 102, 702New York" char_index = get_first_non_list_char_index(incoming_string) result = {incoming_string[char_index:]: incoming_string[:char_index].split(", ")} `result = {'New York': ['02', '102', '702']}`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, regex" }
Turning back from update on SQL Server There is any code from backing from update on SQL Server. I mean without triggers and logs. KR, Çağın
If you happen to have change data capture or audit logging, you can easily recover from a bad change. Or as suggested you can restore yesterday's backup to another instance and then copy the data as much as possible. If you don't have any of these things, perhaps you need to them set up for future problems. Or maybe even hire a database professional so you don't get caught like this again. And of course, take all update, delete and insert rights away from application ddevelopers on production. Sometimes the best thing you can do is at least learn from your mistakes and make the system better for the next time.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql server, tsql" }
Most efficient way to delete data I am working on a forum system and I need to delete all topics and posts from a particular forum. There is a `posts` table that holds all the posts. Each post has `topic_id` field which is the ID of the topic to which it belongs. The topics reside in `topics` table and each topic has `forum_id` field which is the ID of the forum it belongs to. So now when I decide to delete forum with ID `1`, how would I go about deleting all topics and posts from this forum as well?
First of all I recommend you take a good look at your data structure: If you use foreign key constraints of the `ON DELETE CASCADE` flavour, your sub-deletes will automatically be done for you - and this just one of the advantages you get. If for some reasons you can't or don't want to employ such constraints, start by taking a look at how you would select the relvant topics and posts. This should give you quite a good start. In your particular example something like DELETE FROM posts WHERE topic_id IN ( SELECT id FROM topics WHERE forum_id=[id-to-delete] ) and then DELETE FROM topics WHERE forum_id=[id-to-delete] should do the trick. Please understand, that I don't recommend that. Use data consistency tools for data consistency.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": -1, "tags": "mysql" }
Pass values from one page to another without form and without passing in URL I am working on a project where i need to access clean URL's always i.e no parameters can be passed in the URL for getting values on another page. Can anyone please suggest an alternative other than 'Form Submit' method. Thanks In Advance.
For Clean URL's i prefer you may use **HTTP POST** Method. Hope that helps. <form name="frmApp" method="POST" action="/action.php"> </form> Else, you can use **AJAX** with **jQuery** to submit the values to another page. $.ajax({url:"action.php",success:function(result){ $("div").html(result); }}); Check out w3schools to get started with AJAX : < No support for **SESSION** since i don't like writing **php** code inside my web page.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "php, forms, url, post, submit" }
How do I know coordinates of both ends of cylinder I want to show text top of cylinder How do I know coordinates of both ends of cylinder?
The standart Unity cylinder is 2 units talls (when local scale is 1). So top end is y+1 and the bottom is y-1. C# code to get top and bottom points: `Vector3 MyCylinderTopSpot = Cylinder.transform.position + (new Vector3(0, 1, 0) * Cylinder.transform.localScale.y); //Cylinder type is GameObject` `Vector3 MyCylinderBottomSpot = Cylinder.transform.position + (new Vector3(0, -1, 0) * Cylinder.transform.localScale.y);`
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "unity3d" }
Creating a GeoExt Action from OpenLayers Function I am trying to create a GeoExt function out of this OpenLayers function, which displays the getFeatureInfo. I was able to create this GeoExt.Action() but it does not give me any output. Any idea where am I going wrong? This is the function addToPopup(). This is my application, `
It seems that you forgot to add `eventListeners` propperty to your `WMSGetFeatureInfo` control. Working code should looks like: control: new OpenLayers.Control.WMSGetFeatureInfo({ url: " eventListeners: { 'getfeatureinfo': function(evt) { var lonLat = evt.xy; addToPopup(lonLat, evt.text); } } }); !enter image description here
stackexchange-gis
{ "answer_score": 1, "question_score": 1, "tags": "openlayers 2, web mapping, wms, geoext, getfeatureinfo" }
Script to compare the "file size" with "last name of file" and if unmatched delete the file In my environment, we'll be receiving files from clients into our Sftp server. Sftp processes the files, and moves it to another tool, by appending the file size at the end of the file name. For example, `samplefile.20150706` of size 1024 would be created as `samplefile.20150706.1024`. If file size and name (the last part after `.`) matches, our tool will pick the file and send it to ETL. If the file stays in that place for more than an hour (not processed due to unmatched size and name), the tool will send us alerts, as files are over an one hour old. I'm looking for commands, which will extract the last part of the file name and compare it with file size, and eventually delete the file.
Get the file size: size="$(stat --printf="%s" "$path")" Get the path without the last extension: path_without_extension="${path%.*}" Compare the two: [ "${path_without_extension}.${size}" = "$path" ]
stackexchange-unix
{ "answer_score": 4, "question_score": 1, "tags": "shell script, find, filenames, size" }
Change text color based on background color? I've a pretty minimalistic site, so I want to add details to it, like a hidden theme switching. But I don't want to tell the user that the theme can be changed, so I want to hide the text. I've tried this: var tausta = $(body).css("background-color"); $('.piiloteksti').css("color",tausta); But it doesn't do anything. What would be the correct approach? A fiddle.
`if($('.piiloteksti').css("color",tausta);` is a **wrong** statement. Thats a syntax error! There shouldn't be any `if` here. Either remove `if` $('.piiloteksti').css("color",tausta); or complete the `if` statement. if($('.piiloteksti').css("color",tausta)){ // some other code } Also `$(body)` does not refer to anything. Use either `$('body')` or `$(document.body)`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, css" }
Git: git checkout with modified working tree and index I expect `git checkout <commit>` to flash both the working tree and index to the `<commit>` version. However, in some cases it will keep the current changes in both the working tree and index. For example: git branch br1 git branch br2 git checkout br1 <make change M1 to file foo> git add foo <make change M2 to file foo> git checkout br2 Now all the working tree/index changes made in branch `br1` are kept in the branch `br2`, as `git status` on `br2` won't give a clean message. I guess this is because the head of `br1` and `br2` originally have the same version of file `foo`, and Git can automatically detect this. Question: * When does Git decide not to flash the working tree and index? Are there any other corner cases?
The `git checkout` command actually has two different (common) operating modes. 1. If you run `git checkout <branch>`, then you will switch to branch `<branch>`. All changes to the working tree will be kept -- and this works by merging the uncommitted changes to the target branch, so it can fail. Changes in the index will be stashed. 2. If you run `git checkout <path>`, then git will wipe out the changes to `<path>` in both the index and the working copy by getting them from the current commit. So the purpose of `git checkout <branch>` is in case you decide that the changes you're making actually belong on a different branch.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "git" }
Inner private class and public method If I have something like this: public class Outer { private class Inner { public void someMethod() {} } Inner in = new Inner(); in.someMethod(); //What?? } Why doesn't last line code work?
> Why doesn't last line code work? Because it has to be wrapped within a block (initializer, constructor, method). For example (wrapper within a constructor): public class Outer { private class Inner { public void someMethod() {} } public Outer() { Inner in = new Inner(); in.someMethod(); } }
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -1, "tags": "java" }
.NET / COM events interoperability I have an interop assembly generated by TlbImp.exe, the generated classes are heavily evented and the performance is very important. But there's a problem, the events seem to be registered/unregistered/invoked in such a manner that even empty event handlers are counted in. Given a set of **1..N** events, when you register a handler to an event 3 it looks like this: {dummy1, dummy2, eventHandler3, dummy4 ... dummyN} Which generates a large overhead when there's a lot of events that get raised very often. So the question is, is there a better way how to work with COM events in .NET? Any tool or something or do I have to rewrite the event code of the interop assembly from scratch?
Solved by using custom `Advise`/`Unadvise` callbakcs.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, .net, com, interop, com interop" }
Where are the key frames in this animation? I have loaded an animation in Blender 2.83.0. When I press Play, I can see the animation playing. If I press the `Tab` key, my model goes into T pose. I would like to copy this T pose to the first frame of the animation. For some reason, I don't manage to show the key frames at all. I have selected "Dope Sheet", then "Action Editor", and then I selected various elements of the model. But I just don't see any key frames. How could I show them in order to replace them? ![enter image description here](
You have "Only Show Selected" turned on in the bar at the top of the Action Editor ![Only Show Selected]( If you switch to pose mode and select a bone, it will show you the curves for that bone only. You can turn it off to see all the curves instead.
stackexchange-blender
{ "answer_score": 2, "question_score": 0, "tags": "animation" }
Compilation error in maven I got the following error when I build my project with maven. I am using jdk 1.7.0_03 but it tells me like follows. [ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.0.2:compile (default-compile) on project sample: Compilation failure: Compilation failure: [ERROR] /home/dinithi/Training/Practise/Carbon_Assignment/LibrarySystem/Components/src/main/java/com/wso2/carbon/library/sample/LibraryManager.java:[11,7] error: generics are not supported in -source 1.3 I am using a HashMap in my code as follows. Map<String,Book> books=new HashMap<String,Book>(); Can someone help me with this error. P.S. I am using intellij idea as my IDE.
Add (or change) the source element to plugin configuration: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin>
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": -3, "tags": "java, maven, intellij idea, java 7" }
Creating instance in multi threaded environment I am using threaded timer which is creating new instance and call a method like below, Timer_tick() { Car C; C=new Car(); C.Start() /// this will take time to complete } My question is, there is another thread coming with next timer tick and perform same operation. Then the second thread remove the reference from first Car instance & it will call the start method on new Car instance, since first object does not finished his start method (still in progress) but it doesn't have the “C” variable reference anymore. Will this create any problem to first instance `Start()` method completeness or execution. Can it be collected by GC?
The `Car` instance is local to that particular call of the `Timer_tick()` function. Subsequent calls by other threads operate on their own instances of the `Car` object. However, it doesn't look like you're doing anything with the car after the function exits, it will eventually get garbage collected without having done anything to it besides running the start function. Is that what you intended?
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "c#, .net, multithreading, timer, instance" }
Initializing collections that contain nested collections How do I initialize a collection of 'Quote' objects based on the class shown below where 'Quote' would contain a collection of at least 5 'Rate' objects. List<Quote> quotes = new List<Quote> {new Quote { Id = 1, (need 5 Rate objects in here) } } public class Quote { public int Id { get; set; } public List<Rate> Rates { get; set; } } public class Rate { public int Id { get; set; } public string AccommodationType { get; set; } public decimal Price { get; set; } }
List<Quote> quotes = new List<Quote> { new Quote { Id = 1, Rates = new List<Rate> { new Rate { Id = 1, ...}, new Rate { Id = 2, ...}, ... } }, ... };
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c#" }
In Octave, how can I call ls with options? I'm trying to get a list of filenames to iterate through in my Octave program. I currently call x = ls and that works fine. However, I want a list of only text files. I can call ls *.txt But I can't call x = ls *.txt Is there any way to do that? The workaround I've found is x = eval("ls *.txt") but I'm hoping to avoid that.
On top of Andy's answer which explains why you are calling `ls` wrong, you are also wrong in calling `ls` to begin with. This function returns a char array with the list of files which is mostly useless for anything other than display at the Octave prompt. Instead, consider use `glob`: files = glob ("*.txt") which will return a cell array of filenames.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "octave, ls" }
Change image visibility on timer.elapsed event I have this code which makes my image visible and starts timer: image1.Visibility = Visibility.Visible; System.Timers.Timer timer = new System.Timers.Timer(2000) { AutoReset=false}; timer.Enabled = IsEnabled; timer.Start(); timer.Elapsed += hideImage; This is event which fires after 2 seconds: private void hideImage(object sender, System.Timers.ElapsedEventArgs e) { MessageBox.Show("test"); image1.Visibility = Visibility.Hidden; } MessageBox.Show works and message box is displayed. The problem is that image stays visible. Any ideas how to handle this? Thank you.
Try this: private void hideImage(object sender, ElapsedEventArgs e) { Application.Current.Dispatcher.BeginInvoke((Action)(() => image1.Visibility = Visibility.Hidden)); } Not sure how this din't crash for you in the first place cos your Thread is probably not the Main UI thread and that's probably what's blocking the updates too.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c#, wpf, timer, visibility" }
How to prescribe the width and the height of a JLabel? I am making a game, and i'm in the menu, however, I have to put one button. And, to make this, I created a JLabel with one image, and I used the MouseListener, but I have to prescribe the proportion of this JLabel, how can I do this? Thanks for the answer, and sorry my bad english.
1. Use a layout manager to control the position and size of the components. Take a look at Laying Out Components Within a Container for more details 2. Use a `Border` (like `EmptyBorder`) to affect the "padding" to the label, which will change it's overall size. Take a look at How to Use Borders for more details 3. Consider using an undecorated button instead of a `JLabel`. See How to Use Buttons, Check Boxes, and Radio Buttons for more details
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, swing, menu, jlabel" }
array_shift shows warning if the variable has a null or empty value I'm working on a MVC project and i'm on the part to get the URL values, to get each param i use array_shift() and the documentation says this: > Returns the shifted value, or **NULL** if array is empty or is not an array. In my code i have these lines: $arrParams = isset($_GET["params"]) ? explode("/", $_GET["params"]) : ""; $controller = array_shift($arrParams); $action = array_shift($arrParams); $params = array_shift($arrParams); If i access to `mvc-project.local` and i don't pass any param to the URL appears this message: > Warning: array_shift() expects parameter 1 to be array, string given in ... on line 12 Where is the problem?
Try this - $arrParams = isset($_GET["params"]) ? explode("/", $_GET["params"]) : array(); Or (array) $arrParams = isset($_GET["params"]) ? explode("/", $_GET["params"]) : ""; Or $controller = array_shift((array)$arrParams); $action = array_shift((array)$arrParams); $params = array_shift((array)$arrParams);
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "php, arrays" }
Word for letting something pass through unmodified I'd like to phrase the sentence "The system lets certain inputs pass through unmodified" more directly. Could anyone suggest a word to replace the parenthesised 'phrase' below? "The system (lets-pass-through-unmodified) certain inputs".
It's not a single word, but you _could_ use "preserve the value", e.g. "The system preserves the value of certain inputs." However, I prefer your original sentence as it's unambiguous.
stackexchange-english
{ "answer_score": 1, "question_score": 1, "tags": "word choice" }
Rails duplicate sql query even with includes I have trouble understanding why are two duplicate sql queries generated in this situation: I have a Post which `has_many :comments` post = Post.where(id: 4).includes(:comments).first generates these sql statements: SELECT "posts".* FROM "posts" WHERE "posts"."id" = 4 LIMIT 1 SELECT "comments".* FROM "comments" WHERE "comments"."post_id" IN (4) Now: comment = post.comments.first (no sql - good) However: post = comment.post generates the same sql: SELECT "posts".* FROM "posts" WHERE "posts"."id" = 4 LIMIT 1 It seems like the objects are not bound internally. Is there a way I can do that manually to avoid the second sql ?
Use `inverse_of` to specify the bi-directional relationship. From the docs: > Specifying the :inverse_of option on associations lets you tell Active Record about inverse relationships and it will optimise object loading. It may look redundant for simple cases, but associations are 1-way definitions. Specifying `inverse_of` lets Rails know that the two relationships are inverse of one another, and solves problems like the one you're having. # in post.rb has_many :comments, :inverse_of => :post # in comment.rb belongs_to :post, :inverse_of => :comments
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 5, "tags": "ruby on rails, ruby on rails 3, activerecord" }
Put all code in function Here I have an example of how to create a 'side_bar' with javascript when I click on marker var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers["+parseInt(gmarkers.length-1)+"],\"click\");'>"+place.name+"</a><br>"+ $('<div>').raty({ score: place.rating, path: ' }) +"</br>"; document.getElementById('side_bar').innerHTML += side_bar_html; } _''raty is jquery plugin for visualise rating with stars''_ but this code give me this results: Name of place [object Object] ... ... How I can put this code in function to work it correctly? Is any way to do this?
You are concatenating a jQuery wrapper to a string, that is the reason _without changing much from your code_ var side_bar_html = "<a href='javascript:google.maps.event.trigger(gmarkers[" + parseInt(gmarkers.length - 1) + "],\"click\");'>" + place.name + "</a><br>" + '<div class="raty" />' + "</br>"; $(side_bar_html).appendTo('#side_bar').filter('.raty').raty({ score : place.rating, path : ' })
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, jquery, html, function, raty" }
SP2013: how to clone the search result page-layout? I am building a SharePoint 2013 portal. I have created a new page and selected the pagelayout searchresult. Thats the perfect pagelayout but I am missing the horizontal navigation bar in the top of my page. So I would like to clone this pagelayout and customize it to show the horizontal navigation bar. How can I clone this pagelayout?
If you'd like handle it using CSS approach, add the following to your page layout's PlaceHolderAdditionalPageHead section: <style type="text/css"> body.focus-on-content #s4-bodyContainer #s4-titlerow { display: none !important; } #s4-bodyContainer #s4-titlerow { display: block !important; } <style> Alternatively, you could add this above CSS to your page (using Script Editor/CEWP) that inherits your Search Page Layout.
stackexchange-sharepoint
{ "answer_score": 0, "question_score": 0, "tags": "page layout, clone" }
What the heck kind of timestamp is this: 1267488000000 And how do I convert it to a datetime.datetime instance in python? It's the output from the New York State Senate's API: <
It looks like Unix time, but with milliseconds instead of seconds? >>> import time >>> time.gmtime(1267488000000 / 1000) time.struct_time(tm_year=2010, tm_mon=3, tm_mday=2, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=61, tm_isdst=0) March 2nd, 2010? And if you want a `datetime` object: >>> import datetime >>> datetime.datetime.fromtimestamp(1267488000000 / 1000) datetime.datetime(2010, 3, 1, 19, 0) Note that the `datetime` is using the local timezone while the `time.struct_time` is using UTC.
stackexchange-stackoverflow
{ "answer_score": 15, "question_score": 5, "tags": "python, datetime" }
Node.js Web Settings HTTP Server Sorry about the vague title, I'm not entirely sure what to call what I'm looking for. Basically I'm building an application and want to be able to change the settings of the application from anywhere via a website. The server must be capable of updating its contents as the applications data changes and grows. Is there any pre-built and easy to use solution out there?
I used to handle that kind of task. You have to store settings in database, I recommend using redis/memcached because they're really fast, much cheaper performance than using reading files or using other databases. First, you must have a static initial `settings.json` file, and check at bootstrapping if redis contain `app_settings` record yet or not. If not, persist that static json to redis, else skip. Whenever you change settings via website, you have to update the record in redis (and update to file json at the same time asynchronously if needed).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "node.js" }
Extract trend of time series with less than two periods I understand that a time series decomposition won't work if I have a univariate time series (daily frequency) with only one period (e.g., 1-Jan-2019 till 1-Aug-2020). But won't it be possible to extract just the trend for such a series? What are the methods that can help in this regard? and if the function exists within the R paradigm. Thanks
Simply regress your time series on the dates. R will automatically convert your dates into a numerical object that counts days from some origin. The parameter estimate will then show the increment day-over-day. If you want to detrend your series, simply take the residuals from this model. If you don't want to center the detrended series (i.e., don't want to also remove the overall level), then just add the estimated intercept back in. dates <- seq(as.Date("2019-01-01"),as.Date("2020-08-01"),by="day") set.seed(1) foo <- ts(rnorm(length(dates)),start=dates[1]) plot(foo) (model <- lm(foo~dates)) detrended <- ts(residuals(model),start=dates[1]) plot(detrended)
stackexchange-stats
{ "answer_score": 1, "question_score": 2, "tags": "r, time series, trend" }
Do two TensorFlow models on different python files conflict? I have a TensorFlow model that in each training episode I need to run a function on the data in that episode. This function is also a TensorFlow model in another python file that I import to the main file. This function trains the classifier on the data and returns the result to the main function. Does the training process of the model in the function (which is the other python file) mess up with the training of the model in the main file? doesn't the update of the weights in two models get overwritten?
The weights are saved into .data files and your graph and metadata are saved into the .meta file. Also, the actual real weights only exists within a Session. It means that the “restore” action must have access to a session to restore weights inside a Graph. Particular to your question, you are right, if you overwrite .data files from a different python script the weight values would be overwritten.
stackexchange-stats
{ "answer_score": 1, "question_score": 0, "tags": "machine learning, python, deep learning, tensorflow" }
SetSel on EN_SETFOCUS or WM_SETFOCUS doesn't work I've ran into next mystic thing in Winapi/MFC, I have an edit box, contents of which I have to select on Tab, Lclick, Rclick, Mclick and so on. The sort of obvious path is to handle the SETFOCUS message and call SetSel(0, -1), which should select all text. But it doesn't work! What's wrong? I tried googling, everyone seems to override Lclilks or handle SetSel in parent windows, but this is wrong from encapsulation point of view, also multiple clicks (user wants to insert something in the middle of the text) will break, and so on. Why isn't my approach working, I tried like 10 different ways, tried to trap all possible focus messages, looked up info on MSDN, but nothing works as expected. Also, I need to recreate the carret on focus, which also doesn't seem to work. SETFOCUS message gets trapped alright. If I add `__asm int 3`, it breaks every time. It's the create carret and setsel that gets swallowed it seems.
Post the edit an `EM_SETSEL` while handling `WM_SETFOCUS`. The mouse input is probably processed after the focus switches. Or post a user message and on receiving create the caret and then do the selection.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "winapi, mfc" }
What to do about wrong "control reaches end of non-void function" gcc warning? $ cat t.cpp int sign(int i) { if(i > 0) return 1; if(i == 0) return 0; if(i < 0) return -1; } $ g++ -c t.cpp -Wall t.cpp: In function ‘int sign(int)’: t.cpp:5: warning: control reaches end of non-void function $ What do I do about this? Stop using -Wall as it's clearly wrong? Add a bogus return 0 at the end? Clutter the code with "else" clauses?
If you don't want to add "else" clauses because they would make the code longer, then perhaps you would like to remove the final "if" and make the code shorter: int sign(int i) { if(i > 0) return 1; if(i == 0) return 0; return -1; // i<0 } Or if you're really computing "sign" yourself and this isn't a simplification of some longer example: int sign(int i) { return (i>0) ? 1 : ((i<0)?-1:0); }
stackexchange-stackoverflow
{ "answer_score": 17, "question_score": 6, "tags": "c++, gcc, warnings" }
Exporting sites to a new content database I have one site collection and it has grown to almost 500GB, i want to move one of our departments to a new site collection. It contains 5 sub-sites and in total about 200GB of content, so the end result is 2 content databases that are fairly manageable in terms of backups and restores. What is the best way to get this done?
I recommend using the stsadm -o mergecontentdbs command. Todd Klindt has an excellent writeup of it at < It saved me a ton of headaches. As always, perform a full backup before making any changes!
stackexchange-sharepoint
{ "answer_score": 0, "question_score": 4, "tags": "2007, export" }
Compilation error sequence: Static compilation error coming after resolving access modifier error? In the below piece of code: public class ModifierNotAllowInMethodCheck { private int pvtInt; public static void method1() { System.out.println("pvtInt = " + pvtInt); int var1 = 10; System.out.println("var1 = " + var1); public int var2 = 20; System.out.println("var2 = " + var2); } // end of method1() public static void main(String args[]) { method1(); } // end of main() } // end of class When compiled, the statement `public int var2 = 20;` would come as the first compilation error and then the statement `System.out.println("pvtInt = " + pvtInt);` would come as the compilation error, once I resolve the first one. Q - Why doesn't the static variable reference compilation error come first?
Thing is: you **assume** that compiler gives errors in the order they appear in source code. But that isn't how compilers work. Of course, when you have 5 errors of the same kind, you can expect that you get them in the order of line numbers. But when you have different _categories_ , then the compiler can decide what category to worry about first. And you see: identifying **wrong** modifiers within methods is something that can be done much easier, compared to looking at variables and scoping. And note: having access modifiers _within_ method bodies, that is a _syntax_ problem. It makes sense that pure _syntax_ problems are found and reported first. The `pvInt` thing is more complicated, that is about semantics! The compiler needs to fully know the (static) fields of the class before it can do that checking.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "java, compiler errors" }
DataStax Cassandra C# driver: WHERE IN (?) query with collection parameter I have following code C#: IMapper mapper = new Mapper(session); //... var names = new [] {"n1", "n2", "n3"}; //Generation of question marks var inStr = string.Join(",", names.Select(n=>"?")); var users = mapper.Fetch<User>($"SELECT * FROM users WHERE name IN ({inStr})", names); This approach works. But maybe someone knows a more elegant solution?
To provide a dynamic list of values in a single parameter, use the IN operator followed by the question mark placeholder without parenthesis in the query. For example: var names = new [] {"n1", "n2", "n3"}; var users = mapper.Fetch<User>("SELECT * FROM users WHERE name IN ?", names);
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "c#, cassandra, datastax, cql" }
How to write mutually recursive functions within a let binding in SML? I would like to do something like this: fun f () = let fun a() = b() and fun b() = a() in () end where a and b are sensible mutually recursive functions. However, this gives: Error: syntax error: replacing AND with SEMICOLON Is there any way to do this?
Declaration of mutually recursive functions in SML is marked by a `fun ... and ...` block: fun f () =   let fun a() = b() and b() = a() (* There is no 'fun' keyword before b() *) in () end
stackexchange-stackoverflow
{ "answer_score": 11, "question_score": 7, "tags": "sml, smlnj" }
Format plural problems in Views module I built a Drupal 7 site using the Views module and I am using the "comment count" field. If I choose the format plural checkbox, with a comment, it will output "1 comment", and when there are zero comments, 2 or more comments, it will output the number of comments followed by _comments_. If I want to output "no comments yet" when the comment count is 0, I can use the "No result behavior (Count the number 0 as empty)" option. The problem is that the format plural option is not working together with the "No result behavior" option. When I use both of them, I get "0 comments" instead of "no comments yet." How can I achieve my goal?
I managed to get this working by using the following settings for the **Content: Comment count** field: * **Format plural** checked * **Singular form** : @count _comment_ * **Plural form** : @count _comments_ Under **No results behavior** : * **No result text** : _no comments yet_ * **Count the number 0 as empty** checked * **Hide if empty** checked * **Hide rewriting if empty** checked
stackexchange-drupal
{ "answer_score": 3, "question_score": 2, "tags": "views, comments" }
Restructure objects based on their inner arrays duplicates I have this array of tasks: [ { id: 54321, Task: 'Task 1', Topics: ["111", "222"]}, { id: 667566, Task: 'Task 2', Topics: ["222"] }, { id: 76889, Task: 'Task 3', Topics: ["333"] }, ] and I want to restructure it based on duplicate strings inside Topics, So the result should be: [{ name: "111", id: [54321] }, { name: "222", id: [54321, 667566] }, { name: "333", id: [76889] }] basically topic names should become unique and tasks id should group under the topic's name
You can use `Array.reduce()` to create the desired structure, we create a map of topics, using the topic name as the key, then use Object.values() to get the result array: const tasks = [ { id: 54321, Task: 'Task 1', Topics: ["111", "222"]}, { id: 667566, Task: 'Task 2', Topics: ["222"] }, { id: 76889, Task: 'Task 3', Topics: ["333"] }, ] const result = Object.values(tasks.reduce((acc, cur) => { for(let topic of cur.Topics) { if (!acc[topic]) acc[topic] = { name: topic, id: [] } acc[topic].id.push(cur.id); } return acc; }, {})) console.log('Result:', result);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "javascript" }
how to split a string i have a string like 123Prefix1pics.zip i want to split it into 123 Prefix1 pics.zip and store them in different variables i m trying to do it in c#,.net jst litle bit confused on how to use split method
splitArray = Regex.Split(subjectString, @"(?<=\p{N})(?=\p{L})"); will work in C# to split in positions between a number (`\p{N}`) and a letter (`\p{L}`). If you also want to split between a letter and a number, use splitArray = Regex.Split(subjectString, @"(?<=\p{L})(?=\p{N})|(?<=\p{N})(?=\p{L})"); however, that splits your example too much.
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": -3, "tags": "c#, string" }
How to convert nested loop construct into flow chart in C? I'm drawing this code if (V > 24) { do { PWM(); while (I = 0) { RA5 = 0; LED(); I2C(); Delay_ms(1000); RA5 = 1; Delay_ms(1000); if (I != 0) { break; } } LED(); I2C(); } while (v < 28.7) } to this ![flow_chart]( I really don't know how to deal with this nested loop, is there any better idea for it?
Unrelated, but if(I != 0){ break; } Is implied by the for loop, you don't need it. Also be careful: while(I=0) will set I to 0 and your loop will never exit! You may have found this and decided to add the break later to compensate. What you want is: while(I==0) Note that what you did with the do while is correct, and a while loop is the same except the check happens before entering the loop rather then when exiting the loop. Remove the break and have your arrow simply go back to before the check for I == 0.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c, nested loops, flowchart" }
How to completely separate layouts for different customer groups We are building a store in which it is required to make totally different account dashboards for various customer groups. So, for my humble experience, I have two options, to filter on the controller level (to make checks in the AccountController for example and pass vars to block), and to filter (add/remove layout handles) it via observer (according to this link < I decide to do it via observer, but client worrying if some difficulties may occur in future (adding/removing lots of layout handles), in case dashboard for certain user group will grow, and asks me to separate the logic "on the root". Thinking on how to do it and would love to hear some expert's advice on how to plan architecture for this purpose, thanks!
I guess it heavily depends upon _what_ exactly you need to change about the customer experience. Assuming layout modifications (see below), handling it by adding a customer group layout handle using the observer method you outlined in your link above is a good approach. Your controller idea is much more tedious as it will either limit your modifications to routes handled by that single controller or you'd have to override several controllers should you need to modify other pages. By contrast, the layout handle method will allow you to do all kinds of stuff on a customer group basis such as: * Add Blocks * Remove Blocks * Add Styles/Scripts * Change the template files used by a particular blocks...
stackexchange-magento
{ "answer_score": 2, "question_score": 3, "tags": "magento 1.9" }
Saving the state of a program to allow it to be resumed I occasionally have Python programs that take a long time to run, and that I want to be able to save the state of and resume later. Does anyone have a clever way of saving the state either every x seconds, or when the program is exiting?
Put all of your "state" data in one place and use a pickle. > The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling (and unpickling) is alternatively known as “serialization”, “marshalling,” 1 or “flattening”, however, to avoid confusion, the terms used here are “pickling” and “unpickling”.
stackexchange-stackoverflow
{ "answer_score": 12, "question_score": 12, "tags": "python, state" }
Preset Value on Infragistics UltraCombo I have an infragistics `ultraCombo` that I set to a specific `datasource`. I want to pre-select one of those values so the user doesn't have to choose it (most of the time it will be the pre-selected value). However, when I set the `ultraCombo` to that value it modifies the drop-down list to contain only that single value! I've tried using the `ultraCombo.value` method, the `ultraCombo.textbox.text` method, etc, and they all behave the same way. When I look in the debugger the full list appears to be present, just not displayed. How do I pre-select a value in the list without destroying my drop-down list?
Finally got it to work using the following code: Dim tempValue As String = myPreviousValue 'changes to the object loose the selected row--save it off and restore later MyUltraCombo.DataSource = queryDS.Tables(0) 'load the new data 'Restore the previous selection If tempValue <> "" Then For Each row As Infragistics.Win.UltraWinGrid.UltraGridRow In MyUltraCombo.Rows If row.Cells(0).Value.ToString = tempValue Then MyUltraCombo.SelectedRow = row End If Next End If
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "winforms, text, datasource, infragistics, ultracombo" }
What's wrong with my JavaScript Search Recursive Loop? I can't seem to figure out why my recursive search will not behave recursively. Do you see what's wrong? Do I have a `haystack[i]` in the wrong place? Because I am not seeing it. I've tried looking through examples on this site but I can't figure out something so simple. search = function(needle, haystack) { len = haystack.length; for (var i = 0; i < len; i++) { if (typeof haystack[i] == 'object') { search(needle, haystack[i]) } else { if (needle == haystack[i]) { console.log('found'); return; } console.log('value: ' + haystack[i]) } } } var test = [[1], [2], [3,4], [5,6]] search(4, test) Or see the fiddle @ < (Open the Console)
You are missing `var` in front of `len`, it should be `var len = haystack.length;` otherwise it is treated as a global variable. when haystack = [[1], [2], [3,4], [5,6]] then len = 4 but again `search(4, [1])` is called then `len = 1` is assinged then when the loop is returned the value of `len = 1` instead of the original 4 because it is a global variable. Now i =2 and len = 1 so the loop exists
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, recursion" }
Keyboard input not displayed on the screen? We use the `exceed tool to connect to our UNIX servers, but sometimes the command-line behaves erratically. When I am typing some command on the command-line, nothing happens -- nothing is displayed on the screen and I need to close the terminal and open a new one. Why does that happen? Is it related to `stty sane`? I have typed `stty sane` thinking that it is used when your command-line starts behaving erratically; is that what it's for?
I'm not sure if it is what is happening in your case, but pressing `Ctrl`+`S` will freeze the tty, causing no updates to happen, though your commands are still going through. To unfreeze the tty, you need to hit `Ctrl`+`Q`. Again, I'm not totally sure this is what is happening in your case, but I do this by accident often enough, that it is possible it may affect others as well.
stackexchange-unix
{ "answer_score": 3, "question_score": 4, "tags": "linux, shell, command line, terminal, keyboard" }
How can I delete a job and run cleanup code with JobDSL in Jenkins? Similar to this question: _=_ The issue is if I add `removeAction('DELETE')` to the DSL, the job will be deleted which is what I want, but I'd also like to run some cleanup code. Is there a way to query JobDSL, or get a delta of the new jobs being created vs what previously existed last run? The context is, I am using JobDSL to create a pipeline job for each branch that exists in a GIT repository. When the branch is deleted, I want to remove the job and run some cleanup code.
Each build of the seed job stores the names of the generated jobs in a `GeneratedJobsBuildAction`. If you compare the generated jobs of the last build with the previous build, you get the names of the jobs that have been deleted. You can try the following example in Jenkins Script Console to get the names of the jobs that have been deleted with the last run of the seed job: import javaposse.jobdsl.dsl.GeneratedJob import javaposse.jobdsl.plugin.actions.GeneratedJobsBuildAction FreeStyleProject seedJob = Jenkins.instance.getItem('seed') FreeStyleBuild lastBuild = seedJob.lastBuild FreeStyleBuild previousBuild = lastBuild.previousBuild Set<GeneratedJob> lastGeneratedJobs = lastBuild.getAction(GeneratedJobsBuildAction).modifiedObjects Set<GeneratedJob> previousGeneratedJobs = previousBuild.getAction(GeneratedJobsBuildAction).modifiedObjects print previousGeneratedJobs*.jobName - lastGeneratedJobs*.jobName
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "git, jenkins, groovy, jenkins pipeline, jenkins job dsl" }
Running vcvars32.bat before compiling in Code::Blocks? I've installed Visual Studio C++ Express 2012 and want to use it's compiler with Code::Blocks. Starting `cl.exe` does not work (missing _mspdb100.dll_ ) until I run `vcvars32.bat`, but that does only hold on for the current session in the Command-line. The same applies to compiling with Code::Blocks. **How can I make it run the`vcvars32.bat` before compiling?**
## _Workaround_ That workaround is actually not what I was looking for, but it works, and that is important. Instead of letting _Code::Blocks_ running `cl.exe` directly, I've set-up a simple batch-script that runs `vcvars32.bat` before running the actual compiler. REM File: cl.bat call vcvars32.bat call cl.exe %1 %* !enter image description here
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "windows, visual studio 2010, visual c++, environment variables, codeblocks" }
Как на андроид обработать нажатие на кнопку Home? Скажите пожалуйста как на Андроид при нажатии на кнопку Home actionbar , вывести например System.out.println("Hello World!");
> public boolean onMenuItemSelected(int featureId, MenuItem item) { > > > switch (item.getItemId()) { > case android.R.id.home: > > >> >> System.out.println("Hello World!"); >> > > > break; > > } > > return true; } >
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "actionbar, android, java" }
How to split and array into n arrays javascript let's say i have an array [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and i want to split it into n parts let's say 3 part so the result is supposed to be [ 1, 2, 3, 4 ],[ 4, 5, 6, 7],[ 8, 9, 10 ] but the code i have right now is or O(n*m) which is bad. Is there an optimal way of doing this? const items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] const n = 3 const result = [[], [], []] const wordsPerLine = Math.ceil(items.length / 3) for (let line = 0; line < n; line++) { for (let i = 0; i < wordsPerLine; i++) { const value = items[i + line * wordsPerLine] if (!value) continue //avoid adding "undefined" values result[line].push(value) } }
To split up the array as evenly as possible: function split_array(a, nparts) { const quot = Math.floor(a.length / nparts) const rem = a.length % nparts var parts = [] for (var i = 0; i < nparts; ++i) { const begin = i * quot + Math.min(rem, i) const end = begin + quot + (i < rem) parts.push(a.slice(begin, end)) } return parts } var chunks = split_array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3) console.log(JSON.stringify(chunks)) Output: [[1,2,3,4],[5,6,7],[8,9,10]] The size of each part will never differ by more than 1.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "javascript" }
"The final major anatomist was Galen, active in the 2nd century"? I am reading a book at the moment, and I came across this sentence: > "The final major anatomist was Galen, **active** in the 2nd century" I am not sure if the word "active" is correct or not in this sense. And if it is correct, should it not be "The final major anatomist was Galen, who was active in the 2nd century"?
The final major anatomist was Galen, who was active in the 2nd century. The sentence is correct grammatically. The relative clause "who was active in the 2nd century" can be reduced by omitting the relative pronoun who + to be as follows: The final major anatomist was Galen, active in the 2nd century.
stackexchange-ell
{ "answer_score": 2, "question_score": 2, "tags": "grammar" }
Natural Deduction proof of $((A \rightarrow B) \rightarrow A \land B) \rightarrow A$ I am struggling to find a Natural Deduction proof for $$((A \rightarrow B) \rightarrow A \land B) \rightarrow A$$ I have tried out quite a few things now, but I can not find a way. Could you help me?
The most straightforward way to prove a conditional statement in natural deduction is to assume the antecedent and prove the consequent. So I would start by assuming $(A \to B) \to A \wedge B$, and try to prove $A$. Since there is no obvious way to reason directly from the assumption to $A$, the next thing I would try is to assume $\neg A$ and try to reach a contradiction. That gives you a start; see if you can continue on from there.
stackexchange-math
{ "answer_score": 4, "question_score": 0, "tags": "logic" }
Iterators from the same ViewObject do not communicate I am using JDeveloper 11.1.2.3.0 I am facing a strange behavior here. I have created 2 AppModules and in each AppModule I have DataControls from the same View Object (not only but also). When I create a new row using Page1 for example using DataControl from AppModule1 and then navigate to Page2 that uses DataControl from AppModule2, the Commit and Rollback buttons are enabled. Even if I redeploy the application in this case I have to Commit also in Page2. If I do this, then the problem will not show any more. So even through I commit in the first case, I have to commit also in the second page. As I said the EO and VO are the same, just the AppModules are different. Does anyone know why this happens and/or how to fix this? If anyone knows that this is a known bug please tell me.
Well I hurried a little, I just found the solution (the problem actually). Apparently different app modules are completely ignored one by other and have their own db connections. The explanations is here: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jsf, oracle adf, jdeveloper" }
Crash when is no internet connection The following code crashes when is no interenet connection : public String gourl(String myurl,String params) { URL url; String rasp = ""; try { url = new URL(myurl + params); BufferedReader rd = new BufferedReader(new InputStreamReader( url.openStream())); String line = ""; while ((line = rd.readLine()) != null) { rasp=rasp + line; } return rasp; } catch (Exception e) { Log.w("DHA", "EXCEPTIE URL"); } return null; } How can i prevent this from happening ?
Check connection before execute your method, something like that: public boolean isNetworkConnected() { final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.getState() == NetworkInfo.State.CONNECTED; }
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "android, connection" }
How much should I rely on Geometry shaders in WebGL? Geometry shaders appear to have been introduced in 3.2, which makes me wonder how common 3.2-enabled cards are, including support for Geometry shaders within WebGL contexts. Will I be cutting out a large portion of viewers by requiring the use of a geometry shader?
WebGL doesn't even currently support geometry shaders, so to directly answer the question: 100% of all users.
stackexchange-computergraphics
{ "answer_score": 9, "question_score": 6, "tags": "webgl, geometry shader, compatibility" }
Should the image popup be closed when clicking on image? It is obvious that we close popup when we click on dark area, on close button, or press escape key. But should we close it when we click on center image? Let's assume that there are three scenarios, what should happen after clicking on center image: 1. When it's popup with single image (#1). 2. When it's gallery with multiple images (by clicking on arrows on sides user moves to next/prev) (#2). 3. When #1 and #2 appear on the same page. Thank you! !image lightbox
Personally I think that closing a single image by clicking on it it's a good idea since it will minimize mouse movements (and improve ux on small touch screens where it's hard sometimes to tap the close button). Concerning multiple images I think that clicking an image should open next image because of the same reason (and close or restart the gallery at the end). _It's always a good idea to let users do something with minimum movement._ BTW, I think that it's better to place close button at the corner of the image because placing it at the corner of the screen will require more movement (not experienced users will try to click the cross instead of clicking somewhere else to close an image).
stackexchange-ux
{ "answer_score": 0, "question_score": 0, "tags": "image, popup" }
Change TextField's Underline in Flutter I'm working on an application using Flutter SDK. When I use a `TextField` widget, and I focus it, the underline becomes blue. I need to change this color to red, how can I do it? Screenshot of what I need to change. I want just the underline to change, **, not the label color.** !Screenshot of what I need to change. \(I want the underline to change, not the label color\)
While these other answers may somehow work, you should definitely **not** use it. That's not the proper way to get a custom theme in Flutter. A much more elegant solution is as followed : final theme = Theme.of(context); return new Theme( data: theme.copyWith(primaryColor: Colors.red), child: new TextField( decoration: new InputDecoration( labelText: "Hello", labelStyle: theme.textTheme.caption.copyWith(color: theme.primaryColor), ), ), ); At the same time, if you just want to show an error (Red), use `errorText` of `InputDecoration` instead. It will automatically set the color to red.
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 32, "tags": "flutter, dart, textfield, underline" }
How to failover to an AWS RDS MySQL replica in Java I have an AWS MySQL instance on which I have set Multi-AZ redundancy to True. I also have a read-replica that I will use for read-only queries. I am using C3P0 as my connection pool. AWS gives the endpoint for the master instance and for the read-replica, but does not give an endpoint for the redundant master. I am creating two connection pools, one for read access and one for write access. How do I ensure that my service will be able to reach the redundant master if the master fails over? I read about setting the ttl, I am setting that to 30. However, I rebooted the master (and ticked the failover button), but my service was unable to write data until the master had finished rebooting and came back online. I am using Guice to inject the connection pools into my code.
I was able to get the failover to work. (It was actually working, I was just not waiting long enough to see it happen). I had some C3P0 settings that were set too high, that was causing C3P0 to not see that the connections were failed.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, mysql, amazon web services" }
Formatting scale bar text with thousands separator in QGIS I wonder if this is possible. I want to show the text (numbers) of the scale bar in Print Composer with a thousand separator in order to make the labels more readable. All I can do for now is change the font and color. I can not find an option similar to the grid labels, where you can define a custom setting for the label and use format_number(@grid_number,0 for instance. I am using QGIS 2.18 in Win 10.
In QGIS 3.14, we can customize the number format of the scale bar, including the thousand and the decimal separator: ![enter image description here]( ![enter image description here](
stackexchange-gis
{ "answer_score": 5, "question_score": 9, "tags": "qgis, print composer, scale bar" }
how to Construct an HTTP request using Curl and Postman ![enter image description here]( image description here]( I want to get response from this given data, my question is how to set the content type, accept, curl in postman in order to get the response. help is much appreciated
You can import curl commands directly by clicking on the _Import_ button and then pasting the curl command in the _Paste Raw Text_ tab: ![enter image description here](
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, swift, curl, authorization, postman" }
JasperReports: Multiple sub-reports inside a master-report I would desperately need some help to achieve the following: 1. Create a master-report.jrxml, which includes a table of content and the corresponding sub-reports 2. These sub-reports all contain a different chart with different data query, which can be bigger than one page 3. Every page which includes a sub-report must show some static frame with dynamic content like the current sub-report's name and page X of Y My approach so far was, to create a sub-report.jrxml for each of my required charts (I put chart in the sub-report's summary band). Then I created a MasterReport.jrxml with my static frame which included the sub-reports in the summary band. I expected/hoped that JasperReport would render a the according sub-report after each other, but it just overdraws on the same page. How can I configure my report, to display the sub-reports after each other on new pages? Any help with this, would be highly appreciated.
Try with subReports in a detail band and subRepport element has "Run to bottom" property which, if set to true, will make subReport take the whole page and push next item on a new page. There is also a page break element in JasperReports if "Run to bottom" doesn't work for you . For static content on each page use page header/footer bands.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "jasper reports, subreport" }
wsgen command not generating wsdl I am using wsgen command to generate classes and wsdl for my webservice. I am following the below link < wsgen -verbose -keep -cp . com.mkyong.ws.ServerInfo -wsdl But it is generating all class and java files but not the wsdl and xsd files.. I tried from 2 windows machines and the same result.. What am i doing wrong here. I am not getting any errors.. its only generating 4 files instead of 6
The two remaining files(WSDL and XSD) would be created in your current directory. The generated class and java files would be under package directory.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "java, web services, soap, wsdl" }
Backbone serious drawback Consider following example: < Zoo = Backbone.Model.extend({ validate: function() { console.log('val'); return "error"; }, url: '/save/' }); var artis = new Zoo( { name: 'Artis' } ); console.log(artis.get( 'name' ) ); artis.save({name:'Artis2'}) console.log( artis.get( 'name' ) ); If you try to save changes to a model, but validation fails. But you can see in the example that data is changed in the model. Is this really a drawback or I am missing something?
The data will change in this example because you are not forcing validation. If you want to force validation prior to the modification of the client-side model, you must use the set method like this: artis.set({name:'Artis2'}, {validate: true});
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript, backbone.js" }