INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
batch file Subtracting hour current time on Windows I need to subtract, for example, 1 hour from current time in a .bat file on Windows 7. I do it like this. set day=%date:~0,2% set month=%date:~-7,2% set year=%date:~-4,4% :: ———————————————————————– set hour=%time:~0,2% set /A hour= hour - 1 if %hour% lss 0 set hour=23 if %hour% lss 10 set hour=0%hour% echo %year%-%month%-%day% %hour%:00 But the problem, it is get consistence when the subtracting results a day before on a month before. For example, this date, **2016-03-01 00:05** I get **2016-03-01 23:05**. I need to get **2016-02-29 23:05** I found several batch script to subtract one day, but nothing with hours or minutes.
It's not completely Batch, but I find that there are so many exceptions and special cases, that it's not worth it re-coding everything in Batch, especially when it's been done before. I like to just invoke Powershell from a batch file, like this. for /f "delims=" %%a in ('"powershell [DateTime]::Now.AddHours(-1).ToString('yyyy-MM-dd HH:mm')"') do echo %%a Output will be something like: `2016-10-18 02:05`
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "datetime, batch file, windows 7, date manipulation" }
What is the admin url in a Django template (and where is a list of all system urls)? I was looking at some Django examples and I've noticed that you can call certain urls with a variable like this `<a href="{% url auth_login %}">Log in</a></li>`. How would I call the admin page with the same idea? A more general question: is there a list of pre-defined url variables that Django uses? And how are they defined (how can they be overridden)? Some other ones I know that exist are `auth_logout` and `auth_password_change`.
It generally depends on urls you write in your **urls.py**. Relevant Django documentation: < When you add django.contrib.admin, you add its urls by using `(r'^admin/', include(admin.site.urls)),`, which you can view here: <
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "django" }
Why is superconductance not observed at regular ambient temperatures? I have done some reading on superconductance and understand that the reason it happens is due to the formation of Cooper pairs resulting from the attractive momentary charge concentration resulting from a phonon. (As a side-question, is that very different from London dispersion force or a temporary dipole in essence?) What I don't understand is why an electron would cause a phonon to be produced resulting in a Cooper pair at 4 Kelvin but that same election wouldn't at 273 K. Is this because Cooper pairs have relatively weak bonds? Is it just really energetically unfavorable to have these two electrons hanging out in a net-zero spin state? Does nature abhor electrons violating the Pauli exclusion principle?
So upon looking into this further, it looks like Cooper pair interactions are pretty weak, on the order of 10^-3 eV. As such, I'm guessing the reason that we see superconducting at low temps and not at higher temps (with a few "hot superconductors" making an exception) is because at higher temperatures there is enough energy in the system such that Cooper pair interactions would last only momentarily such that you wouldn't have all of the electrons flowing in the conductor taking on a Cooper pair formation simultaneously to allow resistance-free conductance. I feel that's a sufficient answer and this question can be closed.
stackexchange-physics
{ "answer_score": 1, "question_score": 0, "tags": "superconductivity, phonons" }
Adding additional parameters to image classification in ArcGIS for Desktop? I have an RGB ortho rectified Image and I have another grid data with Elevation values. However, an image with only three bands does not give a good classification of landcover, so it is important to add additional information e.g. pattern or elevation data from another dataset. I only have access to ArcGIS software so I wish to know how I can do this in ArcGIS for Desktop? !The following Image will be the Input of classification.
Are you trying to merge the DEM with the imagery as a fourth band? I don't think elevation is a valid dataset for land use classification. However, as you indicated, the pattern of the land derived from the DEM might be better. You may want to look into **Composite Bands**. That will add your land pattern file as a new band to your imagery. The composite bands is available to all license levels of ArcGIS. The ESRI documentation states that the tool: > Creates a single raster dataset from multiple bands and can also create a raster dataset using only a subset of bands. Once you have that, you can use the **Image Classification toolbar**. > The Image Classification toolbar provides a user-friendly environment for creating training samples and signature files for supervised classification. It also serves as a centralized location for performing both supervised classification and unsupervised classification. However, this is only available with the **Spatial Analyst extension**.
stackexchange-gis
{ "answer_score": 1, "question_score": 2, "tags": "arcgis desktop, arcgis 10.1, raster calculator, digital image processing" }
After `M-x pdb` switch to `compilation-mode` automatically? `M-x pdb` is great while debugging. When the python process exits though, often there is a traceback left behind in the `gud` buffer that I'd like to view using `compilation-mode` so I can use `next-error` to step through the stack frames. I can always `M-x compilation-mode` on python exit. Can I have emacs automatically do that for me?
(defun my/turn-on-compilation-shell-minor-mode () (compilation-shell-minor-mode t)) (add-hook 'pdb-mode-hook #'my/turn-on-compilation-shell-minor-mode)
stackexchange-emacs
{ "answer_score": 0, "question_score": 0, "tags": "python, debugging, compilation mode, gud" }
Keeping my header and footer on all webpages? I've finished designing my website home page and I've now moved on the some of the other pages, I want my header and footer to appear the same on every page. I've tried this basic way of linking the same stylesheet that makes up my header/footer in the second HTML file (already used in the homepage): <link rel="stylesheet" href="footer.css" type="text/css"/> <link rel="stylesheet" href="header.css" type="text/css"/> I now understand that this isn't going to work. Would a server-side scripting language be my best bet here? Something like PHP? If so, would anyone be able to link me with an article on how I could do this in PHP, I presume with the include function? Thanks.
You are currently only linking the css for the header and footer. If you want to include the html as the same, create two separate files header.php and footer.php, then include them into each webpage. <?php include('path/to/header.php');?> // in the location you want the header in the page <?php include('path/to/footer.php');?> // in the location you want the footer Essentially, you're making partials and placing them wherever you want them
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "php, html, css, web" }
C# parse DateTime String to time only I am new to C# and I have a string like "2021-06-14 19:27:14:979". Now I want to have only the time "19:27:14:979". So do I parse the string to a specific DateTime format and then convert it back to a string or would you parse or cut the string itself? It is important that I keep the 24h format. I don't want AM or PM. I haven't found any solution yet. I tried to convert it to DateTime like: var Time1 = DateTime.ParseExact(time, "yyyy-MM-dd HH:mm:ss:fff"); var Time2 = Time1.ToString("hh:mm:ss:fff"); But then I lost the 24h format.
Your code is almost working, but `ParseExact` needs two additional arguments and `ToString` needs upper-case `HH` for 24h format: var Time1 = DateTime.ParseExact("2021-06-14 19:27:14:979", "yyyy-MM-dd HH:mm:ss:fff", null, DateTimeStyles.None); var Time2 = Time1.ToString("HH:mm:ss:fff"); Read: < Instead of passing `null` as format provider(means current culture) you might want to pass a specifc `CultureInfo`, for example `CultureInfo.CreateSpecificCulture("en-US")`.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "c#, string, datetime, parsing" }
Field has incomplete type const char * [] I am trying tot pass argv from the main function of my program to the constructor of my class. I want to then set a field in my class to those values. I have `const char * _argv[];` in my header file. My constructor is: `Sweeper(int argc, const char * argv[]){_argc = argc; _argv = argv;}` What do I need to do?
For function parameters (only), `const char * argv[]` is a funny way of spelling `const char **argv`. So the fix is to define `_argv` to match.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c++" }
Does SharePoint 2010 still have the complicated SPWeb.Dispose methods? One of my gripes with SharePoint 2007 are the complicated SPWeb.Dispose rules that can either cause a big resource leak if you don't dispose what you have to, or all sorts of other weird issues if you dispose when you don't have to. Roger Lamb's Posting tries to summarize the madness. but I wonder if SharePoint 2010 improves this? I have the Beta setup but don't really see much difference here, but was some of the stuff at least improved?
Yes. You still need to carefully dispose of SPSite and SPWeb instances in SharePoint 2010. The last I checked, SPDisposeCheck had not been updated for SharePoint 2010. If it hasn't already been released, I'm certain it will be soon.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 5, "tags": "sharepoint, sharepoint 2010" }
BMO1 2013, solving a recurrence relation The question is > Isaac is planning a nine-day holiday. Every day he will go surfing, or water skiing, or he will rest. On any given day he does just one of these three things. He never does different water-sports on consecutive days. How many schedules are possible for the holiday? My attempt: $$ \text{Define a}_{\text{n}}\,\,\text{to be the number of n}-\text{day holiday that the last day is rest} \\\ \text{b}_{\text{n}}\,\,\text{similarly, last day is skiing}. \\\ \text{Then a}_{\text{n}+1}=\text{a}_{\text{n}}+\text{2b}_{\text{n}}, \text{b}_{\text{n}+1}=\text{b}_{\text{n}}+\text{a}_{\text{n}} \\\ $$ Then I do not know how to proceed to solve this sequence
From $a_{n+1}=a_n+2b_n$ we get $a_n=a_{n-1}+2b_{n-1}$. Subtracting the second from the first gives $$a_{n+1}=2a_n-a_{n-1}+2(b_n-b_{n-1})$$ But we know that $b_n-b_{n-1}=a_{n-1}$. So we get $$a_{n+1}=2a_n+a_{n-1}$$ Solving this recurrence in the usual way gives $$a_n=\frac12((1+\sqrt 2)^n+(1-\sqrt 2)^n)$$ Now note that the number of possible schedules for a $9$-day holiday is the same as the number of schedules for a $10$-day holiday that end with a rest day. So the answer we want is $a_{10}=\frac12((1+\sqrt 2)^{10}+(1-\sqrt 2)^{10})$, which Wolfram Alpha evaluates as $3363$. Unfortunately this answer is not very helpful in the context of an exam, when computing $(1+\sqrt 2)^{10}+(1-\sqrt 2)^{10}$ is not really practical. I think in an exam you would just have to compute $a_{10}$ iteratively by hand.
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "sequences and series, combinatorics, recurrence relations, contest math" }
Can open fontawesomefx-glyphsbrowser- windows batch file Can someone tell how to open font awesome font browser (linked below)- windows batch file. when I double click, command is opening but it shows an exception and closing. How can I know whats wrong even a documentation link would be very helpful? < thank you
I just fixed it by dragging and dropping the fontawesomefx-glyphsbrowser.file into cmd and hitting enter that showed the error which showed that my JAVA_HOME is not set up correctly.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "javafx, font awesome" }
JSON parsing Promise not behaving properly I am creating a Promise which is supposed to add any numbers found in an array/JSON object. add() is supposed to take in a string of urls, and output the sum of those urls. The way I have done it is as follows: I have created a helper function called parse, which takes in a string (the url) and should output the JSON object located at the url. My problem is that at the area denoted by the $$$$, the object `jsonObject` is the correctly parsed JSON object. But, at the area denoted by the ****, immediately after where I call parse, the `parsedObj` is no longer the correctly parsed JSON object. For example, if I parse a JSON object containing `[ 1, 2, 5, 4 ]`, I will get `jsonObject = 1,2,5,4` but `parsedObj = [object Promise]`. Why is `parsedObj` an array of [object Promise] and not `1,2,5,4`?
`parse(url: string): any` returns a Promise not your jsonObject So Log.trace("url: " + s.toString()); let parsedObj = that.parse(s); Log.trace("parsedObj: " + parsedObj); // **** really is asynchronous. You'll get the jsonObject by using parsedObj.then(function(jsobObject){ for (var elmt of jsobObject) { if (elmt.isNumber()) { sum += elmt; countNums++; } Log.trace("sum: " + sum); } Log.trace("sum: " + sum); }) You'll want to store your parsedObj (your Promises) in an array to use another Promise.all() to fullfill your parent promise when all work is done
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, json, parsing, typescript" }
Is there isspace in c#? i was thinking that is there any way to check if argument contains characters like space, horizontal, vertical tab, formfeed, carriage return or a newline. Kinda like isspace but in c#. Is that possible?
`Char.IsWhiteSpace` is designed for this purpose. For example, I have used this before when parsing a string, example: public int EatWhitespace(string input, int pos) { while(Char.IsWhiteSpace(input[pos]) ++pos; return pos; }
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": -1, "tags": "c#, whitespace" }
bootstrap css textbox and button positioning Code contains text box and button **HTML** : <div id="input-collection" class="input-group input-group-lg"> <span class="input-group-addon"> <i class="glyphicon glyphicon-link"></i> </span> <input id= "url-input-box" type="url" class="form-control" name = "url" placeholder=" <span class="input-group-btn"> <button id="submit-url-btn" class="btn btn-success" type="button">Go</button> </span> </div> which shows button and texbox like: !text button align I changed `margin-top` and `margin-left` in all above class but no change. Where I need to make change here?
Use Firebug (or chrome developer tools - Ctrl+Shift+J) Look at the margin-bottom settings of: submit-url-btn (the tag) against the margin-bottom of the url-input-box (span) It seems that the button has a high value on margin-bottom. set both to 0 and see how they are positioned.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "css, twitter bootstrap" }
FocusManager.FocusedElement won't bind on a page I used to have a window with an attached property to track the focused control: FocusManager.FocusedElement="{Binding CurrentlySelectedTextBox, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" CurrentlySelectedTextBox was a property in the window's viewmodel. Now my window has a frame. The content of the frame is a page. I moved the original window's content to the page with its own viewmodel. I moved the attached property from the window to the page. Since then the CurrentlySelectedTextBox property is never set. Long days of searching gave nothing. Are pages immune to FocusManager.FocusedElement? **Update:** If the attached property is on the window, FocusManager.FocusedElement gets set even if the focus is on the page's control.
There's a concept of focusscope in wpf which can cause issues like this. The basic problem is your page is a different focusscope to the window. Focusscope allows wpf to maintain a logical rather than physical concept of focus for controls such as tabcontrol and menu. In order to maintain which has logical focus the focusmanager will by default be concerned with the element which has focus within each focusscope. The behaviour is somewhat configurable but you need to be very careful before altering this as there are side effects.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "wpf, xaml, binding, window, focusmanager" }
Recursively run through a vector in Clojure I'm just starting to play with Clojure. How do I run through a vector of items? My naive recursive function would have a form like the classic map eg. (defn map [f xs] ( (if (= xs []) [] (cons (f (first xs)) (map f (rest xs)) ) )) The thing is I can't find any examples of this kind of code on the web. I find a lot of examples using built-in sequence traversing functions like for, map and loop. But no-one doing the raw recursive version. Is that because you SHOULDN'T do this kind of thing in Clojure? (eg. because it uses lower-level Java primitives that don't have tail-call optimisation or something?)?
Clojure re-uses stack frames **only with tail-recurstion and only when you use the explicit`recur`** call. Everything else will be stack consuming. The above map example is not tail recursive because the cons happens after the recursive call so it can't be TCO'd in any language. If you switch it to use the continuation passing style and use an explicit call to `recur` instead of `map` then you should be good to go.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "recursion, clojure" }
Set One Custom message for multiple field in laravel form validation Let I have 3 fields in the form. I write this code for form validation. $rules = array( 'field_1' => 'required', 'field_2' => 'required', 'field_3' => 'required', ); $messages = array( 'field_1.required' => 'Please fill up all value', 'field_2.required' => 'Please fill up all value', 'field_3.required' => 'Please fill up all value', ); $validator = Validator::make(Input::all(), $rules, $messages); Now if user fill up the form 2 fields with blank then the validator return two error message. If user fill up the form 3 fields with blank then the validator return three error message. But I want to show only one message for all fields.
you could change it to $messages = array( 'required' => 'Please fill up all value', ); validator = Validator::make(Input::all(), $rules, $messages); and let your view only output the first error message. {{ $errors->first(null,'<div class="alert alert-danger">:message</div>') }}
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 5, "tags": "validation, laravel 4" }
Is it a fact that a smaller jQuery plugin (in KB) will perform better than same plugin with the same functionality but of a bigger size? Or does it depend on the way in which it is written? My question is related to page rendering time. Can we determine which will give better performance? **Should we always choose a smaller sized plugin?**
If you mean that you have two plugins with comparable functionality, but different size (not just minified but really different code), the answer is: maybe. One thing is obviously for sure: the smaller plugin will load faster. But for a million reasons, the bigger plugin can be faster after that. Without benchmarks, you can only guess.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 0, "tags": "javascript, jquery, performance, jquery plugins, rendering" }
How to parse column separated key-value text with possible multiline strings I need to parse the following text: First: 1 Second: 2 Multiline: blablablabla bla2bla2bla2 bla3b and key: value in the middle if strting Fourth: value Value is a string OR multiline string, at the same time value could contain "key: blablabla" substring. Such subsctring should be ignored (not parsed as a separate key-value pair). Please help me with regex or other algorithm. Ideal result would be: $regex = "/SOME REGEX/"; $matches = []; preg_match_all($regex, $html, $matches); // $mathes has all key and value parsed pairs, including multilines values Thank you. I tried with simple regexes but result is incorrect, because I don't know how to handle multilines: $regex = "/(.+?): (.+?)/"; $regex = "/(.+?):(.+?)\n/"; ...
You can do it with this pattern: $pattern = '~(?<key>[^:\s]+): (?<value>(?>[^\n]*\R)*?[^\n]*)(?=\R\S+:|$)~'; preg_match_all($pattern, $txt, $matches, PREG_SET_ORDER); print_r($matches);
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "php, regex, parsing, preg match all" }
Asp.Net application getting poor performancE I am developing an application which fully works with huge database. In this i am facing a problem that after hosting on server, if one user execute long query then application hangs for the other users. For sql connection i am using a static class to make only one connection. Please help and guide me. If any other information need then please tell me Thanks
It's almost impossible to answer a question without specific code and that is broadly worded. However, in this case, you may just have provided enough information. > For sql connection i am using a static class to make only one connection. Don't do that. You are probably forcing all your users to wait until the single connection to the database is available exclusively for that user. That is like providing a ferry to carry cars across the river that can only hold one car at a time instead of building a bridge. Allow each user to get their own database connection. The underlying database access layer almost certainly provides connection pooling. There's no reason for you to try that on your own.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "asp.net, sql server, asp.net mvc, oracle" }
destroy persistance from blackberry I use PersistentObject to store login and password to enter directly in the application when I want to delete the values I use `PersistentStore.destroyPersistentObject(Info.KEY);` But the values still exist. Should I add something?
To destory the persistent object you should call PersistentStore.destroyPersistentObject(key) . It can throw ControlledAccessException if the caller does not have the permission to do it. Make sure you are calling the same key you are expecting to be deleted.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "blackberry, data persistence" }
How to convert a symmetric matrix into "dist" object? I want to use `hclust` to cluster a data. But I don't want to use "dist()" to generate the dist object. Then I found out that I cannot pass a symmetric matrix as distance matrix into `hclust`. How to convert a symetric matrix into "dist" object?
It sounds like you already have a matrix calculated, and want to use that in hclust. Like @shadow said, you can use `as.dist(yourMatrix)` to convert to the dist format. Given a symmetric table of distances: > yourMatrix<-matrix(c(1,2,3,4,2,1,2,1,3,2,1,3,4,1,3,1), nrow=4) [,1] [,2] [,3] [,4] [1,] 1 2 3 4 [2,] 2 1 2 1 [3,] 3 2 1 3 [4,] 4 1 3 1 > >as.dist(yourMatrix) 1 2 3 2 2 3 3 2 4 4 1 3 Make sure that the values in your matrix are dissimilarity, or distance metrics rather than similarity scores.
stackexchange-stackoverflow
{ "answer_score": 33, "question_score": 27, "tags": "r, matrix, distance" }
Duplicity not supported in 19.10? While upgrading to 19.10 with the software updater it said 7 packages amongst them duplicity would be removed, the reason being that canonical does not support these packages any more. I have backed up with deja dup which uses duplicity - what's happening neither the deja dup nor duplicity sites say anything. Is there a way i can keep backing up this way?
While I'm not certain why your upgrader tried to remove it, duplicity is still supported by Canonical. It looks like there was some churn due to duplicity's python3 port (it was briefly dropped from the desktop image due to bug 1829862). If you upgraded before official release, you may have gotten hit by that? You can manually reinstall it, but Deja Dup should also prompt you to reinstall duplicity if it's missing the next time it tries to back up.
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 0, "tags": "backup, deja dup, 19.10, duplicity" }
Why is Territory management not available? My org doesn`t have Territory Settings in setup. What is reason? Profile - System administrator, Organization Edition - Enterprise Edition
Territory management is not enabled by default in Salesforce. To request territory management for your organization, contact salesforce.com. If you have already done this step and you are seeing this feature missing recently. The following might be the cause Migrating to the new Collaborative Forecasting requires disabling Territory Management 1.0 As per this documentation, the Customizable Forecasting was retired for all customers as of Summer ’20. Users can’t access the Customizable Forecasting feature and its underlying data. Salesforce encourages you to migrate to Collaborative Forecasts. The documentation also quotes "If you agree to the steps above, please contact support to enable permission to allow you to deactivate Customizable Forecasting and/or Territory Management 1.0" I recommend engaging support if you have any specific questions
stackexchange-salesforce
{ "answer_score": 3, "question_score": 2, "tags": "administration, territory management" }
Difference between API and Web Service in Salesforce Can anyone help me in giving the difference between API and Web service in Salesforce ?
A webservice is a service that is accessed over the web. An API is a collection of ways of interacting with software components. As examples in Salesforce specifically: * The SOAP API and REST API are considered both webservices and APIs since they define a set of features and those features are accessible over the web. * The built-in classes and interfaces that make up Apex are a collection of features that can be considered an API, but are not considered webservices since they are not accessed directly through the web. That being said, the Salesforce documentation typically does not use the term API when referring to Apex features, except when referring to code api versions.
stackexchange-salesforce
{ "answer_score": 3, "question_score": 2, "tags": "api, webservices" }
What are pros and cons of Amazon S3 vs Amazon EBS? For websites/applications and eCommerce, which storage solution is more desirable and why? I'm very new to Amazon Cloud Services so I need some direction here.
This article might help you (cached article here). In brief, S3 is general storage whereas EBS is for mounting volumes attached to EC2 instances. S3 is more reliable than EBS. If you use EBS then you should backup to S3 periodically.
stackexchange-webmasters
{ "answer_score": 3, "question_score": 3, "tags": "amazon" }
Simple User's Guide / Tutorial for Apache httpd? Is there a simple user guide or tutorial for Apache httpd? I find that the official documentation (< is a little hard to navigate and learn from if you're not up to speed with a lot of the basics.
It might be best to start with a specific thing with Apache that you want to/need to accomplish. Otherwise Amazon, Borders and Barnes and Noble are your friends! There is an Apache for Dummies book too (no offense!) Things that might be helpful: < Also, each OS might implement Apache a bit differently as far as where it is stored, default settings, etc. Linux does differently than Windows for example.
stackexchange-serverfault
{ "answer_score": 3, "question_score": 4, "tags": "apache 2.2, httpd" }
T-SQL, OpenXml is merging xml tags into single record I have this sql select Alias from OpenXml(@XML, '/Entity/Aliases', 2) with ( Alias varchar(255) '.' ) which is extracting data from xml file xml have this structure: <Entity> <EntityID>123</EntityID> <Aliases> <Alias>TEST 1</Alias> </Aliases> <Aliases> <Alias>TEST 2</Alias> </Aliases> <Aliases> <Alias>TEST 3</Alias> </Aliases> ... On return of select I get `TEST 1TEST 2TEST 3` how can i modify so i get each alias in different record ?
try below query DECLARE @Tmp AS XML =' <Entity> <EntityID>123</EntityID> <Aliases> <Alias>TEST 1</Alias> </Aliases> <Aliases> <Alias>TEST 2</Alias> </Aliases> <Aliases> <Alias>TEST 3</Alias> </Aliases> </Entity>' SELECT xmlData.A.value('.', 'VARCHAR(100)') AS alias FROM @Tmp.nodes('Entity/Aliases/Alias') xmlData(A)
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "sql, sql server, xml, stored procedures, openxml" }
How do I print string backward each letter on separate line, Using while loop in Python? I'm stuck at Excercise problem where I have to print Word "Banana" in reversed each letter on a separate line. Below is my code:- fruit = "BANANA" index = -1 while len(fruit) > index: letter = fruit[index] print(letter) index = index -1 Output:- A N A N A B Traceback (most recent call last): File "C:/Banana.py", line 4, in letter = fruit[index] > IndexError: string index out of range
There is no need to create an index. In fact, it makes the code less efficient and more prone to bugs (as you noticed). Instead You can reverse your string using `[::-1]`, and just iterate through it, because iterating through a string means going through each individual character: fruit = "BANANA" for letter in fruit[::-1]: print(letter)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "python 3.x" }
jQuery height animation at the top, not the bottom of an element HTML/CSS/JS here: < My problem is that the animation is taking place at the bottom of the element, not the top. I figure it's an issue with my CSS positioning, but I can't suss it out. And ideas?
here is another solution <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 4, "tags": "jquery, html, css, jquery animate" }
i want to scrape some website using ruby and mechanize gems i want to scrape some website, which contain pagination. for example < i want scrape each post in each pagination. so, in page/1 , there are about 5 posts. how to scrape each data inside each pagination? until the end page? i've search and research, and i found 2 similar question, but im still confuse it.. here >> first way second way any idea how to combine it? thanks before
You **have** to use mechanize gems? I'd strongly recommend you to use Nokogiri. It's very simple and easy to use. You can have a loop that fetch the pages and stop when you can't find the page. require 'open-uri' require 'nokogiri' pages_count = 1 loop do @html = Nokogiri::HTML(open("somepage.com/#{pages_count}")) ... pages_count = pages_count + 1 end
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -4, "tags": "ruby on rails, ruby, pagination, web scraping" }
How to perform segmentation on complex images like rocks (in c++) I'm trying to perform segmentation on a picture of rocks (I've attached a sample). The end goal is to find the approximate rock area (Not sure if the required method is image segmentation). I have tried several algorithms: * Texture segmentation does not help as all the rocks are similar. * I can get the edges with quite a lot of error. Due to shadows. Although possible to use. Here is an example of input image (you can ignore the basketball): ![Sample image containing rocks]( Please be specific as possible. Considering the complexity of the topic, I'm kind of new.
Slightly blurring the image and applying an image segmentation method like watershed can more-or-less solve the question. But as the rock boundaries similar to the texture of the rocks themselves, this won't be an easy task. I would suggest the following: * If you do not need high accuracy, experiment with the above methods and measure the expected error with some manually annotated images. * If accuracy is very important and you can ask for user help, create a user interface where the user can place a marker over every rock. Then use a watershed variant starting from these markers (also called seed points) to perform seeded segmentation. (The watershed implementation in OpenCV can do that.)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "c++, opencv, image processing" }
Angular call to PHP returns 404 after Grunt build Really hope someone will point me in the right direction, I'm lost :D Building my first ng-app, and the Grunt build results in api calls (php) not being found. Folder structure is dist->api->index.php, so I'm not sure why the calls return 404. I have MAMP as a server, and the calls look like they contain the entire path: ` With grunt-serve in dev, I used a different port and not MAMP, but to my knowledge that has nothing to do with production, right? This is probably nothing, but I'm very much hoping to learn. Thanks in advance!
Grunt-serve can't serve PHP files, if you want to create PHP server replace grunt-serve with grunt-php and configure a **base** and **port**. It should be configured like this: grunt.initConfig({ php: { dist: { options: { port: 8888, base: 'dist/api/', keepalive: true, open: true } } } }); After this you should have got an access to your index.php API.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "php, angularjs, gruntjs, restful url, mamp pro" }
How to get default system style on C# progressbar In Windows Vista & 7 progressbars are green and have a glassy finish. But the one served up by Visual Studio 2010 has the system default of blue highlight (which appears flat and looks a bit Windows 98). How do I get that glassy green look (or whatever the user's theme default is)? (Using C# v4.0 if that makes a difference) !Dull flat blue progress bar **EDIT:** Ok - just noticed how square the buttons look on this and other dialogs' controls - I think somehow the entire app is being styled pre win XP? Can someone tell me how to set the style correctly for the whole app (i.e. to match the current OS)?
Add this line in your `Program.cs` : static void Main() { Application.EnableVisualStyles();
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#" }
What is the terminal labelled "U" in some autotransformers? I'm trying to wire an autotransformer for usage as a speed controller for a brushless motor fan. The terminals are quite self explanatory: ![]( `Pe` for ground, `L-N` are my input, `N1-L1` are unregulated output (same as `L-N`) and `U-N` are the output to my motor. Having that said, I'm still hesitant to wire this up before I understand the the following: * **Q1:** What is the `U` terminal? What does it stand for? * **Q2:** Do I connect my motor's ground to the common Pe? I'd have imagined that there would be a dedicated terminal for the ground near the output to the motor. Here's a picture from inside the transformer's case: ![]( Transformer's datasheet
Sentera's website shows a connection diagram for a similar controller: ![enter image description here]( _Figure 1. Source:Sentera._ > Pe for ground, L-N are my input, N1-L are unregulated output (same as L-N) and U-N are the output to my motor. N1-L should read N-L1. Yes, unregulated output but on when running so it is switched. > Q1: What is the U terminal? What does it stand for? 'U' is commonly used in Europe to mean 'voltage'. It makes sense when you think that we use 'I' for current and avoids confusion between 'voltage' and 'volts'. U1 and U2 are the fan terminals and the naming suggests that neither of them is at neutral potential so the triac is likely to be in the neutral line. > Q2: Do I connect my motor's ground to the common Pe? I'd have imagined that there would be a dedicated terminal for the ground near the output to the motor Yes. It appears that they have been a bit mean with the terminals.
stackexchange-electronics
{ "answer_score": 9, "question_score": 6, "tags": "ac, transformer, terminal" }
QDeclarativeItem mouseMoveEvent(QGraphicsSceneMouseEvent *event) not working I'm trying to catch mouse events in a transparent QDeclarativeItem, wrap it around all the other elements in QML and log information about mouse events in the whole program. **mouseMoveEvents(QGraphicsSceneMouseEvent *)** however is executed only when **mousePressEvent(QGraphicsSceneMouseEvent *)** is implemented and mouse button is pressed. In a QWidget I would sovle this by calling **setMouseTracking(true)**. How to do this in a QDeclarativeItem?
Solved this by using **hoverMoveEvent(QGraphicsSceneHoverEvent *)** and setting **setAcceptHoverEvents(true)**. It works the same way as mouseMoveEvent, but is being called when mouse button is not pressed too.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c++, qt, qml, qt4.8" }
C# Override abstract function with generic data I'm trying to override an abstract function but I'm receiving an error when specifying a type for the list. The type has the interface that the base abstract class is requesting. Base Renderer public abstract class Renderer { abstract void Render(Dictionary<GenericVAO, List<IEntity>> data); } Sprite Renderer public class SpriteRenderer : Renderer { public override void Render(Dictionary<GenericVAO, List<Sprite>> data) {} } Sprite public class Sprite : IEntity { public SpriteVAO model; }
What about using generics for the renderer so that it just works for derived classes? e.g.: public abstract class Renderer<T> where T : IEntity { abstract void Render(Dictionary<GenericVAO, List<T>> data); } Not sure if GenericVAO should be VAOof type T as well. Don't know exactly what you're doing. Sprite renderer override then becomes: public class SpriteRenderer : Renderer<Sprite> { public override void Render(Dictionary<GenericVAO, List<Sprite>> data) {} }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c#, inheritance, interface, abstract" }
Obtain location using service(background) and update gui at regular intervals I am trying to run a service in the background. Where location is obtained at regular interval and the activity text views are updated whether the app is in E background or foreground. Any pointers or tutorials you guys aware of the? Maybe working examples? I searched a lot and couldn't find something concrete Thank you Note: Battery consumption is not an issue for this app
I did a small blog post about Android location services that should help. It's not service based but it will provide you live location updates in the activity whilst running. Once your activity is paused there is little point in the service providing updates any way and it will hammer your battery as @aehs29 mentioned. Example code in the blog too: <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "android" }
Pop index out of range python I am trying to get certain parts off a database. I am using pymongo and have got it into a list in my script. I am trying to use the `pop()` method to remove certain parts of the list. > [{'_id': ObjectId('5fe357f3aa9a0fad99161370'), 'twitch': 'twitchusername', 'serverID': 791003444256178208, 'type': 'user'}] I would like to just keep the 'twitchusername'. However when I do `mylist.pop(4)` I get the error: > Pop index out of range How would I go around this? Thanks :) I will leave my code below: myclient = pymongo.MongoClient("link") mydb = myclient["Cluster0"] mycol = mydb["live"] myquery = { "type": "user" } array = [] array = list(mycol.find(myquery)) print(array) array1 = mylist.pop(4)```
If you only want the value from the `twitch` key, then you can filter out the other columns in the `find` and then iterate the resulting data; example would be: cursor = mycol.find({ "type": "user" }, {'_id': 0, 'twitch': 1}) for item in cursor: print(item.get('twitch'))
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "python" }
Bootstrap Dynamic Navbar won't resize for mobile since I included a logo I am trying to implement a logo in the navbar of my website. This works great on larger screens but on smaller screens the navbar breaks Without the logo: Click Here With the logo and resize issues: Click Here I am guessing I can change the logo image to be responsive/disappear in the custom css for the page but not sure how to. any help appreciated!
if you want your logo to be smaller on smaller screens, so it is not bigger than the viewport, you should set a `max-width`-value in your CSS as you did it with your other pictures. You can do this either by adding `max-width:100%` or adding your `.img-responsive`-class (which you used for the other pics) to the logo-tag.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "html, css, twitter bootstrap" }
ΠŸΠΎΡ€ΡΠ΄ΠΎΠΊ Π²Ρ‹Π·ΠΎΠ²Π° Π² спискС ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·Π°Ρ†ΠΈΠΈ конструктора class A { public: A() { v.resize(a); } A(int a, int b): a(a), b(b), A() {} // ! private: std::vector<int> v; int a, b; }; Π“Π°Ρ€Π°Π½Ρ‚ΠΈΡ€ΠΎΠ²Π°Π½ Π»ΠΈ Ρ‚ΡƒΡ‚ порядок Π²Ρ‹Π·ΠΎΠ²Π° `a, b, A()`, ΠΈΠ»ΠΈ ΠΌΠΎΠΆΠ΅Ρ‚ случится Ρ‚Π°ΠΊ, Ρ‡Ρ‚ΠΎ сначала вызовСтся `A()`, Π° ΠΏΠΎΡ‚ΠΎΠΌ `a, b`? Если Π½Π΅Ρ‚, Ρ‚ΠΎ ΠΊΠ°ΠΊ ΠΈΡΠΏΡ€Π°Π²ΠΈΡ‚ΡŒ, Ρ‡Ρ‚ΠΎΠ±Ρ‹ ΠΏΠΎΠ»ΡƒΡ‡ΠΈΡ‚ΡŒ Π½ΡƒΠΆΠ½ΠΎΠ΅ ΠΏΠΎΠ²Π΅Π΄Π΅Π½ΠΈΠ΅?
ΠŸΠΎΡ€ΡΠ΄ΠΎΠΊ Π²Ρ‹Π·ΠΎΠ²Π° соотвСтствуСт _порядку объявлСния Ρ‡Π»Π΅Π½ΠΎΠ²_ , Ρ‚.Π΅. Ρ‡Ρ‚ΠΎ Π²Ρ‹ Π½ΠΈ Π½Π°ΠΏΠΈΡˆΠ΅Ρ‚Π΅ Π² конструкторС, сначала Π±ΡƒΠ΄Π΅Ρ‚ ΠΈΠ½ΠΈΡ†ΠΈΠ°Π»ΠΈΠ·ΠΈΡ€ΠΎΠ²Π°Π½ `v`, Π·Π°Ρ‚Π΅ΠΌ `a` ΠΈ `b`.
stackexchange-ru_stackoverflow
{ "answer_score": 8, "question_score": 7, "tags": "c++, классы, конструктор, инициализация" }
Select everything to the right of a specific character Given this data: Home: (708) 296-2112 I want everything to the right of the `:` character. This is what I have so far, but I'm getting no results: right(phone1, locate(':', phone1 + ':')-1) phone If I use `left` instead of `right`, I get just "HOME" - just for testing purposes. I know I'm close, but I'm missing something.
You can use `SUBSTRING` (might be `SUBSTR` dependent on your version) instead: SELECT SUBSTRING(phone1, LOCATE(':', phone1) + 1, LENGTH(phone1)) FROM yourtable
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "sql, advantage database server" }
unable to resolve dns after enable ipf I running on Solaris 10 platform. Before I enable IPF, I able to ping and traceroute to yahoo.com After I enabled the IPf, I could not ping nor traceroute to yahoo.com However when I ping to IP 69.147.114.224 (one of yahoo resolved IP) directly, it gives me response. It seem to be that IPF block the DNS resolvability. How could I solve it?
Add a firewall rule to allow UDP and TCP traffic on port 53.
stackexchange-serverfault
{ "answer_score": 3, "question_score": 0, "tags": "firewall, solaris" }
What is the missing step to simplify this equation? From this function: $$ G(L)=\sum_{h=-\infty}^{\infty} \gamma_{h} L^{h}=\gamma_{0}+\sum_{h=1}^{\infty} \gamma_{h}\left(L^{h}+L^{-h}\right). $$ With $h \geq 0,\;\, \gamma_{h}=\sum_{j=0}^{\infty} \psi_{j} \psi_{j+h}\;$ and $\;\gamma_{-h}=\gamma_{h},\;$ we know that $$ \begin{aligned} 1)\ \ \ \ G(L) &=\sigma^{2}\left(\sum_{j=0}^{\infty} \psi_{j}^{2}+\sum_{h=1}^{\infty} \sum_{j=0}^{\infty} \psi_{j} \psi_{j+h}\left(L^{h}+L^{-h}\right)\right). \\\ \end{aligned} $$ But then from here, my textbook derives the next steps with no explanation as to how: $$ \begin{aligned} 2)\ \ \ \ &=\sigma^{2}\left(\sum_{j=0}^{\infty} \psi_{j} L^{j}\right)\left(\sum_{h=0}^{\infty} \psi_{h} L^{-h}\right) \\\ 3)\ \ \ \ &=\sigma^{2} \psi(L) \psi\left(L^{-1}\right) \end{aligned} $$ How do we get there? In particular from 1) to 2).
Observe that to obtain a specific $L^h$, I can make it with any product of the form: $$(\psi_j L^{-j})(\psi_{h+j}L^{h+j})=\psi_j\psi_{j+h}L^h$$ Likewise if I want to make $L^{-h}$: $$(\psi_j L^{j})(\psi_{h+j}L^{-(h+j)})=\psi_j\psi_{j+h} L^{-h}$$ The product $(\sum_j\psi_j L^j)(\sum_i\psi_i L^{-i})$ will expand to make a sum of terms of the above two forms, and also terms of the form $\psi_jL^j\psi_jL^{-j}=\psi_j^2$, which explains the result. Try visualise all the possible ordered pairs in the expanded sum of multiplications. This is very similar to a Cauchy product.
stackexchange-math
{ "answer_score": 3, "question_score": 2, "tags": "calculus, algebra precalculus" }
How to replace variables with names using pandas Consider a column(Result) in a data frame df which is stored with 0's and 1's. 0 indicates Fail and 1 indicates Pass. How do I replace 0's with Fail and 1's with Pass for df['Result'] column?
Us `pandas.Series.map`: df.results = df.results.map({0: 'Fail', 1: 'Pass'})
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python, pandas, numpy" }
How to find a form from many forms in vb6 on a existing project I am working on a old project of vb6 which has hundreds if forms. I am able to run the application and have to fix a runtime error in a form which pop up. I don't know the name of the form and only have visual reference. I tried using debug but It has continues SQL statements running in a loop. Any advice is appreciated. Thanks.
Search the code for the form caption, or the labels of controls on the form, using visual studio's "find in files" or simlar function of your favourite editor. * If the caption is set in the form design, this will take you to the `.frm` file the form is stored in. You can open this in Notepad or another editor to get the name of the class (which is usually the same as the filename). * If the caption is set in code, you can place a breakpoint on that line. Again, this will lead you to the code which instantiates the form.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "sql, forms, debugging, vb6" }
How to bulk print maps using ArcGIS or QGIS? I have a polygon layer that I would like to print images or PDFs from in bulk as there are a large number of them. Rather than having to manually scroll and print each individual'site' in the print composer (QGIS 2.0 or ArcGIS 10) are there any tools that I could use or scripts etc?
For QGIS, have a look at the **Atlas** functionality in the **Print Composer**. < The idea is to have a "coverage layer" which contains all the "sites" that you want to zoom to and make a map of. Atlas has all kinds of functions which let you control the resulting maps, e.g. whether you always want the same scale or not. Some new stuff which is not covered by the user guide yet: * Atlas preview functionality: < * Highlighting the current Atlas feature: < * Adding images which change with the Atlas feature: <
stackexchange-gis
{ "answer_score": 5, "question_score": 3, "tags": "qgis, python, arcgis 10.0, printing" }
Unable to remove certain characters between values in c# I am trying to remove characters starting from (and including) `rgm` up to (and including) `;1.`. ### Example input string: Sum ({rgmdaerudsb;1.Total_Value}, {rgmdaerub;1.Major_Value}) ### Code: string strEx = "Sum ({rgmdaerudsb;1.Total_Value}, {rgmdaerub;1.Major_Value})"; strEx = strEx.Substring(0, strEx.LastIndexOf("rgm")) + strEx.Substring(strEx.LastIndexOf(";1.") + 3); ### Result: Sum ({rgmdaerub;1.Total_Value}, {.Major_Value}) ### Expected result: Sum ({Total_Value}, {Major_Value}) **Note:** only `rgm and ;1.` will remain static and characters between them will vary.
I would recommend to use Regex for this purpose. Try this: string input = "Sum ({rgmdaerudsb;1.Total_Value}, {rgmdaerub;1.Major_Value})"; string result = Regex.Replace(input, @"rgm.*?;1\.", ""); Explanation: The second parameter of Regex.Replace takes the pattern that consists of the following: * **rgm** (your starting string) * **.** (dot - meaning any character) * ***?** (the preceding symbol can occure zero or more times, but stops at the first possible match (shortest)) * **;1.** (your ending string - the dot needed to be escaped, otherwise it would mean any character)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c#, .net, string, replace" }
A new column in pandas which value depends on other columns I have an example data as: datetime col1 col2 col3 2021-04-10 01:00:00 25. 50. 50 2021-04-10 02:00:00. 25. 50. 50 2021-04-10 03:00:00. 25. 100. 50 2021-04-10 04:00:00 50. 50. 100 2021-04-10 05:00:00. 100. 100. 100 I want to create a new column called state, which returns col1 value if col2 and col3 values are less than or equal to 50 otherwise returns the max value between col1,column2 and column3. The expected output is as shown below: datetime col1 col2 col3. state 2021-04-10 01:00:00 25. 50. 50. 25 2021-04-10 02:00:00. 25. 50. 50. 25 2021-04-10 03:00:00. 25. 100. 50. 100 2021-04-10 04:00:00 50. 50. 100. 100 2021-04-10 05:00:00. 100. 100. 100. 100
To improve upon other answer, I would use pandas apply for iterating over rows and calculating new column. def calc_new_col(row): if row['col2'] <= 50 & row['col3'] <= 50: return row['col1'] else: return max(row['col1'], row['col2'], row['col3']) df["state"] = df.apply(calc_new_col, axis=1) # axis=1 makes sure that function is applied to each row print(df) datetime col1 col2 col3 state 2021-04-10 01:00:00 25 50 50 25 2021-04-10 02:00:00 25 50 50 25 2021-04-10 03:00:00 25 100 50 100 2021-04-10 04:00:00 50 50 100 100 2021-04-10 05:00:00 100 100 100 100 `apply` helps the code to be cleaner and more reusable.
stackexchange-stackoverflow
{ "answer_score": 14, "question_score": 8, "tags": "python, pandas, numpy, data science" }
Java 7 Memory Model same as JSR-133? I was re-reading the JSR-133 specification when I wondered if there were any changes that occurred in the Java 7 release. That is, if 133 was obsolete or still valid. I didn't find anything on Google about changes in the memory model for Java 7, but I'm asking here just in case anyone knows.
It is valid w/o plans to change. Extra bonus link to Fences and JMM
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 5, "tags": "java, java memory model" }
C function to read entire file not working I wrote this small program to read an entire file into a `char*`, which I could then parse more freely than from a file. However, when I run it none of the file seems to get copied into `buf`, because neither printing the string or the individual chars seems to work. #include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { FILE *fp = fopen("/home/<not shown>/.profile", "r"); fseek(fp, 0, SEEK_END); char *buf = malloc(ftell(fp) + 1); fseek(fp, 0, SEEK_SET); while ((*buf++ = fgetc(fp)) != EOF) {} printf("%s\n", buf); } I'm pretty new to c, so could you help me find an answer to this conundrum?
When you're done with the loop, `buf` points to the end of the buffer, not the beginning. You should use a separate variable during the loop. fseek(fp, 0, SEEK_END); char *buf = malloc(ftell(fp) + 1); fseek(fp, 0, SEEK_SET); char *p = buf; while (*p++ = fgetc(fp)) != EOF) {} // Replace EOF with null terminator *(p-1) = '\0';
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c" }
How long to store slow-cooked chicken in liquid in fridge? I cooked some chicken in the slow cooker and stored the leftovers in the fridge. I put it all into a sealed tupperware container, but I put the chicken in with the liquid. It just occurred to me that storing the chicken in liquid might have been a bad idea. It's been about 4 days now, is it still ok to eat? Does the liquid or the slow cooker change how long it could be stored for? Thanks!
Assuming it has been treated appropriately in all other ways (not being left out at in the "danger zone" of 40-140 F / 4-60 C for more than about two hours commulative over the entire life time, raw and cooked)) cooked chicken should last 3-4 days in the refrigerator. See for example, the example of fried chicken per South Carolina's Department of Health and Environmental Control. It is the only example of cooked chicken in the list, but should be well representative. Similarly, Still Tasty advises 3-4 days on chicken broth, which would represent the juice or gravy--they indicate the same for chicken Parmesan. You may be noticing a trend here: all chicken based dishes have about the same storage lifetime. The fact that it is stored with the juice or gravy, or that you cooked it in a slow cooker is not really important.
stackexchange-cooking
{ "answer_score": 1, "question_score": 1, "tags": "chicken, slow cooking, storage lifetime" }
Is it plagiarism to copy formulations from others? As a non-native speaker of english, I often struggle with always finding new, well-sounding, non-repetitive descriptions for the same thing and I also, to be honest, find it a waste of time of always having to do something different. For example: Section 1 describes the X while section 2 is about the Y. The Z is explained in section 3 and section 4 refers to A. The next section is about B... Is it ok to just copy the formulation of someone else (of course my X,Y,Z,... are completely different) and always use the same thing?
Sentence patterns are _not_ intellectual property; otherwise, every author who wrote "To X or not to X" would be plagiarizing Shakespeare. (They are "riffing" off of him, but _not_ plagiarizing!) The example you are citing is perfectly innocuous, particularly since you are not doing anything more than summarizing the paper contents. The only thing that would make it wrong would be to copy those sentences directly from someone else's work.
stackexchange-academia
{ "answer_score": 18, "question_score": 16, "tags": "writing, plagiarism" }
AngularJS, UI Bootstrap Carousel link to a specific slide from a different view I'm trying to click through to a different view, with a specific slide in a Bootstrap UI Carousel open. I've been able to create a button that goes to a specific slide by using the active property: $scope.setActive = function(idx) { $scope.slides[idx].active=true; but I can't seem to figure out how to link to another view and also open a specific slide. Here's a plunker that show's my attempt so far. In this example I'm trying to link to the home.html with slide two open from page.html. < I'm new to AngularJS so there might be a very simple answer to this that I'm over looking. I'd appreciate any help. Thanks
You can use $routeParams for this. Here is working example: < //in app.config .when('/home/:slide', { //introducing slide as parameter here templateUrl: 'pages/home.html', controller: 'SlideController' }) //in Ctrl controller $scope.setActive($route.current.params.slide || 0); <!--resulting link for page.html--> <a href="#home/1">View Second Slide</a> **second** item of the array is `array_name[1]`.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "angularjs, carousel, angular ui bootstrap" }
Upwork no project still need to pay taxes How does paypal work with upwork do they just send the money to Paypal and if you can't get project you still have to pay for taxes from upwork?
Basically- if its income, its taxable. you will need to report it and pay appropriate taxes. Upwork has its own payment system. i would recommend using that instead of Paypal because Upwork has a good escrow system to ensure you get paid. I have had good arbitration with Upwork also
stackexchange-freelancing
{ "answer_score": 2, "question_score": -5, "tags": "freelance websites, taxes" }
Need help understanding a piece of code in php <?php if($sitedown==true) { echo <<<MESSAGE <div style="width: 700px; height: 328px; background: transparent url({${constant(BASE_PATH)}}/images/down.jpg) top left no-repeat;"> <p style="font-size: 20px; font-weight: bold; color: #666; font-family: tahoma, arial; margin: 0px; padding: 100px 10px 0px 200px;"> </p> </div> } ?> what exactly does `url({${constant(BASE_PATH)}}` do? `BASE_PATH` is a php config variable.
`url(something)` is CSS for "This is a URL" `${constant(BASE_PATH)}` should give you a string (which should be a URL) which gets interpolated into the string literal.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "php" }
How to set permanent mtu size for ppp0 every time I connect to my VPN, I should run sudo ifconfig ppp0 mtu 1300 How could I make it permanent? I'm using Ubuntu 14.04
You can make your custom script at this address : `/etc/network/if-up.d`, #!/bin/sh if [ "$IFACE" = "ppp0" ]; then sudo ifconfig ppp0 mtu 1300 fi finally make executable and enjoy from your life ...
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "ubuntu 14.04, vpn, mtu, pptp" }
How to prove $A \bigcap B$ is closed and bounded interval if given A&B are both closed and bounded intervals? How to prove $A \bigcap B$ is closed and bounded interval if given A&B are both closed and bounded intervals? I have proved that $A \bigcap B$ is bounded, but I have no idea how to prove it is closed and is an interval. Does anyone could help me? Thanks!
HINT: Let $A=[a_0,a_1]$ and $B=[b_0,b_1]$. Consider $\max\\{a_0,b_0\\}$ and $\min\\{a_1,b_1\\}$.
stackexchange-math
{ "answer_score": 3, "question_score": 0, "tags": "real analysis" }
How to stub exported function in ES6? I have file foo.js: export function bar (m) { console.log(m); } And another file that uses foo.js, cap.js: import { bar } from 'foo'; export default m => { // Some logic that I need to test bar(m); } I have test.js: import cap from 'cap' describe('cap', () => { it('should bar', () => { cap('some'); }); }); Somehow I need override implementation of `bar(m)` in test. Is there any way to do this? P.S. I use babel, webpack and mocha.
Ouch.. I found solution, so I use `sinon` to stub and `import * as foo from 'foo'` to get object with all exported functions so I can stub them. import sinon from 'sinon'; import cap from 'cap'; import * as foo from 'foo'; sinon.stub(foo, 'bar', m => { console.log('confirm', m); }); describe('cap', () => { it('should bar', () => { cap('some'); }); });
stackexchange-stackoverflow
{ "answer_score": 99, "question_score": 78, "tags": "javascript, ecmascript 6" }
How do I get command+tab to stop re-ordering spaces Right now I have Chrome set up in Desktop 1, Terminal in Desktop 2, and Spotify in Desktop 3. If I command+tab to Spotify, it changes the order of the desktops, so now Desktop 3 is Desktop 2 and Desktop 2 is Desktop 3. This is frustrating because I expected them to stay put. What I would like to have happen when I command+tab to Spotify is have it go to Desktop 3 and not reorder the Desktops.
You can change the default preference easily: System Prefs > Mission Control > Automatically rearrange Spaces based on most recent use. ![enter image description here](
stackexchange-apple
{ "answer_score": 31, "question_score": 20, "tags": "macos, spaces" }
Mail on macOS Catalina: Disable "Load remote content in messages" In previous versions of Mail on macOS, there was an entry in Settings that read "Load remote content in messages". I'd like to disable loading remote content. Is that possible to do in Catalina, either via the GUI or via the command line?
From < > Load remote content in messages > When remote content is retrieved from a server, information about your Mac can be revealed. You can deselect the option for increased security, but some messages may not display correctly. > > Remote content isn’t displayed in messages that Mail marks as junk. This is found in > ... the Mail app on your Mac, choose Mail > Preferences, then click Viewing.
stackexchange-apple
{ "answer_score": 2, "question_score": 2, "tags": "mail.app, privacy" }
MySQL timestamp auto updating I have a table which contains a couple timestamp fields and but I'm having some problems having some of the fields defaulting to NULL. In my _users_ table I have these timestamp tables: (field),(NULL),(default val) deleted_on YES NULL last_change_attemp YES NULL newpass_time YES NULL last_login YES NULL created NO 0000-00-00 00:00:00 updates YES NULL When I go edit a row in phpMyAdmin, the row I'm editing already has the NULL checkbox checked for all NULL fields, except the first field: *deleted_on*. If I manually check the checkbox, it allows me to maintain that field as NULL. When I update another field via a query, it automatically does a current_timestamp on that first field. Is this expected?
I've read through the docs again and noticed this piece of text > To specify automatic default or updating for a TIMESTAMP column other than the first one, you must suppress the automatic initialization and update behaviors for the first TIMESTAMP column by explicitly assigning it a constant DEFAULT value (for example, DEFAULT 0 or DEFAULT '2003-01-01 00:00:00'). Then, for the other TIMESTAMP column, the rules are the same as for the first TIMESTAMP column, except that if you omit both of the DEFAULT and ON UPDATE clauses, no automatic initialization or updating occurs. < So for the time being I have the fields default to 0000-00-00 00:00:00 to prevent auto updates.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "mysql, time, timestamp" }
LINQ UNPIVOT Several columns I have the following: 1_A | 1_B | 2_A | 2_B | 3_A | 3_B | ------+-------+-------|-------+-------+---------| 10 | 100 | 12 | 50 | 300 | 52 | and it should become: Type | A | B | ------+-------+-------| 1 | 10 | 100 | 2 | 12 | 50 | 3 | 300 | 52 | Is it feasible in LINQ? If not, what would be the most efficient query in SQL Server? Thanks S.
It depends on the LINQ query provider capabilities, but in general the LINQ solution is to use the `SelectMany`.aspx) method: var query = db.Table .SelectMany(e => new[] { new { Type = 1, A = e.A1, B = e.B1 }, new { Type = 2, A = e.A2, B = e.B2 }, new { Type = 3, A = e.A3, B = e.B3 }, };
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "sql server, linq" }
Does Java Messaging Service (JMS) has a look alike or same structure on PHP? Is there a look a like structure of JMS on PHP which can be implemented? JMS can run only on ApacheMq which I have developed a system on PHP that runs on Apache which if I run both only one is running. I dont have to have another server to run JMS? Is there look alike which can be run to Apache? Thanks in advance.
AFAIK, JMS only runs on Java or a native compiled version e.g. Tibco EMS. These servers have clients for a wide range of languages and you shouldn't need to know what language the server uses for its implementation. You could build a PHP version of JMS. But I would be surprised if one exists. BTW ActiveMQ is not the only JMS server, there are many others. <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "java, php, jms" }
system method can i stop status code? So I'm doing a program that deals with $PATH and it gotta test each path to see if that command is located in that path and i was using the system() method , but i get all the status code for the paths that do not have that command. is there a way to stop the status code? For example, when I type echo hi i get : sh: /usr/lib64/qt-3.3/bin/echo: No such file or directory sh: /usr/NX/bin/echo: No such file or directory sh: /usr/local/bin/echo: No such file or directory hi
You can use redirection some_cmd 2>/dev/null
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "c" }
Dynamic Branding on Android My requirement is that i need to change all the images and colors at run time. But as far as i know the images needs to be in the drawable folders. So my question is, after i export the apk file will i be able to download the images from a server through the application and set them as the images in the app? For an example, lets say i have a linear layout with a background image which is in my drawable folder. After installing the app in the device can i download an image from a server and set it as the background of the linear layout? I hope i have made the question clear. Any help would be greatly appreciated. Thanks in advance.
try this one (i posted my version for FrameLayout, Imageview should be similar): String myJpgPath = "/sdcard/picture.jpg"; Bitmap image_b = BitmapFactory.decodeFile(myJpgPath); final BitmapDrawable image_d = new BitmapDrawable(image_b); final FrameLayout main = (FrameLayout) findViewById(R.id.main_view); main.setBackgroundDrawable(image_d);
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "java, android, themes, branding" }
Do I need <ul> with when I have <nav> with <li>? Regarding the `<nav>` HTML5 tag. What is the difference between this: <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">News</a></li> <li><a href="#">Photos</a></li> <ul> </nav> and this: (can this work?) <nav> <li><a href="#">Home</a></li> <li><a href="#">News</a></li> <li><a href="#">Photos</a></li> </nav>
You cannot put `li` elements outside of a `ul`/`ol`. But you don't have to use a list at all. You can just put those `a` tags directly under the `nav`: <nav> <a href="#">Home</a> <a href="#">News</a> <a href="#">Photos</a> </nav> * * * For a little more history and a more thorough exploration, read this: **Navigation in Lists: To Be or Not To Be**.
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 0, "tags": "html, tags, html lists, nav" }
Querying Random 10 Percent for Each Record in SQL Server 2008 We audit 10% of files for each of our clients and need to create a SQL script. I can create a query for each client by using a WHERE statement. However, I need it run on for each client. If I did it manually, I would need to run this for each individual client. Is there a way to query the 10% for each client in a script? > SELECT TOP 10 PERCENT b.loan_no > > FROM borrower b JOIN clients c ON b.clients_id = c.clients_id WHERE b.funded >= '04/01/2011' AND c.dba IN 'ABC COMPANY' ORDER BY NEWID()
Select clients_id, Loans.loan_no From clients As c Cross Apply ( Select Top 10 Percent b.loan_no From borrower As b Where b.clients_id = c.clients_id And b.funded >= '20110401' And b.dba In( 'ABC Company' ) Order By NewId() ) As Loans
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "sql, sql server, tsql" }
Create does not work in GAE Datastore viewer When I try to create some entities I don't see the option to input fields. I just see the SaveEntity button. !enter image description here However I can view all the existing entities. !enter image description here What is very strange is - there is another entity called VideoEntity for which the create did not work yesterday but works today. Can somebody help me with this seemingly unpredictable tool ? Regards, Sathya
i think the console knows what properties each entity has based on existing data, rather then your models. and the data is only updated periodically. when did you upload your app? maybe waiting a few hours will give the console time to update. alternatively, you could use the remote api to add your entities, or write a small snippet and upload such as ... VideoStatsEntity(app='home', ip='116.89.52.67', params='tag=20130210').put()
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "google app engine, google cloud datastore" }
Send a String[] array through the request body to a web service, using Retrofit I want to use a web service that accepts a String[] array in the body of the web request. public void fooWebService(@RequestBody String[] ids) What would be the best way to send the String[] array from my `Android` client using `Retrofit`? I am assuming I would need to use the `@Body` annotation. The `content-type` is `application/json`.
Retrofit's default serialization is JSON so this will basically work out-of-the-box. You can use either a `String[]` or `List<String>` on the client (I prefer the latter). @POST("/endpoint") void sendIds(@Body List<String> ids); After creating an instance of the service using your `RestAdapter` you can pass an existing list of IDs or create one. service.sendIds(ids); // .. or .. service.sendIds(Arrays.asList("foo", "bar"));
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "android, spring, retrofit" }
Strict warning: Only variables should be passed by reference in Open Restaurant I installed Open Restaurant based on Drupal 7.x. As soon as I insert any menu item into create categories, I get this warning: > Strict warning: Only variables should be passed by reference in sizzle_preprocess_views_view__content__menus__all_menus() (line 69 of /web/htdocs/xxxxxxxxxxx/home/profiles/restaurant/themes/sizzle/includes/menu.inc). I checked the line and I got this code: // Render the category and add it to template. $variables['term'] = drupal_render(taxonomy_term_view($term, $view_mode)); I don't know how to improve this, in order to solve the issue. Writing to the group that made Open Restaurant I didn't got any answer. Hence my post here.
`drupal_render` takes reference. `taxonomy_term_view($term, $view_mode)` is not a variable, so you shouldn't use it in places where reference is needed - because if something takes reference, it will try to update what it got, and it's impossible with a function. So to fix this, you need to create variable, then store result of `taxonomy_term_view` in it, and pass that variable to `drupal_render`. Then, create patch file nd post it in their issue queue for everybody to see.
stackexchange-drupal
{ "answer_score": 1, "question_score": 0, "tags": "7, theming" }
Loop in elixir with delay interval I have the following code in elixir, where I want to call a function - parseCsvFiles in a loop: def loopParseFiles do spawn(Parse_Csv,:parseCsvFiles,[self]) receive do {:parse_complete} -> loopParseFiles after 20000 -> loopParseFiles end end In the above code, I want to set a delay such that, the loopParseFiles function is called back after 20000 miliseconds or after :parse_complete is received - **whichever is more**. TIA :)
So you want to always wait for at least 20 seconds, and then wait until `:parse_complete` is received? You can do it like this: def loopParseFiles do spawn(Parse_Csv,:parseCsvFiles,[self]) :timer.sleep 20000 receive do {:parse_complete} -> loopParseFiles end end Even if the `:parse_complete` message arrives during the call to `:timer.sleep`, it will still be waiting in the mailbox once the `receive` expression is ready to pick it up.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "elixir" }
.NET - Return a List<CustomSerializableObject> from a webservice Is it a **good idea** to try and return a strongly typed List of custom objects from a webservice? Any pitfalls I should know about? [WebMethod] public List<CustomSerializableObject> GetList() { List<CustomSerializableObject> listToReturn = new List<CustomSerializableObject>(); listToReturn.Add(new CustomSerializableObject()); listToReturn.Add(new CustomSerializableObject()); listToReturn.Add(new CustomSerializableObject()); return listToReturn; }
I don't know of any specific pitfalls to speak of other than possible support for third-parties that would want to communicate to it. You would probably be better to return an array of objects by doing listToReturn.ToArray(). You can easily fill a new list on the client side if that is what you need.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "c#, .net, list, serialization, web services" }
Assembly not packaged for Azure worker role I am facing a strange problem with packaging an assembly for Azure worker role. I am building a sample Azure cloud application having one website and a worker role. I am referencing a third party assembly, `myasm.dll` in both website and worker role project. The `myasm.dll` has dependency on two other assemblies. When I build the project all three(myasm.dll and two dependent assemblies) third party assemblies are getting copied to bin directory for both website and worker role projects. So far so good. When packaging is done for worker role, off the three third party assemblies, only two assemblies are included in the package, the third assembly is not included. Strangely enough, packaging of Website project includes all three assemblies. I created one more worker role to test the behavior but same behavior was seen again. Is this a known issue or something? Any help is highly appreciated. I use VS2012 Update 4.
Package will not include any dll which is not explicitly used in your project or referenced. I know this problem occurs when you do not use type explicitly in a your project(old bug raised \- with won't fix status) I guess your best option is to explicitly reference those missing dll's (see here) or try to add dummy usage of types from missing dependencies.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "visual studio 2012, azure, package, azure worker roles" }
Excel VBA: concatenate formula with if condition I am trying to use the below coding to concatenate the cells based on criteria.. It throws me an syntax error. Can you please help me to correct this code or do I need to use a different method. Request: ![enter image description here]( Code: Sub Conc() Dim lastrow As Range Dim str As String With Worksheets("sheet1") lastrow = .Cells(Rows.Count, "A").End(xlUp).Row Range("F2").Select Range("F2:F" & LastRow).Formula = "=IF(B2="[email protected]",CONCATENATE(E2," -",MID(A2,FIND("SECN",A2),14)),IF(B2<>"[email protected]",CONCATENATE(MID(A2,FIND("SECN",A2),14)," - ",C2)))" End With End Sub
First, you need to to double on your `"` inside the formula string. Second, you need to fully qualify all your `Cells`, `Rows.Count` and `Range` objects nested inside your `With Worksheets("sheet1")` statement. Third, there's no need to `Select` the `Range` before setting the `Formula` to it. With Worksheets("sheet1") LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row .Range("F2:F" & LastRow).Formula = "=IF(B2=""[email protected]"",CONCATENATE(E2,"" - "",MID(A2,FIND("" SECN"",A2),14)),IF(B2<>""[email protected]"",CONCATENATE(MID(A2,FIND(""SECN"",A2),14),"" - "",C2)))" End With
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "excel, vba, concatenation, formula" }
Is it possible to show a video on discord bot camera? I have seen a discord bot existing that could show specific videos from its camera. Is there any way I could add a command that would accept a direct video link and display it on a discord bot's camera? At least to show a video. (During streams)
I think that it may be possible but not yet available to the general public. I think maybe the bot you are referring to could have been taken down for breaking TOS. You might be able to do it but I do not think its allowed.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "python, video, discord, bots, discord.py" }
How long does it take for Google to change redirect uri I have setup a redirect uri for a Google API, since I have changed the redirect uri I get an error response that the redirect uri is mismatched. In the developer console I see the updated redirect uri but when I `var_dump` the Google Object I see for the property `redirect_uri` is still referring to the old one. So my question is, how long does it take before my changed redirect uri is active? I cannot find anything in the docs. Is there anyone who can help me out?
use below link, which gives you basic introduction about configuration. google api setup for php and if you change your redirect_uri, redownlaod `client_Secret.json` after 15 minutes. hope this may work for you.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 2, "tags": "php, api, redirect, google api" }
Spark jobs submitted through jenkins I'm looking to deploy a spark jar into a CI/CD pipeline using Jenkins. I have not been able to get spark-submit to work with Jenkins natively. I'm curious if anyone has gone down this path.
simple solution overlooked there is an arg to disconnect. \--conf spark.yarn.submit.waitAppCompletion=false
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "apache spark, jenkins" }
Add two tensors with different dimensions in tensorflow I am basically trying to add two tensors in tensorflow, the crux is that they are of different lengths `a = [1, 2, 3, 4, 5]` and `b = [1, 2, 3]` and am looking for a function that I am calling `tf.myadd` in the following tf.myadd(a, b) = [2, 4, 6, 4, 5] I have been looking into broadcasting, yet this has not the expected behavior.
Broadcasting is the default for all tensor operations in `tf`. In this case, you are trying to avoid broadcasting since the 2 tensors ((5,) and (3,)) are NOT broadcastable along the axis=0 by the standard broadcasting rules. **So what you need is an element-wise addition without broadcasting.** What you can do as in this case is use post-padding on the smaller array such that the two 1D tensors have the same shape and then add them elementwise over `axis=0`. Like this - import numpy as np import tensorflow as tf a = [1, 2, 3, 4, 5] b = [1, 2, 3] b_pad = np.pad(b, (0,len(a)-len(b))) tf.add(a,b_pad).numpy() array([2, 4, 6, 4, 5], dtype=int32)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 3, "tags": "python, tensorflow, machine learning" }
Javascript function not returning properly? function IsSwap() { var urlString = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/GetModelType")%>"; var id = { id : GetGUIDValue() } $.ajax({ type: "POST", url: urlString, data: id, success: function(data) { if (data.toString() == 'SwapModel') { return true; } } }); Expected result is `true`. I can alert right before the return so I know it's getting to that point fine. In another function, I tried to get my bool and use it like this: var isSwap = IsSwap(); if (isSwap) and it keeps saying `isSwap` is undefined. Why?
You are using ajax requests, which are asynchronous. You can't return value from an ajax request. Try this instead: function IsSwap() { var urlString = "<%= System.Web.VirtualPathUtility.ToAbsolute("~/mvc/Indications.cfc/GetModelType")%>"; var id = { id : GetGUIDValue() } $.ajax({ type: "POST", url: urlString, data: id, success: function(data) { if (data.toString() == 'SwapModel') { ResultIsTrue(); // call another function. } } }); After execution, instead of using this: var isSwap = IsSwap(); if (isSwap){ // Do Somethinh } Try that: IsSwap(); function ResultIsTrue(){ // Do Same Thing }
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "javascript" }
Trying to access my json using $.getJson function of jquery I am trying to access token from < it returns me string with Content-Type:application/json on browser I try to load this token using $.getJson from my wordpress application uploaded on url < but it does not return me that token my code : $.getJSON(" { format: "json" }, function(token) { alert(token); }); Please help me
You will need to use jsonp since the domain is different from your page (due to the port number). The xhr request is considered cross domain and is falling foul of the same origin policy. See the Additional Notes section from the jquery getJson docs > Additional Notes: Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol. Script and JSONP requests are not subject to the same origin policy restrictions.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "jquery, json, servlets, cross domain, getjson" }
object oriented-ness, extensability and modularity for simple program How efficiently we can apply object oriented-ness, extensability and modularity for simple program? If it is application I can identify Entities and relations between them. When it comes to simple program I am not able to do this. Please help me in achieving object oriented-ness, extensability and modularity in the Berlin clock program in the link. < Thanks in Advance.
Here's how I would tackle the problem 1. **object oriented-ness** First of all find out all the entities involved in your problem. Then intepret them as classes. In this case for example the clock is based on different Lights and their inter communication to display actual time. So I would consider Light as an abstract class and would also inherit different other lights (E.g. RedLight, YelloLight etc) from this abstract Light class and extend them. 2. **Extensability** Always use interfaces rather than directly accessing the classes. In this way you could replace or extend your classes 3. **Modularity** Have your Model (Classes), Business Logic, UI Logic etc separated in different class libraries (or separate projects). Hope this simple explanation helped.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "oop, modularity" }
Views not registered in django rest urls Why my views is not registered in url? here's my view code, class AView(APIView): def get(self, request, format=None): return Response(apps.get_models()) here's my url code from a_module import views from .views import * from rest_framework_nested import routers app_name = 'a_module' router = routers.DefaultRouter() router.register(r'endpoint', views.AView, base_name="endpoint") urlpatterns = [ url(r'^', include(router.urls)), ] There's other view in a_module that registered in url, but the only view that is not registered is AView, i tried registering with views.AView.as_view() it doesn't work too. It when I access the view through `/endpoint` it returns not found.
Since your view class does not inherited from **`Viewsets`** , you can not use a **`router`** here. So, remove those portions and directly mention the view class in **`urls()`** function with **`.as_view()`** as below, from a_module import views from .views import * app_name = 'a_module' urlpatterns = [ **url(r'endpoint/', views.AView.as_view(),name='endpoint'),** ]
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "django, django rest framework, django urls" }
Explain this transition: $4 \cdot 4^{n}-1 = 3\cdot 4^{n}+(4^n-1)$ I'm reading through a proof for $4^n-1 $ is divisible by $3$ and it has a step which I'm not understanding. The induction step: $4^{n+1}-1=4 \cdot 4^{n}-1 = 3\cdot4^n+(4^n-1)$ Can anyone explain this transition: $4 \cdot 4^{n}-1 = 3\cdot 4^n+(4^n-1)$
You want to show that $4^n-1$ is divisible by $3$ for all $n\geq 1$. Clearly it holds for $n=1$. Now suppose it holds for $n\geq 1$. Then $$4^{n+1}-1=4 \cdot 4^n-1=(3+1)\cdot 4^n-1=3\cdot 4^n+(4^n-1).$$ Clearly $3\cdot 4^n$ is divisible by $3$. By assumption $4^n-1$ is divisible by $3$ as well. Hence the sum is divisble by $3$ and thus $4^{n+1}-1$ is divisible by $3$. By induction we're done.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "induction, exponentiation" }
jvisualvm difference between live objects and allocated objects As seen in the screenshot here, 0 live objects, 9 allocated objects. What's the difference between a live and an allocated object ? !jvisualvm screenshot
* Allocated objects are all objects that have been created since application start (or reset) * Live objects are reachable objects that are being actively used by your program (likely still in the Young Generation)
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 20, "tags": "java, jvisualvm" }
java utf-8 file reading I am trying to read a UTF-8 encoded file as follows- import java.io.*; class main { public static void main(String[] args) throws java.lang.Exception { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("temp.txt"), "UTF-8")); String line; line = br.readLine(); line = line.trim(); boolean val1 = line.length() != 0; boolean val2 = !line.startsWith("//"); System.out.println(val1 + " " + val2); br.close(); } } File temp.txt contains first line as- //,<verb>,<verb> So, the output should be true false But I get output as true true Can somebody tell me how to fix this?
Open your temp.txt in a text editor and make sure that you don't have any characters in front of the `//`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "java" }
joining DataFrames in spark I would like joing two dataframes: edges and selectedComponent by two keys using `or` function val selectedComponent = hiveContext.sql(s"""select * from $tableWithComponents |where component=$component""".stripMargin) but not this way val theSelectedComponentEdges = hiveContext.sql( s"""select * from $tableWithComponents a join $edges b where (b.src=a.id or b.dst=a.id)""") but using join function edges.join(selectedComponent, edges("src")===selectedComponent("id")) but I am not sure how I supposed to using here "or". Anyone can help me :-)?
edges.join(selectedComponent, (edges("src")===selectedComponent("id")) || (edges("dst")===selectedComponent("id")))
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "scala, apache spark, apache spark sql" }
How to extract city and state code from an address I have a string var looks like this: str = "1234 South St, Boston, MA" Is there any way that I can extract only the city and state code? So I want this result: extractedStr = "Boston, MA"
You can use `NSDataDetector` for `CheckingType.address` and get city and state `NSTextCheckingKey`s from its `addressComponents`: let str = "1234 South St, Boston, MA" do { if let addressComponents = try NSDataDetector(types: NSTextCheckingResult.CheckingType.address.rawValue) .matches(in: str, range: NSRange(location: 0, length: str.utf16.count)).first?.addressComponents, let city = addressComponents[.city], let state = addressComponents[.state] { print("city:", city) print("state:", state) let result = "\(city), \(state)" print(result) } } catch { print(error) } * * * This will print > city: Boston > > state: MA > > Boston, MA
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "swift" }
Do parallel LNAs at 90-degrees to eachother reduce the noise floor more than side-by-side? Wiring amplifiers in parallel in a summing configuration improves the signal to noise ratio because amplifier noise in each LNA is uncorrulated. However, external noise sources will still be a factor because both LNAs receive those noise sources, thus the external noise sources are correlated. With 2 LNAs, would any of these be useful to reduce the correlation of external noise sources? If so, what might be best? * Physically rotate LNA1 90-degrees from LNA2 * Physically rotate LNA1 180-degrees from LNA2 * Mount one LNA flat on the board and one vertical or on its side (think horizontal vs vertical polarization) -Eric, KJ7LNW
> With 2 LNAs, would any of these be useful to reduce the correlation of external noise sources? No. If your noise has already coupled into the input of the LNA(s), then it helps nothing. The mounting of the LNA generally has little effect at all - the amount of electromagnetic noise picked up depends on the length of whatever picks up the noise in parallel to the electric field (or perpendicular to the magnetic field). LNAs are small. In fact, that mounting method just makes sure you build a "noise sensor" in two orthogonal directions. It sounds more like a method to pick up more noise, than less. Also, as per your previous question: Two LNAs in parallel are not what you usually do. You use one LNA, to dominate the system noise figure. That makes shielding it easy, too: it's but a few components you really need to shield.
stackexchange-electronics
{ "answer_score": 3, "question_score": 1, "tags": "amplifier, signal integrity, signal to noise, low noise amplifier, noisefloor" }
Eclipse and database giving different results I have a large Java EE system connecting to an Oracle database via JDBC on Windows. I am debugging a piece of code that does a retrieval of a field from the database. The code is retrieving the field but when I run the exact same SELECT, copied from Eclipse, it does not yield any results. Can any of you tell me why this would be the case? I'm at a loss..
One possible reason is that the application might see uncommited data which it just created, but not yet committed. When you execute the same statement in a different session it doesn't see the data (depending on your transaction isolation level)
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "java, eclipse, oracle" }
Prolog compact? I have a problem, I need to compact a derivative result like this: 0*x*x + 2*(1*x + x*1) =====> example: 0+2*(2*x) =====> 0+2*4*x====>8*x Is it possible? Thanks for your help. Regards, Volter
Yes, this is possible, it just takes some work. You'll need to write out atomic rules such as rule(0*_, 0). rule(_*0, 0). rule(1*X, X). rule(X*1, X). and implement a fixpoint predicate (maybe a failure-driven loop) that applies rules until convergence.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "prolog, calc, derivative" }
Using sed or tr to capitalize the last letter of words that begin with a specified character/expression I want to capitalize the last letter of words that begin with certain letters. Example: `At The Movies` to `AT ThE Movies` I tried... $ sed 's/\<[ABEXY][[:alpha:]]*\([[:alpha:]]\>\)/\U\1/g' file1 But this replaces all the words I am trying to change with an upper case of their last letter Also tried: $ sed '/\<[ABEXY][[:alpha:]]*\([[:alpha:]]\>\)/ y/\1abcdefghijklmnopqrstuvwxyz/\1ABCDEFGHIJKLMNOPQRSTUVWXYZ/' file1 But backcalling doesn't work with `sed y` So I just got all caps.
Capture the start of the word too, and include it in the replacement: sed 's/\<\([ABEXY][[:alpha:]]*\)\([[:alpha:]]\>\)/\1\U\2/g' file1
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "regex, sed, tr" }
Most efficient way to convert float 16ths to 4 bit integer in C As part of an anti-aliasing routine I'm running on an STM32 (single precision FPU, if that matters), I'm looking to convert a float value 0 ≀ x < 1 to a 4 bit nibble representing opacity. Basically each LSB of the nibble corresponds to a 16th of the float, so 0 ≀ x < 0.0625 would be 0x0, 0.0625 ≀ x < 0.125 would be 0x1, so on. Are there any bit manipulation tricks I could use to make this operation fast/efficient?
For any floating-point value, `x`, such that `0 <= x < 1`, the value `y = x * 16` will give `y <= 0 < 16`. Casting this `float` value to an `unsigned char` will set the lower nibble of that byte to the number of 16ths. Thus: float x = 0.51; unsigned char b = (unsigned char)(x * 16); Then `b` will have the value `0x08` \- representing eight sixteenths; and likewise for any other (valid) value of `x`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -1, "tags": "c" }
Fit ballon overlay in mapview I have balloon popups showing in Android MapView when a user tap:s on specific points on the map. Depending on where the user taps the balloon does not always fit insize the MapView. I solve this now by using MapController.animateTo to always have the tapped point in center. However, this is not the way I prefer it to be. I would like to animate the MapView only so much that the balloon layout fits inside MapView. Any tips on how this can be solved?
One way to fit the balloon overlay is to override the dispatchDraw method, check the bounds of the display using getMeasuredWidth and getMeasuredHeight, and, draw the balloon such that it fits within the display area. I am not sure if you have seen the Android MapView Balloons project on github. I have been using this code for a while and it is excellent, may be you can find some pointers to your problem from there. Hope this helps.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "android, android mapview, balloon" }
Some good Unicode tutorials in C? Anyone knows of some good Unicode tutorials with examples in C? I have to create a console app (to be run in xterm), with Unicode support, _and_ it has to be on C. :(
This might help you to get started. This handles UTF8-encoded unicode though.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "c, unicode" }
jQuery UI Calendar widget to change date when changing year or month I'm using the jQuery UI calendar widget with the month and year drop downs, like show here: < Apparently some people pick a day, then open the widget again, pick a year and a month and let it close. The issue is that picking the year and month doesn't change the year and month of the date being entered, only the one being displayed to the user. Is there a way to have the year and month have an immediate effect on the date, so that if I have the date 22/06/2012 and chose 1990, it'll automatically go to 22/06/1990.
You should set trigger to this event `onChangeMonthYear`. For example: $(function() { $( "#datepicker" ).datepicker({ changeMonth: true, changeYear: true, onChangeMonthYear: function(year, month, inst) { if(inst.currentYear != inst.drawYear || inst.currentMonth != inst.drawMonth) { $(this).datepicker("setDate", new Date(year, month - 1, inst.selectedDay)); } }); });
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery, jquery ui" }
Is $\phi(t)=\max\{t^2+1-2|t|,1/2\}$ a characteristic function? > Consider the function $\phi$ defined by $$\phi(t) = \left\\{\begin{array}{ccc}t^2+1-2|t|& \rm for &|t|\le 1- \frac{1}{\sqrt{2}}\\\ \frac{1}{2}&\rm for& |t|> 1- \frac{1}{\sqrt{2}}\end{array}\right. $$ Is $\phi$ a characteristic function? I assume it is not, as it do not have a derivative at $t=1- \frac{1}{\sqrt{2}}$, but how to prove that?
If we define $$\varphi_1(t) := \begin{cases} 2t^2-4 |t| +1, & |t| \leq 1- \frac{1}{\sqrt{2}} \\\ 0, & |t| > 1- \frac{1}{\sqrt{2}}\end{cases},$$ then $\varphi_1$ is an even continuous real-valued function which satisfies $$\varphi_1(0)=1 \quad \text{and} \quad \lim_{|t| \to \infty} \varphi_1(t)=0.$$ Moreover, $\varphi_1|_{(0,\infty)}$ is convex. It follows from Polya's theorem that $\varphi_1$ is a characteristic function. On the other hand, $$\varphi_2(t) := 1$$ is clearly a characteristic function. This implies that $$\varphi(t) = \frac{1}{2} \varphi_1(t) + \frac{1}{2} \varphi_2(t)$$ is a characteristic function.
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "probability theory, characteristic functions" }
jQuery UI won't format date according to expectation The following prints `Nov 30` on both Chrome and FF. I was expecting `Dec 01`. <html> <head> <link rel="stylesheet" href="jquery-ui.min.css"> <script src="jquery-1.11.1.min.js"></script> <script src="jquery-ui.min.js"></script> <script> $(document).ready(function(){ var $t = $.datepicker.formatDate("M dd", new Date("2014-12-01")); console.log($t); }); </script> </head> <body> </body> </html> What am I doing wrong?
Try using `parseDate('M dd', '2014-12-01')`.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "javascript, jquery, jquery ui, jquery ui datepicker, date formatting" }
Can I have partial template specialization with the using keyword? In the code of the OpenCV library I find this: template<typename _Tp, int cn> class Vec { ... } typedef Vec<int, 2> Vec2i; typedef Vec<int, 3> Vec3i; typedef Vec<float, 2> Vec2f; typedef Vec<float, 3> Vec3f; I would like to have a `Vec` of type `float` and variable length `N`. Is it possible to write something like using Vecf<N> = Vec<float, N>; ?
Yes, and you are nearly there. The correct syntax would be template<int N> using Vecf = Vec<float, N>;
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 2, "tags": "c++11, templates, using" }
Replacement for spring form tag in facelets since I know I can't use the Spring tag library in Facelets, I wonder if anyone can tell me what should I use instead of <sf:form method="POST" modelAttribute="spitter"> ..... </sf:form> Where prefix `sf` refers to (in JSP only): `<%@ taglib prefix="sf" uri=" %>` I really like the idea of this form, that it binds all properties directly to `modelAttribute` object. Is there any possibility that `<h:form>...</h:form>` can do the same? Or is there any other tag, that can handle it? I can't use JSP because i want to use PrimeFaces. I'm just a beginner in J2EE, so please be patient :) Thank you in advance
Yes, `<h:form>` does a similar thing. Even though the JSF approach is a bit different, the end result is similar: With spring the object gets submitted, and with jsf the field values end up in your managed bean. You will just have to use <h:inputText value="#{bean.property}" /> (where `bean` is a `@ManagedBean`-annotated class (for jsf2), or declared in faces-config (for jsf1)) This difference is that the spring form is submitted to the target url, and spring finds the target method based on the mapping, while here you specify which method of the managed bean to invoke in your `<h:commandButton />`
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "spring, jsf, jakarta ee, spring mvc, facelets" }