INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
PHP include directoy: first time using the include I want to include bd.php to my file inside the folder Cidadao. Like this: ![enter image description here]( i tried this code: <?php include 'bd.php';?> bus this not working. this is the code.
Try this: <?php include '../bd.php';?>
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, directory, include" }
Is it bad software design to mix JDBC SQL calls and use an ORM in an application? Is it bad software design to have JDBC/raw SQL and also use an ORM? I don't mind using an ORM for boilerplate CRUD, but some queries are better in SQL (for me). I'm not arguing for or against ORMs. I've read about them until I'm blue in the face. I used JDBC in my question, but it could have been DBI, or some other database interface. ORM can be any of them. How about maintainability? Would mixing the strategies complicate it? To me the maintainability of an application efficiently becomes even more blurrier, if it is a compiled language vs. a scripting language. I have to recompile Java. I don't have to recompile Python or PHP. If my SQL is in a model layer, does that change anything? EDIT: If I use find a point where I need to use SQL in my ORM, in my model, what kind of data is sent back? I won't be able to use something like person.save('somevalue'), for example, will I?
It depends on your application needs. For example, I've been working for banking, and when you have to generate thousands of invoice payments orders, it's better to have an stored procedure to do the task (it'll be by far faster) and to update the model tables directly in the database. Then you can show the results with ORM, even update a payment order (but not thousands). If your application is not performance critical, it's better for programming mantainability to deal with ORM, so that you don't need to know about the underlaying DB technology. So that one more time, it depends on your needs and if you keep the code organized and clean (apply a DAO pattern for it, for example), it's not a bad architecture nor unmaintainable code.
stackexchange-softwareengineering
{ "answer_score": 1, "question_score": 4, "tags": "design, sql, orm" }
Is DirectAccess in server 2012 replacement for VPN solution? I have read about some new features for server 2012, and I saw DirectAccess. I am a little bit confused about that. Is this feature a replacement for VPN solution? Or can this features be a replacement for a VPN solution?
Yes. It's a VPN replacement if your environment matches the DA deployment requirements. The clients must be Windows 7 Enterprise or Ultimate, or Windows 8 Enterprise, and in your domain. You also need to have a Server 2012 DA infrastructure configured properly, which will depend on a few things.
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "windows, vpn" }
How can I clean a double-layer tea filter? I have a double-layer tea filter like this one: ![tea filter]( I use it to filter rooibos tea, which can have very fine particles. The problem I have is that over time, many tiny particles have become trapped between the two mesh layers, shown by the arrow. The only way I can think of to remove them is by burning them using a blowtorch. However, since the mesh wire is so fine this would probably destroy it. Is there a better method?
No doubt, by now, you have rapped, tapped, blown, washed, rinsed, and repeated. You gave me the idea about _burning_ them, but _not_ with a blowtorch—with _chemicals_. If nothing else has worked, you can **Try a household oven cleaner to "burn" the particles from between the screens**. Lye, from a hardware store, will work faster; but, would cost more than replacing the tea filter. Follow instructions on the label. " _oven_ " cleaners contain corrosive alkalis that will have a very similar effect on the tea leaves as a blowtorch would. It just takes longer. After overnight treatment, neutralize the stuff as suggested (in cool water), wash and rinse thoroughly. Better? Repeat.
stackexchange-lifehacks
{ "answer_score": 3, "question_score": 1, "tags": "cleaning, drinks" }
How to delete an arrow created with ax.arrow()? For context, I have a curve where I would like to highlight the width of a plateau with an annotation + an arrow (this one was made in Paint.NET). ![enter image description here]( To update the text and arrow, every time an input parameter changes I do: ax.texts = [] # Clear the previous annotations. ax.text(x, y, plateau_width_str) ??? # What goes here to clear the arrow? ax.arrow(x, y, dx=plateau_width, dy=0) For now I'm not using `gid`s here because I only have one text and one annotation at a time. What should be the third line? After calling `ax.arrow()` I tried exploring `ax.collections` and `ax.patches` but they are empty lists. Thanks in advance.
You could directly create a method that removes the old and creates a new arrow, like `self.create_arrow(*args, **kwargs)`. It might look like def create_arrow(self, *args, **kwargs): gid = kwargs.get("gid") if gid in self.some_dic: self.some_dic[gid].remove() arrow = self.ax.arrow(*args, **kwargs) self.some_dic.update({kwargs.get("gid") : arrow}) Where you have a dictionary `self.some_dic` to store the references in.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python 3.x, matplotlib" }
Ошибка синтакиса $('input[type="submit"]').click(function() { var data = { title: $('input[name=POST_TITLE]').val(), url: $('#post-code-text').text(), text: $('#LHE_iframe_LHEBlogId').contents().find('body').text() } if ($('#post-code-text').text() != '' && $('input[name=POST_TITLE]').val() != '') { $.ajax({ url: '/ajax/blog_subs.php', dat a: data, dataType: 'json', type: 'post', success: function() {} }); } }; Ошибка на последнюю строку "Uncaught SyntaxError: Unexpected token ; " в чем причина?
1. Поставьте точку с запятой в шестой строке 2. Оператор сравнения с "пустотой", лучше использовать **!==** 3. Про очепятку " **dat a** " уже сказал [@DreamChild](/users/10162/dreamchild) 4. Последняя строка - круглой скобки не хватает " **});** "
stackexchange-ru_stackoverflow
{ "answer_score": 5, "question_score": -1, "tags": "jquery" }
Why does checking if temp table exists when "CONCAT_NULL_YIELDS_NULL" is set to ON doesn't work? SET CONCAT_NULL_YIELDS_NULL OFF; IF OBJECT_ID ('tempdb..##QueryResults') IS NOT NULL DROP TABLE ##QueryResults; Why is it that if i set set `CONCAT_NULL_YIELDS_NULL` to off as shown above and temp table `##QueryResults` exists, it is successfully dropped but if i set it to ON, then temp table is not dropped even when it exists?
This works as expected on SQL Server 2014 SP1 SET NOCOUNT ON; SET CONCAT_NULL_YIELDS_NULL OFF; CREATE TABLE ##QueryResults (foo int); SELECT OBJECT_ID ('tempdb..##QueryResults'); IF OBJECT_ID ('tempdb..##QueryResults') IS NOT NULL DROP TABLE ##QueryResults; SELECT OBJECT_ID ('tempdb..##QueryResults'); GO SET CONCAT_NULL_YIELDS_NULL ON; CREATE TABLE ##QueryResults (foo int); SELECT OBJECT_ID ('tempdb..##QueryResults'); IF OBJECT_ID ('tempdb..##QueryResults') IS NOT NULL DROP TABLE ##QueryResults; SELECT OBJECT_ID ('tempdb..##QueryResults'); gives ----------- 373576369 ----------- NULL ----------- 389576426 ----------- NULL
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "sql server, tsql, sql server 2005" }
How to Store Multi-Dimensional Arrays using Phonegap 1.0 for iOS 4.3+ I am building an iOS App using HTML/CSS/JS(jQuery) + PhoneGap and need to load a set of default records into local storage at each application load for usage in the App. Each record can have an unlimited number of steps, with each step having a set of five sub-steps, each with its own set of vars. My thought is to store the records as a multi-dimensional object in JSON format in an external file and then insert it into the local database using $.getJSON. Once inserted, I could retrieve the records and parse them using jQuery. Problem is that I cannot figure out how to store/retrieve multi-dimensional arrays in sqLite. I've also looked at Lawnchair but the documentation is spotty and doesn't seem to do what I need it to. Is this even possible? Can anyone provide me with a working example or alternative I should look at? Thank you all!
If you are only targeting iOS then Lawnchair, while a good solution, is overkill. Sqlite will likely be around for a while but it is deprecated for IndexedDB. For now, I would reccomend you just use localStorage. var data = [[0,0,0],[0,0,0],[0,0,0]] , store = window.localStorage // save data store.setItem('data', JSON.stringify(data)) // retreive data console.log(JSON.parse(store.getItem('data')))
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, sqlite, ios4, cordova, lawnchair" }
How to push to Github from C9? I linked my Github account to C9 and cloned a private repository. Then I made some changes to the files and uploaded a couple of folders through the IDE, and in the end used `git push` in the terminal in C9. This caused the changes in the files to update, but the new folders that I had uploaded and the files in them are not there.
You told us that: > and in the end used git push in the terminal in C9. This caused the changes in the files to update, but the new folders that I had uploaded and the files in them are not there. You may have done a `git push` to the repository, but this would not send any files/folders new or old which were not _staged_. To see where you stand locally, type `git status` from the Git console. My guess is that you will see the folders which never seemed to make it to the repository under the `"Changes not staged for commit"` section. To fix this, you can do `git add` on the files and folders, and then push again.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "git, cloud9 ide" }
Regex to match 4 groups of letters/numbers, separated by hyphens I need a regular expression that will match this pattern (case doesn't matter): > 066B-E77B-CE41-4279 4 groups of letters or numbers 4 characters long per group, hyphens in between each group. Any help would be greatly appreciated.
With such a small sample of data, it's not easy to be certain what you actually want. I'm going to assume that all the characters in that string are hex digits, and that's what you need to search for. In that case, you would need a regular expression something like this: ^[a-f0-9]-[a-f0-9]-[a-f0-9]-[a-f0-9]$ If they can be _any_ letter, then replace the `f`s with `z`s. Oh, and use `myRE.IgnoreCase = True` to make it case insensitive. If you need further advice on regular expressions, I'd recommend < as good site. They even have a VB.net-specific page.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "regex, vb.net" }
How to reduce memory footprint of t1.Micro Amazon AMI? I recently launched Amazon Linux AMI 2012.09 (several tries) because of Amazon's 1 year free tier offer. However, its always running out of memory/RAM! How can I reduce the initial memory footprint of this AMI? thanks!
You could provide more information, but there is some general steps you could take, such as installing low memory versions of stuff, such as mingetty. Here's a checklist that could be of use: <
stackexchange-serverfault
{ "answer_score": 1, "question_score": 0, "tags": "amazon ec2, amazon web services" }
Interface Builder iPhone iPad simulated interface elements When you create the Interface Builder file in xcode, you are asked to create it for the iPhone or iPad. That is not only the question for the screen dimmensions at start up, but also is important to properly displaying the navigation bar - custom colors, as well tables and so on. Is there any way to change the iPhone/iPad format in the existing Interface Builder file?
I'm not quite sure I understand your question but there are two things you can look at: \- (in IB) Under `File` you can `Create an iPad Version` of an iPhone view and `Create an iPhone/iPod Touch version` of an iPad view \- .xib files are text files, so you can open them up with an editor and modify them
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "iphone, xcode, ipad, interface, builder" }
Showing torsion of a curve is constant I tried to simply find the torsion first by computing $- \frac{{\mathbf N\times B'}}{||\mathbf{r'(t)}||} $ and I was hoping to obtain a constant, but the algebra was too messy and so gave up on that method. I also tried to parametrise the curve with its natural parametrise but I couldn't find this due to t>0. So I was wondering how this can be done. ![enter image description here](
I'll write $\;r(t)=\left(\,1+t\log t,\,-t\log t,\,t^2\,\right) , \;t>0\;$ , so the torsion at any point is given by $$\tau(t)=\frac{\left(r'\times r''\right)\cdot r'''}{\left\|r'\times r''\right\|^2}$$ and $$\begin{cases}&r'=(\,\log t+1,\,-\log t-1,\,2t\,)\\\\{}\\\ &r''=\left(\,\frac1t,\,-\frac1t,\,2\,\right)\\\\{}\\\ &r'''=\left(\,-\frac1{t^2},\,\frac1{t^2},\,0\,\right)\end{cases}\;\;\;\;\implies $$ $$\implies r'\times r''=\begin{vmatrix}i&j&k\\\ 1+\log t&-1-\log t&2t\\\ \frac1t&-\frac1t&2\end{vmatrix}=\left(\,-2\log t,\,-2\log t,\,0\,\right)$$ and $$ \tau(t)=\frac1{8\log^2t}\left(\,\frac{2\log t}{t^2}-\frac{2\log t}{t^2}\,\right)=0$$
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "vectors, algebraic curves, parametrization" }
How to “pad” a variable-length string with a string? Say I have a variable `$foo` that has a length between 1 and 10. And there is a variable `$bar` with a length of 12 that is initially set to `Iamheretopad`. I want to overwrite the second variable **right-justified** with the first one. A few examples: $foo $bar 1 Iamheretopa1 123 Iamhereto123 123456 Iamher123456
If $bar is 12 characters long and $foo is 5 characters long, then you want the first 7 characters of $bar, 7 being the difference of the lengths (12-5). $bar = substr($bar, 0, length($bar)-length($foo)) . $foo; Alternatively, if $foo is 5 characters long, you could replace the last 5 characters of $bar. substr($bar, -length($foo)) = $foo; By the way, if you wanted to pad with spaces or zeroes, you can use `sprintf`. $bar = sprintf('%12s', $foo); # Spaces, constant size $bar = sprintf('%*s', $size, $foo); # Spaces, variable size $bar = sprintf('%012s', $foo); # Zeroes, constant size $bar = sprintf('%0*s', $size, $foo); # Zeroes, variable size
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": -2, "tags": "perl" }
Kivy: Check if a function is already scheduled Is there a way to check if a function has been scheduled already? I was looking at the `Clock` methods but didn't see anything I could use. I am trying to avoid a rescheduling(`Clock.unschedule(func)` -> `Clock.schedule_interval(func, dt)`) of a function unless it is already scheduled to begin with.
You can use `kivy.clock.Clock.get_events()` to get the list of scheduled events: from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.lang import Builder Builder.load_string(""" #:import Clock kivy.clock.Clock <MyWidget>: Button: text: "Print events" on_press: print(Clock.get_events()) Button: text: "Add event" on_press: Clock.schedule_once(root.my_callback, 5) """) class MyWidget(BoxLayout): def my_callback(self, arg): print("my_callback") class MyApp(App): def build(self): return MyWidget() if __name__ == '__main__': MyApp().run() **OLD ANSWER** : Not a very clean way, but you can examine the content of `kivy.clock.Clock._events` list.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "python, python 2.7, kivy" }
How to see if the nyquist plot is stable or unstable? Is there a method to determine the stability of the nyquist plot to check if it's stable or unstable ? I currently needs to manually input the transfer function to another m.file to view the pz location to determine syms s w G = (2*s+1)/((s^2)+(5*s)+6); %transfer function G_w = subs(G,s,j*w); W= [-100:0.1:100]; %[min_range:step size:max_range] nyq = eval(subs(G_w,w,W)); x = real(nyq) y = imag(nyq) plot(x,y) This is the code i am using
I have found this video quite useful! Nyquist Stability Criterion, Part 1 All this channel video are really good for control theory and give a better understanding to then move everything on MATLAB. Hope this was useful.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "matlab, nyquist" }
How do I tell if Apache is restarting? Trying to restart Apache, and can't tell if it's restarting -- are there logs for the restart, or if I input the commandline to restart should I expect a response (error msg, confirmation, status, etc.) Never done it before and not sure what's going on. This is exactly what I'm typing, no $/# before it... **COMMANDS INPUT:** sudo apache2ctl restart \-- or -- apache2ctl restart **CONTEXT:** Commands executed from the root directory, meaning... "cd /" **RESULT:** Nothing appears to happen.
Depending on how Apache and syslog are configured on your machine, it may vary, however with a stock Debian or Ubuntu Apache 2 installation, you'd find the logs in `/var/log/apache2/error.log`. If it's restarting you should clearly see it in the logs. Additionally, checking the output of `ps`, particularly the start time, you should be able to tell if it has restarted. One last thing, if you're ever trying to find out if a command you just ran succeeded or failed, try `echo $?`. It'll print the return code of the last command. 99% of the time 0 is what you're looking for there.
stackexchange-serverfault
{ "answer_score": 2, "question_score": 3, "tags": "linux, apache 2.2, configuration, command line interface" }
What's the maximum reputation for a user I have take a look at Jon Skeet's info page, and found that his current reputation is 538k. And now I have a question, **what is the maximum reputation for a user**? Is it 1000k or _unlimited_?
This depends entirely on the datatype used for the total reputation column in the database. The Stack Exchange software stack is based on Microsoft SQL Server 2012 (although it started out on MS SQL Server 2008). MS SQL Server has several integer types; if the column is of type `int`, then the limit is 2,147,483,647 (2 billion plus change). And the Stack Exchange Data Explorer filtered copy of the site data uses `int` for reputation, making it _very_ likely that the production database uses the same type. Edit: Nick Craver confirmed `int` is used. That means we have another 2000 years to go before Jon Skeet's reputation forces a database upgrade to `bigint`.
stackexchange-meta
{ "answer_score": 14, "question_score": 2, "tags": "discussion" }
Need a regex for a string that must have letters but can't have purely numbers and cant have special chars Need a regex for string such that: 1. Can have letters, numbers 2. ignore special characters like: < > { } [ ] # ~ ^/\" 3. Can't have purely numbers 4. Max size is 20 chars Valid answers a) "hello world 123 -" b) "123 hello - world" c) "- hello 123 world" Invalid answers a) "123456" b) "123456 " c) "abc>>>" c) "abc123>>>" d) ">>>>" The closest i've come up with is: ^([A-Za-z0-9 '\-!\£\$:;%&amp;\*\(\)_=\+,.\?@\n\r\t]{1,20}$ But point 3 of "Can't have purely numbers" becomes invalid. Any idea?
You can use this lookahead based regex: ^(?![0-9]+$)(?!.*?[<>{}\[\]#~^\/"]).{1,20}$ ^ - Line start (?![0-9]+$) - Not just numbers (?!.*?[<>{}\[\]#~^\/"]) - Doesn't have these special characters .{1,20} - 1 to 20 characters $ - Line end
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "regex" }
What is the best way to unscramble words with PHP? I have a word list and I want to unscramble words using this word list, in PHP. It seems to me that PHP doesn't have a built-in function that does this. So could someone please suggest a good algorithm to do this, or at least point me in the right direction? EDIT: edited to add example So basically, what I'm talking about is I have a list of words: apple banana orange Then, I'm given a bunch of jumbled letters. pplea nanaba eroang
Given a dictionary of known words: foreach ($list as $word) { if (count_chars($scrambled_word,1) == count_chars($word,1)) echo "$word\n"; } Edit: A simple optimization would be to move the `count_chars($scrambled_word,1))` outside the loop since it never changes: $letters = count_chars($scrambled_word,1) foreach ($list as $word) { if ($letters == count_chars($word,1)) echo "$word\n"; }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 4, "tags": "php, algorithm" }
What is the ideal fridge temperature I notice that in both countries where I lived the fridges are kept at 6 or 7 °C (43-45 °F). When it would be colder, people find their drinks to cold, when served straight out of fridge (especially in winter). Also a lower temperature would cost more energy. What would be the best temperature for food storage. Would that be even lower? For storing meals, how much time longer would food stay good when the fridge would be colder?
The USDA says refrigeration temperature should be 40°F (4.4°C) or below. If food is in there at a higher temperature (such as the 43-45°F the question mentions), for longer than 2 hours, and they're saying the food isn't safe. Keep in mind that when too cold, after a while parts of things freeze, which can damage items, or severely diminish their pleasant taste. This especially goes for produce such as lettuce or even tomatoes. If you want to store leftovers longer, consider freezing them. Edit: corrected to 40°F _or below_
stackexchange-cooking
{ "answer_score": 9, "question_score": 10, "tags": "food preservation, refrigerator" }
How to know or recover my pg_dump password? I would like to backup my Postgre db using pg_dump. However, the first question asked by the prompt is the password. But I have no idea what it is. Indeed, it is different from my admin account password, and I don't know where to find it or recover it.
pg_dump does not have a password specific to itself. You run pg_dump as a certain database user (often the user spelled 'postgres', but not always), and authenticate however that user would authenticate for any other (non-pg_dump) connection. So your question really has nothing to do with pg_dump. You probably can't recovery the password (unless you are willing to crack md5 hashes to brute force it--which is really only feasible with poor passwords or with big bucks), but you can use your "admin account" to reset the password to something you do know. How you do that depends on whether "admin account" means a database superuser account, or an OS account for the OS user who owns and runs the database files. Also, it might depend on your settings in pg_hba.conf.
stackexchange-dba
{ "answer_score": 1, "question_score": 0, "tags": "postgresql, pg dump, password, postgresql 11" }
Use SVG code licensed under CC I want to use SVG icons which are licensed under CC BY 4.0 on my website. The CC BY 4.0 asks to give attribution. So, the question is do I give the attribution in the SVG code as "Icons provided by ... licensed under CC BY 4.0" or somewhere the user can see like the footer or the webpage? Also is the format "Icons provided by ..., licensed under CC BY 4.0" correct?
Fair disclosure: I'm not a lawyer. Short version: I'd do both. Longer version: The way I understand the CC license(s), the point is to make it very clear where the images you're using come from. Most users won't look inside the SVG code, they'll just use your website, so having a footer that mentions the attribution is a good idea. On the other hand, someone that will want to reuse those icons may very well download them and then in a later time use or modify them and not even remember where they came from, so adding the attribution inside the SVG code is also a good idea. Since doing one doesn't prohibit doing the other, I'd just add the attribution in both places.
stackexchange-opensource
{ "answer_score": 12, "question_score": 8, "tags": "copyright, license, license notice, creative commons" }
How to get all tags inside a specific tag using xpath I need to get all the links in the table on this page : < I am using this library: < The issue is that when I print results it only gives me the first link. let results = xpathT.fromPageSource(data).findElement("//tbody[@class='searchResultsRowClass']//a"); console.log("HERE NOSEDSS"); console.log(results); console.log("The href value is:", results[1].getAttribute("href")); How do I get all the links?
According to the doc you have to use `findElements` with a **s**. If I modify a bit your XPath, you can have something like this : const nodes = xpath.fromPageSource(html).findElements("//a[@class='classifiedTitle']"); console.log("Number of ads found:", nodes.length); console.log("Link[0]:", nodes[0].getAttribute("href")); console.log("Link[1]:", nodes[1].getAttribute("href")); ... Of course it's better if you write a loop to print all the links. Something like : for (let x = 0; x < nodes.length; x++) { console.log(nodes[x].getAttribute("href")); }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "html, node.js, xpath" }
How to format to display leading zero I am trying to display the duration in this format: 05:02:09 which is hour, minute and second. At the moment I can display it without the leading zero in this format: 5:02:09 =IIF( Fields!DataValue.Value < 0, 0, Floor(Fields!DataValue.Value / 3600) &":"&Format( DateAdd("s",IIF(Fields!DataValue.Value < 0, 0, Fields!DataValue.Value),"00:00"), "mm:ss" ) ) How can add a leading zero when the hour is less than 10? ![enter image description here](
I found a solution, which I tried before but failed. Strangely, it worked this time. =IIF( Fields!DataValue.Value < 0, 0, Format(Floor(Fields!DataValue.Value / 3600), "00") &":"&Format( DateAdd("s",IIF(Fields!DataValue.Value < 0, 0, Fields!DataValue.Value),"00:00"), "mm:ss" ) )
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "reporting services, ssrs 2008, reporting, ssrs 2008 r2" }
Pass an entire inital object in an edit form (data pre-population) in Django I have a very complicated form and I choose to not use `ModelForm` since I needed flexibility and control over the fields. Since I am not using `ModelForm`, I can't simply do something like `instance=order`, where `order = Order.objects.get(pk=1)`. Currently I am pre-populating every field with `initial` in the `forms.py` as oppose to the `views.py` like this self.fields['work_type'] = forms.ChoiceField(choices=Order.WORK_TYPE_CHOICES, initial=order.work_type) But I was wondering if I could pass the entire `order` object to a form or do I have to declare `initial` to _every_ field? Is there a way to do something like order_form = OrderEditForm(data=request.POST, initial=order) in `views.py`?
For future reference to other people: I have since found out after reading SO's comments and answers that it's better to use `ModelForm` even if you end up explicitly defining every field manually (using something like `self.fields['foo'] = forms.CharField()`). In any case, if you are trying to pass a dictionary of current values in a form then the best (built-in) way to convert a model to a dictionary is actually using `model_to_dict`: from django.forms.models import model_to_dict order = Order.objects.get(pk=1) dictionary = model_to_dict(order) form = OrderEditForm(dictionary) I got the solution from this blog. I hope this will be helpful for someone.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, django, django forms" }
Linux (Ubuntu) Terminal Screwey CTRL+A, for example, is printing "^A" instead of returning my cursor to the start of the line. This happens via ssh, in a screen session, or on the hard console. $TERM shows either xterm or linux depending on which one I'm on. How do I get the keymap fixed?
You have enabled vi mode for bash somewhere like this "set -o vi" (probably in your ~/.bashrc file) You need to remove that line or change to "set -o emacs"
stackexchange-serverfault
{ "answer_score": 1, "question_score": 1, "tags": "linux, ubuntu, terminal, console" }
Array with fixed size at runtime I know I can use `std::array<Type, Size>` to a have an array of the type `Type` and a size, which is fix at compile time. Furthermore, `std::vector` can be used, if the size is not fixed at compile time, but given at runtime. Is there an std container, which can be set at runtime to a certain size and this size is than unchangeable? My intend is to get a compile error, if the size is changed after the creation of this container. Of course this can be archived with old school arrays using pointers. Nevertheless, this also comes with the disadvantage of having to pass the pointer and the length to a function?
> Is there an std container, which can be set at runtime to a certain size and this size is than unchangeable? No there's no such standard container providing that feature (yet). You may write a simple wrapper class for `std::vector` using a fixed size like proposed in the answers here: * Constant-sized vector
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "c++, arrays, stl, containers" }
What's the name of the black-brown decoration sauce used in French cooking? When my boyfriend and I visited France a few months ago, I noticed that a lot of savory dishes were drizzled with some black-brown colored sauce on top (see picture I took, which is a plain risotto). The sauce tasted fairly sweet and not salty. My best amateur guess is that this is some sort of reduced sugary balsamic vinegar sauce, but it does not taste acidic at all. Maybe the vinegar evaporated while reducing? !plain risotto
It is most probably crema di balsamico, a quite popular condiment, even often only used for decorative purposes. It can both be used with savory dishes, but also with sweet dishes, as in e.g. ice cream or gelato. Traditionally, crema di balsamico is made by reducing grape juice and optionally wine to the point where the sugar in the grape juice starts to caramelise and then deglaze the reduction with balsamic vinegar. Convenience products are often pepped with food colouring and thickening agents.
stackexchange-cooking
{ "answer_score": 6, "question_score": 2, "tags": "sauce, french cuisine" }
How does type conversion works in JS? I'm new to programming, and currently I learn JS. There's one thing about operators/type conversions that kind of confused me. Here are some practice examples that I tried: `"4px" - 2` //this returns **NaN** because this string can't be converted into number to do the arithmetic. "2" * "3" // this returns **6** because they can be converted into numbers. " \t \n" - 2 // now this one is the one that I don't get it. The result is **2**. I thought this string can't be converted. Please enlighten me on the last example, thanks!
Strings that consist of all whitespace characters are converted to the number 0. It's section 7.1.3.1 in the spec. A numeric literal can include leading or trailing spaces plus zero or more digits. If there are no digits, the value is 0.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, type conversion" }
3d graphics implementation using images in using webgl,html5 canvas I'm new to HTML5 and have got one project in HTML5 canvas. I still have to analyze the requirement. I'm done with almost every part, the problem I'm stuck at is: Is it possible to make a 3d out of some images formed after drag and drop and then combining them together using `webgl` or maybe `three.js` and `kinetic.js`? For example in this site: < Is it possible to first fully design a headstone using pre loaded images and then making a 3d view out of it?
You might be able to use javascript / CSS 3D transforms to combine the images into 3d shapes without needing to use WebGL theres a nice tutorial here: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "javascript, html5 canvas, webgl, kineticjs" }
Is there an OrderBy option for ViewBag I am trying to sort the items of a `ViewBag` list called via `ForEach`. I see that there is a `Model.OrderBy` option. Is there something similar for `ViewBag`? My code is as follows: <select class="list-box tri-state" id="ParentID" name="ParentID"> @foreach (var item in ViewBag.EmployeeList) { <option value="@item.Id">@item.FirstName @item.LastName</option> } </select> Ideally I would like the Selection list to be sorted by `FirstName`, `LastName`, but it is default sorting by `Id`. How should I remedy this?
`ViewBag` is dynamic. So assuming it was set in the controller like List<Employee> employees = getEmployeeList(); this.ViewBag.EmployeeList = employees; //... return View(model); In the view, cast the property to a known type collection and the extension method should then be available. @foreach (var item in (ViewBag.EmployeeList as List<Employee>) .OrderBy(_ => _.FirstName).ThenBy(_ => _.LastName)) { <option value="@item.Id">@item.FirstName @item.LastName</option> } Alternatively you can sort it in the controller before assigning it to the `ViewBag` as well and just have the code loop the collection in the view. List<Employee> employees = getEmployeeList() .OrderBy(_ => _.FirstName).ThenBy(_ => _.LastName) .ToList(); this.ViewBag.EmployeeList = employees; //...
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "c#, asp.net mvc, razor, viewbag" }
patch broke my saved powershell secure strings I wonder if others noticed too. I have a powershell script connecting via new-pssession to some other machines (windows servers) and the credentials are saved as XML via $credential = Get-Credential $credential| export-clixml somepath.xml After september updates it can no longer import those XML files because Import-CliXml : Key not valid for use in specified state. If I recreate them again with the same credential set it works again! But I see the string in there is different! Seems like some crypto have changed and I will have to recreate all those saved credentials :-\ Is it possible patch caused this or am I doing something else wrong?
As mentioned in comments, the encryption is based on current windows user (including password). To import the xml after changing windows password, you'll have to export it again first. There's a new vault module from MS to serve a similar purpose, but it's still a work-in-progress at the moment. Maybe more relevant to future readers. For more information - < <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "powershell, windows server 2012 r2, password encryption" }
How do I call a defined function in another php script? how do I call a defined function from a php script in another one? I've got funktion.php which returns the time of the day. <?php date_default_timezone_set("Europe/Berlin"); function Uhrzeit() { echo date( 'H:i:s' ); } Uhrzeit(); ?> I'd like to call the function in another php script(test.php) so that **Uhrzeit();** from test.php has access to the function Uhrzeit() from funktion.php. How do I implement it? Any help or hint or link is much appreciated. Thank you in advance.
<?php require_once("funktion.php"); Uhrzeit(); ?> (Edit: changed `include` to `require_once`, since it is more appropriate for this task.)
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 1, "tags": "php, html" }
How can I find a value in 4 tables? I have 4 tables in sql developer (TABLE, TABLE1, TABLE2 and TABLE3) and I would like to know if a certain value exist in one of this 4 tables (for example TIE = 100). The 4 tables have the same structure with "TIE" column. I would like to know in which table the TIE value equals 100. I have written this in sql, but it doesn't work : SELECT TIE , instr FROM (SELECT TABLE1.TIE, 'terre' instr FROM TABLE, TABLE1 ) UNION (SELECT TABLE2.TIE, 'air' instr FROM TABLE, TABLE2 ) UNION (SELECT TABLE3.TIE, 'mer' instr FROM TABLE, TABLE3 ) WHERE TIE = '100'; Any help would be appreciated...
Below query might give the required result :- select TIE,instr from ( SELECT TIE,'terre' instr FROM TABLE UNION SELECT TIE,'terre' instr FROM TABLE1 UNION SELECT TIE, 'air' instr FROM TABLE2 UNION SELECT TIE,'mer' instr FROM TABLE3 ) A where TIE=100
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, inner join, union" }
Como modificar un arreglo Estoy resolviendo este problema: Escribe un programa que lea una secuencia de enteros y un entero y que reimprima la secuencia dada, reemplazando los enteros que no son múltiplos de por una X mayúscula. Ya tengo la parte donde en arreglo reconoce cuales son los multiplos, pero me falta colocar las X en la parte del arreglo donde no hay multiplo. int main(){ int a,b; int res=0; cin>>a; int arr[a]; char brr[a] = {'X'}; for(int i=0; i<a; i++){ cin>>arr[i]; } cin>>b; for(int i=0; i<a; i++){ if(arr[i]%b == 0){ cout<<arr[i]<<" "; } } } ![introducir la descripción de la imagen aquí]( Se supone que asi tiene que quedar el ejercico, ya solo me falta poner las X, pero no logro hacer eso.
Buen día, Te hace falta escribir la acción en caso de que no sea múltiplo En tu `if` ya consideras si es un múltiplo o no, solo agrega el `else` if(arr[i]%b == 0){ cout<<arr[i]<<" "; } else { cout<<brr[0]<<" "; } Ejemplo completo: int main() { int a,b; int res=0; cin>>a; int arr[a]; char brr[a] = {'X'}; for(int i=0; i<a; i++){ cin>>arr[i]; } cin>>b; for(int i=0; i<a; i++){ if(arr[i]%b == 0){ cout<<arr[i]<<" "; } else { cout<<brr[0]<<" "; } } }
stackexchange-es_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c++, dev c++" }
Bootstrap UI disturbance when using SELECT in Table I wanted to put a form field into Bootstrap's table classes and all was going well until I added a SELECT element to the form the bad juju crept in. Now -- while the form still works and kind of renders "ok" -- there are weird visual artefacts littered vertically at the horizontal start and end points of the aforementioned select dropdowns. The example can be seen here:[ [example]]( You have to click the button to get the modal control up and then scroll down vertically a bit to see the offending SELECT fields.
It appears that there is a defect in the rendering engine in Chrome for Mac. It doesn't appear in Windows Chrome or on Mac on Firefox or Mac Safari. Based on this I'm going to consider this closed.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "twitter bootstrap" }
Pthread server programming: how to release a thread which is blocked on a recv call to handle a request from another thread I have a simple server program, written in C on Debian using the pthread lib. The program handles the communication between some clients which want to share files. For each client there is a handler thread. Now, at some point, each thread will block on recv() waiting for any client file requests. If one of the clients asks for a specific file owned, by another client, the server has to get this file from its owner, through its handler thread, and then deliver the file to the client which requested it, through its handler thread. As all the threads are blocked on the recv() calls, how can they be noticed by other threads that they have to request a file to the client they are handling? Is there any way to "interrupt" the recv(), serve the request and then go back to the recv()?
The classic way to do this is to create a `pipe()` for each thread, and instead of blocking on the `recv()` call, the thread blocks in `poll()` monitoring both the socket and the read end file descriptor of the pipe. When `poll()` returns, if the socket is readable then call `recv()`; if the pipe is readable then read from it and check for requests from other threads. When you want to make a request to another thread, you can wake it up by writing to that thread's pipe.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c, multithreading, pthreads, recv" }
In-class member initialization with an initializer list using uniform initialization syntax? I am trying to compile the following with MSVC2013: class SomeClass { struct SomeStruct { bool a,b,c; }; SomeStruct ss{false, false, false}; } The compiler gives me the following error: `SomeClass::SomeStruct::SomeStruct: no overloaded function takes 3 arguments.` If I change the code to this: class SomeClass { struct SomeStruct { bool a,b,c; }; SomeStruct ss{{false, false, false}}; } the program compiles and runs fine. Is this a problem with the compiler, or do I not understand the syntax? From what I've been reading, the first version should compile.
Here is the responsible grammar from N3797: // after a member declaration: braced-or-equal-initializer-list: = initializer-clause braced-init-list braced-init-list: { initializer-list ,OPT } { } initializer-list: initializer-clause initializer-list, initializer-clause initializer-clause: assignment-expression braced-init-list So I'd say the first statement is correct and it is indeed accepted by a recent `gcc` and `clang`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "c++, c++11, initializer list, uniform initialization, in class initialization" }
find_or_create_by - not updating I'd like to submit a product ID and a retailer ID to my controller, if that combo exisiting in the DB I want to update that record with the submitted params, if not, create a new record. My controller is below and currently I can see that if the the combo does not exist the record is created but when the combo is found it does a select query and the record is not updated. How can I get it to update and not just select? Thanks Controller: def AddNewPrice @newPrice = ProductPrice.find_or_create_by(product_id: params[:product_id], retailer_id: params[:retailer_id]) end **Update** Sorry..Just to mentioned, when I update I want to update the price attribute that comes in as a param
As, its clear from method name that it finds record matching given conditions, or create a new record with product_id, and retailer_id given, if record does't exists. You need to do some thing like this to update records def add_new_price new_price = ProductPrice.find_or_create_by(product_id: params[:product_id], retailer_id: params[:retailer_id]) new_price.update_attributes({attr: params[:attr]}) end
stackexchange-stackoverflow
{ "answer_score": 7, "question_score": 9, "tags": "ruby on rails, ruby, activerecord" }
SQL Server 2005 login issue I have SQL Server 2005 SP3 running one server with mixed mode authentication. I tried to connect to the database engine, using the SQL Management Studio installed on the same machine. But I get a login error that says Login failed for user *user*, (Microsoft SQL Sever, Error: 18456) Strangely I'm able to connect to the Database through SQL Server Management Studio running on a different server. What am I doing wrong?
Okay, I solved the problem myself. Thank you all for your answers. I found this link which solved the problem < Basically, I started Reporting Services configuration by going to **Start > Program > Microsoft SQL Server > Configuration Tools** and connected to **Reporting Server**. Then filled out the information in **Database setup node** and clicked apply. After this I was able to use SQL Server Management Studio in the local machine to connect to the SQL server
stackexchange-serverfault
{ "answer_score": 1, "question_score": 0, "tags": "sql server 2005, login" }
Get IP that the server is running on I'm trying to get the IP of my server. I couldn't use `Bukkit.getServer().getIp()` because I would need to set `server-ip=` in the _server.properties_ file.
In Java: InetAddress IP = InetAddress.getLocalHost(); System.out.println("IP: " + IP.getHostAddress()); Another way if you're using Servlet: request.getRemoteAddr();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "java, ip address, bukkit" }
How to split single column into multiple columns I have a SQL Server table table_name like: col1 col2 SomeString_1 23 SomeString_1 65 SomeString_1 300 SomeString_1 323 What I want to do is for one unique value in col1, I want to select all the values from col2 but each in it's own column. So the query should be something like: select col2 from table_name where col1 = 'SomeString_1'; But I need output in the form: 23 65 300 323 Basically each selected value should be in it's own column. So the result should always have one row and as many columns as the SomeString_1 is repeated. I tried to search on SO but few questions I found had different conditions.
Seems like OP is asking for separate column value for each row value: create table #Table1 (COL1 VARCHAR(100), COL2 VARCHAR(10)) INSERT INTO #Table1 VALUES ('SomeString_1', '23'), ('SomeString_1', '65'), ('SomeString_1', '300'), ('SomeString_1', '323') DECLARE @columns nvarchar(MAX) = STUFF(( SELECT DISTINCT ',[col-' + cast(row_number() over (order by (select 1)) as varchar(4))+']' FROM #Table1 FOR XML PATH('')), 1, 1, '') DECLARE @sql nvarchar(MAX) = N' SELECT * FROM ( SELECT col2, ''col-'' + cast(row_number() over (order by (select 1)) as varchar(4)) as dupcol2 FROM #Table1 where col1 = ''SomeString_1'' ) T PIVOT (MAX(col2) FOR dupcol2 IN ('+@columns+')) P' EXEC (@sql) Output: col-1 | col-2 | col-3 | col-4 ------------------------------ 23 | 65 | 300 | 323
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "sql, sql server" }
changing class properties with its methods I'd like to change my class properties with a method defined for that class: classdef triangle<handle properties a h end methods function obj = triangle() obj; end function obj = setProps(obj, a, h) obj.a = a; obj.a = h; end end end Calling: t = triangle(); t.setProps(a, h); It's not working at all - I get this error: The class 'handle' is not a super-class of class 'triangle', as required to invoke a super-class constructor or method. Error in triangle (line 13) function obj = triangle() I'm using matlab 2012a. My code is based on this example: link
Try `clear` before doing this. It is possible that you've overwritten `handle` with something. Otherwise, this works for me on Matlab 2012a: clear; a = 'hello'; h = 1; t = triangle(); t.setProps(a, h);
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "matlab, methods, properties" }
static const vs #define Is it better to use `static const` vars than `#define` preprocessor? Or maybe it depends on the context? What are advantages/disadvantages for each method?
Personally, I loathe the preprocessor, so I'd always go with `const`. The main advantage to a `#define` is that it requires no memory to store in your program, as it is really just replacing some text with a literal value. It also has the advantage that it has no type, so it can be used for any integer value without generating warnings. Advantages of "`const`"s are that they can be scoped, and they can be used in situations where a pointer to an object needs to be passed. I don't know exactly what you are getting at with the "`static`" part though. If you are declaring globally, I'd put it in an anonymous namespace instead of using `static`. For example namespace { unsigned const seconds_per_minute = 60; }; int main (int argc; char *argv[]) { ... }
stackexchange-stackoverflow
{ "answer_score": 155, "question_score": 254, "tags": "c++, c, constants" }
Remove empty values from hash I have recive such params from request params[:search] = {"user_id_in"=>[""], "status_in"=>[""], "priority_in"=>["", "8"]} I need to clear it, because metasearch gem works incorrect with it params[:search] = {"priority_in"=>["8"]}
I have a solution with double select usage: params[:search] = {"user_id_in"=>[""], "status_in"=>[""], "priority_in"=>["", "8"]} params[:search].select! do |k, v| v.select! do |vv| !vv.empty? end v.length > 0 end
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "ruby, ruby on rails 3" }
Error in selenium when we execute multiple times In Selenium first I record the some scenario and execute the test case, it works fine. Next execution however results in an error message > Element not found When I run the same test case, it is displaying the error message. Sometimes it is execution is working the same commands. Please help me to solve the issue
Multiple reasons for getting ' _Element not found' error_. Some solutions: **Reason 1** : If driver/script tries click/check the Web-element before it's loading then you might get the same message. **Solution** : Try using **WaitAndClick**. **Reason 2** : If the attribute used to locate Web-Element is Dynamic. **Solution :** Try using other attribute if Web-Element which is unique and static.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "selenium" }
Imbalanced class with same rows? In my dataset i have 3 classes-> 0,1,2. 0(72k),1(13k)and 2(13K) in brackets are there count. So whenever i try to predict them with any algorithm ,i observed that almost all the "2"'s are predicted as "0". On little exploration i found that there are some rows where attributes of 0 and 2 are exactly same. Any technique to tackle this issue?
The further exploration of your data would help. Are there, for example, some clusters where relative frequencies of your classes are much different from average? Now I see two ways to increase sensitivity of your algorithm toward class 2: 1. Use probabilistic prediction. Maybe what you really need is to estimate the probability that the current example belongs to class 2. If identical observations are sometimes marked as 0 and sometimes as 2, you cannot do much better then say "with probability X this is the second class". 2. Use `class_weights` and increase them for class 2. This will lead to more predictions of 2 and less predictions of 0 and 1. With imbalansed datasets it sometimes helps.
stackexchange-datascience
{ "answer_score": 1, "question_score": 0, "tags": "python, data, class imbalance" }
calculate $\frac{\partial f }{ \partial \operatorname{Re} (z)} $ from $\frac{\partial f }{ \partial z}$ for meromorphic function $f(z)$ is a meromorphic function, how to derive $\frac{\partial f }{ \partial \operatorname{Re} (z)} $ if the derivative $\frac{\partial f }{ \partial z} $is given? I guess $$ \frac{\partial f }{ \partial \operatorname{Re} (z)} =\frac{\partial f }{ \partial z} $$ $$ \frac{\partial f }{ \partial \operatorname{Im} (z)} =i\frac{\partial f }{ \partial z} $$ I tested the two equations with a special case $f(z)=(m+ni)z^2$, where $z=a+bi$. $$ \frac{\partial f }{ \partial \operatorname{Re} (z)} = 2(m+ni)(a+bi) $$ $$ \frac{\partial f }{ \partial \operatorname{Im} (z)} = 2(-n+mi)(a+bi) $$ Am I right? Happy holiday!
Let $z=x+iy$ and $f(x+iy)=u(x,y)+iv(x,y)$. So: $$\frac{\partial f(x+iy)}{\partial x}=\partial_x u(x,y)+i\partial_xv(x,y)=f'(x+iy)$$ Why? Because: \begin{align} f'(x+iy) &= \lim_{h\to 0, k=0} \frac{u(x+h,y+k)+iv(x+h,y+k)-u(x,y)-iv(x,y)}{h+ik}\\\ &=\lim_{h\to 0} \frac{u(x+h,y)-u(x,y)}{h} +i\frac{v(x+h,y)-v(x,y)}{h}\\\ &=\partial_x u(x,y)+i\partial_x v(x,y) \end{align} So we may conclude: \begin{align} \frac{\partial f(z)}{\partial \operatorname{Re}{(z)}}=f'(z) \end{align} So your guess is right! The second expression you gave is also true. Verify it as I done above.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "complex analysis, derivatives" }
pull data from a Datagridview in vb I have my datagridview and i want to pass that info into a datatable or another place, i'm trying this Dim dt As DataTable dt = CType(DataGridView1.DataSource, DataTable) But i only get null, any ideas? I don't know how to get the info from the datagridview
I got a solution, it's a bit dirty but... it works for me Dim valor As Integer valor = DataGridView1.RowCount valor = valor - 2 For indice As Integer = 0 To valor ' DataGridView1.Item(0, indice).Value.ToString() ' DataGridView1.Item(1, indice).Value.ToString() ' in my case i only have two colums but if tyou have more you can use double for Next Hope this help somebody :)
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "vb.net, visual studio, datagridview" }
The Uniform convergence of $\sum\limits_{n=1}^\infty{\frac{\arctan(nx)}{1+(x-n)^{3}}}$ on $x \in [0, 10]$. I've stumbled upon this problem, while preparing to my exams. The problem is that I cannot understand which $M_n$ should I finally come to, trying to apply the Weierstrass M-test. I also couldn't have found similar-to questions here. I made several attempts, stating that $\forall n \in\mathbb{N}, \forall x\in E[0,10] : \arctan(nx) \leqslant nx$ or $\arctan(nx) \leqslant \frac{\pi}{2}$, but for some reason nothing works out for me. My best attempt for now was to state that the given $|u_n(x)| \leqslant \frac{\pi}{(n-x)^2}$, but the thing is that it is not true for all x in the given $E$. Thank you in advance for your help.
If $n>10$ and $x\in[0,10]$, then$$1+(x-n)^3>1+(10-n)^3=1-(n-10)^3,$$and so$$|1+(x-n)^3|>(n-10)^3-1.$$Furthermore, $\arctan(nx)<\frac\pi2$. Therefore,$$\left|\frac{\arctan(nx)}{1+(x-n)^3}\right|<\frac{\pi/2}{(n-10)^3-1}.$$Since the series$$\sum_{n=11}^\infty\frac{\pi/2}{(n-10)^3-1},$$converges, then your series converges uniformly, by the Weierstrass $M$-test.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "real analysis, sequences and series, uniform convergence" }
Django Viewflow with custom views - start different flows, depending on user selection in the first screen I have a view with `StartFlowMixin`, it contains a form - user posts the form and a workflow starts. That works fine currently, but I need to introduce a dropdown in the form with 4 options - based on the selection in that dropdown I need to run a different flow. E.g. the dropdown contains options like `Apply for position A`, `Apply for position B`, etc. Based on the selection the applicant needs to enter different information and different people need to approve the application. How can I do this? One option would be to have a single workflow with a lot of ifs, but I don't like that.
The core of the BPMN approach for business process modeling is to record every user's decisions. You could use flow.Switch for that case - < Or you could use your own view, that would call required flow.StartFunction, to start actual flow - <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "django viewflow" }
Gnome-do wont recognize anything after crashing I was trying to activate the Skype plugin for `gnome-do` and the app crashed on me. Now after restarting it, no matter what I type inside, it wont recognize anything. I have tried to re install it clean like this apt-get purge gnome-do apt-get install gnome-do and it still did not solve the problem. What can I do?
`apt-get purge` will only purge global configuration files. You might also have to remove your user-specific configuration files and data. For `gnome-do` all files should be located under the following folders: ~/.gconf/apps/gnome-do ~/.local/share/gnome-do **Note** : You can use `locate gnome-do` to identify any residual items pertaining to `gnome-do`. Sources: < <
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 1, "tags": "gnome do" }
Force.com IDE: Can't deploy Individual Fields (Option is not coming) I have downloaded Eclipse Mars2.0 on two systems. On one system's Eclipse, I am getting the option to select individual fields and on another system's Eclipse, I am not getting the option to select individual fields (here i am getting the option to select object only). Can anyone explain the reason why? ![enter image description here](
For me only reinstallation of Eclipse/jre helped and I used V37.0, cause v38.0 keeps on being buggy. Also when choosing at least one component the 'package.xml' is created in src folder. You can always manually add fields there as a quickfix. <types> <members>*ObjectAPIName*.*FieldAPIName*</members> <name>CustomField</name> </types>
stackexchange-salesforce
{ "answer_score": 0, "question_score": 6, "tags": "eclipse, force.com ide" }
iphone app that recognises colour Can you give me a starter point for creating an iphone app that recognises colour. I have seen this app < and it would be excellent to be able to find out the technique used for the colour recognition part. Thanks.
Probably the easiest way would be to display a `UIImagePickerController` with it's source type set to `UIImagePickerControllerSourceTypeCamera`. Once the user snaps a photo, you can then get a `CGImage` of the photo taken, and look for the color info that way. This question might help you with figuring out the color info you want.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "iphone" }
Solve the inequality $\sqrt { x + 2} - \sqrt { x + 3} < \sqrt { 2} - \sqrt { 3}$ Solve for $x$ real the inequality $$\sqrt { x + 2} - \sqrt { x + 3} < \sqrt { 2} - \sqrt { 3}.$$ Obviously $x\ge-2$. After that I tried to square the whole inequality, which led me to $x < \- \frac { 18} { 4\sqrt { 6} - 5}$. Now, the answer is $[-2;0) $. Should there be a different approach?
One approach: \begin{align} \sqrt{ x + 2} - \sqrt{ x + 3} &< \sqrt{ 2} - \sqrt{ 3} \\\ \sqrt{ x + 2} + \sqrt{ 3} &< \sqrt{ x + 3} + \sqrt{ 2} \tag{1}\\\ (x + 2) + 3 + 2\sqrt{ 3}\sqrt{ x + 2} &< (x + 3) + 2 +2\sqrt{ 2}\sqrt{ x + 3} \tag{2}\\\ 2\sqrt{ 3}\sqrt{ x + 2} &< 2\sqrt{ 2}\sqrt{ x + 3} \tag{3}\\\ 3(x + 2) &< 2( x + 3) \tag{4}\\\ x &< 0 \tag{5} \end{align} where we > $(1)$ added $\sqrt{ x + 3} + \sqrt{3}$ > > $(2)$ squared both sides (they are positive) > > $(3)$ subtracted $x+5$ > > $(4)$ divided by $2$ and squared (again both sides are positive) > > $(5)$ subtracted $2x+6$ Now just combine it with the condition $x\geq -2$ and you are done.
stackexchange-math
{ "answer_score": 1, "question_score": 2, "tags": "algebra precalculus, inequality" }
You say something but you don't really mean it: an adjective to describe that offer or a phrase What adjective do you use to describe something that you say, but you do not really mean it. For example when you make an offer to someone, but you don't really mean it and kind of hope they say no! Let's say in a rather insincere way, although you are trying to be polite. What type of offer is that? Or is there a phrase or something used to refer to that?
That type of offer is called an **_Empty_ gesture**. Urban Dictionary definition: > to say something without an intention of actually doing it. Making an offer that is not intended to be fulfilled or even taken up by someone.
stackexchange-english
{ "answer_score": 12, "question_score": 8, "tags": "single word requests, phrase requests, adjectives" }
Invalid label value on K8s on GCP An earlier version of my deployment in K8s had `"${PROJECT_NAME}"` as a label value in preferredDuringSchedulingIgnoredDuringExecution. I realized my mistake and the value is now changed to "api". So far so good. The problem starts I scale my node pool to more than one node. Then I get this error: invalid label value: "${PROJECT_NAME}": at key: "app": a valid label must be an empty string or consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character (e.g. 'MyValue', or 'my_value', or '12345', regex used for validation is '(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])?') It seems like the old value is still stored somewhere in the system. I have therefore checked all the YAML's and none have the wrong value in it anymore. What can I do? PS: I'm using helm for deploying those YAML's
You haven't provided the details if you are redeploying your Helm charts, but it sounds like you are redeploying after the node pool is scaled and the `${PROJECT_NAME}` substitution is not happening before deployment. I would recommend finding out where `${PROJECT_NAME}` is in your Helm chart and just substitute it with just `api` and see if that's the issue. Then go back and find out if maybe (?) you are using bash (or some shell to deploy) and `${PROJECT_NAME}` is missing from your environment (?).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "kubernetes, google cloud platform" }
Destroy “freewall” jquery plugin draggable function after clicked Currently I'm using freewall plugin to build my grid view page (< HOwever, there is a function to switch the grid view to listing view so that I'd like to destroy the function and make my div clean. Found the question asked here: Destroy a freewall instance At which, the answer in this question is: $('#freewall').freewall('destroy') or $('#freewall').destroy() How do I remove the draggable function after button clicked?
You need to reset the firewall instance's properties. For this you need to use `reset()` method and set `draggable` (boolean property) to false on button click. For eg: **Your firewall instance:** var wall = new freewall('.free-wall'); **The button click handler:** $("button").click(function(){ wall.reset({ selector : '.brick', draggable : false //remove element's draggable property }); }); Please refer to **link** for more details
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "jquery, html, css, jquery plugins" }
Pythagorean theorem painting I came across this painting(< which clearly shows a dissection proof of the pythagorean theorem. The closest proof I found was #72 on this page. I have two questions. 1) Would someone be kind enough to walk me through a proof of the #72 diagramm on the above page and 2) Can anyone suggest a proof based on the dissection in the painting. Thanks in advance!
As @DavidQuinn notes, the appearance of the black equilateral triangle forces the right triangle to be $30^\circ$-$60^\circ$-$90^\circ$. However, as @G.Sassatelli notes, the "orange+green+black" subdivisions aren't actually relevant to the dissection, since those elements are treated as a fixed grouping. If we ignore the black equilateral triangle, and merge the "orange+green+black" into a single quadrilateral region, then the dissection ---which applies to arbitrary right triangles, so long as $a$ is the shorter leg--- can be understood by observing multiple appearances of the $a$-$b$-$c$ triangle throughout the figure. Labeling various edge-lengths should make this pretty clear: ![enter image description here]( As for proof of Cut-the-Knot's #72 ... I'll have to come back to that.
stackexchange-math
{ "answer_score": 4, "question_score": 6, "tags": "geometry, art" }
SQL Server Primary Login Restrictions I have read only routing setup and working fine. I have a SQL login that accesses the readable secondary via the listener using `ApplicationIntent=ReadOnly`. However I want to prevent the user from accessing the primary. I have seen a lot of topics on this and they all seem to suggest disabling the login on the primary. When I do this connections to the listener with `ApplicationIntent=ReadOnly` fail with `Login failed for user ''. Reason: The account is disabled.` I have ensured the accounts are the same SID. Thanks for any help.
> I have a SQL login that accesses the readable secondary via the listener using ApplicationIntent=ReadOnly. However I want to prevent the user from accessing the primary. More specifically: > The user should not be able to connect to the primary replica, only secondary. In this case, it's not possible to do what you're wanting. You can't use read only routing with this as the first step in read only routing is to connect to the primary to _check_ if the requirements to meet read only routing are correctly used and then get the metadata from the primary to understand where the new connection should take place. You can, however, use something such as a network load balance appliance to dynamically update a cname or A record (AAAA if IPv6) to always point to a secondary. This would be specific to the load balancing software/hardware you choose to use. You could also write your own with a trivial amount of work.
stackexchange-dba
{ "answer_score": 5, "question_score": 4, "tags": "sql server, availability groups, sql server 2017" }
C++ Como chamar um outro arquivo cpp no script Eu tenho dois arquivos cpp. Um é o principal, o outro é um secundario que vai abrir programas do windows. Então eu inclui os dois na mesma pasta. No arquivo principal, eu adicionei: `#include iapt2.cpp` que é a segunda parte do script, porem ele diz que não tem arquivo no diretorio. Como posso resolver isso?
Tente: #include "nomedocpp.h" OBS: utilize aspas
stackexchange-pt_stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c++" }
Find a simple speech engine I'm doing a project on text recognition. One of the main points here is text-to-speech translation after the recognition. Could you help me find a very **simple** , plain speech engine for **C++ Builder project**? All that I've found were not only very complicated, but also they were suitable for MFC. So, the problem is that I'd like to convert **text to speech**. No recognizing, just simple convertion. Please share some info about this problem, maybe I should look it up somewhere? Basically, I do not even know, if I'm calling it right, so I'm sorry for misunderstanding if it happens.
Microsoft's Speech API (SAPI) is implemented as a set of COM objects, and thus is usable in C++Builder projects with minimal effort.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++, audio, c++builder, text to speech" }
"A number of students" vs. "the number of students" > **Possible Duplicate:** > A number of questions "has been" or "have been" asked? From the grammatical view both are correct, but please explain the difference in meaning: 1. The number of students in the class **is** fifteen. 2. A number of students **were** late for class.
> The number of students in the class is fifteen. The verb is singular because it refers to 'the number'. The subject of this sentence is 'the number'. 'Of students' is a modifier of 'the number' 'A number of' means several, some. > Several students were late for class. > > Some students were late for class. > > A number of students were late for class. The subject of these sentences is 'students', and 'some', 'several', 'a number of' are modifiers of 'students'. The verb agrees with the subject.
stackexchange-english
{ "answer_score": 7, "question_score": 14, "tags": "meaning, grammatical number, verb agreement" }
How to JOIN three tables in Codeigniter I'm using codeigniter framework to develop one music cms. i have 3 tables in mysql database, Currently im working in "Album" Table and "Model, Controller". i want to SELECT "Album" Table 1 and JOIN "Album" -> "cat_id" with "Category" -> "cat_id", and fetch all categories records. Then i want to JOIN "Album" -> "album_id" on "Soundtrack" -> "album_id" then fetch all soundtrack records A to Z. Please somebody help me to show proper codeigniter query, how i can SELECT and JOIN Tables then fetch records from 3 tables, ? **Table 1 -> Category** * cat_id * cat_name * cat_title * date **Table 2 -> Album** * cat_id * album_id * album_title * album_details **Table 3 -> Soundtrack** * album_id * track_title * track_url * date
Use this code in model public function funcname($id) { $this->db->select('*'); $this->db->from('Album a'); $this->db->join('Category b', 'b.cat_id=a.cat_id', 'left'); $this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left'); $this->db->where('c.album_id',$id); $this->db->order_by('c.track_title','asc'); $query = $this->db->get(); if($query->num_rows() != 0) { return $query->result_array(); } else { return false; } }
stackexchange-stackoverflow
{ "answer_score": 50, "question_score": 20, "tags": "php, mysql, codeigniter, join" }
Unset a property from codebehind I have this TextBox that has a MaxHeight value of 62 by default in my XAML file, and I want to programmatically unset it from codebehind on a certain event. Sadly, this: myTextBox.MaxHeight = 0; actually sets the maximum height to zero... making it invisible. Isn't there a method on UI elements to purely **unset** a specific property?
You can set it back to it's default value: myTextBox.MaxHeight = double.PositiveInfinity; This allows the text box to grow to "any height".
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "silverlight, xaml, silverlight 4.0, dependency properties" }
Input Validation on the go I want to validate a year in the form (XXXX) after the user enters 4 digits into the box, once the user has entered 4 digits I want to have that value so I can pass it to an ajax call. <h6>What year was the car manufactured</h6> <input name="car_year" type="text"> <div class="car_make_error car_year_error">Car Year Error</div> jquery: $("input[name='car_year']").change(function() { validate to make sure 4 digits are in the proper range and get the value of the 4 digits } I know I could use key up but I was not exactly sure how any help would be appreciated. **EDIT** I've used this code: $(car_year).keyup(function() { var year = $(this).attr('value'); $('.car_year').html(year); });
Looks like you were already on the right track. Is this what you need? $(function() { var LOWER_RANGE = 2000; var UPPER_RANGE = 2020; var $carYearInput = $('#car_year'); $carYearInput.keyup(function() { var value = $carYearInput.val(); // Check that we were given 4 numbers if(value.match(/^[0-9]{4}$/)) { // Convert the value to an int var year = parseInt(value, 10); // Check that the year is in range if(year > LOWER_RANGE && year < UPPER_RANGE) { alert(year); } } }); });
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "jquery" }
Ionic2 Build folder structure missing I'm starting to learn `Ionic2`, I have created a new project with `ionic start myproject --v2` and everything works correctly if I do `ionic serve`. The build folder is missing in ionic 2 project folder. Whenever I am trying to download any existing `Ionic2` template in that one also build folder missing. ionic -v 2.0.0-beta.30 cordova -v 6.2.0 node -v v6.2.1 npm -v 3.9.5 ![enter image description here](
First you need to add support for the platform/s you are working with, by executing from Ionic CLI console: ionic platform add android or ionic platform add ios And then you should build your project by executing: ionic build android or ionic build ios
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": 0, "tags": "ionic framework, angular, ionic2" }
Is macbook air 501 64-bit or 32-bit? Which version of Eclipse should I choose? The information from "unname -a" tells that it is i386. But I found that some applications in the Activity Monitor are with types "Intel 64". What's more, the System Profiler says:64-bit Kernel and Extensions, no. So, which version of Eclipse should I choose, 64-bit or 32-bit?
The same of Java, try java -version 32-bit: java version "1.6.0_26" Java(TM) SE Runtime Environment (build 1.6.0_26-b03) Java HotSpot(TM) Client VM (build 20.1-b02, mixed mode, sharing) 64-bit: java version "1.6.0_20" Java(TM) SE Runtime Environment (build 1.6.0_20-b02) Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "java, eclipse, macos" }
git pull conflicts when pulling a non current branch I have a problem when manipulating git pull. Consider I have 2 branches on my remote (origin) repository : A and B. The remote B branch is ahead of the local B branch by 1 commit. This additional commit (on the remote B branch) just add a new file, say "newfile". In my local branch A, I have a file "newfile" and its content is different from the one of the remote B branch. Then, I run this commands: git checkout A git pull origin B:B I can see the following behavior: the branch B is updated as I expected. B has been fast-forwarded, and then contains "newfile". But I also have a conflict on "newfile". and in my current directory, the file "newfile" contains the conflicts markers. Why is there a conflict while the merge has already been done ? Thank you.
I think I misunderstood the semantics of git pull. I thought that : git pull origin B:B meant : fetch the remote B + merge the remote B into the local B I realize that it means : fetch the remote B and updates (if fast-forward is possible) the local B + merge the remote B into the local branch In fact git pull will always make its merge into the local branch, independently of the refspec. In other words, pull = fetch + merge. The update of the local B branch is done by "fetch", and the conflict is generated by the following merge operation (into the local branch).
stackexchange-superuser
{ "answer_score": 0, "question_score": 0, "tags": "git" }
How to detach branch from the parent in git? I'm trying to detach `develop` branch from `master`. The `develop` branch was intended to be separate branch not a child of `master`. So I need the following: A---B---C (master) \ D (develop) into: A---B---C (master) D (develop) The intention to move into Gitflow workflow at existing project. Even if you think something isn't logical here - I just want to know how to do it :)
# preserves branch config, remotes, reflog, merge options, what not git rev-parse develop >.git/info/grafts git filter-branch -- develop rm .git/info/grafts or # preserves branch config etc git log -1 --format=%B develop \ | git commit-tree develop: \ | xargs git update-ref refs/heads/develop or # wipes branch config etc and you'll have to redo the commit message git checkout develop^0 git branch -D develop git checkout --orphan develop or # preserves branch config etc git checkout develop git checkout --orphan junk git commit -C develop git checkout -B develop git branch -D junk
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "git, github" }
Create points pattern in R using spatstat package with specified number of points Is it possible to generate points pattern with Poisson and Thomas process in R using spatstat package with specified number of points? I had genereted Strauss point pattern using the Metropolis-Hastings algorithm with specified number of points (20 points) like this: Model <- list(cif="straush",par=list(beta=10,gamma=0.5,r=0.5,hc=0.5), w=c(0,10,0,10)) P <- rmh(model=Model,start=list(n.start=20), control=list(p=1,nrep=1e5,nverb=5000)) but I can not generate Poisson or Thomas point pattern using the Metropolis-Hastings algorithm.
As also pointed out in off-site correspondence: A Poisson process conditional on the number of points is just a collection of independent and identically distributed points with density proportional to the intensity, so you can use the spatstat function `rpoint` to simulate that process. I don't think it is mathematical tractable to express the distribution of a Thomas process conditional on the total number of points inside the observation window.
stackexchange-stats
{ "answer_score": 1, "question_score": 0, "tags": "r, point process" }
CMD get string from file and SET it as a variable to use in cd I'm new to batch files and I'm trying to write one to do part of my work (I know lazy right) So far I have the following... SET skip=1 REM for all the directories indicated to contain core repositories FOR /F "skip=%skip% delims=" %%i IN (C:\Repos.txt) DO ( SET TgtDir =%%i echo %TgtDir% >> C:\result.txt ) The contents of Repos.txt is: 60000 C:\somedir\someotherdir\ C:\a\b\c\ Basically I want this script to go through a file, ignoring the first line which will be used for a delay setting later, and extract each line then (ideally) pass it to a cd command but for now I'm just trying to get it into the variable TgtDir. When i run this script the output in C:\result.txt is: ECHO is on. ECHO is on. Any help?
You'll want to look at the EnableDelayedExpansion option for batch files. From the aforementioned link: > Delayed variable expansion is often useful when working with FOR Loops. Normally, an entire FOR loop is evaluated as a single command even if it spans multiple lines of a batch script. So your script would end up looking like this: @echo off setlocal enabledelayedexpansion SET skip=1 REM for all the directories indicated to contain core repositories FOR /F "skip=%skip% delims=" %%i IN (C:\Repos.txt) DO ( SET TgtDir=%%i echo !TgtDir! >> C:\result.txt ) As an alternative, just use the `%%i` variable in your inner loop, rather than creating a new variable.
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 5, "tags": "batch file, cmd" }
Is there a workaround for SSL Renegotiation Attack? I read that the theoretical weakness in SSL has been proven real. Is there a workaround that we can apply as users or admins to protect our users/selves?
The hole only allows for data to be injected, if that injection can cause a data leak of some kind, then you'll need to re-work the server side program to ensure that injected data cannot cause the leaking of sensitive information. That is, the user's session remains secure on the outbound side (that is, server to client), those communications remain secret, the communications from the inbound side (client to server), the data from the client still remains secret as well, however, that data can have information appended or prepended to it by a man-in-the-middle attack. So, there is no need for a workaround unless your server/service is made to be vulnerable by this type of attack, and if it is, then the workaround would be specific to your web application.
stackexchange-serverfault
{ "answer_score": 1, "question_score": 2, "tags": "security, ssl" }
using fourier series to find the sum of series I have a question about this. Using only the fact that $$ 1 + \frac{1}{3^2} + {1 \over 5^2} + .... = {\pi^2 \over 8} ,$$ can we show $$ 1 + \frac{1}{2^2} + {1 \over 3^2} + {1 \over 4^2} + .... = { \pi^2 \over 6}. $$ I know that the second sum has to equal that, but I don't know how to show it using just that fact? thank you!
Yeah! Think about the latter sum as: $$(1+1/3^2+1/5^2\cdots)+(1/2^2+1/4^2+1/6^2)=k$$ $\therefore (\pi^2/8)+(1/4)(1+1/4+1/9\cdots)=k$ ... and you notice something astonishing! $$\pi^2/8+k/4=k$$ which Ron Gordon essentially said. Take it from here to solve $k$
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "calculus, fourier series" }
Ruby REST client publish-subscribe communication possible or not? I am aware of rails REST interface which allow me to access sources. and I am aware of publish-subscribe strategy for message passing Is it possible to implement REST client(not browser but ruby client works on arduino device) to access resource if resource (ex. server informed client that resource is now available you can receive) available via publish subscribe strategy ? I am aware of Faye. is it possible to implement REST client using Faye to receive via publish-subscribe for ruby ? If it is not possible with Faye which can be other solution for Ruby REST client to build a publish subscribe communication ? How can Faye inform ruby client for resource notification ?
REST is based on HTTP, so it is Request-Response. you can't make Pub/Sub service with REST. If I were you, I would use Faye to notify client about new resources, or whatever you want to monitor. And after notification you can make Ajax request to REST and get new record for example. But the best approach is to use Faye for pushing changes to client. Don't be aware, it is quite simple.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ruby on rails, ruby, rest, faye" }
Convert integer into its character equivalent, where 0 => a, 1 => b, etc I want to convert an integer into its character equivalent based on the alphabet. For example: 0 => a 1 => b 2 => c 3 => d etc. I could build an array and just look it up when I need it but I’m wondering if there’s a built in function to do this for me. All the examples I’ve found via Google are working with ASCII values and not a character’s position in the alphabet.
Assuming you want lower case letters: var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ... 97 is the ASCII code for lower case 'a'. If you want uppercase letters, replace 97 with 65 (uppercase 'A'). Note that if `n > 25`, you will get out of the range of letters.
stackexchange-stackoverflow
{ "answer_score": 353, "question_score": 193, "tags": "javascript, integer, alphabet" }
Can two devices with different static IP addresses find eachother? The setup I currently have is two computers connected through a crossover cable. I am trying to use the command line or Python to find the ip address of the other computer. Is there any way I could get one of the computers to find the ip address of the other computer if they are on a different network number?
This depends on the network mask. Depending on the network mask used, the same IP address can end up in different networks. To communicate directly (without routers involved), two devices need to be on the same network. Have a look at this post: <
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "networking" }
Common-mode choke with inputs shorted together I came across this configuration in a schematic, and it makes no sense to me. I have to admit common-mode chokes are not my strong suit, but is this even going to act as an inductor? !schematic simulate this circuit - Schematic created using CircuitLab
It'll act like an inductor with an inductance equivalent to one of the windings. Imagine both inductors as bifilar windings like this: - ![enter image description here]( Image from here. If you think about it, it might as well be one inductor with a wire of twice the cross-sectional area. And, of course, it gives you lower copper losses. > _is this even going to act as an inductor?_ If the winding dots were on different ends then, it won't particularly act as an inductor other than having an inductance that is very much smaller (defined by leakage inductance) and fairly tricky to predict in value.
stackexchange-electronics
{ "answer_score": 8, "question_score": 3, "tags": "inductor, common mode" }
What's the best way to acquire a list of strings that match a string inside a string, by looking through a string list? Basically I have a string array that I am using to match inside a single string: string[] matches = { "{A}", "{B}", "{CC}" }; Then I from these I look if I find any of these inside my string: string text = "Lorem Ipsum is {CC} simply dummy text {A} of the {CC} printing and typesetting industry {B}." In which case, the resulting array I want to gather should be: string[] allmatches = { "{CC}", "{A}", "{CC}", "{B}" }; Is there an easy way to do this using LINQ or maybe Regex?
Construct the regex by first `Escape`ing each element in `matches` using `Select`, then `Join`ing with `|`. After that, get the `Matches` of the regex against `text` and `Select` the `Value`s: var regex = string.Join("|", matches.Select(Regex.Escape)); var result = Regex.Matches(text, regex) .Cast<Match>() .Select(x => x.Value).ToArray();
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, arrays, .net, regex, linq" }
Blocking dialog like construct in android Looking for a blocking,value returning dialog like custom construct in android. Something like this: Output outValue = MyPopupBuildingClass.showWindow(inValue, R.layout.my_layout); Yes that's the all too familiar `MessageBox` for `Windows programmers` :) and I think there is `JOptionPane` in Swing too. The complexity here is that I don't want a small default android dialog, but more of a popup fragment with some detailed layout and functionality. It accepts an object, pops up a window, lets user do something to it and return it back when user accepts or dismiss. Any thoughts?
Like @Luksprog said in comments, Blocking dialogs in android are hard to implement and should be avoided.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android, user interface, dialog" }
how to check if a checkbox is checked, convert tobool fails since its lower case 'false' I am doing: `convert.toboolean(request.form["mycheckbox"]` but since the value is 'false', it doesn't seem to cast to boolean. What should I do? I don't like checking for `== "false"` and then converting to boolean. is there a cleaner way? **Update** All I am doing is: if (Convert.ToBoolean(request.Form["somecheckbox"])) { }
Looks like the `Html.Checkbox` helper creates a checkbox and a hidden field, both with the name that you provide ("mycheckbox"). The hidden field appears to have the original value of the checkbox (though I could be off on what, exactly, its purpose is). I would say that if you're getting values manually out of the `Request` collection, you should be creating your controls manually, too, instead of using `Html.Checkbox` and similar helpers, which may add other stuff that the framework knows about but you don't. The other alternative would be to let the framework bind that value, rather than getting it manually.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net, asp.net mvc, checkbox" }
Do any laptops exist with multiple power connectors? Are any laptops available with multiple places a power cable could be plugged-in? It would be very handy to have a connector on either side of the machine, and not just one (for when the available outlet is on the other side from where the connector on the laptop is).
As of late 2018, at least Acer Chromebooks that power over USB-C (like this one) can be powered from either side
stackexchange-superuser
{ "answer_score": 1, "question_score": 2, "tags": "laptop, power supply" }
assigning a value to a class object i'm tasked with the job to create a class of strings and integers between 1 and 10. I basically did the following... class hello(): __slots__ = ('name', 'number') def __init__(self): self.name = myName self.number = myNumber The only problem is that I don't know how to make myNumber = an integer between 1 and 10. Similarly, how would I compare myNumber if it's assigned to a name to other objects? Thanks
You the constructor and enforce a check at assignment. Try doing this with the `property` decorator: class MyClass(): def __init__(self, value): self.something = value @property def something(self): return self.item @something.setter def set_something(self, value): if value is not None: self.time = value else: raise Error This is one way to put in logic which prevents setting a `None` value on a property of a class. You could also doing something with this to change it to check the values you want it to be.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "python, class" }
resource files under webapp/WEB-INF or src/main/resources? In my project i see some xmls under `src/main/webapp/WEB-INF` while some under `src/main/resources`. Is there any convention what kind of file should go under these location
src/main/resources contains Application/Library resources. The Servlet 2.4 specification says this about WEB-INF: A special directory exists within the application hierarchy named WEB-INF. This directory contains all things related to the application that aren’t in the document root of the application. The WEB-INF node is not part of the public document tree of the application. No file contained in the WEB-INF directory may be served directly to a client by the container. However, the contents of the WEB-INF directory are visible to servlet code using the getResource and getResourceAsStream method calls on the ServletContext, and may be exposed using the RequestDispatcher calls.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 6, "tags": "java" }
How to get the id of closest input text without jquery? Doing my project in IE 7 (unfortunately). I have this DOM where I want to know the ID of the closest input text that is positioned after the button I clicked, not the input text before it. Here's the example DOM: <input type="text" id="txt1" /> <br/> <button>Get ID</button> <input type="text" id="txt2" /> <br/> I know how to do it in Jquery but does someone know how to do it the 'hard' way (if possible)? Thanks.
It should be easy if they're always siblings like that. var nextInputId = buttonClicked.nextSibling.id; jsFiddle. This is fragile and not recommended for anything but a very simple set of limited markup. Unfortunately, `nextElementSibling` isn't available until IE9, so if you have a text node there (even some whitespace), you're in for some pain. A pretty good solution that is relatively robust would be... var node = buttonClicked; var nextInputId = null; while (node = node.nextSibling) { if (node.tagName && node.tagName.toLowerCase() == "input") { nextInputId = node.id; break; } } jsFiddle.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript" }
How do I remove empty space using Regex? I have an object with a value that I save to a SQL database. When I run a report on the SQL database, I occasionally display a `&#x20;` in the report. I tried cleaning up the properties in my objects before saving them to SQL by using the following Regex: Regex rgx = new Regex("[^a-zA-Z0-9 - , = % & ( )]"); myObject.Description = rgx.Replace(myObject.Description, ""); The Regular expression is doing a good job removing some unwanted text. How do I use a Regular expression to remove `&#x20;` ?
Just add your string into the original regex delimited by `|` Regex rgx = new Regex(@"[^a-zA-Z0-9-,=%&()#\s]|&#x20;");
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, regex" }
Appending characters to RichTextBox from a handheld barcode scanner without it creating a new line for each character in the serial number I'm building an app that for a coworker that allows the user to scan a barcode using a handheld scanner. The app will automatically append that barcode to a RichTextBox. I have it fully working except for one problem: **When a user scans a barcode, it scans each character in a new line**. Example: A 1:20 PM R 1:20 PM C 1:20 PM 0 1:20 PM 1 1:20 PM instead of ARC01 1:20 PM Can someone tell me what am I missing in my code below? Private Sub RichTextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RichTextBox1.TextChanged Dim currentTime As String = Format(TimeOfDay, "HH:mm:ss") RichTextBox1.AppendText(" " + currentTime + vbLf) End Sub
Presumably whatever driver is feeding the input is doing it one char at a time. If you don't have control over that code, and you have a static number of chars in your bar code, you could wait for the line to contain that many chars and _then_ add the space, time stamp and linefeed. Something like Dim lastLine As String lastLine = RichTextBox1.Lines.Last If lastLine.Length = 5 Then RichTextBox1.AppendText(" " + currentTime + vbLf) End If
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "vb.net, visual studio 2010" }
Detect High density pixel areas in a binary image I am doing background subtraction, and I obtain a binary image with foreground objects and with some noise. I want to obtain a ROI for each object on the binary image and them analyze it to ensure that is the object that I want. How do I segment only the areas with high pixel intensity (objects)? One example of obtained image: ![Image example](
Have a look at openCv `simpleBlobDetector`, there are several configurable parameters to it and tons of tutorials online. The documentation can be found here: < Alternatively you could just convolve a white rectangle across multiple scale spaces and return the median values over each scale space.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -2, "tags": "c++, opencv, computer vision, roi, binary image" }
What is Core Data Source Fetch I am looking at the **Entity Mapping** panel of core data in Xcode, and notice a setting named **Source Fetch**. There are two options **Default** and **Custom**. What is this **Source Fetch** about? ![enter image description here](
> You specify the sourceExpression for the mapping using a combination of the the source fetch popup menu and the text view beneath it. You can select either the default fetch—in which case you can optionally specify a filter predicate for the fetch—or a custom fetch, in which case you specify the source expression directly. Entity Mapping Detail
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "xcode, core data, core data migration" }
App Store - Are updates automatically released on approval? As the question says, I am wondering whether UPDATED apps are automatically released onto the app store once they are approved? My update is finished and has been tested, and as it takes a few days to approve I would like to submit it for approval now. In the meantime I need to change update a few things on my server, however I do not want the app update to go live until I have finished my server stuff. Will the app go live immediately or do I get to choose the release date (after approval of course)? Many thanks
You have an option to * choose the release date * release immediately on approval * once approved wait until I release it, (wait for you to click the release button so you can make server changes) aka Version Release Control. This can all be done from iTunes Connect when submitting your application. However, if you select the option to "release when i'm ready" that application approval is only valid for that build. If you upload a new build, it must be re-approved.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "app store, itunes, app store connect" }
What's the official name of '.' and '->' operators in C and C++? Im curious if they have an official name or just 'dot' and 'arrow'? I try search this in cpluscplus and in Deitel, but didn't find anything
The C standard calls them _member access operators_ , but only in the index. They aren't given a name anywhere else except the one place in the index. In the same place, the `->` operator is called _arrow operator,_ the `.` operator is called _structure/union member operator._
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "c++, c, operators" }
Ubuntu 18.10: Installing nvidia drivers leads to black screen after GRUB I upgraded from Ubuntu 18.04 to 18.10 without any errors. When I restarted, I got a black screen with a blinking cursor (couldn't type anything) right after GRUB. Pressing Ctrl-Alt-F2 got me to a terminal session. I rebooted, then tried editing GRUB by pressing `e` and changing `quiet splash` to `nomodeset`. Pressed F10. It didn't work. I had to reboot, press Ctrl-Alt-F2 then remove the nvidia drivers by typing `sudo apt-get purge ^nvidia`. Only then was Ubuntu able to boot successfully. I installed the nvidia 340.107 drivers from the Additional Drivers tab in Software & Updates. Rebooting got me to the same black screen as before, and I had to purge the nvidia drivers again. System: AMD FX-6300 CPU, Asrock 970 Extreme mobo, 8 GB RAM, Nvidia GeForce 9600GT. Thank you.
I had this issue too with the nvidia drivers and Ubuntu 18.10. I found a thread on the French Ubuntu website which helped me. It's a fix for Ubuntu 17.10 but it worked for me on 18.10. Try this: 1. Edit `/etc/gdm3/custom.conf`: sudo gedit /etc/gdm3/custom.conf 2. Here uncomment the line #WaylandEnable=false which becomes also WaylandEnable=false Don't forget to save! With this you should be able to install the nvidia drivers (I'm using the 390 version which works for me). Source
stackexchange-askubuntu
{ "answer_score": 22, "question_score": 19, "tags": "boot, grub2, nvidia" }
How to define camel jetty routes for https request and pass the parameter to some api for authentication? I want to send https consumer request using camel-jetty component and that address returns some response in JSON format, below I mention my DSL code. from("jetty: I am getting this warning: [WARNING] java.net.SocketException: Permission denied at sun.nio.ch.Net.bind0 (Native Method) at sun.nio.ch.Net.bind (Net.java:433) at sun.nio.ch.Net.bind (Net.java:425) at sun.nio.ch.ServerSocketChannelImpl.bind But whenever I hit this HTTP URL in browser it will execute perfectly with authentication. If anyone knows what to do to perform this action in apache camel please help me it will be very cheerful for me and others. And how could I know which method camel using for sending a request like POST or GET. **Thank You**
Could you try this instead? I'll comment each line to help understand your problem. // endpoint to start your route. could be a http endpoint you expose via jetty, jms, vm, seda or any other option. Here I'm using the simplest one. from("direct:start") // logs on .to("log:DEBUG?showBody=true&showHeaders=true") // consume the endpoint .to(" // log the body to the console so you could process the response later knowing what to do (the token you are mentioning should be in here. .to("log:DEBUG?showBody=true&showHeaders=true") .to("stream:out") //or whatever you want to Don't forget the `camel-http` dependency for this example to work: <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-http</artifactId> </dependency> Cheers!
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "https, apache camel, maven jetty plugin" }
Trying to set squid proxy password on ec2 instance I'm trying to set up basic auth on squid proxy on an ubuntu 14.4 EC2 instance. I'm following < Following the article I tried to set a password for a user like so: What am I doing wrong? ubuntu@ip-172-31-36-156:~$ which htpasswd ubuntu@ip-172-31-36-156:~$ sudo sh -c 'echo "$PATH"' /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin edit: ubuntu@ip-172-31-36-156:~$ sudo find / -name basic_ncsa_auth ubuntu@ip-172-31-36-156:~$ ubuntu@ip-172-31-36-156:~$ sudo htpasswd /etc/squid3/passwd soad sudo: htpasswd: command not found
You don't have `htpasswd` installed on your system to manage HTTP users. You can use the one from the Apache HTTP Server utility programs ![Install apache2-utils]( package. Even though it's meant for Apache and not Squid, the password file format is the same (according to your reports).
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 0, "tags": "14.04, proxy, squid" }
this.innerHTML doesnt works for links? I want to get the following value: `I want this text`. function get(v){ alert(v); } <a href="javascript:get(this.innerHTML);">I want this text</a> I tried many combinations of this, this.innerHTML, etc.. They all return `undefined`... Any tips?
Try using the onclick handler instead: function get(v){ alert(v); } <a onclick="get(this.innerHTML); return false" href="#">I want this text</a>
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "javascript" }
If $a_n=\left[\frac{n^2+8n+10}{n+9}\right]$, find $ \sum_{n=1}^{30} a_n$ I am working on a problem, assuming high school math knowledge. > Let ${a_n}$ be the sequence defined by $$a_n=\left[\frac{n^2+8n+10}{n+9}\right]\,,$$ where $[x]$ denotes the largest integer which does not exceed $x$. Find the value of $ \sum\limits_{n=1}^{30} a_n$. I honestly do not understand the text in bold. The answer provided is $445$. Could you please explain what I should be looking at here?
$[x]$ is the largest integer which does not exceed $x$. For example, $[12.4]=12$, $[10.995]=10$, $[7]=7$, $[-2.3]=-3$. For this problem $\displaystyle a_n=\left[\frac{(n-1)(n+9)+19}{n+9}\right]=n-1+\left[\frac{19}{n+9}\right]$. For $n=1,2,\dots, 10$, $a_n=n$. For $n=11,12,\dots, 30$, $a_n=n-1$.
stackexchange-math
{ "answer_score": 3, "question_score": 3, "tags": "sequences and series" }
How to prove that $P(A \cap B) \leq P(A) + P(B)$ using $P(A \cup B) = P(A) + P(B) - P(A \cap B)$ I need to prove that $P(A \cap B) \leq P(A) + P(B)$ using $P(A \cup B) = P(A) + P(B) - P(A \cap B)$. So far I have: \begin{align*} P(A \cup B) & = P(A) + P(B) - P(A \cap B)\\\ P(A \cup B) - P(A) - P(B) & = - P(A \cap B)\\\ -(P(A \cup B) - P(A) - P(B)) & = P(A \cap B)\\\ -P(A \cup B) + P(A) + P(B) & = P(A \cap B)\\\ P(A) + P(B) - P(A \cup B) & = P(A \cap B) \end{align*} Is this correct so far? How do I finish the proof from here? Namely, where does the $\leq$ come from? Thanks so much!
Because $$P(A)+P(B)-P(A\cap B)=P(A\cup B)\geq0.$$
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "probability, inequality" }
Different actions for different causes of end editing I have a tableview with two textfields in each cell. My intended behavior is that the user can either drag the tableview to end editing or press Return to advance to the next cell/textfield. I have been trying to use the `textFieldShouldReturn` and `textfieldDidEndEditing` methods, however, I am unable to determine in the `EndEditing` method what the cause of end editing was. Should I be using some other method to determine that a `textfield` will end editing due to a drag?
First, you need a trigger when the table view is dragged. User this method from `UITableViewDelegate` func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { yourTextField.resignFirstResponder() } Now, you need to find your text field in this delegate method. I will just give you a hint on this. Since each cell has the textfield, in your `cellForRow` method, simply set your textfield's tag to be `indexPath.row`. Then in this delegate method, you can find our your cell and textfield by index number.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ios, swift, uitextfield" }
On-demand self-hosted AWS EC2 runner for GitHub Actions name: On-demand self-hosted AWS EC2 runner for GitHub Actions uses: machulav/ec2-github-runner@v2 with: github-token: *** ec2-instance-type: t2.micro ec2-instance-id: i-03d221ab975187b _Error: Error: The 'mode' input is not specified Error: The 'mode' input is not specified Error: TypeError: Cannot read property 'mode' of undefined Error: Cannot read property 'mode' of undefined_ Can anybody give how to mention **mode** in this with the start/stop operation?
* start - to start a new runner; * stop - to stop the previously created runner. Start mode is that you want to start a new runner even tho your precious build is still running. Stop mode means you want to stop the previous run and start a new one. github-token: *** ec2-instance-type: t2.micro ec2-instance-id: i-03d221ab975187b mode: start
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "amazon web services, github, amazon ec2, github actions" }