qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
57,810,418
I'm creating a dataframe out of a string data, the header of which have duplicate columns. Because of pandas default check to auto-rename in case of duplicate columns, it adds '.1, .2, and so on' suffix to each duplicate. ```py formatted_data = "a|b|c|a\n1|xyz|3|4" final_data = StringIO(formatted_data) df = pd.read_csv(final_data, sep='|') ``` **Output df:** ``` a b c a.1 1 xyz 3 4 ``` I followed the solution mentioned [here](https://github.com/pandas-dev/pandas/issues/19383) ```py df = pd.read_csv(final_data, sep='|', header=None) df = df.rename(columns=df.iloc[0], copy=False).iloc[1:].reset_index(drop=True) ``` Output df is as expected but it messes up with the metadata forcing the dtype for all columns to be **dtype('O')**. This dtype has cascading effects to my transformation code where I create an arrow\_table out of the transformed\_df. ```py arrow_table = pa.Table.from_pandas(df, preserve_index=False) ``` It errors out: **pyarrow.lib.ArrowTypeError: ('an integer is required (got type str)', 'Conversion failed for column a with type object')** To fix the above error, before creating the table, I assign the df type to str & the issue gets resolved: ```py df = df.astype(str) ``` But the table's metadata stores **'pandas\_type': "unicode"** for all the cols. The end-state of my datafile is parquet & as parquet operations are highly-dependent on metadata, the above data\_type is not the expected. Is there a pandas in-built option or work around to get the expected df without losing the dtype or auto re-assigning the dtype based on values: **Expected df:** ``` a b c a 1 xyz 3 4 ``` ```py df.a.dtype > dtype('int64') ```
2019/09/05
[ "https://Stackoverflow.com/questions/57810418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8551891/" ]
``` create table mytab(p_id number, p_code varchar2(10), comm varchar2(10), mdate date); insert into mytab values(112, 'WXCVA', null, to_date('20190202','yyyymmdd')); insert into mytab values(112, 'UCXVA', 'WXCVA', to_date('20190909','yyyymmdd')); insert into mytab values(222, 'DCVA', null, to_date('20180808','yyyymmdd')); insert into mytab values(222, 'UCVA', 'DCVA', to_date('20091209','yyyymmdd')); COMMIT; select * from mytab; P_ID P_CODE COMM MDATE 112 WXCVA NULL 02-FEB-19 112 UCXVA WXCVA 09-SEP-19 222 DCVA NULL 08-AUG-18 222 UCVA DCVA 09-DEC-09 ``` Merge statement to perform the required update. ``` MERGE INTO MYTAB C USING (SELECT A.P_ID, B.P_CODE, B.COMM, A.MDATE FROM MYTAB A INNER JOIN MYTAB B ON A.P_ID = B.P_ID AND A.P_CODE = B.COMM) D ON ( C.P_ID = D.P_ID AND C.P_CODE = D.P_CODE) WHEN MATCHED THEN UPDATE SET C.MDATE = D.MDATE; select * from mytab; P_ID P_CODE COMM MDATE 112 WXCVA NULL 02-FEB-19 112 UCXVA WXCVA 02-FEB-19 222 DCVA NULL 08-AUG-18 222 UCVA DCVA 08-AUG-18 ```
Is this what you want? ``` update tab set mdate = (select t2.mdate from tab t2 where t2.p_code = tab.comm ) where tab.comm is not null; ```
7,366,817
I need to add some validation that will only allow one capital letter in a string that may include spaces. The capital letter can be anywhere in the string, but can only be used once or not at all. I was going to incorporate the solution below as a separate rule, but I have this bit of validation and wondering if I can just tweak it to get the desired result: ``` // Validate Sentence Case if(dataEntryCaseId.toString().match("4")){ var newValue = toTitleCase(value); if(newValue != value){ for(var x = 1, j = value.length; x < j; x++){ if(value.charAt(x) != newValue.charAt(x)){ valid = false; $("#text_10").attr({"value":$("#text_10").attr("value").replace(value.charAt(x), "")}); finalVal = finalVal.replace(value.charAt(x), ""); } } } } if(!valid){ for(var x = 0, j = styleNoteJsonData.styleGroupNote.length; x < j; x++){ if(styleNoteJsonData.styleGroupNote[x].styleName == styleGroupName){ alert(styleNoteJsonData.styleGroupNote[x].styleNote); $(".styleNote").addClass("alertRed"); SendErrorMessage(styleNoteJsonData.styleGroupNote[x].styleNote); } } ```
2011/09/09
[ "https://Stackoverflow.com/questions/7366817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335514/" ]
``` "this is A way to do it with regex".match(/^[^A-Z]*[A-Z]?[^A-Z]*$/) ``` Regex breaks down like this... start of string (`^`) followed by not capital letter (`[^A-Z]`) zero or more times (`*`) follow by optional (`?`) capital letter (`[A-Z]`) followed by not capital letter (`[^A-Z]`) zero or more times (`*`) followed by end of string (`$`) --- EDIT: simpler method based on idea from @IAbstractDownvoteFactory's answer ``` var string = "This is a simple way to do it" // match all capital letters and store in array x var x = string.match(/[A-Z]/g) // if x is null, or has length less than 2 then string is valid if(!x || x.length < 2){ // valid } else { // not valid } ``` Regex matches all capital letters, and returns an array of matches. The length of the array is how many capitals there are, so less than 2 returns true.
Could you loop through each character to check if it is equal to ascii code 65 through 94? ``` var CharArr = "mystring".toCharArray(); var countCapsChars = 0; for(var i =0;i<= CharArr.length;i++) { if (CharArr[i].CharCodeAt(0) >= 65 && CharArr[i].CharCodeAt(0) <=94) { countCapsChars++; } if (countCapsChars == 1 || countCapsChars == 0){ //pas } else { //fail } ```
34,619,135
I'm using this code to customize UIButtons on my main ViewController and have placed it in it's own separate .swift file to be referenced wherever a UIButton exists. I want to be able to modify the properties of the MyCustomButton from within my main ViewController after a button is pressed. For example, I press a button that's using the properties from MyCustomButton and its color changes. I'm just getting into swift and am not greatly familiar with it's ins and outs quite yet. Any help is appreciated. ``` import Foundation import UIKit class MyCustomButton: UIButton { required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.layer.cornerRadius = 25; self.layer.borderColor = UIColor.blackColor().CGColor self.layer.borderWidth = 3 self.backgroundColor = UIColor.redColor() self.tintColor = UIColor.whiteColor() self.setTitle("", forState: UIControlState.Normal) self.titleLabel?.numberOfLines = 0 self.titleLabel?.textAlignment = NSTextAlignment.Center } } ```
2016/01/05
[ "https://Stackoverflow.com/questions/34619135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3912266/" ]
Consider this code, ``` String str1 = "ABC"; String str2 = new String("ABC"); System.out.println(str1==str2); // false System.out.println(str1.equals(str2)); //true ``` The reason for this is that when you write `String str1="ABC"` this string is kept in **string pool** and `String str2 = new String("ABC")` creates the new object in **heap** and it won't check the string pool if it is already present. But as contents of the both string are same, **equals** method returns true.
Strings are immutable in nature. So, when we do this, ``` String a1 = "a"; String a2 = "a"; ``` Actually in memory, only one instance of String "a" is created. Both a1 and a2 will point to the same instance. That's why, `a1 == a2` and `a1.equals(a2)` are both true. But, in this, ``` String a1 = "a"; String a2 = new String("a"); ``` We created a new String instance explicitly. So, `a1.equals(a2)` will be true. But `a1 == a2` will not.
26,759,069
I have an angular service that wraps my rest api calls and returns a $http promise. My question is how do I throw an error so that a promise that triggers the .error method gets called? I don't want to just throw error since I want it to use the .success/.error in the calling function rather than doing a try catch block around it. ``` myFunction: function(foo) if (foo) { return $http.put(rootUrl + '/bar', {foo: foo}); } else { //what do I return here to trigger the .error promise in the calling function } ```
2014/11/05
[ "https://Stackoverflow.com/questions/26759069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/611750/" ]
First inject the $q-service in your service. Then in your else: ``` else { var deferred = $q.defer(); deferred.reject("reject reason, foo was false"); return deferred.promise; } ``` Not as clever as Blazemonger's, but its quick to do.
You can raise or throw a custom error using `throw new Error ("custom error")`. For http: ``` http.get('url').toPromise().then (result =>{ throw new Error ("My Custom Error") // New Custom error New is optional w }).catch(err => { throw err }); // catch will catch any error occur while http call ```
19,509,725
I have an object like ``` { a: 2.078467321618, b :13521.4, c : 4503.9, more...} ``` (In debug mode) I want to loop through the object and separate key and value; How can I achieve this?
2013/10/22
[ "https://Stackoverflow.com/questions/19509725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1770457/" ]
``` Object.keys(obj).forEach(function(key) { var val = obj[key]; ... }); ```
``` Try the following: for(var key in object){ var value = object[key]; //now you have access to "key" and "value" } ```
6,144,166
So I am writing a little utility to format my inventory file is such a manner that I can import it to a preexisting db. I am having a large issue trying to just do fscanf. I have read tons of file in c in the past. What am I doing wrong here. Edit based on Christopher's suggestion still getting NULL. ``` #include <stdio.h> #include <string.h> int main () { FILE* stream; FILE* output; char sellercode[200]; char asin[15]; string sku[15]; string fnsku[15]; int quality; stream = fopen("c:\out\dataextract.txt", "r"); output = fopen("c:\out\output.txt", "w"); if (stream == NULL) { return 0; } for(;;) { //if (EOF) break; fscanf(stream, "%s", sku); fprintf(output, "%s %s %s %s %i\n", sku, fnsku, asin, quality); } return 0; } ```
2011/05/26
[ "https://Stackoverflow.com/questions/6144166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/673191/" ]
``` if (stream = NULL) { return 0; } ``` should be ``` if (stream == NULL) { return 0; } ```
Backslash is escape character inside strings. Use forward slash in your pathnames. "c:/foo/bar.txt"
202,772
How does this website need to change in order to discourage the endless 'I'm a newbie help me out, here's my homework'? Also, how do we discourage people from 'here's the solution, give me some points now' kind of answers? EDIT - context: <https://stackoverflow.com/questions/19555424/simple-nested-loop-program/19555488#19555488>
2013/10/24
[ "https://meta.stackexchange.com/questions/202772", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/237711/" ]
> > Why do people not do their own homework? > > > 1. They're lazy or they aren't interested in learning 2. Their behavior is almost always reinforced by *copy/paste* answers > > How do we discourage people from answering? > > > That seems almost impossible. I think we should try to discourage copy/paste answers to useless/duplicate questions that show no effort. Maybe we could reward less (or no) reputation for answers to closed questions. Or maybe answers to upvoted questions should be worth more points. Another way is to **encourage** quality answers that provide more than just a snippet of code to *copy/paste*. And... If a question shows no effort, vote to close it. > > My approach: > > > If a question smells like it came from a lazy student (but has potential value to others), I try to add a small twist to my answer that prevents the OP from copy/pasting it. You can usually find a way to provide an answer that will help anybody who wants to understand and/or learn, but will not help those who are trying to avoid learning. Sometimes all you have to do is break the important logic out into a sub-routine or a simple class. Your answer will still be clear to future visitors, but the OP will have to understand the most basic principles to finish his homework. (*he might even learn something!*) Note that I only do this when it's obvious that the site is being used to mindlessly complete homework. When someone asks a high quality question, the best thing to do is give them the exact answer they're looking for. The other thing I try to do is to steer students and newbs towards the right tools to help them teach themselves. For Java questions, this means pointing them towards the API documentation and encouraging them to look there before asking a question. Learning how, when, and where to consult the documentation is one of the most valuable things you can learn as a programmer.
If your question is on topic for the site, well written (for your definition of "well"), and answerable, *and* I am inclined to do so, **I will answer the question, regardless of if it's a homework question or not.** Discouraging users from asking these questions, as tempting as it may be, isn't entirely in the spirit of the community. I can live with your question, even if it's a homework question, if it's on topic for the site. Discouraging users from just blatantly posting the answer, as tempting as it may be, is one of those things I used to do, but quickly discovered that it wasn't the correct approach to the "problem". For most students looking to cheat, [the problem readily takes care of itself](https://stackoverflow.com/questions/4161475/counting-and-generating-perfect-squares#comment11014758_4161475); for others, they're only hurting and depriving themselves of the most important facet of software engineering: **problem solving.** I don't see a problem with homework questions. Poor quality questions are closed and deleted. High quality questions rise to the top. The system *works*. I don't have a problem with it.
11,278,308
I stumbled upon <https://codereview.stackexchange.com/questions/10610/refactoring-javascript-into-pure-functions-to-make-code-more-readable-and-mainta> and I don't understand the answer since the user uses an @ symbol in a way I've never seen before. What does it do when attached to the if keyword? Can you attach it to other keywords?
2012/06/30
[ "https://Stackoverflow.com/questions/11278308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1493605/" ]
It's not a JavaScript thing. It's a symbol used by whatever templating system that answer was referring to. Note that the `<script>` element has type `text/html`, which will prevent browsers from paying any attention to its contents. Some other JavaScript code will find that script and fetch its `innerHTML` in order to merge the template with some data to create ... well whatever that template makes.
@: syntax in Razor Said by @StriplingWarrior at [Using Razor within JavaScript](https://stackoverflow.com/questions/4599169/using-razor-within-javascript) It is razor code, not javascript, if you are interested in razor check: <http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx>
37,624,903
Since I am creating a dataframe, I don't understand why I am getting an array error. ``` M2 = df.groupby(['song_id', 'user_id']).rating.mean().unstack() M2 = np.maximum(-1, (M - 3).fillna(0) / 2.) # scale to -1..+1 (treat "0" scores as "1" scores) M2.head(2) AttributeError: 'numpy.ndarray' object has no attribute 'fillna' ```
2016/06/03
[ "https://Stackoverflow.com/questions/37624903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5187157/" ]
`(M - 3)` is getting interpreted as a `numpy.ndarray`. This implies that `M` is defined somewhere as a `numpy.ndarray`. Test it out by running: ``` print type(M) ```
You are calling the `.fillna()` method on a numpy array. And `numpy` arrays don't have that method defined. You can probably convert the `numpy` array to a `pandas.DataFrame` and then apply the `.fillna()` method.
25,907,478
somehow I am struggling with finding out whether it is possible to define an imported library in CMake, specifying target properties (include\_directories and library path) and hoping that CMake will append the include directories once I add that project to target\_link\_libraries in another project. Let's say I have an imported library in a file called Module-Conf.cmake: ``` add_library(mymodule STATIC IMPORTED) set_target_properties(mymodule PROPERTIES IMPORTED_LOCATION "${OUTPUT_DIR}/lib") set_target_properties(mymodule PROPERTIES INCLUDE_DIRECTORIES "${OUTPUT_DIR}/include") ``` And in a project I add the dependency: ``` include(Module-Conf) target_link_libraries(${PROJECT_NAME} mymodule) ``` Will CMake append the include\_directories property to the include path? Right now I cannot see the path so it seems that I have to do it by myself by using get\_target\_property? Question: Can I do some CMake magic to automatically append the include to the include directories of another project? Thanks a lot. Martin
2014/09/18
[ "https://Stackoverflow.com/questions/25907478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/260493/" ]
The difference between the `INCLUDE_DIRECTORIES` property and the `INTERFACE_INCLUDE_DIRECTORIES` property is transitivity. Set `INTERFACE_INCLUDE_DIRECTORIES` instead. <http://www.cmake.org/cmake/help/latest/manual/cmake-buildsystem.7.html#transitive-usage-requirements>
Starting from CMake 3.11, it's possible to use [target\_include\_directories()](https://cmake.org/cmake/help/latest/command/target_include_directories.html) with IMPORTED targets. ``` add_library(mymodule SHARED IMPORTED) target_include_directories(mymodule INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>) ``` Another way is [set\_property()](https://cmake.org/cmake/help/latest/command/set_property.html), which also allows using [generator expressions](https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html). ``` set_property(TARGET mymodule PROPERTY INTERFACE_INCLUDE_DIRECTORIES $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>) ```
618,643
> > Given $\varphi: \mathbb{Z} \to \mathbb{Z}\_{10}$ such that $\varphi(1)=6$, compute $\ker(\varphi)$ and $\varphi(19)$. > > > In my attempt I found that since $\varphi(1)=6$ has order 5, then $\ker(\varphi)= \{5 \mathbb{Z} \}$ and since the function is homomorphism I got $\varphi(19)=4$. Am I right? Thanks.
2013/12/26
[ "https://math.stackexchange.com/questions/618643", "https://math.stackexchange.com", "https://math.stackexchange.com/users/117722/" ]
You are right to conclude from $\phi(5)=20+10\mathbb Z=0+10\mathbb Z$ that $5\mathbb Z= \ker \phi$ (or first only "$\subseteq$", but there is no subgroup properly between $5\mathbb Z$ and $\mathbb Z$). But note that you "spelled" this statement wrong (no $\{\}$ here). But from $19\cdot 4=76=7\cdot 10+6$ you should obtain $\phi(19)=6+10\mathbb Z$. (I prefer to write "$a+10\mathbb Z$" instead of "$a$ in $\mathbb Z\_{10}$", but that may be a matter of notation introduced).
@nzobo, you are absolutely correct. Im($\phi$) has order $5$ and so Ker($\phi$)=$5\mathbb{Z}$. Your second conclusion follows from $19=15+4$ so that $\phi(19)=\phi(15)+\phi(4)=\phi(4)=(6\times 4) ~mod ~ 10=4$ (This should be a comment but I can't comment.)
41,061
I have these albums and songs in my iTunes Library. They should appear grouped, but for some reason, iTunes splits them up and shows them as separate albums with the same name and details: ![iTunes splits the songs on this album.](https://i.stack.imgur.com/b4g8r.png) I check the metadata and everything seems to be in order. Here are screen shots of the first two songs: ![Metadata for song that's been separated.](https://i.stack.imgur.com/MNjBq.png) ![Metadata for another song in the same album.](https://i.stack.imgur.com/vG8xa.png) Why is iTunes doing this? Thanks for your help!
2012/02/20
[ "https://apple.stackexchange.com/questions/41061", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/13705/" ]
I've only ever seen this happen when the metadata absolutely differs in some way between tracks. There are two ideas that come to mind: 1. Highlight each individual character and make sure 3 dots ( ... ) haven't been transformed into a single character elipses ( … ). Highlight each of the dots above and you should understand the difference. 2. Check the 'Sorting' section too and make sure all of that data is identical, notably in the 'Grouping' fields.
I would suggest selecting all four songs and doing the following: 1. Delete metadata from the tracks: at least Grouping, Album, Artist, Sort Album, and Sort Artist, but more wouldn't hurt. 2. Save the absence of the data by selecting "Done." 3. While they continue to be selected, Get Info again and fill in the relevant information. I've found that no matter how much some fields may look identical, resetting them to be identical together often solves the problem.
7,270,177
I'm new to WPF and the MVVM pattern so keep that in mind. The project I'm tasked with working on has a view and a view model. The view also contains a user control that does NOT have a view model. There is data (custom object ... Order) being passed to the view model that I also need to share with the user control. It looks like the UserControl does share data between the view model already via `DependencyPropertys` but this data is just text boxes on the user control that look to be bound back to propertys on the view model. I need to share data that will NOT be represented by a control on the user control. Is there a good way to pass this data (complex Order object)? Maybe I do need some kind of hidden control on my user control to accomplish this but I'm just not that sure being new to this. Any advice would be appreciated.
2011/09/01
[ "https://Stackoverflow.com/questions/7270177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/447341/" ]
Yes: Use the [Scripting API](http://download.oracle.com/javase/6/docs/technotes/guides/scripting/programmer_guide/index.html). There are implementations to run scripts written in JavaScript, Groovy, Python and lots of other languages. **[EDIT]** Since it was mentioned in the comments: Be wary of security issues. There are several options: 1. You allow end-customers to supply scripts (say in a web form) 2. You don't allow customers to supply scripts; if a script needs to be changes an administrator or developer must start a specific tool. 3. You develop a system which only allows to execute "safe" scripts Option #3 doesn't work (= only works for the most simple cases). There is a mathematical proof that a computer program can never tell what another program can potentially do without actually executing it. So you can get away with option #3 if you don't allow to call methods (or only a very, very limited set of methods). But most scripting languages allow to access Java classes which means you can eventually get `System.exit()` or `Runtime.exec()`. This in turn means you have to write a parser which makes sure that the code doesn't contain something odd. Which you will have to update every day because the customers will come up with new ... err ... *interesting* ways to use the feature. Also chances are that you'll make a mistake - either the parser won't accept valid input or it will let malicious code pass. Given the complexity of the problem, the chance is between 99.9999% and 100%. Option #1 means no security at all but after the third change, customers will berate you to adopt it. It will work for some time until the first script kiddie comes along and ruins everything. Guess whose fault that will be? The manager who hired ~~his nephew~~... the kid? So a human will have to eyeball the scripts, fix all the bugs in them and configure the system to run them. Option #2 will cause all kinds of griefs, too, but it will cause less grief, all things considered.
Sure, see [Mozilla Rhino](http://www.mozilla.org/rhino/)
5,631,566
``` "NewsML": [ { "Identification": {"NewsIdentifier": { "ProviderId": "timesofindia.com", "NewsItemId": "7954765" }}, "NewsLines": { "HeadLine": "I want KKR to win for Ganguly: Shah Rukh", "DateLine": "IANS, Apr 12, 2011, 04.41am IST" }, "NewsComponent": [ { "Role": {"@FormalName": "WebURL"}, "ContentItem": { "MediaType": {"@FormalName": "Link"}, "DataContent": {"media-caption": "http://timesofindia.indiatimes.com/sports/cricket/ipl-2011/news/I-want-KKR-to-win-for-Ganguly-Shah-Rukh/articleshow/7954765.cms"} } }, { "Role": {"@FormalName": "Caption"}, "ContentItem": { "MediaType": {"@FormalName": "Text"}, "DataContent": {"media-caption": "Aware of the negative vibes in Kolkata after the exclusion of Dada from the team, Shah Rukh Khan dedicated his team's victory to Sourav Ganguly."} } }, { "Role": {"@FormalName": "Keywords"}, "ContentItem": { "MediaType": {"@FormalName": "Text"}, "DataContent": {"media-keyword": "Sourav Ganguly, Shah Rukh Khan, KKR, IPL"} } }, { "Role": {"@FormalName": "Photo"}, "ContentItem": { "@Href": "http://timesofindia.indiatimes.com/photo.cms?photoid=7954812&phototype=1&width=400&height=300", "MediaType": {"@FormalName": "Photo"}, "Format": {"@FormalName": "JPEG Baseline"}, "Characteristics": [ { "@FormalName": "Width", "@Value": "450" }, { "@FormalName": "Height", "@Value": "300" } ] } }, { "Role": {"@FormalName": "Photo-Caption"}, "ContentItem": { "MediaType": {"@FormalName": "Text"}, "DataContent": {"media-caption": "Kolkata Knight Riders owner Saha Rukh Khan greets his supporters during their IPL match against Deccan Chargers at Eden Gardens. (PTI photo)"} } }, { "Role": {"@FormalName": "Thumb"}, "ContentItem": { "@Href": "http://timesofindia.indiatimes.com/thumb.cms?photoid=7954812", "MediaType": {"@FormalName": "Photo"}, "Format": {"@FormalName": "JPEG Baseline"} } }, { "Role": {"@FormalName": "Story"}, "ContentItem": { "MediaType": {"@FormalName": "Text"}, "DataContent": {"body": {"body.content": "KOLKATA: Aware of the negative vibes in Kolkata after the exclusion of local boy Sourav Ganguly from the team, Kolkata Knight Riders co-owner Shah Rukh Khan on Monday night dedicated his team's nine-run victory to Sourav Ganguly and the sports loving people of the city.\n\nI came back only for the fans. I wanted to do this for Knight Riders, the fans of Kolkata, I wanted to do this for Sourav Ganguly.\n\nI want my team KKR to win the IPL for Kolkata and Sourav Ganguly, said the matinee idol.\n\nI am very happy. It was really a cool moment. (Skipper Gautam) Gambhir and (Jacques) Kallis were really cool. It was really a cool moment as our team is unused to wins, said Shah Rukh Khan after KKR clinched their first win in IPL edition four.\n\nShah Rukh also expressed his disappointment over unnecessary controversies revolving the team for the last three seasons.\n\nA win is always welcome. We had lot of unnecessary controversies in the last three seasons, said Shah Rukh. "}} } } ] }, } ] ```
2011/04/12
[ "https://Stackoverflow.com/questions/5631566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/703525/" ]
I pulled up designer and made your layout without any trouble at all. As shown in the hierarchy in the top right of my screenshot, I created a line edit and a text edit. Joined those in a vertical layout. Created a treeWidget and joined that with the layout in a horizontal splitter. I was able to get it to look like yours by editing the vertical layout properties so that there was a nonzero layout margin. But it looks like the generated code is explicitly setting that to zero in yours... ![Widgets line up here](https://i.stack.imgur.com/QOaC8.jpg)
The widget on the right side of the splitter (the one containing the QLineEdit and the QListWidget) probably has default values for the layout. In QtCreator, select the QWidget, then in the property editor, scroll all the way down to the Layout section, and set the 4 values for layoutLeftMargin, layoutTopMargin, layoutRightMargin and layoutBottomMargin to 0.
49,015,827
I have the error `MethodNotAllowedHttpException` when I submit form data using `ajax`. **HTML** ``` <form class="form-signin" id="loginForm" role="form" method="POST"> // Form </form> <script> $('#loginForm').submit(function () { initLogin($('#email').val(),$('#password').val()); }); </script> ``` **JavaScript** ``` function initLogin(email, password) { $.ajax( { headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, url:'loginModal', method:'POST', data: { strEmail: email, strPassword: password }, success: function( bolUpdated ) { alert('yes'); }, fail: function() { alert('no'); } }); } ``` **Route** `Route::post( 'loginModal', 'Auth\LoginController@loginModal' );` **Controller** ``` public function loginModal( Request $request ) { Log::info('test'); } ``` I tried changing the form's type but no luck. Any idea what might be the issue?
2018/02/27
[ "https://Stackoverflow.com/questions/49015827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2898592/" ]
Here's a regex that can do what I think you're looking for: ``` /(?:(?:^|[-+_*/])(?:\s*-?\d+(\.\d+)?(?:[eE][+-]?\d+)?\s*))+$/ ``` <https://regex101.com/r/w74GSk/4> It matches a number, optionally negative, with an optional decimal number followed by zero or more operator/number pairs. It also allows for whitespace between numbers and operators. ```js const re = /(?:(?:^|[-+_*/])(?:\s*-?\d+(\.\d+)?(?:[eE][+-]?\d+)?\s*))+$/; function test(s) { console.log("%s is valid? %s", s, re.test(s)); } // valid test(" 1 "); test("1 + 2"); test(" 1 * 2 * 3 "); test("-1 * 2 - -3"); test("-1 * 2 - -3e4"); test("-1 * 2 - -3.5E6"); // invalid test("1 +"); test("1 + foo"); ``` This may need to be expanded, based on what you want to allow. One thing it does not handle is parentheses to override operator precedence.
Using [`complex-js`](https://www.npmjs.com/package/complex-js), you can wrap [`Complex.compile()`](https://github.com/patrickroberts/complex-js#compile) in a `try/catch` statement: ```js function isMathExpression (str) { try { Complex.compile(str); } catch (error) { return false; } return true; } console.log(isMathExpression('2+2')) console.log(isMathExpression('foo+bar')) console.log(isMathExpression('sin(5)+sqrt(2/5i)')) ``` ```html <script src="https://unpkg.com/complex-js@5.0.0/dst/complex.min.js"></script> ``` The grammar for this parser is [here](https://github.com/patrickroberts/complex-js/blob/master/compiler/grammar.ne#L36-L121), if you're interested in seeing what constructs it supports. Full disclosure, I am the author of this library
1,113,280
There is a sample code of apple named "reachability" which tells us the network status of the device, wifi or edge/gprs, but I couldn't see any documentation or sample code regarding gathering if the device is on 3g or not while accessing to internet. I also googled, but no hope. Is it possible to do that, if so how?
2009/07/11
[ "https://Stackoverflow.com/questions/1113280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133617/" ]
### Column / Row > > ... I don't need the transactional integrity to be maintained across > the entire operation, because I know that the column I'm changing is > not going to be written to or read during the update. > > > Any `UPDATE` in [PostgreSQL's MVCC model](https://www.postgresql.org/docs/current/transaction-iso.html) writes a new version of ***the whole row***. If concurrent transactions change *any* column of the same row, time-consuming concurrency issues arise. [Details in the manual.](https://www.postgresql.org/docs/current/transaction-iso.html#XACT-READ-COMMITTED) Knowing the same *column* won't be touched by concurrent transactions avoids *some* possible complications, but not others. ### Index > > To avoid being diverted to an offtopic discussion, let's assume that > all the values of status for the 35 million columns are currently set > to the same (non-null) value, thus rendering an index useless. > > > When updating the ***whole table*** (or major parts of it) Postgres ***never uses an index***. A sequential scan is faster when all or most rows have to be read. On the contrary: Index maintenance means additional cost for the `UPDATE`. ### Performance > > For example, let's say I have a table called "orders" with 35 million > rows, and I want to do this: > > > > > > ``` > UPDATE orders SET status = null; > > ``` > > I understand you are aiming for a more general solution (see below). But to address ***the actual question*** asked: This can be dealt with in ***a matter milliseconds***, regardless of table size: ``` ALTER TABLE orders DROP column status , ADD column status text; ``` [The manual (up to Postgres 10):](https://www.postgresql.org/docs/10/sql-altertable.html#SQL-ALTERTABLE-NOTES) > > When a column is added with `ADD COLUMN`, all existing rows in the table > are initialized with the column's default value (`NULL` if no `DEFAULT` > clause is specified). If there is no `DEFAULT` clause, this is merely a metadata change [...] > > > [The manual (since Postgres 11):](https://www.postgresql.org/docs/current/sql-altertable.html#AEN67134) > > When a column is added with `ADD COLUMN` and a non-volatile `DEFAULT` > is specified, the default is evaluated at the time of the statement > and the result stored in the table's metadata. That value will be used > for the column for all existing rows. If no `DEFAULT` is specified, > NULL is used. In neither case is a rewrite of the table required. > > > Adding a column with a volatile `DEFAULT` or changing the type of an > existing column will require the entire table and its indexes to be > rewritten. [...] > > > And: > > The `DROP COLUMN` form does not physically remove the column, but > simply makes it invisible to SQL operations. Subsequent insert and > update operations in the table will store a null value for the column. > Thus, dropping a column is quick but it will not immediately reduce > the on-disk size of your table, as the space occupied by the dropped > column is not reclaimed. The space will be reclaimed over time as > existing rows are updated. > > > Make sure you don't have objects depending on the column (foreign key constraints, indices, views, ...). You would need to drop / recreate those. Barring that, tiny operations on the system catalog table `pg_attribute` do the job. Requires an **exclusive lock** on the table which may be a problem for heavy concurrent load. (Like Buurman emphasizes in his [comment](https://stackoverflow.com/questions/1113277/how-do-i-do-large-non-blocking-updates-in-postgresql/22163648?noredirect=1#comment112262872_22163648).) Baring that, the operation is a matter of milliseconds. If you have a column default you want to keep, add it back *in a separate command*. Doing it in the same command applies it to all rows immediately. See: * [Add new column without table lock?](https://stackoverflow.com/questions/10412078/add-new-column-without-table-lock/10412790#10412790) To actually apply the default, consider doing it in batches: * [Does PostgreSQL optimize adding columns with non-NULL DEFAULTs?](https://dba.stackexchange.com/a/61017/16892) General solution ================ [**`dblink`**](https://www.postgresql.org/docs/current/dblink.html) has been mentioned in another answer. It allows access to "remote" Postgres databases in implicit separate connections. The "remote" database can be the current one, thereby achieving *"autonomous transactions"*: what the function writes in the "remote" db is committed and can't be rolled back. This allows to run a single function that updates a big table in smaller parts and each part is committed separately. Avoids building up transaction overhead for very big numbers of rows and, more importantly, releases locks after each part. This allows concurrent operations to proceed without much delay and makes deadlocks less likely. If you don't have concurrent access, this is hardly useful - except to avoid `ROLLBACK` after an exception. Also consider [`SAVEPOINT`](https://www.postgresql.org/docs/current/sql-savepoint.html) for that case. ### Disclaimer First of all, lots of small transactions are actually more expensive. This ***only makes sense for big tables***. The sweet spot depends on many factors. If you are not sure what you are doing: ***a single transaction is the safe method***. For this to work properly, concurrent operations on the table have to play along. For instance: concurrent *writes* can move a row to a partition that's supposedly already processed. Or concurrent reads can see inconsistent intermediary states. *You have been warned.* Step-by-step instructions ------------------------- The additional module dblink needs to be installed first: * [How to use (install) dblink in PostgreSQL?](https://stackoverflow.com/questions/3862648/how-to-use-install-dblink-in-postgresql/13264961#13264961) Setting up the connection with dblink very much depends on the setup of your DB cluster and security policies in place. It can be tricky. Related later answer with more **how to connect with dblink**: * [Persistent inserts in a UDF even if the function aborts](https://dba.stackexchange.com/a/105186/3684) Create a **`FOREIGN SERVER`** and a **`USER MAPPING`** as instructed there to simplify and streamline the connection (unless you have one already). Assuming a `serial PRIMARY KEY` with or without some gaps. ``` CREATE OR REPLACE FUNCTION f_update_in_steps() RETURNS void AS $func$ DECLARE _step int; -- size of step _cur int; -- current ID (starting with minimum) _max int; -- maximum ID BEGIN SELECT INTO _cur, _max min(order_id), max(order_id) FROM orders; -- 100 slices (steps) hard coded _step := ((_max - _cur) / 100) + 1; -- rounded, possibly a bit too small -- +1 to avoid endless loop for 0 PERFORM dblink_connect('myserver'); -- your foreign server as instructed above FOR i IN 0..200 LOOP -- 200 >> 100 to make sure we exceed _max PERFORM dblink_exec( $$UPDATE public.orders SET status = 'foo' WHERE order_id >= $$ || _cur || $$ AND order_id < $$ || _cur + _step || $$ AND status IS DISTINCT FROM 'foo'$$); -- avoid empty update _cur := _cur + _step; EXIT WHEN _cur > _max; -- stop when done (never loop till 200) END LOOP; PERFORM dblink_disconnect(); END $func$ LANGUAGE plpgsql; ``` Call: ``` SELECT f_update_in_steps(); ``` You can parameterize any part according to your needs: the table name, column name, value, ... just be sure to sanitize identifiers to avoid SQL injection: * [Table name as a PostgreSQL function parameter](https://stackoverflow.com/questions/10705616/table-name-as-a-postgresql-function-parameter/10711349#10711349) Avoid empty UPDATEs: * [How do I (or can I) SELECT DISTINCT on multiple columns?](https://stackoverflow.com/questions/54418/how-do-i-or-can-i-select-distinct-on-multiple-columns/12632129#12632129)
I am by no means a DBA, but a database design where you'd frequently have to update 35 million rows might have… issues. A simple `WHERE status IS NOT NULL` might speed up things quite a bit (provided you have an index on status) – not knowing the actual use case, I'm assuming if this is run frequently, a great part of the 35 million rows might already have a null status. However, you can make loops within the query via the [LOOP statement](http://www.postgresql.org/docs/8.3/static/plpgsql-control-structures.html#PLPGSQL-CONTROL-STRUCTURES-LOOPS). I'll just cook up a small example: ``` CREATE OR REPLACE FUNCTION nullstatus(count INTEGER) RETURNS integer AS $$ DECLARE i INTEGER := 0; BEGIN FOR i IN 0..(count/1000 + 1) LOOP UPDATE orders SET status = null WHERE (order_id > (i*1000) and order_id <((i+1)*1000)); RAISE NOTICE 'Count: % and i: %', count,i; END LOOP; RETURN 1; END; $$ LANGUAGE plpgsql; ``` It can then be run by doing something akin to: ``` SELECT nullstatus(35000000); ``` You might want to select the row count, but beware that the exact row count can take a lot of time. The PostgreSQL wiki has an article about [slow counting and how to avoid it](http://wiki.postgresql.org/wiki/Slow_Counting). Also, the RAISE NOTICE part is just there to keep track on how far along the script is. If you're not monitoring the notices, or do not care, it would be better to leave it out.
29,272,827
i have the following `three.js` code: ``` var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 65, window.innerWidth/window.innerHeight, .1, 1000 ); var renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appendChild( renderer.domElement ) var geometry = new THREE.SphereGeometry( 5, 32, 32 ); var texture = THREE.ImageUtils.loadTexture( "world_map.jpg" ); var material = new THREE.MeshBasicMaterial( {color: 0xffff00, map:texture } ); var sphere = new THREE.Mesh( geometry, material ); scene.add( sphere ); camera.position.z = 14; var render = function () { requestAnimationFrame( render ); sphere.rotation.x += .01; sphere.rotation.y += .01; renderer.render(scene, camera); }; render(); ``` Since i am completely new to `three.js` so right know i am able to make this much of code. Now my problem is that texture is not loading. Actually i want to make a revolving earth by my own. when i am trying to load the texture it is giving me the following error: > > THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter is set to THREE.LinearFilter or THREE.NearestFilter. ( world\_map.jpg ) > > > and > > three.min.js:556 Uncaught SecurityError: Failed to execute 'texImage2D' on 'WebGLRenderingContext': The cross-origin image at file:///E:/sanmveg/libs/world\_map.jpg may not be loaded. > > > please i am new to so please help me.
2015/03/26
[ "https://Stackoverflow.com/questions/29272827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3524493/" ]
You need to have an image that has a square size in the power of two to use this kind of texture, so make sure your images is 2x2, 8x8, 16x16, 32x32, etc..
please try [**fileReader Object**](https://developer.mozilla.org/en-US/docs/Web/API/FileReader) which lets web applications to read the contents of files, and in this case an image, stored on the user's computer. Hope that you can go to next step from here.
4,289,381
I am trying to answer a question about line integrals, I have had a go at it but I am not sure where I am supposed to incorporate the line integral into my solution. $$ \mathbf{V} = xy\hat{\mathbf{x}} + -xy^2\hat{\mathbf{y}}$$ $$ \mathrm{d}\mathbf{l} = \hat{\mathbf{x}}\mathrm{d}x + \hat{\mathbf{y}}\mathrm{d}y $$ $$ \int\_C\!\mathbf{V}\cdot\mathrm{d}\mathbf{l} = \int\!xy\,\mathrm{d}x - \int\!xy^2\,\mathrm{d}y = \left[ \frac{x^2y}{2}\right ]\_?^? - \left[ \frac{xy^3}{3} \right]\_?^? $$ I have a feeling that the parabola in question must come into play in the limits of the integrals, although I dont know how they are supposed to. The parabola in question is $y = \frac{x^2}{3}$ and the coordinates at which the line integral is supposed to go over are $a=(0,0)$ and $b=(3,3)$.
2021/10/27
[ "https://math.stackexchange.com/questions/4289381", "https://math.stackexchange.com", "https://math.stackexchange.com/users/824765/" ]
* One could also use a parametrization. Set $x(t)=t$ and and $y(t)= t^2/3$. * The parabola corresponds to the endpoint of the position vector : $ \vec r (t)= t\vec i + \frac {t^2}{3} \vec j$. * This allows to calculate the differential $d\vec r$: $d\vec{\mathbf{r}}(t)=\vec{\mathbf{r\space '}}(t) dt = (1\vec i + (2t/3) \vec j) dt$ * With the parametrization chosen, we get $\vec{\mathbf{V}}(t)= (t. \frac{t^2}{3})\vec i - (t. (\frac{t^2}{3})^2)\vec j$ * One can then apply the definition : vector line integral = $\int\_C \vec V(t).d\vec r(t)= \int\_{t\_1}^{t\_2} \vec (V(t).\vec r\space '(t) )dt$ , with, here, $t\_1 = 0$ and $t\_2 =3$.
In this case, it's as simple as plugging in $y=\frac{x^2}{3}$ into the first integral and integrating from $x=0$ to $x=3$. In the second integral, do the same thing, but plug in $dy=\frac{2x}{3}dx$. In other words, parameterize the whole curve in terms of $x$. In other examples (like circles), it may be more convenient to parameterize $x$ and $y$ with a different variable.
2,808,022
I have to parse an XML file in C++. I was researching and found the RapidXml library for this. I have doubts about `doc.parse<0>(xml)`. Can `xml` be an .xml file or does it need to be a `string` or `char *`? If I can only use `string` or `char *` then I guess I need to read the whole file and store it in a char array and pass the pointer of it to the function? Is there a way to directly use a file because I would need to change the XML file inside the code also. If that is not possible in RapidXml then please suggest some other XML libraries in C++. Thanks!!! Ashd
2010/05/11
[ "https://Stackoverflow.com/questions/2808022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337891/" ]
We usually read the XML from the disk into a `std::string`, then make a safe copy of it into a `std::vector<char>` as demonstrated below: ``` string input_xml; string line; ifstream in("demo.xml"); // read file into input_xml while(getline(in,line)) input_xml += line; // make a safe-to-modify copy of input_xml // (you should never modify the contents of an std::string directly) vector<char> xml_copy(input_xml.begin(), input_xml.end()); xml_copy.push_back('\0'); // only use xml_copy from here on! xml_document<> doc; // we are choosing to parse the XML declaration // parse_no_data_nodes prevents RapidXML from using the somewhat surprising // behavior of having both values and data nodes, and having data nodes take // precedence over values when printing // >>> note that this will skip parsing of CDATA nodes <<< doc.parse<parse_declaration_node | parse_no_data_nodes>(&xml_copy[0]); ``` For a complete source code check: [Read a line from xml file using C++](https://stackoverflow.com/questions/5443073/read-a-line-from-xml-file-using-c/5443512#5443512)
The [manual](http://rapidxml.sourceforge.net/manual.html#classrapidxml_1_1xml__document) tells us: > > function xml\_document::parse > > > [...] Parses zero-terminated XML string > according to given flags. > > > RapidXML leaves loading the character data from a file to you. Either read the file into a buffer, like [anno](https://stackoverflow.com/users/121322/anno) suggested or alternatively use some memory mapping technique. (But look up `parse_non_destructive` flag first.)
2,408,976
Could you please help me how to format a `struct timeval` instance to human readable format like "2010-01-01 15:35:10.0001"?
2010/03/09
[ "https://Stackoverflow.com/questions/2408976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/289637/" ]
Combining previous answers and comments, changing the format to be [RFC3339](https://www.rfc-editor.org/rfc/rfc3339)-compliant, and checking all of the error conditions, you get this: ``` #include <stdio.h> #include <sys/time.h> ssize_t format_timeval(struct timeval *tv, char *buf, size_t sz) { ssize_t written = -1; struct tm *gm = gmtime(&tv->tv_sec); if (gm) { written = (ssize_t)strftime(buf, sz, "%Y-%m-%dT%H:%M:%S", gm); if ((written > 0) && ((size_t)written < sz)) { int w = snprintf(buf+written, sz-(size_t)written, ".%06dZ", tv->tv_usec); written = (w > 0) ? written + w : -1; } } return written; } int main() { struct timeval tv; char buf[28]; if (gettimeofday(&tv, NULL) != 0) { perror("gettimeofday"); return 1; } if (format_timeval(&tv, buf, sizeof(buf)) > 0) { printf("%s\n", buf); // sample output: // 2015-05-09T04:18:42.514551Z } return 0; } ```
This is what I use: ``` #include <time.h> #include <string.h> #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <winsock2.h> #define gmtime_r(ptime,ptm) (gmtime_s((ptm),(ptime)), (ptm)) #else #include <sys/time.h> #endif #define ISO8601_LEN (sizeof "1970-01-01T23:59:59.123456Z") char *timeval_to_str(char iso8601[restrict static ISO8601_LEN], unsigned precision, const struct timeval * restrict tv) { struct tm tm; if (!gmtime_r(&tv->tv_sec, &tm)) return memcpy(iso8601, "Error: Year overflow", sizeof "Error: Year overflow"); tm.tm_year %= 10*1000; char *frac = iso8601 + strftime(iso8601, sizeof "1970-01-01T23:59:59.", "%Y-%m-%dT%H:%M:%SZ", &tm); if (precision) { unsigned long usecs = tv->tv_usec; for (int i = precision; i < 6; i++) usecs /= 10; char *spaces = frac + sprintf(frac - 1, ".%-*luZ", precision, usecs) - 3; if (spaces > frac) while (*spaces == ' ') *spaces-- = '0'; } return iso8601; } ``` `precision` specifies the width of the seconds fraction. Code is y10k- and y`INT_MAX`-proof.
56,701,988
**models.py** ``` class UserManager(BaseUserManager): def create_user(self, phone, password=None): if not phone: raise ValueError('Please provide a valid Phone') user = self.model( phone = phone, ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, phone, password): user = self.create_user( phone, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, phone, password): user = self.create_user( phone, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user phone_regex = RegexValidator(regex=r'^(\+\d{1,3})?,?\s?\d{8,13}', message="Phone number should be in the format '+9999999999', Up to 14 digits allowed.") class User(AbstractBaseUser): phone = models.CharField(validators=[phone_regex],max_length=15,unique=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.phone def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active ``` **admin.py** ``` class UserCreationForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('phone',) def clean_password2(self): password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super().save(commit=False) user.set_password(self.cleaned_data["password1"]) if commit: user.save() return user class UserChangeForm(forms.ModelForm): password = ReadOnlyPasswordHashField() class Meta: model = User fields = ('phone', 'password') def clean_password(self): # Regardless of what the user provides, return the initial value. # This is done here, rather than on the field, because the # field does not have access to the initial value return self.initial["password"] class UserAdmin(BaseUserAdmin): # The forms to add and change user instances form = UserChangeForm add_form = UserCreationForm # The fields to be used in displaying the User model. # These override the definitions on the base UserAdmin # that reference specific fields on auth.User. list_display = ('phone', 'admin') list_filter = ('admin',) fieldsets = ( (None, {'fields': ('phone', 'password')}), ('Personal info', {'fields': ()}), ('Permissions', {'fields': ('admin',)}), ) # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin # overrides get_fieldsets to use this attribute when creating a user. add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('phone', 'password1', 'password2')} ), ) search_fields = ('phone',) ordering = ('phone',) filter_horizontal = () admin.site.register(User, UserAdmin) admin.site.register(PhoneOTP) admin.site.unregister(Group) ``` **serializers.py** ``` User = get_user_model() class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('phone','password') extra_kwargs = {"password":{'write_only': True}} def create(self,validated_data): user = User.objects.create(validated_data['phone'],None,validated_data['password']) return user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id','phone'] class LoginSerializer(serializers.Serializer): phone = serializers.CharField() password = serializers.CharField(style= { 'input_type': 'password'},trim_whitespace=False) def validate(self, data): user = authenticate(**data) if user.phone and user.password: return user raise serializers.ValidationError("Unable to log in with provided credentials.") ``` When I try to create user using APIView the user is created and I can see the user in the Django admin as well but the password field is unhashed and it says `Invalid password format or unknown hashing algorithm.` I have used a custom user model here to use the phone number as the username field but the problem remains the same. I am on the current version of Django i.e, 2.2 and because of this, I am also not able to login into the app as well.
2019/06/21
[ "https://Stackoverflow.com/questions/56701988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9632454/" ]
try this ``` from django.contrib.auth.hashers import make_password ... def create(self,validated_data): user = User.objects.create(validated_data['phone'],None,make_password(validated_data['password'])) return user ```
In view.py "use make\_password()" if validated: temp\_data = { 'phone': phone, 'password': make\_password(password), }
38,060,505
I have googled quite a bit, and I have fairly decent reading comprehension, but I don't understand if this script will work in multiple threads on my postgres/postgis box. Here is the code: ``` Do $do$ DECLARE x RECORD; b int; begin create temp table geoms (id serial, geom geometry) on commit drop; for x in select id,geom from asdf loop truncate table geoms; insert into geoms (geom) select someGeomfield from sometable where st_intersects(somegeomfield,x.geom); ----do something with the records in geoms here...and insert that data somewhere else end loop; end; $do$ ``` So, if I run this in more than one client, called from Java, will the scope of the geoms temp table cause problems? If so, any ideas for a solution to this in PostGres would be helpful. Thanks
2016/06/27
[ "https://Stackoverflow.com/questions/38060505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3059517/" ]
One subtle trap you will run into though, which is why I am not quite ready to declare it "safe" is that the scope is per session, but people often forget to drop the tables (so they drop on disconnect). I think you are much better off if you don't need the temp table after your function to drop it explicitly after you are done with it. This will prevent issues that arise from trying to run the function twice in the same transaction. (On commit you are dropping)
Temp tables in PostgreSQL (or Postgres) (PostGres doesn't exists) are local only and related to session where they are created. So no other sessions (clients) can see temp tables from other session. Both (schema and data) are invisible for others. Your code is safe.
236,849
I have a potentially-repeated question, but I was unable to find anything about this. So, I need to create a giant binomial coefficient in LaTeX (something around 1000pt). When I compile the below, though, it scales the `\binom{}{}` up, but not the a and b. Is there any way to make the whole thing bigger? ``` \documentclass[12pt,border=5pt]{standalone} \usepackage{amsmath, amssymb, amsthm} \usepackage{hyperref} \DeclareMathSizes{12}{1000}{1000}{1000} \begin{document} $\displaystyle \binom{a}{b}$ \end{document} ```
2015/04/04
[ "https://tex.stackexchange.com/questions/236849", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/75612/" ]
You can use the Latin Modern fonts, provided you fix the `largesymbols` font: ``` \documentclass[border=10]{standalone} \usepackage{lmodern} \usepackage{amsmath} \DeclareFontFamily{OMX}{lmex}{} \DeclareFontShape{OMX}{lmex}{m}{n}{ <-> lmex10 }{} \SetSymbolFont{largesymbols}{normal}{OMX}{lmex}{m}{n} \begin{document} \fontsize{1000}{1000}\selectfont $\displaystyle \binom{a}{b}$ \end{document} ``` ![enter image description here](https://i.stack.imgur.com/b6HT8.png)
Easiest here is just to scale the entire construction to suit your needs using [`graphicx`](http://ctan.org/pkg/graphicx)'s `\resizebox` or `\scalebox` functionality: ![enter image description here](https://i.stack.imgur.com/2AFtl.png) ``` \documentclass[12pt,border=5pt]{standalone} \usepackage{amsmath, graphicx} \begin{document} \resizebox{!}{1000pt}{$\displaystyle \binom{a}{b}$} \end{document} ```
30,602,250
I am trying to use Roo to import data from an Excel spreadsheet into a table (data\_points) in a Rails app. I am getting the error: ``` undefined method `fetch_value' for nil:NilClass ``` and that error references my data\_point.rb file at line (see below for full code excerpt): ``` data_point.save! ``` The "Application Trace" says: ``` app/models/data_point.rb:29:in `block in import' app/models/data_point.rb:19:in `import' app/controllers/data_points_controller.rb:65:in `import' ``` I am puzzled by this because a "find all" in my entire app shows no instance of fetch\_value Here is the other code in my app: In my model, data\_point.rb: ``` class DataPoint < ActiveRecord::Base attr_accessor :annual_income, :income_percentile, :years_education def initialize(annual_income, income_percentile, years_education) @annual_income = annual_income @income_percentile = income_percentile @years_education = years_education end def self.import(file) spreadsheet = open_spreadsheet(file) header = spreadsheet.row(1) (2..11).each do |i| annual_income = spreadsheet.cell(i, 'A') income_percentile = spreadsheet.cell(i, 'B') years_education = spreadsheet.cell(i, 'C') data_point = DataPoint.new(annual_income, income_percentile, years_education) data_point.save! end end def self.open_spreadsheet(file) case File.extname(file.original_filename) when ".xlsx" then Roo::Excelx.new(file.path) else raise "Unknown file type: #{file.original_filename}" end end end ``` In my controller, data\_points\_controller.rb I have added, in addition to the standard rails framework: ``` def import DataPoint.import(params[:file]) redirect_to root_url, notice: "Data points imported." end ``` In the Excel file I'm using, the header row has column names that are exactly the same as the 3 attributes noted above for DataPoints: annual\_income, income\_percentile, years\_education P.s. I have already watched RailsCast 396: Importing CSV and Excel, and read the comments many times. I think I am struggling with translating the example code to Rails 4 and / or my assignment of individual attributes (vs. the approach used in the RailsCast). Thanks in advance for any help!
2015/06/02
[ "https://Stackoverflow.com/questions/30602250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4797451/" ]
This is the problem encountered yesterday, the reason is I defined a Database field with name `class`, which is a reserved word for the Ruby language. It caused the conflict.
If you are not restricted to delete the `initialize` method for some reason, instead of removing it, you can try to add a `super` call like so: ``` def initialize(annual_income, income_percentile, years_education) super() @annual_income = annual_income @income_percentile = income_percentile @years_education = years_education end ``` **Sources:** * More info about `super` can be found [here](https://www.rubyguides.com/2018/09/ruby-super-keyword/).
10,270,914
Greeting people...i develop a web..everything working fine till deployment...my question is - why is it this error appear? because if i run the web on Visual Studio Server everything fine...but when i deploy and run it on IIS server suddenly this error appear..why is people? really need some help here.. ``` string tarikh = Convert.ToDateTime(txtTarikh.Text).ToString("yyyy-MM-dd"); ``` the line is where the cause of error..thanks in advance
2012/04/22
[ "https://Stackoverflow.com/questions/10270914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1124948/" ]
Chances are the server-side default culture is different to the one you've been using in development. What format are you expecting the date to be in, anyway? You should either use [`DateTime.TryParseExact`](http://msdn.microsoft.com/en-us/library/system.datetime.tryparseexact.aspx) or *at least* use [`DateTime.TryParse`](http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx) specifying the appropriate `CultureInfo`. (For example, the culture of the user.) Likewise I would suggest that you supply an appropriate `CultureInfo` to `ToString` - possibly `CultureInfo.InvariantCulture`.
[![enter image description here](https://i.stack.imgur.com/xaBI2.png)](https://i.stack.imgur.com/xaBI2.png) Issue is resolved by setting up .net globlization settings in IIS
3,367,553
Is $S$ linearly dependent on $\textsf V = \mathcal{F}(\Bbb R,\Bbb R)$ and $S = \{t, e^t ,\sin(t)\}$. How to prove that a set of functions are linearly dependent?
2019/09/24
[ "https://math.stackexchange.com/questions/3367553", "https://math.stackexchange.com", "https://math.stackexchange.com/users/708009/" ]
Suppose we have some scalars $a\_0,a\_1,a\_2$ in $\Bbb R$ such that $$a\_0t+a\_1e^t+a\_2\sin t =0 \tag{1}$$ for all real number $t$. Making $t=0$ this gives us $a\_1=0$. Returning to $(1)$, we have $$a\_0t+a\_2\sin t =0 \tag{2}$$ Now, make $t=\pi$ and then $a\_0\pi=0$, which means $a\_0=0$.
HINT.- A good way to try this problem is to consider that the elements of $V$ are $f\_1,f\_2,f\_3$ where $f\_1(t)=t,f\_2(t)=e^t,f\_3(t)=\sin(t)$ so you have to show that if the linear combination $$a\_1f\_1+a\_2f\_2+a\_3f\_3=0$$ where les $f\_i$ are three vectors and les $a\_i$ are scalars in your vectorial space, then $a\_1=a\_2=a\_3=0$ (Obviously for each $t$ you have $$(a\_1f\_1+a\_2f\_2+a\_3f\_3)(t)=a\_1f\_1(t)+a\_2f\_2(t)+a\_3f\_3(t)=0)$$
42,359,944
There are a few loops in javascript including forEach, some, map, and reduce. However, from what I currently understand, none of these are appropriate if you want to iterate through an array and return the value of a particular index. It seems like I am pretty much left with the standard for loop only. Is that true? So for instance, if I have an array of objects... and I would like to find the index of the item with a particular value... could I use anything other than the regular for loop?
2017/02/21
[ "https://Stackoverflow.com/questions/42359944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3534132/" ]
[Array.prototype.findIndex()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) , as suggested by @Andreas in comments. You can pass in a function to findIndex() method and define your equality criteria in that function. It will return the index of first array element, that satisfies the equality criteria defined in your function.
[Array.prototype.findIndex()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex) or [Array.prototype.indexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf) like everyone said.
296,665
Sorry for such a noob question, but where is the log out? I have looked under every menu option. Can not find it in the title bar. Typed in search box looking for results or instructions, not listed on the help page. Checked the footer. Am I suppose to stay logged on forever?
2015/06/11
[ "https://meta.stackoverflow.com/questions/296665", "https://meta.stackoverflow.com", "https://meta.stackoverflow.com/users/-1/" ]
It's hidden under the StackExchange dropdown menu at the top left. ![Log Out](https://i.stack.imgur.com/ghnX3.png)
Click on the StackExchange banner up in the nav bar (far left), on the very right of the popup menu you'll find the logout link.
14,741,966
Please recommend a scrum/agile project management tool. First, it should be able to be installed or deployed on my local computer. Additionally, it should be free, no need for complete unlimited usage, just that it can support 5 users and some scrum project functions, such as "kanban". I found some answers of other questions like mine. Some of the tools which have been recommended are too old, so please recommend newer tools for me. And if it has a nice look that would be better, something like [scrumwise](http://www.scrumwise.com/) or [targetprocess](http://www.targetprocess.com/). Must haves: 1. local applications 2. free 3. kanban
2013/02/07
[ "https://Stackoverflow.com/questions/14741966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1954315/" ]
Given that you're wanting a local application, I'm assuming that your team is all located in the same place. If so, I'd advise against using tools. As the agile manifesto says: "We value Individuals and Interactions over processes and tools". I'd urge you to consider co-locating your team(s), improving communication, using cards, physical boards and information radiators. Hope that helps.
<http://www.simple-kanban.com> This seems like it meets your requirements. There are other possibilities if you will accept a hosted solution rather than a local install.
175,739
I'm trying to mount an hfsplus filesystem in a Xubuntu 12.04 VM (kernel version 3.2.0-23-generic) but when I type `mount -o remount,rw /dev/sdb3` in command line it returns `not mounted or bad option`. Any help would be appreciated.
2012/08/14
[ "https://askubuntu.com/questions/175739", "https://askubuntu.com", "https://askubuntu.com/users/83303/" ]
for busybox/android users: > > Oddly, I needed to *add* a space (in contrast to normal usage) between 'remount' and 'rw': > > > ``` mount -o remount, rw / ``` otherwise it wouldn't work. > > UPDATE: it seems that this is almost never the case (see comments). Not sure which busybox-version + android-version I was running. I'll just leave this here in case anyone still runs into it. > > >
First, let us fix NTFS problems (if you have an Ubuntu/Windows dual boot setup) ``` sudo ntfsfix /dev/sda7 ``` Before mounting we need a Directory (folder) ``` mkdir ~/Desktop/disk ``` Now mount the partition ``` sudo mount /dev/sda7 ~Desktop/disk ``` In this case "sda7" is the partition name. Now you read from and write to the partition.
10,309,529
I was thinking of a class like: ``` template < typename ...Whatever > class MyClass { public: static constexpr bool has_default_ctr = Something; // I want this only if "has_default_ctr" is "true". MyClass(); //... }; ``` I don't think I can use a constructor template and `std::enable_if` for this (because there's no arguments). Am I wrong? If not, is there some other way to do this?
2012/04/25
[ "https://Stackoverflow.com/questions/10309529", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1010226/" ]
C++11 allows to (reliably) use `enable_if`-style SFINAE in template arguments: ``` template< // This is needed to make the condition dependent bool B = has_default_ctr , typename std::enable_if<B, int>::type = 0 > MyClass(); // When outside of class scope: // have to repeat the condition for out-of-line definition template<bool B, typename std::enable_if<B, int>::type = 0> MyClass::MyClass() /* define here */ ``` In C++03 you could have used a unary constructor with a defaulted parameter -- the default parameter means that the constructor still counts as a default constructor.
With `enable_if` it's easy (it works if the class templated also): ``` #include <type_traits> class MyClass { public: static constexpr bool has_default_ctr = Something; // I want this only if "has_default_ctr" is "true". template <typename = std::enable_if<has_default_ctr>::type> MyClass(); //... }; ```
60,547
Whilst working on a recent project, I was visited by a customer QA representitive, who asked me a question that I hadn't really considered before: > > How do you know that the compiler you are using generates machine code that matches the c code's functionality exactly and that the compiler is fully deterministic? > > > To this question I had absolutely no reply as I have always taken the compiler for granted. It takes in code and spews out machine code. How can I go about and test that the compiler isn't actually adding functionality that I haven't asked it for? or even more dangerously implementing code in a slightly different manner to that which I expect? I am aware that this is perhapse not really an issue for everyone, and indeed the answer might just be... "you're over a barrel and deal with it". However, when working in an embedded environment, you trust your compiler implicitly. How can I prove to myself and QA that I am right in doing so?
2008/09/13
[ "https://Stackoverflow.com/questions/60547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
> > ...you trust your compiler implicitly > > > You'll stop doing that the first time you come across a compiler bug. ;-) But ultimately this is what testing is for. It doesn't matter to your test regime how the bug got in to your product in the first place, all that matters is that it didn't pass your extensive testing regime.
If your worried about *malicious* bugs in the compiler, one recommendation (IIRC, an NSA requirement for some projects) is that the compiler binary predate the writing of the code. At least then you know that no one has *added* bugs targeted at *your* program.
5,379,093
I am not familiar with the lambda function itself, and don't really know how to debug this issue. Django-1.1.2 I am using, [django-activity-stream](https://github.com/philippWassibauer/django-activity-stream) in order to render activity streams for my users. In the documentation for this items it says that you need to pass two lambda functions to incorporate with existing newtworks, such as django-friends(the one I am using) Here are the functions that need to be pasted into your settings.py file. ``` ACTIVITY_GET_PEOPLE_I_FOLLOW = lambda user: get_people_i_follow(user) ACTIVITY_GET_MY_FOLLOWERS = lambda user: get_my_followers(user) ``` I have done so, but now everytime I try and render the page that makes use of this, I get the following traceback. ``` Caught NameError while rendering: global name 'get_people_i_follow' is not defined ``` Although this has been set in my settings... Your help is much appreciated!
2011/03/21
[ "https://Stackoverflow.com/questions/5379093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348869/" ]
Somewhere above where these lambdas are defined, you need to import the names `get_people_i_follow` and `get_my_followers`. I'm not familiar with django-activity-stream, but it's probably something like `from activity_stream import get_people_i_follow, get_my_follwers`. Lambda is a keyword for creating anonymous functions on the fly, so the meaning of your code is basically the same as if you had written the following. ``` def ACTIVITY_GET_PEOPLE_I_FOLLOW(user): return get_people_i_follow(user) def ACTIVITY_GET_MY_FOLLOWERS(user): return get_my_followers(user) ```
If you are integrating with a pre-existing network I don't believe you're actually supposed to write verbatim: ``` ACTIVITY_GET_PEOPLE_I_FOLLOW = lambda user: get_people_i_follow(user) ACTIVITY_GET_MY_FOLLOWERS = lambda user: get_my_followers(user) ``` I believe the author was just showing an example that `ACTIVITY_GET_PEOPLE_I_FOLLOW` and `ACTIVITY_GET_MY_FOLLOWERS` need to be set to a lambda or function that accepts one user argument and returns a list of users. You should probably be looking for something like `friends_for_user` in django-friends, or writing your own functions to implement this functionality. `get_people_i_follow` is indeed defined in `activity_stream.models` but it is just importing what's defined in settings.py. So if settings.py has `ACTIVITY_GET_PEOPLE_I_FOLLOW = lambda user: get_people_i_follow(user)` you're going to get a wild and crazy circular import / infinite recursion.
62,533,888
I decided to learn Python since I now have more time (due to pandemic) and have been teaching myself Python. I am trying to scrape tax rates from a site and can get almost everything I need. Below is a snippet of the code that comes out of my *Soup* variable as well as the relevant piece of Python. Where I am having difficulty is I am finding the `option` tag along with the `data-alias` that is empty (""). However, if you look at the code below there are some `data-alias` stages that are not empty **(see UAE or Great Britain)**- they have some countries listed. I am looking to get the `data-url` and country name from these as well. How do I code this to get empty tags and non-empty tags as I am losing some required information? Thanks, Seth **My code:** ``` import requests from bs4 import BeautifulSoup import re l=[] r = requests.get("https://taxsummaries.pwc.com/") c=r.content soup = BeautifulSoup(c, "html.parser") all = soup.find_all("option", {"data-alias":""}) ``` **Website Information:** ```html <option data-alias="" data-id="c9ddd85e-f3dc-4661-a4cb-8101f4644871" data-url="https://taxsummaries.pwc.com:443/uganda">Uganda</option> <option data-alias="" data-id="d21e8abe-784c-4617-a90e-5369b49a202f" data-url="https://taxsummaries.pwc.com:443/ukraine">Ukraine</option> <option data-alias="UAE" data-id="9e3f5e7b-f110-47dd-95d8-3d8160466e4a" data-url="https://taxsummaries.pwc.com:443/united-arab-emirates">United Arab Emirates</option> <option data-alias="Great Britain UK Britain Whales Northern Ireland England" data-id="3c42b2a9-7ed6-4b19-821d-5d78ef6f2b5d" data-url="https://taxsummaries.pwc.com:443/united-kingdom">United Kingdom</option> ```
2020/06/23
[ "https://Stackoverflow.com/questions/62533888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13798125/" ]
First thing the response from API is not a json list, its a simple json object. If you wanna iterate over the keys of the above object you can create a list with all the keys and then use key index to get the actual key name in the response. ``` final List<String> keys = ["alm","co2","hu","temp","th","tm","ts"]; ``` then you can modify your body widget like following - ``` body: new ListView.builder( itemCount: data == null ? 0 : data.length, itemBuilder: (BuildContext context, int index) { return new ListTile( leading: const Icon(Icons.stay_primary_portrait), title: Text(data.length.toString()), subtitle: Text(data[keys[index]]), trailing: Icon(Icons.more_vert), dense: true, isThreeLine: true, ); }, ), ``` Hope this helps!
You're getting a `Map` from your API. you cannot use that on a `ListView.builder`. You can use a regular `ListView` and add the ListTiles manually. Create the `ListView` and add the ListTiles manually using each key in the map. ```dart body: ListView( children: <Widget>[ buildTile('alm'), buildTile('co2'), buildTile('hu'), buildTile('temp'), // continue this for others ], ), ``` Create the `ListTile` to be used in the `ListView` ```dart buildTile(String key){ return ListTile( leading: const Icon(Icons.stay_primary_portrait), title: Text('$key'), subtitle: Text('${data['$key']}'), trailing: Icon(Icons.more_vert), dense: true, isThreeLine: true, ); } ```
38,056,899
I'm not able to run simple JMH benchmark inside eclipse. Maven dependencies: ``` <dependency> <groupId>org.openjdk.jmh</groupId> <artifactId>jmh-core</artifactId> <version>1.12</version> </dependency> <dependency> <groupId>org.openjdk.jmh</groupId> <artifactId>jmh-generator-annprocess</artifactId> <version>1.12</version> </dependency> ``` **Java code:** ``` public class BTest { @Benchmark public void test() { // todo } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder() .include(BTest.class.getSimpleName()) .build(); new Runner(opt).run(); } } ``` **Result of run:** > > Exception in thread "main" java.lang.RuntimeException: ERROR: Unable > to find the resource: /META-INF/BenchmarkList at > org.openjdk.jmh.runner.AbstractResourceReader.getReaders(AbstractResourceReader.java:96) > at org.openjdk.jmh.runner.BenchmarkList.find(BenchmarkList.java:104) > at org.openjdk.jmh.runner.Runner.internalRun(Runner.java:256) at > org.openjdk.jmh.runner.Runner.run(Runner.java:206) at > com.test.BTest.main(BTest.java:24) > > > Maybe the problem is, that I'm running it from eclipse.
2016/06/27
[ "https://Stackoverflow.com/questions/38056899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6381145/" ]
pom.xml must have the below dependencies and configurations to Java Micro-benchmark Harness (JMH) Framework ``` <properties> <jmh.version>1.21</jmh.version> </properties> <dependencies> <dependency> <groupId>org.openjdk.jmh</groupId> <artifactId>jmh-core</artifactId> <version>${jmh.version}</version> </dependency> <dependency> <groupId>org.openjdk.jmh</groupId> <artifactId>jmh-generator-annprocess</artifactId> <version>${jmh.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>java-jmh</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <annotationProcessorPaths> <path> <groupId>org.openjdk.jmh</groupId> <artifactId>jmh-generator-annprocess</artifactId> <version>${jmh.version}</version> </path> </annotationProcessorPaths> </configuration> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <executions> <execution> <id>run-benchmarks</id> <phase>integration-test</phase> <goals> <goal>exec</goal> </goals> <configuration> <classpathScope>test</classpathScope> <executable>java</executable> <arguments> <argument>-classpath</argument> <classpath /> <argument>org.openjdk.jmh.Main</argument> <argument>.*</argument> </arguments> </configuration> </execution> </executions> </plugin> </plugins> ``` After this go to command line and run the command $mvn clean install
Add version as well. This works for me ``` <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.0.0</version> ```
2,585,092
Thinking about this [question on testing string rotation](https://stackoverflow.com/questions/2553522/interview-question-check-if-one-string-is-a-rotation-of-other-string), I wondered: Is there was such thing as a circular/cyclic hash function? E.g. ``` h(abcdef) = h(bcdefa) = h(cdefab) etc ``` Uses for this include scalable algorithms which can check *n* strings against each other to see where some are rotations of others. I suppose the essence of the hash is to extract information which is order-specific but not position-specific. Maybe something that finds a deterministic 'first position', rotates to it and hashes the result? It all seems plausible, but slightly beyond my grasp at the moment; it must be out there already...
2010/04/06
[ "https://Stackoverflow.com/questions/2585092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36537/" ]
Here's an implementation using Linq ``` public string ToCanonicalOrder(string input) { char first = input.OrderBy(x => x).First(); string doubledForRotation = input + input; string canonicalOrder = (-1) .GenerateFrom(x => doubledForRotation.IndexOf(first, x + 1)) .Skip(1) // the -1 .TakeWhile(x => x < input.Length) .Select(x => doubledForRotation.Substring(x, input.Length)) .OrderBy(x => x) .First(); return canonicalOrder; } ``` assuming generic generator extension method: ``` public static class TExtensions { public static IEnumerable<T> GenerateFrom<T>(this T initial, Func<T, T> next) { var current = initial; while (true) { yield return current; current = next(current); } } } ``` sample usage: ``` var sequences = new[] { "abcdef", "bcdefa", "cdefab", "defabc", "efabcd", "fabcde", "abaac", "cabcab" }; foreach (string sequence in sequences) { Console.WriteLine(ToCanonicalOrder(sequence)); } ``` output: ``` abcdef abcdef abcdef abcdef abcdef abcdef aacab abcabc ``` then call .GetHashCode() on the result if necessary. sample usage if ToCanonicalOrder() is converted to an extension method: ``` sequence.ToCanonicalOrder().GetHashCode(); ```
I did something like this for a project in college. There were 2 approaches I used to try to optimize a Travelling-Salesman problem. I think if the elements are NOT guaranteed to be unique, the second solution would take a bit more checking, but the first one should work. If you can represent the string as a matrix of associations so abcdef would look like ``` a b c d e f a x b x c x d x e x f x ``` But so would any combination of those associations. It would be trivial to compare those matrices. --- Another quicker trick would be to rotate the string so that the "first" letter is first. Then if you have the same starting point, the same strings will be identical. Here is some Ruby code: ``` def normalize_string(string) myarray = string.split(//) # split into an array index = myarray.index(myarray.min) # find the index of the minimum element index.times do myarray.push(myarray.shift) # move stuff from the front to the back end return myarray.join end p normalize_string('abcdef').eql?normalize_string('defabc') # should return true ```
8,530,275
Senario I have an object Keyword -> It has a name and a Value (string) A keyword cannot contain itsSelf... but can contain other keywords example `K1 = "%K2% %K3% %K4%"` where K2,K3,K4 are keywords..... Just Relpacing them with their values works but here a catch that i am facing Examlple : `K3= "%K2%"` `K2= "%K4%"` `K4="%K2%"` Now if i start replacing there will a infinite loop as K2 gives K4 and Vice Versa... I wish to avoid such problem But it is required that i allow the uesr to nest other keyword... how could i check "While adding if the DeadLock Occur" i will display invalid... Should i use a HashTable or what... `Some Code Direction would be nice...`
2011/12/16
[ "https://Stackoverflow.com/questions/8530275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/756987/" ]
From your comment: > > I want to be able to take a Context Free Grammar and run an analyzer on it that determines if there is **any** "infinite cycle". > > > That is easily done. First off, let's clearly define a "context free grammar". A CFG is a substitution system which has "terminal" and "non-terminal" symbols. Terminals are things which are "done"; non-terminals are replaced with a sequence of terminal and non-terminal symbols. In my examples, non-terminals will be in UPPERCASE and terminals will be in lowercase. Substitution rules will be written as "NONTERMINAL : substituted symbols". So an example of a CFG is: ``` SENTENCE : SUBJECT VERB OBJECT SUBJECT : ARTICLE NOUN ARTICLE : a ARTICLE : the NOUN : can NOUN : man VERB : saw VERB : kicked OBJECT : ARTICLE NOUN ``` So if we start with SENTENCE then we can make substitutions: ``` SENTENCE SUBJECT VERB OBJECT ARTICLE NOUN VERB OBJECT the NOUN VERB OBJECT the man VERB OBJECT the man kicked OBJECT the man kicked ARTICLE NOUN the man kicked the NOUN the man kicked the can ``` and we have no more non-terminals, so we're done. CFGs can have cycles: ``` EQUATION : TERM = TERM TERM : 1 TERM : ADDITION ADDITION : TERM + TERM ``` And now we do productions: ``` EQUATION TERM = TERM 1 = TERM 1 = ADDITION 1 = TERM + TERM 1 = 1 + TERM 1 = 1 + 1 ``` This one can eventually stop but it can go forever also. Of course you can define CFGs that *must* go forever; if there had been no production "TERM : 1" then this one would go forever without finding a valid sequence of only terminals. So how do you determine if there are *any* productions that can run forever? What you do is make a *directed graph* data structure. Make all the non-terminals into *nodes* in the graph. Then add an edge for every production rule that has a non-terminal on the right-hand side. So for our first example, we'd have the graph: ``` SENTENCE -----> SUBJECT | | | | | | | | v | | | VERB | | | v v | OBJECT--->ARTICLE | \ v ---------->NOUN ``` In the second example we'd have the graph: ``` EQUATION --> TERM ---> ADDITION <-----/ ``` If the graph contains a cycle *that is reachable from the start symbol* then the grammar contains productions which can be expanded forever. If it does not, then it cannot. So now all you have to do is build a cycle detector, and that's an easy problem in graph analysis. If there are no cycles, or if the only cycles are not reachable from the start symbol, then the grammar is good.
Each time you're going to replace a keyword, add it to a collection. If, at some point, that collection contains the keyword more than one time, it is recursive. Then you can throw an exception or just skip it.
2,451,757
We know that the definition of a limit is: $\forall \epsilon > 0 \space \exists\delta>0, 0<|x-c|<\delta \to |f(x) - L| < \epsilon$ From my understanding, this means that the closer $x$ gets to $c$, then the closer $f(x)$ gets to $L$. However, since $x$ is never actually at $c$, then isn't it impossible for $f(x) = L$? If so, then why don't write $0<|x-c|<\delta \to 0<|f(x) - L| < \epsilon$ since it $f(x)$ can never equal $L$?
2017/09/30
[ "https://math.stackexchange.com/questions/2451757", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
It is possible for $f(x)$ to be $L$, even if $x\neq c$. Maybe $f$ takes the value $L$ at another point than $c$. This happens for instance for all constant functions.
Is such an example what you are after: If $f(x) = 1$, then $f(x) = f(1)$ for all $x \neq 1$.
322,341
The System process running on my Windows 7 installation uses almost 50% of CPU arbitrarily. I monitor the process with Process Explorer from [Sysinternals](http://www.sysinternals.com). *Click the images to enlarge them...* [![System Process eating CPU](https://i.stack.imgur.com/NdDKA.jpg)](https://i.stack.imgur.com/NdDKA.jpg) [![enter image description here](https://i.stack.imgur.com/9t6aY.jpg)](https://i.stack.imgur.com/9t6aY.jpg) What could be the problem?
2011/08/12
[ "https://superuser.com/questions/322341", "https://superuser.com", "https://superuser.com/users/93931/" ]
In my situation it was cpu fan speed that was somehow slower than usual. For some reason or another, the fan was slow, after 5 years of perfect operation, its settings got corrupt or whatever. So cpu got hot, so system was protecting things with this "high cpu usage in system process" trick. That is a trick to reduce core temperature. In process explorer, system was ~40%, interrupts were 5-10%, dpc's were 5-10%. These were some suggested solutions. * restored the system, it did not help. * scanned for viruses, nothing. * re-installed graphics driver, nothing. * plugged out all usb devices to see if they were doing this, nothing. * deleted the pio entries in device manager > ide/ ata/atapi controllers, nothing. All these with ample restarts. The solution was, turning the fan full on, instead of the automatic speed change. Possibly something went wrong with the automatic fan speed settings. Bios > somehow reach fan and cpu temperature related sections > check cpu temperature. If 90C, you have it. The fan speed was 1500rpm, which was slower than what I could remember, 2500rpm. Also, there was no fan noise, normally I would hear a lot of fan noise if the cpu was hot. In the related section of bios, turn the fan full on, and save bios settings. Fan should turn on full after restart of bios. And process explorer should again show 100% idle :) Hope this helps.
To diag the CPU usage issues, you should use Event Tracing for Windows (ETW) to capture CPU Sampling data / Profile. To capture the data, [install the Windows Performance Toolkit](http://social.technet.microsoft.com/wiki/contents/articles/4847.install-the-windows-performance-toolkit-wpt.aspx), which is part of the [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk). [![enter image description here](https://i.stack.imgur.com/yYJsp.png)](https://i.stack.imgur.com/yYJsp.png) Now run `WPRUI.exe`, select `First Level`, under Resource select **CPU usage** and click on **start**. [![enter image description here](https://i.stack.imgur.com/1vXVx.png)](https://i.stack.imgur.com/1vXVx.png) Now capture 1 minute of the CPU usage. After 1 minute click on **Save**. Now [analyze the generated ETL file with the Windows Performance Analyzer](https://channel9.msdn.com/Shows/Defrag-Tools/Defrag-Tools-42-WPT-CPU-Analysis) by drag & drop the `CPU Usage (sampled)` graph to the `analysis pane` and order the colums like you see in the picture: [![enter image description here](https://i.stack.imgur.com/57XUp.png)](https://i.stack.imgur.com/57XUp.png) Inside WPA, [load the debug symbols](https://msdn.microsoft.com/en-us/library/windows/hardware/hh448108.aspx) and expand Stack of the SYSTEM process. In this demo, the CPU usage comes from the nVIDIA driver.
4,053
We are currently getting some new [survey marks](http://en.wikipedia.org/wiki/Survey_marker) established in the main town of our shire, we have been told that there are different orders based on accuracy: 1st, 2nd and 3rd both for horizontal and vertical. In the main town we already have a few good 1st order horizontal but very few 1st order vertical marks, and we where told that they would just shoot from these marks to make the new ones. My question is: How do they establish a 1st, 2nd or 3rd order mark in a town that doesn't already have a good mark to use; and how do you know it's right? *I know this might not be directly GIS related but to me surveying is important to GIS.*
2010/12/01
[ "https://gis.stackexchange.com/questions/4053", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/97/" ]
In order to establish a mark of a particular order, you have to design the survey so that it meets all the Class and Order requirements (listed in the standards) AND meet the error requirements, which vary depending on the method used (differential or GPS/Trigonometric). The actual position/elevation measurement is fairly trivial, the requirements are designed such that if you meet them, you should meet the closure requirements. Australia has a very well-developed set of [national surveying standards](http://www.icsm.gov.au/icsm/publications/index.html#surveying_sp1), due in part to its history, and land registration system. Surveyors use existing control points to establish the position/elevation of the new control point. For vertical control, depending on the Class/Order requirements, survey or geodetic-grade GPS or more rarely, [differential leveling](http://www.ngs.noaa.gov/heightmod/Leveling/leveling_index.html) is used. High-accuracy GPS surveys involve collections on multiple known points and the new unknown point simultaneously, and the data is then post-processed together to remove systematic error from things like atmospheric effects. With leveling, you measure the difference in heights between your known points and the unknown point, Level runs start and end on known points, so the error can be quantified very accurately if good techniques are used. This is very labor intensive and requires lots of time and trained personnel, especially if the new point is very far from the known control points. Generally, the further away the known control points are from new mark, the more work is required for good accuracy, but it is still possible. Systems like [OPUS](http://www.ngs.noaa.gov/OPUS/about.html#discussion) can generate very good results with fairly long baselines and longer collection times. As for how you can be sure a mark is "right", all (good) survey measurements include a method of quantifying the error and uncertainty. So a mark is considered "right" if its error and uncertainty fall within the accepted standards.
The more points in the 'survey control' the more accurate the data. Can be denoted as: ``` First order: f = +/- 0.02(sqrt(M)) Second order: f = +/- .035(sqrt(M)) Third order: f = +/- .05(sqrt(M)) ``` These reflect the closure between established control where f is the maximum misclosure in feet and M is the distance in miles Standard Survey practice <http://www.dot.ca.gov/hq/row/landsurveys/SurveysManual/Land_Surveys_Interim_Guidelines.pdf>
24,984
Making a single pancake **in a microwave** is easy: just take a Tefal round pan (no sharp corner no sparks), drop your dough, wait 2.5 minutes (it also work on any eating plates, but the first one is quite hard to unstick). But it's not really efficient in terms of time and energy. There should be a way to make several pancakes at once, and (optional) maybe even while using the same energy, or just a little more. Using several layers of Tefal cooking plates won't be efficient since the microwaves don't pass through the metal. So there are 2 challenges to solve: 1. Finding the right material to cook the crepe: it must be 1) food-safe (also under microwaves: so no plastic to be sure) 2) transparent to microwaves (or low loss). (What about using a thin sheet of glass? Cheap and safe.) 2. Finding the best vertical structure: what shape, how tall, how many layers? (Knowing that it should be rechargeable with dough quickly and also disassembled to clean it) It's an engineering challenge, but that's the kind of hack that could really be a turning point for humankind. Any advice is welcome. PS: once again **the question is about cooking pancakes IN MICROWAVE** **EDIT: the question was suddenly closed** (after some weeks/upvotes, and several answers) just when I dared to tell the people that their answer is off-topic. (I said to @virolino `what does it have to do with microwave cooking?` he replied `I do not like the tone of your question-comment`. **If you also believe it was unjustifiably closed, please signal it** (eg. upvote my last comment).
2021/08/06
[ "https://lifehacks.stackexchange.com/questions/24984", "https://lifehacks.stackexchange.com", "https://lifehacks.stackexchange.com/users/9915/" ]
**What is the special liquid for cleaning the peeing liquid on the floor?** Generally speaking any anti-bacterial solution or soap will do to clean the area affected. However, if the smell persists I would recommend using the product: [**Fresh-Aire Deodorant Concentrate**](https://www.amazon.ca/12015627-RMC-Fresh-Aire-Deodorant-Concentrate/dp/B015G8KM6W). [![RMC Fresh-Aire Deodorant Concentrate](https://i.stack.imgur.com/cMKn1.jpg)](https://i.stack.imgur.com/cMKn1.jpg) I work as a supervisor in housekeeping at a mall and this is the very product we use to get odours out. Use a spray bottle to get maximum effect. It is great on urine and many or types of bad smells. In order to avoid bad aiming, simply sit on the toilet when peeing, at least when at home!
I have no idea how well they work on human urine but any major pet store will have products to remove pet odors and stains from cat and dog urine. They have various enzymes to break down the odor causing elements.
5,652,570
I have written a following code (see code comments for the question), ``` #include<stdio.h> int main() { int size; scanf("%d",&size); int arr[size]; /*is it a valid statement?*/ for(int i=1;i<=size;i++) { scanf("%d",&arr[i]); printf("%d",arr[i]); } return 0; } ```
2011/04/13
[ "https://Stackoverflow.com/questions/5652570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681929/" ]
The use of a non constant array size is valid C99 but not C90. There is an older gcc extension allowing it. Note that taking advantage of this make it harder to check that memory allocation succeed. Using it with values provided by the user is probably not wise.
The compiler tries to evaluate `int arr[size]` at compile time. In this case, arr is allocated on the stack, so the compiler wants to know its size ahead of time. Instead, you need to allocate arr on the heap using `malloc`, like this. ``` #include<stdio.h> int main() { int size; scanf("%d",&size); int *arr = malloc(sizeof(int) * size); for(int i=1;i<=size;i++) { scanf("%d",&arr[i]); printf("%d",arr[i]); } free(arr); return 0; } ``` See [this post](https://stackoverflow.com/questions/4836516/c-best-practices-stack-vs-heap-allocation) for more information on when to use `malloc`
45,984,737
Does anyone know if it's possible to capture the variables from an Adobe Analytics implementation and pass them to GTM so that they can be used as custom dimensions in Google Analytics? I was wondering if there was some javascript that i could implement in GTM that would extract the neccessary props i want from the adobe data layer, but im not a developer so im not even sure if this is possible. Thank you!
2017/08/31
[ "https://Stackoverflow.com/questions/45984737", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8543980/" ]
``` UPDATE my_table SET [Col 1] = CASE WHEN [Flag] = 0 THEN [Col 1] ELSE 0 END, [Col 2] = CASE WHEN [Flag] = 1 THEN [Col 2] ELSE 0 END , [Col 3] = CASE WHEN [Flag] = 1 THEN [Col 3] ELSE 0 END ```
Assuming that `Flag` only has values `0` or `1`: ``` update ThyTable set Col1 = Col1 * ( 1 - Flag ), Col2 = Col2 * Flag, Col3 = Col3 * Flag ```
30,031,952
I've been working as a Java developer for just short of a year now and am gradually trying to increase my knowledge to speed up development times. One of the habits I find myself doing is forcing an occasional *clean* without really knowing if I need it. I get that if you use it, your project will be completely re-built, however I don't fully understand under what circumstances I would want to use it. If I understand correctly, most, if not all, changes to a project will be built automatically, so with that there should only be a rare occasion that I would actually need to use a project clean.
2015/05/04
[ "https://Stackoverflow.com/questions/30031952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768351/" ]
Clean is useful if some external tool modifies your output folder. For example, you are using Eclipse, but occasinally compile via command line compiler into the same folder. In this case Eclipse may fail to do incremental build and display errors in code when they are actually absent. Another case is working around some bug in Eclipse compiler itself. In very rare cases and in specific Eclipse versions/updates some classes which are necessary to be recompiled after specific code changes might be overlooked by compiler. If you were (un)happy enough to encounter such case, clean will help you.
It is for example useful if you delete a class, and then you forget to remove a reference to it in another class. If you do not clean the project, your local copy will still work, but what you actually did is that you just broke the build. ;) Your local copy of the project will still work because the .class of the deleted class will still be there. To find out problems like this, is usually a good thing to compile the project from scratch on the integration system.
223,328
Carl Barks created the Duckverse. Don Rosa created "The Life and Time of Uncle Scrooge". Generally, all comics by those two artists are considered canon. Apart from those two artists, which other artists (or stories) are considered Duck canon?
2019/11/20
[ "https://scifi.stackexchange.com/questions/223328", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/89771/" ]
It depends highly on what you consider canon. There are numerous Donald Duck stories published in Europe, mostly by Italian and Spanish artists, now under the auspices of Danish publishing house Egmont. Being official, licensed productions, they can be considered canon. [This site](https://www.lambiek.net/comics/disneyartists.htm) has a list of all Disney comic book artists, but doesn't distinguish between Donald Duck, Mickey Mouse, and other characters. A lot of characters that are now considered canon were created by artists other than Barks and Rosa. Dick Kinney and Al Hubbard created Donald's cousin [Fethry Duck](https://en.wikipedia.org/wiki/Fethry_Duck), while [Moby Duck](https://en.wikipedia.org/wiki/Duck_family_(Disney)#Moby_Duck) was created by Vic Lockman and [Tony Strobl](https://art-bin.com/art/strobleng.html) (who drew quite a lot of US Donald Duck stories. [Al Taliaferro](https://en.wikipedia.org/wiki/Al_Taliaferro), with writer Bob Karp, did the Donald Duck newspaper strip from 1938 to 1968 and Sunday pages from 1939 to 1969. The strips introduced in comic form (both had appeared in cartoons) Donald's cousin Gus and love interest Daisy Duck, as well as Grandma Duck, all of which must be considered canon. Taliaferro also created Donald's iconic car. Much of this happened before Carl Barks began on the comic book in 1943, and Barks used many of Taliaferro's characters. If you consider Barks canon, you hence must also consider Taliaferro canon. A popular superheroic version of Donald Duck, [Paperinik or Duck Avenger](https://en.wikipedia.org/wiki/Donald_Duck_in_comics#Paperinik_(Duck_Avenger)), was created by Italians Guido Martina and Giovan Battista Carpi. One of the most productive Duck-artist was Victor "Vicar" Arriagada Rios, (deceased 2012). He had his own studio where he and his assistants drew the stories sent in by Egmont. Some fans don't consider any post-Barks stories canon except those by Rosa (and some even don't count these), while others consider all licensed stories canon. It depends on a matter of taste; I doubt that Disney has any official opinion on the matter. [Wikipedia](https://en.wikipedia.org/wiki/Donald_Duck_in_comics) has more detail about the development of Donald Duck comics.
It depends on how you view the DuckVerse and continuity. First, you have to understand that each version of the Duck world is its own continuity. That’s a undisputed fact. There are many minor and major differences between each incarnation of this world. However, you can have your own headcanon, which is what you, the viewer, see as canonical. Let’s take me for example. Carl Barks created several characters and locations that are essential to the Ducks, so I consider his stories canon. Ducktales (the 1987 version), despite its own creative liberties from the source material, syncs up well with Barks’ version of Duckburg, so I consider that canon. I believe that the Life and Times of Scrooge McDuck is the canonical biography of Scrooge in all canons to some extent. Don Rosa’s goal with his stories is to be as in-sync with Barks as possible, so they are canon. For a headcanon to work, you need to find ways to “reconcile” elements that don’t mesh with each other. For example, I consider Ducktales and Don Rosa’s stories to be split timelines branching from Barks’ stories, stemming from Donald’s decision to go to the navy. Unfortunately, there are certain continuities that you can’t reconcile. Case-in-point: Ducktales 2017. That canon is too different from the others to be properly fitted into the larger canon, so it’s a different timeline from everything else. Now you know, and knowing is half the battle!
819,514
Say I have 1280x720 pixels on my screen and the current resolution is set to 1280x720 as well. What are the differences between the 1080p version and the 720p version of the same media? Is it noticeable to an end user (a non-video expert or enthusiast)? **Clarification Edit**: The question was in regard to .mkv files rather than YouTube videos.
2014/10/01
[ "https://superuser.com/questions/819514", "https://superuser.com", "https://superuser.com/users/279815/" ]
The result depends on the resizing algorithm. But the default algorithm in most situations will produce a sharper image. So a 1080p video may look better on a 720p screen, provided that the 720p is the original version and was not scaled down from 1080p or a higher resolution Scaling down has another advantage that some algorithms may use [subpixel rendering](https://en.wikipedia.org/wiki/Subpixel_rendering) which increases the effective resolution a bit --- In fact scaling up then downs is how may antialiasing algorithms work, and also how fractional dpi scaling works in many OSes like iOS or macOS. For example on a screen at 150% dpi the interface will be rendered at 3 times the physical resolution, and then it'll be scaled down to a half the scaled up version, resulting in a 3/2 scaling ratio * To have an effective resolution of 1920×1200 macOS renders the screen at 3840x2400 then scale down to the real resolution of the screen 2880×1800 * The plus version of iPhone 6-8 uses 300% dpi, so the interface is rendered at 1242×2208 then down sampling to 1920×1080 Further reading: * [Oversampling, or scaling down](https://lwn.net/Articles/619995/) * [The Ultimate Guide To iPhone Resolutions](https://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions) * [Fractional scaling on Linux Xorg](https://ricostacruz.com/til/fractional-scaling-on-xorg-linux) * [The Curious Case of iPhone 6+ 1080p Display](https://medium.com/we-are-appcepted/the-curious-case-of-iphone-6-1080p-display-b33dac5bbcb6)
Personally I think that 1080 and 720 thing was a screwup in multiple ways. First, 1920x1080 is a 16:9 aspect ratio. Why not make it 2048\*1024 so that is a perfect 2:1 aspect ratio and cuz it is well known that computers love powers of 2? For smaller TVs such as 21" or even smaller, they could just toss away every other pixel in the 2048x1024 signal, thus making an effective 1024x512 resolution which is plenty for a small TV like on a kitchen counter. I also hate that frames with a lot of motion tend to be very blurried as that is not HD. Real HD would have freeze frames of motion shots just as sharp as non motion frames but they are not even close in quality. But to answer your original question, it depends on many factors. Using still images as a basis for moving images, there are competing factors: starting with higher resolution and then resizing down usually yields a better quality image as noise (such as in a blue sky) is cleaned up. The quality is especially good if the downsized image is an exact 50% resolution drop in each dimension. So for example if we took a 2048x1536 still image (3MP) and downsized it to 1024x768 (3/4 MP). The other competing factor is the more stages of processing (in an attempt to save storage space of the image), usually the worse the image quality gets. For example, a JPG originally in 2048x1536 in a camera will have artifacts then when resized down and resaved as a smaller JPG, more artifacts will be introduced.
129,393
Let $S$ be an orientable compact surface. A homeomorphism $f: S \to S$ induces an isomorphism $f\_{\*}: H\_1(S) \to H\_1(S)$. How much can we say the converse? Namely, if we are given an element of $\alpha \in$ $\operatorname{Aut}(H\_1(S))$, is there a self-homeomorphism $f$ of $S$ (unique up to isotopy or something) such that $f\_\*=\alpha$?
2012/04/08
[ "https://math.stackexchange.com/questions/129393", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
The set of self-homeomorphisms of a surface up to isotopy is called the mapping class group of the surface. For genus one, this is determined by the action on homology, but for higher genus there is a very large and interesting subgroup of the mapping class group, called the Torelli group, which consists of self-homeomorphisms inducing the trivial map on homology.
Here's an example without the assumption that $S$ is a surface: Let $S = S^1 \vee A$ where $A$ is a closed annulus. Then $H\_1(S) = \mathbb Z \oplus \mathbb Z$. Take the isomorphism $\varphi: (a,b) \mapsto (b,a)$. A homeomorphism $f$ inducing $\varphi$ would have to map $x$ in $S^1$ to $f(x) \in A$. But $S^1$ and $A$ are not homeomorphic.
13,510,504
I'm learning multi-threading in C# and I saw a code below ``` static readonly object _locker = new object(); static void Main() { lock (_locker) { AnotherMethod(); // ...some work is going on } } static void AnotherMethod() { lock (_locker) { Console.WriteLine ("Another method"); } } ``` I wonder when does it require to use nested locking? Why don't use only one lock in this case?
2012/11/22
[ "https://Stackoverflow.com/questions/13510504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468345/" ]
My first response would be that AnotherMethod can be called directly, not going through the Main method, so therefor you might need nested locking.
To allow [re-entrant](https://stackoverflow.com/questions/391913/re-entrant-locks-in-c-sharp) code. Your example is not appropriate. Locks are used to provide controlled access to [critical section](http://en.wikipedia.org/wiki/Critical_section). If one critical section invokes another critical section, then deadlock would occur. To prevent this, re-entrant code is allowed. [Why do nested locks not cause a deadlock?](https://stackoverflow.com/a/5035177/649524)
37,366,664
I'm trying to run some PhpUnit tests and it's working great but I keep running into the following problem. When I write a Unittest and it fails for whatever reason I'm getting the following error message (I'm also getting a unclear message why the test failed): `1) testUser_ReadOnly::testLoginFunction PHP Warning: require_once(../classes/PHP_Invoker.php): failed to open stream: No such file or directory in C:\xampp\htdocs\map\src\tests\autoload.php on line 6` Now I found a sollution on the internet that just says I have to add the following line to my composer.json: `"phpunit/php-invoker": "1.1.*"` When I then try to run the composer update function I'm getting the following error messages: ``` Problem 1 - phpunit/php-invoker 1.1.4 requires ext-pcntl * -> the requested PHP extension pcntl is missing from your system. - phpunit/php-invoker 1.1.3 requires ext-pcntl * -> the requested PHP extension pcntl is missing from your system. - phpunit/php-invoker 1.1.2 requires ext-pcntl * -> the requested PHP extension pcntl is missing from your system. - phpunit/php-invoker 1.1.1 requires ext-pcntl * -> the requested PHP extension pcntl is missing from your system. - Installation request for phpunit/php-invoker 1.1.* -> satisfiable by phpunit/php-invoker[1.1.1, 1.1.2, 1.1.3, 1.1.4]. ``` Is there anybody who has a sollution for this problem? Any help is appreciated! Thanks in advance!
2016/05/21
[ "https://Stackoverflow.com/questions/37366664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5763101/" ]
Allright, I found the sollution to this problem. It was not clear for me when I started with phpUnit I had to run the commands from the Xampp shell instead of the windows commandline. You can find this by opening the Xampp control panel and click the 'shell button'. Since I execute the phpUnit commands here, I never had these problems again. So when you get the same errors as I posted in the question about, try to execute the PHPUnit commands within the Xampp shell.
The error message is indeed not very clear on first sight, but that already is the solution to the problem: Your setup is incompatible with PHPUnit, the autoloader you have configured in file `C:\xampp\htdocs\map\src\tests\autoload.php` brings the testsuite to halt. As often with configuration problems they are hard to grasp until finally solved. Then they appear quite easy. Just inspect the file in question and fire-up the test-suite with a step-debugger (e.g. [xdebug](http://xdebug.org/)) placing a breakpoint at the line in question. You should be able to quickly find the culprit and most likely immediately spot the causing issue.
44,153,497
I did some research and couldn't find any solution and hence posting it here. We have a dataload job which runs on a daily basis. We have separate DML statements to insert, update etc. We wanted to avoid insert statements to run multiple times. Is there an option to use merge statement in this scenario to update if the record is present or insert if not present? Please give me an example if possible as I am quite new to sql statements. We are using Oracle db2 for dbms Thanks in advance!
2017/05/24
[ "https://Stackoverflow.com/questions/44153497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/803449/" ]
Try this ``` select date_format(created_at,'%Y') as Year, sum(case when date_format(created_at,'%m')='01' then 1 else 0 end) as val01, sum(case when date_format(created_at,'%m')='02' then 1 else 0 end) as val02, sum(case when date_format(created_at,'%m')='03' then 1 else 0 end) as val03, sum(case when date_format(created_at,'%m')='04' then 1 else 0 end) as val04, sum(case when date_format(created_at,'%m')='05' then 1 else 0 end) as val05, sum(case when date_format(created_at,'%m')='06' then 1 else 0 end) as val06, sum(case when date_format(created_at,'%m')='07' then 1 else 0 end) as val07, sum(case when date_format(created_at,'%m')='08' then 1 else 0 end) as val08, sum(case when date_format(created_at,'%m')='09' then 1 else 0 end) as val09, sum(case when date_format(created_at,'%m')='10' then 1 else 0 end) as val10, sum(case when date_format(created_at,'%m')='11' then 1 else 0 end) as val11, sum(case when date_format(created_at,'%m')='12' then 1 else 0 end) as val12, count(*) as total from reservations group by date_format(created_at,'%Y') ```
If this had been Oracle, you could have used Function based index on column Created\_at and using the same function (EXTRACT in this case) in your query: ``` CREATE INDEX IDX1 ON RESERVATIONS (EXTRACT(YEAR FROM CREATED_AT)) ``` Since, this is MySQL, try using [this](http://mysqlserverteam.com/generated-columns-in-mysql-5-7-5/) as alternative. Make sure after creating the index, it is getting used by verifying the Query plan.
56,151,300
I make a call to a REST-API and get a list of persons in JSON format. How do I just refer to one specific Object e.g. "Adam"? I make the call via Node.js and would like to pass the Javascript object to another function. I use: ``` request('rest-api-URL', function (error, response, body) { if (!error && response.statusCode == 200) { console.log(response.body); // Prints the JSON object var object = JSON.parse(body); console.log(Object.keys(name)[0]); } ``` Maybe my problem is that I can not express my question clearly (and do not find any information) This is the JSON: ``` "persons": [ { "name": "Adam", "age": "20", }, { "name": "Bob", "age": "21", }, { "name": "Christy", "age": "22", } ] } ```
2019/05/15
[ "https://Stackoverflow.com/questions/56151300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5122411/" ]
Styling for `IFrame` should be within the `IFrame` itself. Note that the `Sticky` rule will apply WITHIN the `IFrame` ```html <!DOCTYPE html> <html> <body> <style> iframe { height:200px; border: 0; } </style> <p>Your Page with Some Content...</p> <iframe srcdoc="<!DOCTYPE html><html><body><div id='accessBar'>AccessBar</div>Long Document Ahead:<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>End of Long Document<style>html, body{ min-height:100%;position:relative} #accessBar { background: #e8eeff; position: -webkit-sticky; /* Safari */ position: sticky; top: 0; height: 20px; }</style></body></html>"></iframe> </body> </html> ``` P.S I have used an inline `IFrame` so i wont have to create a page somewhere to host it.
Position:sticky does appear to work if you have a scrollable iframe: <iframe scrolling="yes"... The content is sticky in relation to the iframe's scroll bars, not the host page's. The height of the iframe content must overflow (be larger than) the specified iframe height.
223,885
In Fallout Shelter you're able to rush the product of a resource. According to the game, it is influenced by the luck of the people assigned to the room and whether or not you have recently rushed the room. However, as the incident rate goes down, so do the rewards for rushing. What are the underlying mechanics? I would like to maximize my rush success chances, and the possible payoffs.
2015/06/16
[ "https://gaming.stackexchange.com/questions/223885", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/107588/" ]
**Failure rate = 40 - 2 \* (Average room Luck + Average room Skill) + 10 for each successive rush (up to +50)** Use one maxed dweller in a tripple lvl 3 room and you always complete the first rush. Average room luck also increases chance to get +200 caps when picking up reasources. Source: <https://docs.google.com/spreadsheets/d/1Nai09D_aM2syl3iPP5hkveDcOUwhsoUDR6s1lwC0e8c/htmlview?pli=1&sle=true#>
I am currently gathering intel on this as well and here is what I have seen from my own observations * The incident rate seems to start at around 31% (this is with 2-4 people in the room with ok stats) * It increases every time you do a rush whether you fail or succeed by about 10% * The chance of failure also seems to decrease again once you successfully collect a resource from the room (with out having rushed it ofcourse). I have not had good luck finding lucky people to see how they impact the results, not a large variation in stats as I have just started and do not have the stat raising rooms as of yet for further exploration of this.
175,656
So, let's say long ago, somewhere along the evolutionary process, homo sapiens got fully prehensile tails that can support their weight, of about 1,5 to 2 meters long. The tail is naked, about as much hair as an arm. It also has a tactile pad at the end. The tail is not taboo and they only cover it to shield it from cold. Assuming they build their cities in tree tops, and do some constant tree swinging, how would they design this four particular things? For example: Beds as we know it would be VERY uncomfortable, unless they all slept with their belly down...and didn't move at night, and I think hammocks would have the same problem. Couches: I can't imagine one with a big hole on the back... Doors: The doors we have would cause an serious amount of pain if closed on their tails, and since they're about 1,5 - 2m long, I think a "normal door" would be banned from their society. A "doggy door" thing is the best idea I had so far, but... how would they lock it? Clothes: There can't be dresses or skirts, since, even if they have an extra sleeve for the tail, some taboo parts of the body would show if they lifted their tail too high, or used it to have a good grip on a tree branch.
2020/05/05
[ "https://worldbuilding.stackexchange.com/questions/175656", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/75533/" ]
One day you may find your soulmate. And you will wish to share a bed with that person. Very probably that person will want you to spoon with them, and at times you will be the big spoon. And when that happens you'd better be healthy and free of circulatory problems, for you will be in for the kinda of suffering your hominids would suffer on a human bed. Even if you don't spoon, simply using your own arm as a pillow should show you the amount of discomfort your creatures are in for. Spoiler alert - we live just as uncomfortably as they would. We try to circumvent it with bizarre inventions. Google "bed with hole for arm" and see. --- For sitting, your creatures would probably use things similar to the bi chair - the chair for people who can't sit straight. When you stop laughing, google it and see that the thing is real. This would provide them with ways to sit without pressing on their tail. Also I need one of those. Alternatively, they could go full ancient roman and just do things while lying down. Seriously. They ate while lying down because they thought eating with a vertical stance was bad for the stomach. [Here's the wiki for the roman *triclinium*](https://en.wikipedia.org/wiki/Triclinium), and here's an image I found in Google Images when searching for it: [![A roman triclinium being used. Those people knew how to live.](https://i.stack.imgur.com/va8tg.jpg)](https://i.stack.imgur.com/va8tg.jpg) --- Finally, to operate vehicles, rather than a seat as we humans are used to they might be more like stools, or there might be some hole for the tail. See the picture below, this is a chair from our real world. We humans use that hole to drop a coin into an unsuspecting friend's coin slot, but your tailed humanoids could use it for comfort rather than practical jokes. [![enter image description here](https://i.stack.imgur.com/bRy3V.jpg)](https://i.stack.imgur.com/bRy3V.jpg)
Doors would roll up, be counter-weighted with the knob or handle at the center bottom. Reach out between your legs with your tail as you approached the door, flip it up, go through, close door without breaking stride. Smooth.
22,410,148
I have the following html ``` <table> <tr> <td headers="Monday"> <div class="foo"> Some stuff </div> </td> <td headers="Tuesday"> <div class="foo"> Some stuff </div> </td> <td headers="Wednesday"> <div class="foo"> Some stuff </div> </td> </tr> </table> ``` How can I target the td with Monday headers and remove .foo?
2014/03/14
[ "https://Stackoverflow.com/questions/22410148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2735572/" ]
You can remove class with something like this: ``` $('td[headers="Monday"] > div').removeClass('foo'); ``` **Demo:** <http://jsfiddle.net/8qbba/>
Try this... ``` if($('.foo:contains("Monday")')){ $('table').each(function(){ var mondayHeader = $(this).find('tr.td[headers="Monday"]'); $(mondayHeader).closest('div').removeClass('foofoo'); }); } ```
577,756
I have a genealogical database (about sheep actually), that is used by breeders to research genetic information. In each record I store fatherid and motherid. In a seperate table I store complete 'roll up' information so that I can quickly tell the complete family tree of any animal without recursing thru the entire database... Recently discovered the hierarchicalID type built into SQL server 2008, on the surface it sounds promising, but I and am wondering if anyone has used it enough to know whether or not it would be appropriate in my type of app(i.e. two parents, multiple kids)? All the samples I have found/read so far deal with manager/employee type relationships where a given boss can have multiple employees, and each employee can have a single boss. The needs of my app are similar, but not quite the same. I am sure I will dig into this new technology anyway, but it would be nice to shortcut my research if someone already knew that it was not designed in such a fashion that it would allow me to make use of it. I am also curious what kind of performance people are seeing using this new data type versus other methods that do the same thing.
2009/02/23
[ "https://Stackoverflow.com/questions/577756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/53686/" ]
Assuming each sheep has one male parent and one female parent, and that no sheep can be its own parent (leading to an Ovine Temporal Paradox), then what about using two HierarchyIDs? ``` CREATE TABLE dbo.Sheep( MotherHID hierarchyid NOT NULL, FatherHID hierarchyid NOT NULL, Name int NOT NULL ) GO ALTER TABLE dbo.Sheep ADD CONSTRAINT PK_Sheep PRIMARY KEY CLUSTERED ( MotherHID, FatherHID ) GO ``` By making them a joint PK, you'd be uniquely identifying each sheep as the product of its maternal hierarchy and it's paternal hierarchy. There may be some inherent problem lurking here, so proceed cautiously with a couple simple prototypes - but initially it seems like it would work for you.
SQL Server hierarchyID is not a robust solution for many genealogy analytic questions. It is based on ORDPATH and I've used it for awhile in genealogy; but there are too many scenarios in genealogy that cannot be readily addressed with ORDPATH methods for directed acyclic graphs. A graph database is much more robust and well suited for genealogy. I use Neo4j: <http://stumpf.org/genealogy-blog/graph-databases-in-genealogy>.
9,592,736
I have an activities view that contains an array of activities. This array gets sorted sometimes based on a calculated property(distanced\_from\_home) that the user can update. When the array is sorted I want the child views to be re-rendered by according to the new order. Here is my Template and View: *index.html* ``` <script type="text/x-handlebars" data-template-name="activities"> <h1>Activities</h1> {{#each activities}} {{view App.ActivityView activityBinding="this"}} {{/each}} </script> ``` *app.js* ``` App.ActivitiesView = Em.View.extend({ templateName: 'activities', activities: (function() { var list; list = App.activityController.activities; console.log("Activities View"); console.log(list); return list; }).property('App.activityController.activities', 'App.activityController.activities.@each.distance_to_home').cacheable() }); ``` When I cause the distance\_to\_home property to change, the console.log output shows the list array is properly sorted, but the children views are not re-rendered in the new order. If I leave this view and then comeback to it (it is rendered again) then the correct order is shown. What should I do to get the view to update automatically? Thanks, *EDIT* ------ This seems to be working [here](https://stackoverflow.com/questions/8962839/sorting-a-list-in-emberjs-and-having-that-reflect-in-the-view) and my 'activities' computed function is definitely firing, but no re-ordering of the view... I also tried to use an observer, but the results are the same. ``` App.ActivitiesView = Em.View.extend({ templateName: 'activities', classNames: ['activities rounded shadow'], homeBinding: 'App.user.home', activities: [], homeChanged: (function() { console.log("homeChanged()"); this.set('activities', App.activityController.activities.sort(this.compare_activities)); return null; }).observes('home'), compare_activities: function(a, b) { var result; result = 0; if (App.user.home != null) { result = a.get('distance_to_home') - b.get('distance_to_home'); } return result; }, }); ``` I also tried to set the 'activities' parameter to an empty array and then reset it to the ordered array to force it to re-render, but this has no effect. ``` App.ActivitiesView = Em.View.extend({ templateName: 'activities', classNames: ['activities rounded shadow'], homeBinding: 'App.user.home', activities: [], homeChanged: (function() { console.log("homeChanged()"); this.set('activities', []); this.set('activities', App.activityController.activities.sort(this.compare_activities)); return null; }).observes('home'), compare_activities: function(a, b) { var result; result = 0; if (App.user.home != null) { result = a.get('distance_to_home') - b.get('distance_to_home'); } return result; }, }); ``` *EDIT (the second)* ------------------- So it seems that using Ember.copy finally solved this. Setting the array property to an empty array (or null) did not have any effect. Here's the View code that finally worked: ``` App.ActivitiesView = Em.View.extend({ templateName: 'activities', classNames: ['activities rounded shadow'], homeBinding: 'App.user.home', activities: [], homeChanged: (function() { var list; list = App.activityController.activities.sort(this.compare_activities); this.set('activities', Ember.copy(list), true); return null; }).observes('home'), compare_activities: function(a, b) { var result; result = 0; if (App.user.home != null) { result = a.get('distance_to_home') - b.get('distance_to_home'); } return result; } }); ```
2012/03/06
[ "https://Stackoverflow.com/questions/9592736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/354101/" ]
Does this help? <http://jsfiddle.net/rNzcy/> Putting together this simple example, I was a little confused why the view update didn't "just work" when sorting the content array in the ArrayController. It seems there are 2 simple things you can do to trigger the view update. Either: * Set the content array to null, sort the original content, and then set the sorted content. or * Clone the content array when sorting it, via Ember.copy() I guess Ember detects when a completely new Array object is set, and that triggers all the expected binding/view updates. Otherwise, maybe it's doing some sort of caching and if the Array object does not change (i.e. it's sorted in place) then no bindings fire? Just guessing. UPDATE: See discussion @ <https://github.com/emberjs/ember.js/issues/575#issuecomment-4397658> which has an improved workaround using propertyWillChange() and propertyDidChange() (http://jsfiddle.net/rNzcy/4/) -- should be a lot more efficient then cloning a large array.
I met the same issue. And I don't think observe `array.@each` or `array.length` is good practice. At last I found this <http://jsfiddle.net/rNzcy/4/> i.e. call `this.propertyDidChange('foo')`
29,287,742
I've just upgraded IntelliJ IDEA (ultimate) to Version 14.1 and the font used in the Project View, Menus and Dialogs seems not to be rendering correctly. I exported the same settings from my 14.0.3 version just in case, although they seem identical, but it still remained the same. I didn't do any changes to the JDK or anything, and if I run the old version the font changes back to the nice and crisp one. I am using Ubuntu 14.04. This problem does not happen on Windows 7. Under IntelliJ IDEA 14.0.3: ![IntelliJ IDEA 14.0.3](https://i.stack.imgur.com/ZSuX2.png) Under IntelliJ IDEA 14.1: ![enter image description here](https://i.stack.imgur.com/WkyjR.png) In the new one the font seems to be a bit larger (even though in both cases I they are set to Font Size 22, and I imported the settings from the previous IntelliJ IDEA installation). Notice how for example the 'g' is cut off underneath. There are also other problems where the text is misaligned on the buttons, or not fully visible in dialog boxes. Usually this doesn't happen when I upgrade. Is there some way to make the font look like before? Did something changed in this latest version and I need to do some JVM switch in the startup script or something? **Update: 5/11/2015** Just updated to IntelliJ 15, and the problem is still there. Attached new screenshot. Notice how the text is cut out at the bottom where there are letters like p and y, and the button text is offset. [![IntelliJ 15](https://i.stack.imgur.com/Zd6Qz.png)](https://i.stack.imgur.com/Zd6Qz.png)
2015/03/26
[ "https://Stackoverflow.com/questions/29287742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/340088/" ]
I am using OSX. It may not help. Double tap shift and search for 'Switch IDE boot JDK'. Try different JDKs if there are.
This might not be the answer you are looking for - but ever since I've started using tuxjdk, I haven't had problems any more with font rendering & intellij on ubuntu. Maybe give it a try?
5,683,371
I am trying to code a function that basically gets a "property" from a sentence. These are the parameters. ``` $q = "this apple is of red color"; OR $q = "this orange is of orange color"; $start = array('this apple', 'this orange'); $end = array('color', 'color'); ``` and this is the function I am trying to make: ``` function prop($q, $start, $end) { /* if $q (the sentence) starts with any of the $start and/or ends with any of the end separate to get "is of red" */ } ``` not only am I having problems with the code itself, I am also not sure how to search that if any of the array values start with (not just contains) the $q provided. Any input would be helpful. Thanks
2011/04/15
[ "https://Stackoverflow.com/questions/5683371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/325499/" ]
Something like this should work ``` function prop($q, $start, $end) { foreach ($start as $id=>$keyword) { $res = false; if ((strpos($q, $keyword) === 0) && (strrpos($q, $end[$id]) === strlen($q) - strlen($end[$id]))) { $res = trim(str_replace($end[$id], '', str_replace($keyword, '', $q))); break; } } return $res; } ``` So in your case this code ``` $q = "this orange is of orange color"; echo prop($q, $start, $end); ``` prints > > is of orange > > > and this code ``` $q = "this apple is of red color"; echo prop($q, $start, $end); ``` prints > > is of red > > > This code ``` $start = array('this apple', 'this orange', 'my dog'); $end = array('color', 'color', 'dog'); $q = "my dog is the best dog"; echo prop($q, $start, $end); ``` will return > > is the best > > >
Use `strpos` and `strrpos`. If they return 0 the string is at the very beginning/end. Not that you have to use `=== 0` (or `!== 0` for the inverse) to test since they return `false` if the string was not found and `0 == false` but `0 !== false`.
3,977,554
Recently I've been assigned a bug to fix, which from my point of view, was actually a change request. After some investigation it turned out that this bug was caused by a defect in business requirements, but it was still considered as a bug. I often see change requests being pushed forward masqueraded as bugs. I am just trying to figure out if there are any differences.
2010/10/20
[ "https://Stackoverflow.com/questions/3977554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/294915/" ]
A "bug in requirements" means there was something wrong with how the functionality was originally designed. A "change request" means that everything was defined correct, but the customer wants a piece of functionality changed/added.
It happens all the time. We as developers generally get annoyed if we get our things thrown back at us as having bugs to fix where it wasn't our fault. What to do depends on the situation and on the process. Unless you get your performance reviews damaged by those, just don't think of those much and implement those bugs/changes.
133,389
I've downloaded a game (Shank) but the bin file doesn't run. The error that is shown when I try to launch the executable is: ``` bash: ./shank-linux-120720110-1-bin: No such file or directory ```
2012/05/07
[ "https://askubuntu.com/questions/133389", "https://askubuntu.com", "https://askubuntu.com/users/53662/" ]
By installing the deb for 32 bit I realized I was missing some libraries (in addition to ia32-libs and libc6). I first solved this problem by giving this command: ``` sudo apt-get install -f ``` Then I got another error: ``` Message: SDL_GL_LoadLibrary Error: Failed loading libGL.so.1 ``` Obviously, these libraries were properly installed. Without going into details I had to link the libraries by hand. I realized then that could also an easier solution through Synaptic install the following packages: ``` libgl1-mesa-glx:i386 libgl1-mesa-dri: i386. ``` After that the next problem was the black screen while playing, which I solved by replacing the executable in /Shank/bin with this: <http://treefort.icculus.org/smb/smb-linux-mesa-hotfix-test.tar.bz2>. I hope it will be useful to someone. If you need more help or more details please feel free to contact me.
As posted in <https://askubuntu.com/a/1035037/676490> ``` sudo apt-get install lsb ``` solved the problem
14,879,903
I'm having certain items on my page. When someone hovers an item, I'd like an overlay div over that item. This is working if I'm using the function without `$(this)`, but then it's overlaying all the items. I would like to only overlay the item that I'm hovering at that moment. My code: jQuery: ``` <script> $(document).on("mouseenter", ".item" , function() { $(this).('.item-overlay').stop().fadeTo(250, 1); }); $(document).on("mouseleave", ".item" , function() { $(this).('.item-overlay').stop().fadeTo(250, 0); }); </script> ``` HTML: ``` <div class="item"> <a href="#"><img src="<?=$row['item_pic']?>" class="item-img"></a> <div class="item-overlay" style="background:#999; display: none; position:absolute; top:0px; left: 0px; width:400px; height:200px; z-index:900;">test</div> </div> ```
2013/02/14
[ "https://Stackoverflow.com/questions/14879903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1852721/" ]
This: ``` $(this).('.item-overlay') ``` is invalid, and should probably be: ``` $(this).find('.item-overlay') ``` In total: ``` <script type="text/javascript"> $(function() { $(document).on({ mouseenter: function() { $(this).find('.item-overlay').stop().fadeTo(250, 1); }, mouseleave: function() { $(this).find('.item-overlay').stop().fadeTo(250, 0); } }, '.item'); }); </script> ``` just for fun, here's a shorter version: ``` $(function() { $(this).on('mouseenter mouseleave', '.item', function(e) { $(this).find('.item-overlay')[e.type=='mouseenter'?'fadeIn':'fadeOut'](250); }); }); ```
``` $(function() { $(document).on("mouseenter", ".item" , function() { $(this).children('.item-overlay').stop().fadeTo(250, 1); }); $(document).on("mouseleave", ".item" , function() { $(this).children('.item-overlay').stop().fadeTo(250, 0); }); ``` }); needed "children"
42,577,526
Ive want to pull down a list of dates in excel to auto fill a bunch of rows eg. type 03/03/17 and then pull down the cell to auto populate the dates all the way through march. Normally this is straight forward, but in this instance im trying to get all of the workdays only and no weekend dates, how could that be done automatically without having to input all dates and remove rows where they fall on weekends ?
2017/03/03
[ "https://Stackoverflow.com/questions/42577526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1183150/" ]
Put this formula below your first date and then autofill the formula down. make sure your first date is a weekday. ``` =IF(WEEKDAY(A1+1)<>7,A1+1,A1+3) ``` How it works WEEKDAY(A11+1)<>7 if the cell above + 1 day is not Saturday then add a day A1+1 else add 3 days to the cell above A1+3. You can copy and paste as values once you have the dates you need. You can also keep it as a template and change the first date to change all the dates below as required.
The `WORKDAY(Start_date, Days [Holidays])` function returns the Monday to Friday dates based on a Start\_date, number of days and optional Holidays array of dates. Data Validation allows you to create a list of comma separated items or a named range of cells. Create a list of Public Holidays in a column and name the range `Holidays`. Enter a workday date in a cell (say G2) and in the cell below it (G3), enter this formula: `=WORKDAY(G2,1,Holidays)` Copy the formula down for about 65 rows (i.e. to cover 3 months allowing 22 workdays per month). Delete dates from the bottom of the list that are greater than your desired end date. Select the dates and name it Workdays. In the range that you want to have dropdown lists: [![Data Validation dialogue](https://i.stack.imgur.com/ZobCa.jpg)](https://i.stack.imgur.com/ZobCa.jpg)
16,122,987
I was reading about it quite a bit in the past couple of hours, and I simply cannot see any reason (**valid** reason) to call `shutdown()` on the `ExecutorService`, unless we have a humongous application that stores, dozens and dozens of different executor services that are not used for a long time. The only thing (from what I gather) the shutdown does, is doing what a normal Thread does once it's done. When the normal Thread will finish the run method of the Runnable(or Callable), it will be passed to Garbage Collection to be collected. With Executor Service the threads will simply be put on hold, they will not be ticked for the garbage collection. For that, the shutdown is needed. Ok back to my question. Is there any reason to call shutdown on `ExecutorService` very often, or even right after submitting to it some tasks? I would like to leave behind the case someone is doing it and right after that calls to `awaitTermination()` as this is validated. Once we do that, we have to recreate a new `ExecutorService` all over again, to do the same thing. Isn't the whole idea for the `ExecutorService` to reuse the threads? So why destroy the `ExecutorService` so soon? Isn't it a rational way to simply create `ExecutorService` (or couple depending on how many you need), then during the application running pass to them the tasks once they come along, and then on the application exit or some other important stages shutdown those executors? I'd like an answer from some experienced coders who do write a lot of asynchronous code using the ExecutorServices. Second side question, a bit smaller deals with the android platform. IF some of you will say that it's not the best idea to shutdown executors every time, and your program on android, could you tell me how do you handle those shutdowns (to be specific - when you execute them) when we deal with different events of the application life cycle. Because of the CommonsWare comment, I made the post neutral. I really am not interested in arguing about it to death and it seems it's leading there. I'm only interested in learning about what I asked here from experienced developers if they are willing to share their experiences. Thanks.
2013/04/20
[ "https://Stackoverflow.com/questions/16122987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905938/" ]
The `shutdown()` method does one thing: prevents clients to send more work to the executor service. This means all the existing tasks will still run to completion unless other actions are taken. This is true even for scheduled tasks, e.g., for a ScheduledExecutorService: new instances of the scheduled task won't run. It also frees up any background thread resources. This can be useful in various scenarios. Let's assume you have a console application which has an executor service running N tasks. If the user hits CTRL-C, you expect the application to terminate, possibly gracefully. What does it mean gracefully? Maybe you want your application to not be able to submit more tasks to the executor service and at the same time you want to wait for your existing N tasks to complete. You could achieve this using a shutdown hook as a last resort: ``` final ExecutorService service = ... // get it somewhere Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { System.out.println("Performing some shutdown cleanup..."); service.shutdown(); while (true) { try { System.out.println("Waiting for the service to terminate..."); if (service.awaitTermination(5, TimeUnit.SECONDS)) { break; } } catch (InterruptedException e) { } } System.out.println("Done cleaning"); } })); ``` This hook will shutdown the service, which will prevent your application to submit new tasks, and wait for all the existing tasks to complete before shutting down the JVM. The await termination will block for 5 seconds and return true if the service is shutdown. This is done in a loop so that you're sure the service will shutdown eventually. The InterruptedException gets swallowed each time. This is the best way to shutdown an executor service that gets reused all over your application. This code isn't perfect. Unless you're absolutely positive your tasks will eventually terminate, you might want to wait for a given timeout and then just exit, abandoning the running threads. In this case it would make sense to also call `shutdownNow()` after the timeout in a final attempt to interrupt the running threads (`shutdownNow()` will also give you a list of tasks waiting to run). If your tasks are designed to respond to interruption this will work fine. Another interesting scenario is when you have a ScheduledExecutorService that performs a periodic task. The only way to stop the chain of periodic tasks is to call `shutdown()`. EDIT: I'd like to add that I wouldn't recommend using a shutdown hook as shown above in the general case: it can be error-prone and should be a last resort only. Moreover, if you have many shutdown hooks registered, the order in which they will run is undefined, which might be undesirable. I'd rather have the application explicitly call `shutdown()` on `InterruptedException`.
> > Isn't the whole idea for the ExecutorService to reuse the threads? So why destroy the ExecutorService so soon? > > > Yes. You should not destroy and re-create `ExecutorService` frequently. Initialize `ExecutorService` when you require (mostly on start-up) and keep it active until you are done with it. > > Isn't it a rational way to simply create ExecutorService (or couple depending on how many you need), then during the application running pass to them the tasks once they come along, and then on the application exit or some other important stages shutdown those executors? > > > Yes. It's rational to shutdown `ExecutorService` on important stages like application exit etc. > > Second side question, a bit smaller deals with android platform. IF some of you will say that it's not best idea to shutdown executors every time, and you program on android, could you tell me how you handle those shutdowns (to be specific, when you execute them) when we deal with different events of application life cycle. > > > Assume that `ExecutorService` is shared across different Activities in your application. Each activity will be paused/resumed at different intervals of time and still you need one `ExecutorService` per your application. Instead of managing the state of `ExecutorService` in Activity life cycle methods, move ExecutorService management ( Creation/Shutdown) to your custom [Service](https://developer.android.com/reference/android/app/Service.html). Create `ExecutorService` in Service => `onCreate()` and shutdown it properly in `onDestroy()` Recommended way of shutting down `ExecutorService` : [How to properly shutdown java ExecutorService](https://stackoverflow.com/questions/36644043/how-to-properly-shutdown-java-executorservice/36644320#36644320)
13,508,147
I have a SQL which counts the number of rows. Say the result is 80. I would like to have a parameter that is user-input, to be the total. Lets say the user enters 100. How would I use the two numbers, 80 and 100, to create a pie chart that shows the data takes up 80% of the total? I cannot find a way to add custom slice in a pie chart in Crystal Report, is it even possible? Thanks!
2012/11/22
[ "https://Stackoverflow.com/questions/13508147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/883376/" ]
What you could do is: ``` private Thread tMethod1 = new Thread(runMethod1); private Thread tMethod2 = new Thread(runMethod2); private Thread tMethod3 = new Thread(runMethod3); private void runThreads(); { tMethod1.Start(); //starts method 1 tMethod2.Start(); //starts method 2 tMethod1.Join(); //waits for method 1 to finish tMethod2.Join(); //waits for method 2 to finish tMethod3.Start(); //starts method 3 tMethod3.Join(); //waits for method 3 to finish } private void runMethod1() { Method1(); } private void runMethod2() { Method2(); } private void runMethod3() { Method3(); } ``` This will run `Method1` and `Method2` simultaniously and waits for those to finish before the `Method3` is started. It's a little work around, but works.
Sounds like you have a multiple-producer-single-consumer problem, with the downloading tasks being producers and giving images to the consumer task to be compared. There is high potential for parallelism here: ``` Download task 1 \ Compare task / Download task 2 ``` You can achieve parallelism both between the first two tasks that can run in parallel as well as with the comparison task using a pipeline model. But how to implement all this? What you can do is start 3 parallel tasks, one for each of the above. Each of the two download tasks will own a blocking collection ([BlockingCollection](http://msdn.microsoft.com/en-us/library/dd267312.aspx)) and put images as they get downloaded. Assuming corresponding images (with the same product id) arrive in order, the compare task can then wait on both collections and compare the images as they arrive.
881,777
I came across the use of [Descartes' theorem](http://en.wikipedia.org/wiki/Descartes'_theorem) while solving a question.I searched it but I could only find the `theorem` but *not* any `proof`.Even `Wikipedia` also, just states the theorem!!I want to know the procedure to find the `radius` of the `Soddy Circle`?? I apologize if its duplicate and to mention it is *not* a homework.
2014/07/29
[ "https://math.stackexchange.com/questions/881777", "https://math.stackexchange.com", "https://math.stackexchange.com/users/99578/" ]
**Part I** - *Proof of Soddy-Gosset theorem (generalization of Descartes theorem)*. For any integer $d \ge 2$, consider the problem of placing $n = d + 2$ hyper-spheres touching each other in $\mathbb{R}^d$. Let $\vec{x}\_i \in \mathbb{R}^d$ and $R\_i \in \mathbb{R}$ be the center and radius for the $i^{th}$ sphere. The condition for these spheres touching each other can be expressed as: $$|\vec{x}\_i - \vec{x}\_j| = | R\_i + R\_j | \quad\text{ for }\quad 1 \le i < j \le n$$ or equivalently $$|\vec{x}\_i - \vec{x}\_j|^2 = (R\_i + R\_j)^2 - 4R\_iR\_j\delta\_{ij}\quad\text{ for }\quad 1 \le i, j \le n\tag{\*1}$$ where $\;\delta\_{ij} = \begin{cases}1,&i = j\\0,& i \ne j\end{cases}\;$ is the [Kronecker delta](http://en.wikipedia.org/wiki/Kronecker_delta). Since the $n = d+2$ points $\vec{x}\_i$ live in $\mathbb{R}^d$, the $d+1$ vectors $\vec{x}\_2 - \vec{x}\_1, \vec{x}\_3 - \vec{x}\_1, \ldots, \vec{x}\_n - \vec{x}\_1$ are linear depedent, this means we can find $n-1$ numbers $\beta\_2, \beta\_3, \ldots, \beta\_n$ not all zero such that $$\sum\_{k=2}^n \beta\_k (\vec{x}\_k - \vec{x}\_1 ) = \vec{0}$$ Let $\beta\_1 = -(\beta\_2 + \ldots + \beta\_n)$, we can rewrite this relation in a more symmetric form: $$ \sum\_{k=1}^n \beta\_k = 0 \quad\text{ and }\quad \sum\_{k=1}^n \beta\_k \vec{x}\_k = \vec{0} \quad\text{ subject to some }\;\; \beta\_k \ne 0 $$ If we fix $j$ in $(\*1)$, multiple the $i^{th}$ term by $\beta\_i$ and then sum over $i$, we get $$ \sum\_{i=1}^n\beta\_i |\vec{x}\_i|^2 = \sum\_{i=1}^n\beta\_i R\_i^2 + 2 \left( \sum\_{i=1}^n \beta\_i R\_i \right) R\_j - 4R\_j^2 \beta\_j $$ This leads to $$4R\_j^2 \beta\_j = 2 A R\_j + B \quad\text{ where }\quad\ \begin{cases} A &= \sum\limits\_{i=1}^n \beta\_i R\_i\\ B &= \sum\limits\_{i=1}^n\beta\_i ( R\_i^2 - |\vec{x}\_i|^2 ) \end{cases} \tag{\*2} $$ Divide $(\*2)$ by $R\_j$ and sum over $j$, we get $$4A = 2nA + B\sum\_{j=1}^n\frac{1}{R\_j}\quad\iff\quad A = -\frac{B}{2d}\sum\_{j=1}^n\frac{1}{R\_j}\tag{\*3}$$ A consequence of this is $B$ cannot vanish. Otherwise $B = 0 \implies A = 0$ and $(\*2)$ implies all $\beta\_j = 0$ which is clearly isn't the case. Divide $(\*2)$ by $R\_j^2$ and sum over $j$, we get $$0 = 4\sum\_{j=1}^n \beta\_j = 2A\sum\_{j=1}^n\frac{1}{R\_j} + B\sum\_{j=1}^n\frac{1}{R\_j^2}$$ Combine with $(\*3)$, the RHS becomes $$B \left( \sum\_{j=1}^n \frac{1}{R\_j^2} - \frac{1}{d}\left( \sum\_{j=1}^n\frac{1}{R\_j}\right)^2\right) = 0 \quad\iff\quad \left( \sum\_{j=1}^n\frac{1}{R\_j}\right)^2 = d\sum\_{j=1}^n \frac{1}{R\_j^2}\tag{\*4} $$ The RHS of $(\*4)$ is sometimes called Soddy-Gosset theorem. When $d = 2$, it reduces to the [Descartes four circle theorem](http://en.wikipedia.org/wiki/Descartes%27_theorem), the theorem we wish to prove: $$\left( \frac{1}{R\_1} + \frac{1}{R\_2} + \frac{1}{R\_3} + \frac{1}{R\_4} \right)^2 = 2 \left( \frac{1}{R\_1^2} + \frac{1}{R\_2^2} + \frac{1}{R\_3^2} + \frac{1}{R\_4^2} \right) $$ **Part II** - *Construction of inner/outer Soddy hyper-spheres* There is an interesting side-product of the proof in Part I. $\beta\_k$ is determined up to an overall scaling factor. If we normalize $\beta\_k$ such that $B = 4$, $(\*2)$ and $(\*3)$ together allows us to derive an explicit expression for $\beta\_j$ $$\beta\_j = \frac{1}{R\_j^2} - \left(\frac{1}{d} \sum\_{k=1}^n \frac{1}{R\_k}\right)\frac{1}{R\_j}\tag{\*5}$$ We can use this relation to construct the inner and outer Soddy hyper-spheres. Assume we already have $n-1 = d+1$ hyper-spheres touching among themselves. The inner Soddy hyper-sphere is the sphere outside all these $n-1$ spheres and yet touching all of them. Let $\vec{x}\_k$ and $r\_k$ be the center and radius for the $k^{th}$ hyper-sphere for $1 \le k < n$. Let $\vec{x}\_{in}$ and $r\_{in}$ be the center and radius of the inner Soddy hyper-sphere. If we let $$\vec{x}\_n = \vec{x}\_{in}\quad\text{ and }\quad R\_k = \begin{cases}r\_k,& 1 \le k < n\\ r\_{in},& k = n\end{cases}$$ discussions in Part I tell us $$\left( \frac{1}{r\_{in}} + \sum\_{k=1}^{n-1} \frac{1}{r\_k} \right)^2 = d \left( \frac{1}{r\_{in}^2} + \sum\_{k=1}^{n-1} \frac{1}{r\_k^2} \right)\tag{\*6a}$$ We can use this to determine $r\_{in}$. If the $n-1$ points $\vec{x}\_1, \vec{x}\_2, \ldots, \vec{x}\_{n-1}$ are in general position, i.e. they are vertices of a non-degenerate $d$-simplex, the $d$ vectors $\vec{x}\_2 - \vec{x}\_1, \ldots, \vec{x}\_{n-1} - \vec{x}\_1$ will be linearly independent. This implies there exists $d$ coefficients $\gamma\_2, \gamma\_3, \ldots, \gamma\_{n-1}$ such that $$\vec{x}\_{in} - \vec{x}\_1 = \gamma\_2 (\vec{x}\_2 - \vec{x}\_1) + \ldots + \gamma\_{n-1} ( \vec{x}\_{n-1} - \vec{x}\_1 )$$ A consequence of this is $\beta\_n \ne 0$. This means we can use $(\*5)$ and the relation $\sum\limits\_{k=1}^n \beta\_k \vec{x}\_k = \vec{0}$ to compute the center $\vec{x}\_{in}$ of the inner Soddy hyper-sphere. For the outer Soddy hyper-sphere. It is a sphere that contains the original $n-1$ spheres and touching each of them. Let $\vec{x}\_{out}$ and $r\_{out}$ be the center and radius of the outer Soddy hyper-sphere. The touching condition now takes the form: $$\begin{array}{ccccl} |\vec{x}\_{out} - \vec{x}\_j | &=& | r\_{out} - r\_j |\quad & \text{ for }\quad & 1 \le j < n\\ |\vec{x}\_i - \vec{x}\_j | &=& | r\_i + r\_j | \quad & \text{ for }\quad & 1 \le i < j < n \end{array} $$ Once again, if we let $$\vec{x}\_n = \vec{x}\_{out}\quad\text{ and }\quad R\_k = \begin{cases}r\_k,& 1 \le k < n\\ -r\_{out},& k = n\end{cases}$$ we can repeat discussions in Part I to obtain $$\left( -\frac{1}{r\_{out}} + \sum\_{k=1}^{n-1} \frac{1}{r\_k} \right)^2 = d \left( \frac{1}{r\_{out}^2} + \sum\_{k=1}^{n-1} \frac{1}{r\_k^2} \right)\tag{\*6b}$$ We can use this to determine $r\_{out}$. Once again, if $\vec{x}\_1,\ldots,\vec{x}\_{n-1}$ are in general position, we will find $\beta\_n \ne 0$. As a result, we can use $(\*5)$ to compute $\vec{x}\_{out}$, the center of the outer Soddy hyper-spheres, from the remaining centers. If one compare $(\*6a)$ and $(\*6b)$, they are very similar, $r\_{in}$ and $-r\_{out}$ are the two roots of the same equation in $R$. $$\left( \frac{1}{R} + \sum\_{k=1}^{n-1} \frac{1}{r\_k} \right)^2 = d \left( \frac{1}{R^2} + \sum\_{k=1}^{n-1} \frac{1}{r\_k^2} \right)$$ If the two roots of this equation has different sign, the positive root will be the inner Soddy radius $r\_{in}$, the negative root will be $-r\_{out}$, the negative of the outer Soddy radius.
In high-school, my geometry teacher mentioned the Soddy-Gosset theorem and I had been curious about its proof ever since. About 5 years ago, I decided to attempt to prove it and came up with a nice proof and a corollary that, according to my investigation, was unknown, at least in the form that I have. The first section below is taken from a paper I wrote at that time. The later sections are a clarification of the later parts of that paper. --- **Tangent Spheres** Suppose that the sphere with radius $r\_1$ and center $c\_1$, $(c\_1,r\_1)$, and the sphere with radius $r\_2$ and center $c\_2$, $(c\_2,r\_2)$, are externally tangent. Then we have $$ \begin{align} |c\_1-c\_2|^2&=(r\_1+r\_2)^2\tag{1a}\\ |c\_1|^2-2c\_1\cdot c\_2+|c\_2|^2&=r\_1^2+2r\_1r\_2+r\_2^2\tag{1b} \end{align} $$ For a given sphere, $(c,r)$, the radius of the inverted sphere, $\bar{r}$, satisfies $$ \begin{align} \frac{|c|^2}{r^2}-1&=\frac1{r\bar{r}}\tag{2a}\\ |c|^2-r^2&=\frac r{\bar{r}}\tag{2b} \end{align} $$ We don't actually use any of the properties of spherical inversion, so we can simply take $(2)$ as a definition of $\bar{r}$. Thus, if we subtract $r\_1^2+r\_2^2$ from both sides of $\mathrm{(1b)}$ and use equation $\mathrm{(2b)}$, we get $$ \begin{align} \frac{r\_1}{\bar{r}\_1}+\frac{r\_2}{\bar{r}\_2}-2c\_1\cdot c\_2&=2r\_1r\_2\tag{3a}\\ \frac{c\_1}{r\_1}\cdot\frac{c\_2}{r\_2}-\frac{1}{2}(\frac{1}{\bar{r}\_1r\_2}+\frac{1}{r\_1\bar{r}\_2})&=-1\tag{3b} \end{align} $$ Furthermore, from equation $\mathrm{(2a)}$, we get $$ \frac{|c|^2}{r^2}-\frac{1}{r\overline{r}}=1\tag{4} $$ Therefore, if, for a sphere in $\mathbb{R}^n$, $(c,r)$, we define the row vector in $\mathbb{R}^{n+2}$ $$ v=\left\langle\frac cr,\frac1r,\frac1{\bar{r}}\right\rangle\tag{5} $$ and make a square matrix, $V$, from $n+2$ of these row vectors for $n+2$ mutually tangent spheres, then we get from equation $\mathrm{(3b)}$, for the off-diagonal elements, and equation $(4)$, for the diagonal elements, that $$ V\left[\begin{array}{c c c} I\_n & 0\_{n\times 1} & 0\_{n\times 1} \\ 0\_{1\times n} & 0 & -\frac{1}{2} \\ 0\_{1\times n} & -\frac{1}{2} & 0 \end{array}\right]V^T = 2I\_{n+2}-C\_{n+2}\tag{6} $$ where $C\_{n+2}$ is an $(n{+}2)\times(n{+}2)$ matrix of all $1$s. Because $C\_{n+2}^2=(n+2)C\_{n+2}$, it is easily verified that $$ (2I\_{n+2}-C\_{n+2})^{-1}=\frac{1}{2}I\_{n+2}-\frac{1}{2n}C\_{n+2}\tag{7} $$ Invert equation $(6)$ and move $V$ to the right side to get $$ \left[\begin{array}{c c c} I\_n & 0\_{n\times 1} & 0\_{n\times 1} \\ 0\_{1\times n} & 0 & -2 \\ 0\_{1\times n} & -2 & 0 \end{array}\right] = V^T(\frac{1}{2}I\_{n+2}-\frac{1}{2n}C\_{n+2})V\tag{8} $$ Looking at the $(n+1,n+1)$ element of the matrix equation $(8)$, we get the equation $$ n\sum\_{k=1}^{n+2}\frac{1}{r\_k^2}=\left(\sum\_{k=1}^{n+2}\frac{1}{r\_k}\right)^2\tag{9} $$ If one of the spheres encompasses the rest, so that all the other spheres are internally tangent to it, then equation $\mathrm{(1a)}$ becomes $|c\_1-c\_2|^2=(r\_1-r\_2)^2$. If we consider the radius of the encompassing sphere to be negative, then this becomes $|c\_1-c\_2|^2=(r\_1+r\_2)^2$ as before. Therefore, we will consider the radius of an encompassing sphere to be negative. Thus, we have shown > > **The Soddy-Gosset Theorem**: Given $n+2$ mutually tangent spheres in $\mathbb{R}^n$, their radii, $\{r\_k:1\le k\le n+2\}$ satisfy equation $(9)$ if the radius of an encompassing sphere is considered negative. > > > Furthermore, if we look at the $(j,n+1)$ elements of the matrix equation $(8)$, for $1\le j\le n$, we get the vector equation $$ n\sum\_{k=1}^{n+2}\frac{c\_k}{r\_k^2}=\sum\_{k=1}^{n+2}\frac{c\_k}{r\_k}\;\sum\_{k=1}^{n+2}\frac{1}{r\_k}\tag{10} $$ If we divide equation $(10)$ by equation $(9)$, we get $$ \frac{\displaystyle\sum\_{k=1}^{n+2}\frac{c\_k}{r\_k^2}}{\displaystyle\sum\_{k=1}^{n+2}\frac{1}{r\_k^2}} =\frac{\displaystyle\sum\_{k=1}^{n+2}\frac{c\_k}{r\_k}}{\displaystyle\sum\_{k=1}^{n+2}\frac{1}{r\_k}}\tag{11} $$ Thus, we have derived the following > > **Corollary**: Given $n+2$ mutually tangent spheres in $\mathbb{R}^n$ with radii $\{r\_k:1\le k\le n+2\}$, the mean of the centers weighted by $\frac1{r\_k^2}$ is equal to the mean of the centers weighted by $\frac1{r\_k}$. > > > --- **Conclusions from Soddy-Gosset** Given the radii of $n+1$ mutually tangent spheres in $\mathbb{R}^n$, the Soddy-Gosset Theorem allows us to compute the radius of two possible spheres that are tangent to the other $n+1$. That is, we can solve $(9)$ for $\frac1{r\_{n+2}}$: $$ n\left(\color{#C00000}{\frac1{r\_{n+2}^2}}+\sum\_{k=1}^{n+1}\frac1{r\_k^2}\right) =\color{#C00000}{\frac1{r\_{n+2}^2}}+2\color{#C00000}{\frac1{r\_{n+2}}}\sum\_{k=1}^{n+1}\frac1{r\_k}+\left(\sum\_{k=1}^{n+1}\frac1{r\_k}\right)^2\tag{12a} $$ $$ (n-1)\color{#C00000}{\frac1{r\_{n+2}^2}}-2\color{#C00000}{\frac1{r\_{n+2}}}\sum\_{k=1}^{n+1}\frac1{r\_k}+n\sum\_{k=1}^{n+1}\frac1{r\_k^2}-\left(\sum\_{k=1}^{n+1}\frac1{r\_k}\right)^2=0\tag{12b} $$ applying the quadratic formula to $(12)$, we get $$ \frac{n-1}{r\_{n+2}}=\sum\limits\_{k=1}^{n+1}\frac1{r\_k}\pm\sqrt{n}\left[\left(\sum\limits\_{k=1}^{n+1}\frac1{r\_k}\right)^2-(n-1)\sum\limits\_{k=1}^{n+1}\frac1{r\_k^2}\right]^{1/2}\tag{13} $$ Note that the discriminant in $(13)$ vanishes precisely when the first $n+1$ spheres satisfy the Soddy-Gosset Theorem on $\mathbb{R}^{n-1}$. This implies that $\{c\_k:1\le k\le n+1\}$ lie in an $n-1$ dimensional hyperplane, and the two possibilities for $(c\_{n+2},r\_{n+2})$ are reflections of each other across this hyperplane. --- **Conclusions from the Corollary** Given the radii of $n+2$ mutually tangent spheres and the centers of the first $n+1$ of them, the Corollary allows us to determine $c\_{n+2}$, except in the case where the coefficients of $c\_{n+2}$ cancel in $(11)$. That is, when $$ \frac{\dfrac1{r\_{n+2}^2}}{\displaystyle\sum\_{k=1}^{n+2}\frac{1}{r\_k^2}} =\frac{\dfrac1{r\_{n+2}}}{\displaystyle\sum\_{k=1}^{n+2}\frac{1}{r\_k}}\tag{14} $$ which is equivalent to $$ \begin{align} \frac1{r\_{n+2}} &=\frac{\displaystyle\sum\_{k=1}^{n+2}\frac1{r\_k^2}}{\displaystyle\sum\_{k=1}^{n+2}\frac1{r\_k}} =\frac{\displaystyle\sum\_{k=1}^{n+1}\frac1{r\_k^2}}{\displaystyle\sum\_{k=1}^{n+1}\frac1{r\_k}}\tag{15a,15b}\\ &=\frac1n\sum\_{k=1}^{n+2}\frac1{r\_k} =\frac1{n-1}\sum\_{k=1}^{n+1}\frac1{r\_k}\tag{15c,15d} \end{align} $$ Explanation: $\mathrm{(15a)}$: restatement of $(14)$ $\mathrm{(15b)}$: multiply $\mathrm{(15a)}$ by $\sum\limits\_{k=1}^{n+2}\frac1{r\_k}$, subtract $\frac1{r\_{n+2}^2}$, then divide by $\sum\limits\_{k=1}^{n+1}\frac1{r\_k}$ $\mathrm{(15c)}$: apply $(9)$ to $\mathrm{(15a)}$ $\mathrm{(15d)}$: multiply $\mathrm{(15c)}$ by $n$, subtract $\frac1{r\_{n+2}}$, then divide by $n-1$ Note that $\mathrm{(15b)}$ and $\mathrm{(15d)}$ say that the first $n+1$ spheres satisfy the Soddy-Gosset Theorem in $\mathbb{R}^{n-1}$. Again, this implies that $\{c\_k:1\le k\le n+1\}$ lie in an $n-1$ dimensional hyperplane. Furthermore, $\mathrm{(15d)}$ matches $(13)$ when the discriminant vanishes. --- **Locating $\boldsymbol{c\_{n+2}}$ in the Exceptional Case** By rotation and translation, we can arrange that the $n-1$ dimensional hyperplane containing $\{c\_k:1\le k\le n+1\}$ is $x\_n=0$. That is, if $1\le k\le n+1$, $$ c\_{k,n}=0\tag{16} $$ and $c\_{n+2,n}$ is the perpendicular distance of $c\_{n+2}$ above or below that hyperplane. For clarity of presentation, let $\hat{p}$ be the projection of $p$ onto the hyperplane $x\_n=0$; that is, $\hat{p}\_k=p\_k$ for $1\le k\le n-1$ and $\hat{p}\_n=0$. Looking at the $(j,n)$ elements of matrix equation $(8)$ for $1\le j\le n-1$, we get the vector equation $$ \begin{align} \frac{\hat{c}\_{n+2}}{r\_{n+2}} &=\frac1n\sum\_{k=1}^{n+2}\frac{\hat{c}\_k}{r\_k}\tag{17a}\\ &=\frac1{n-1}\sum\_{k=1}^{n+1}\frac{c\_k}{r\_k}\tag{17b} \end{align} $$ which, in light of $\mathrm{(15d)}$, gives the vector equation $$ \hat{c}\_{n+2}=\frac{\displaystyle\sum\_{k=1}^{n+1}\frac{c\_k}{r\_k}}{\displaystyle\sum\_{k=1}^{n+1}\frac1{r\_k}}\tag{18} $$ Looking at the $(n,n)$ element of matrix equation $(8)$ we get $$ \begin{align} 1 &=\frac12\frac{c\_{n+2,n}^2}{r\_{n+2}^2}-\frac1{2n}\frac{c\_{n+2,n}^2}{r\_{n+2}^2}\\ &=\frac{n-1}{2n}\frac{c\_{n+2,n}^2}{r\_{n+2}^2}\tag{19} \end{align} $$ which gives us $$ c\_{n+2,n}=\pm r\_{n+2}\sqrt{\frac{2n}{n-1}}\tag{20} $$ We can now remove the rotation, and use $(18)$ and $(20)$ to get that $$ c\_{n+2}=\frac{\displaystyle\sum\_{k=1}^{n+1}\frac{c\_k}{r\_k}}{\displaystyle\sum\_{k=1}^{n+1}\frac1{r\_k}}\pm ur\_{n+2}\sqrt{\frac{2n}{n-1}}\tag{21} $$ or equivalently, using Soddy-Gosset and the Corollary in $\mathbb{R}^{n-1}$ and $\mathrm{(15b)}$, $$ \frac{c\_{n+2}}{r\_{n+2}}=\frac{\displaystyle\sum\_{k=1}^{n+1}\frac{c\_k}{r\_k}\frac1{r\_k}}{\displaystyle\sum\_{k=1}^{n+1}\frac1{r\_k}}\pm u\sqrt{\frac{2n}{n-1}}\tag{22} $$ where $u$ is a unit vector perpendicular to the plane containing $\{c\_k:1\le k\le n+1\}$.
41,700,616
How do I update a `List` object without deleting all objects and appending a record with a specific primary key twice? For example: I have a `User` object. This user has many `locations` from type `UserLocation`. If I ask my RESTful API now for all locations (e.g. `/api/users/6/locations`) I want to check if still all locations are up to date and eventually update and delete invalidated once.
2017/01/17
[ "https://Stackoverflow.com/questions/41700616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3756358/" ]
You can use `UserLocation.create(..., update: true)` for updating the objects with existing primary keys, see more in [docs](https://realm.io/docs/swift/latest/#creating-and-updating-objects-with-primary-keys). As for deletion you have to manually delete invalid objects, however you don't need to delete if from `Lists`, you can just delete it from realm and your relationships will be updated automatically.
I had to do similar thing in one of my past projects. I am not sure this is the best way to do that. ``` let realm = try! Realm() realm.beginWrite() let locations = User.locations //existing locations var locIdsAdded : [String] = [] //1. collect existing locations let existingIds = channels.map({ (loc) -> String in return loc.primaryKey }) //2. add or update objects from server for loc in locationDictsFromServer { let locObj = parseFromDict(loc) //parse dictionary into RealmObject realm.add(locObj, update: true) // update: true not to add duplicated if(existingIds.index(of: locObj.primaryKey) == nil) { // check if need to add user.locations.append(locObj) } locIdsAdded.append(locObj.primaryKey) } //3. remove non updated objects var removeSet:Set<String> = Set(existingIds) removeSet.subtract(locIdsAdded) for(removeId) in removeSet { if let obj2Remove = realm.object(ofType: UserLocation.self, forPrimaryKey: removeId) { realm.delete(obj2Remove) } } try! realm.commitWrite() ```
36,467,031
I have a XAML page layout defined that includes a `WebView` populated from an HTML string: ``` <WebView HorizontalOptions="Fill" VerticalOptions="FillAndExpand"> <WebView.Source> <HtmlWebViewSource Html="{Binding Flag.Description}" /> <!-- <HtmlWebViewSource Html="&lt;html>&lt;body>&lt;p>The HTML string.&lt;/p>&lt;/body>&lt;/html>" />--> </WebView.Source> </WebView> ``` When I hard code the string into the XAML it displays correctly, but it will not bind to the `Flag.Description` string. The XAML includes a couple of labels that bind correctly but I can't find any reason why the WebView source isn't binding correctly.
2016/04/07
[ "https://Stackoverflow.com/questions/36467031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132599/" ]
The accepted answer worked for me but I will add that it only works when you specify a height and width. There are a few combinations that worked: 1. define HeightRequest and WidthRequest ``` <WebView Source="{Binding HtmlSource}" HeightRequest="300" WidthRequest="250" /> ``` 2. define HorizontalOptions and VerticalOptions ``` <WebView x:Name="WebViewTermsOfService" Source="{Binding HtmlSource}" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" /> ``` However, when I specifed `CenterAndExpand` as a value, the HTML did not render
Seems like Binding `Html` property for `HtmlWebViewSource` just won't work out of the box. I think a `IValueConverter` will do the job. Please have a look how it is done in this [answer](https://forums.xamarin.com/discussion/comment/106437/#Comment_106437). I think that should be enough
15,246,878
Method inside the model: ``` public function get_fichas(){ $query = $this->db->query("SELECT * FROM fichas;"); return $query->result(); } ``` Then, I'm trying to pass this data to the controller. Method on the controller: ``` public function listar_fichas(){ $data['fichas_info'] = $this->fichas_model->get_fichas(); $this->load->view('templates/header'); $this->load->view('fichas/listar_fichas', $data); } ``` When I try to list the data in a view, I get the following error: > > "Fatal error: Cannot use object of type stdClass as array" > > > Here is how I'm trying to list: View file: ``` <?php foreach($fichas_info as $row){?> <table> <tr> <td><?php echo $row['cod_produto'] ;?></td> <td><?php echo $row['nome_produto'] ;?></td> <td ><?php echo $row['versao'];?></td> </tr> </table> <?php }?> ``` I think I'm doing something wrong on the view. Perhaps I'm passing the data incorrectly to the view. Can someone please tell what I'm doing wrong? Thank you!
2013/03/06
[ "https://Stackoverflow.com/questions/15246878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1511579/" ]
``` <td><?php echo $row['cod_produto'] ;?></td> <td><?php echo $row['nome_produto'] ;?></td> <td><?php echo $row['versao'];?></td> ``` should be: ``` <td><?php echo $row->cod_produto ;?></td> <td><?php echo $row->nome_produto ;?></td> <td ><?php echo $row->versao;?></td> ``` The result set is an object, so each column name is a property of the object. You were accessing them as an index of an array.
Do this : ``` <?php foreach($fichas_info as $row){?> <table> <tr> <td><?php echo $row->cod_produto ;?></td> <td><?php echo $row->nome_produto ;?></td> <td ><?php echo $row->versao;?></td> </tr> </table> <?php }?> ```
165,793
I installed an [Ecosmart 27kw tankless water heater](https://www.amazon.ca/Ecosmart-ECO-24-Modulating-Technology/dp/B002635ODW/ref=pd_rhf_se_s_cr_simh_0_8?_encoding=UTF8&pd_rd_i=B005NM3K2K&pd_rd_r=f44fd24e-3c52-49cf-adfb-102ff733d6b7&pd_rd_w=6XIvH&pd_rd_wg=c8ikG&pf_rd_p=a3d30d92-9f26-4e0d-8f24-fd3e9e75bbfd&pf_rd_r=3R7NF6MMH8ZXWCYK3QN1&refRID=3R7NF6MMH8ZXWCYK3QN1&th=1) yesterday and as far as heating the water goes, everything works perfectly. The issue is when the water heater is running, I lose internet! **Specs**: * Heater is 240v 27kw @ draw 112.5amps * Breakers are 3x 40amp dual pole across both sides of the split phase * Wiring is 3x 8awg * My internet is 10mbit ADSL down the phone line. -- My *suspicion* is that the high amp lines are creating an electrical field which is interfering with the low voltage phone line system, killing my internet. When turning on the hot water, I loose access to ping google.com, however I can still ping 192.168.2.1 [my router] which says it's not the router that's being interfered with via power loss. **Any recommendations regarding minimum distance between the high amp cables and the phone line. Am I even on the right track here?** Thanks - Jon --- Update: Fixed by installing a new phone line externally, 2 meters away from the high amp lines with cat7 cable.
2019/05/24
[ "https://diy.stackexchange.com/questions/165793", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/101692/" ]
Something you might want to consider here is that your phone line inside the house is probably something crappy and unshielded. Cat3, for instance, offers virtually no shielding at all. What I would suggest is upgrading your phone line from the box to your modem with something that is better shielded, like Cat6. If you can afford it, going even higher (Cat6a or 7) would afford you greater shielding. 10MB down a copper line is probably highly susceptible to even minor interference.
First, make sure that your three supply cables are paired properly. The unit has 3 heaters internally. There are several ways cables could be crossed that would result in power from 1 heater coming up one cable and returning on another cable. The heater would work properly, but would kick stupid large amounts of EMF from the two imbalanced cables. Just double-check it. --- Or, the heater may be throwing high frequency electromagnetic hash, with the cable(s) becoming antennas and making this worse. Now, electric resistive heating elements, *alone*, do not throw electromagnetic hash. That would only happen from * a) control electronics, which will surely only be on one cable/circuit; or * b) power choppers ("dimmers") which could be on 1 or all of the circuits, but there'd be no useful reason to have them on more than 1 circuit. Also, there's a thing I don't like about how Ecosmarts are installed - they expect you to cram three #8 cables through one 1" hole, which is a lot to ask, and requires just the right cable clamps to not violate Code. I would install a 6" square deep or larger **metal** box right below the EcoSmart and a short EMT conduit nipple connecting it to the EcoSmart's wiring hole. Bring the 3 cables into the large box with correct clamps; leaving space for up to 3 "surge suppressors" to be fit onto 3 knockouts. Then I would consult with EcoSmart and ask them a) which circuit powers the control electronics and b) whether they *merely switch* all 3 heaters, or whether they use power choppers, and if they do, *on which circuit(s)*. On the circuits which do not use choppers or electronics, those can be wired straight through the 6" box, up the conduit nipple and to the terminals. For the circuit(s) which do use choppers or electronics, you run a pigtail from the EcoSmart's terminal into this box. Then you mount a "surge suppressor" in one of the knockouts (or not, if it's a type that can live inside the junction box e.g. Meanwell SPD-20-277P). Then join those wires to the power line from the panel. This wires the Ecosmart and the suppressor in parallel (the usual way you "tee" a connection) - it's not wired in series like a switch. [![enter image description here](https://i.stack.imgur.com/hOFZq.png)](https://i.stack.imgur.com/hOFZq.png) At this point, the surge suppressor(s) should be damping out the EM interference before it leaves the metal faraday cage of the Ecosmart + junction box. I suppose Ecosmart could build this into the product, but that would raise the price-point, and so you might not have selected the product.
45,254,596
I am new in **Codeigniter** and I need to show success and error message after `insert` data's in database. How can I show the message in the `view` page? This is my coding: **Model** ``` function addnewproducts($data) { if($data['product_name']!="" && $data['product_qty']!="" && $data['product_price']!="" && $data['date']!="") { $res=$this->db->insert('product_list',$data); return $this->db->insert_id(); } else { return false; } } ``` **Controller** ``` function addnewproduct() { $this->load->model('products'); $data['product_name'] = trim(strip_tags(addslashes($this->input->post('product_name')))); $data['product_qty'] = trim(strip_tags(addslashes($this->input->post('product_qty')))); $data['product_price'] = trim(strip_tags(addslashes($this->input->post('product_price')))); $data['datetime']=date('d-m-Y'); $res = $this->products->addnewproducts($data); if($res==true) { $data['success'] = 'Successful'; $this->load->view('addproduct',$data); } } ``` **View** ``` <p><?php echo $success; ?></p> ```
2017/07/22
[ "https://Stackoverflow.com/questions/45254596", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7870379/" ]
There are many ways but below is which i recommend: Set temp session **in controller** on success or error: ``` $res = $this->products->addnewproducts($data); if($res==true) { $this->session->set_flashdata('success', "SUCCESS_MESSAGE_HERE"); }else{ $this->session->set_flashdata('error', "ERROR_MESSAGE_HERE"); } ``` In View you can display flashdata as below: ``` echo $this->session->flashdata('success'); or echo $this->session->flashdata('error'); ``` Source : Codeigniter official website <https://codeigniter.com/userguide3/libraries/sessions.html>
Controller: ``` function addnewproduct() { $this->load->model('products'); $data['product_name'] = trim(strip_tags(addslashes($this->input->post('product_name')))); $data['product_qty'] = trim(strip_tags(addslashes($this->input->post('product_qty')))); $data['product_price'] = trim(strip_tags(addslashes($this->input->post('product_price')))); $data['datetime']=date('d-m-Y'); if($this->products->addnewproducts($data)); { $this->session->set_flashdata('Successfully','Product is Successfully Inserted'); } else { $this->session->set_flashdata('Successfully','Failed To inserted Product'); } // redirect page were u want to show this massage. redirect('Controller/Fucntion_name','refresh'); }// close function ``` view : On Redirect Page write This code top of Form ``` <?php if($responce = $this->session->flashdata('Successfully')): ?> <div class="box-header"> <div class="col-lg-6"> <div class="alert alert-success"><?php echo $responce;?></div> </div> </div> <?php endif;?> ```
4,761,767
I need to display words on a WPF Canvas in such a way that they perfectly fit in pre-defined boxes. One box typically contains a single line of text, from one letter to a few words. The text inside a box must be as large as possible, i.e: touching all borders of the box (except maybe where it would cause too much text distortion due to abnormal box witdh/height ratio). I could not find a good way to calculate the appropriate font height, scaling and offset, based on the text content. A first solution where the original text width/height ratio can't be changed would already be very nice ! I'd like to use TextBlock elements, but anything else that works should be ok.
2011/01/21
[ "https://Stackoverflow.com/questions/4761767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/93447/" ]
As the answer by Robery Levy said, you can use a `Viewbox` to achieve this. The text itself won't stretch however so you'll still have some "margin" on zero or more sides depending on your text (as you noticed). To work around this you can create a custom control which builds a `Geometry` from a `FormattedText` and then draw this with `DrawGeometry` in OnRender. You'll notice how the quality of the text improves with a larger `FontSize`. A very small text (e.g. `FontSize="10"`) won't look very sharp in a large `Viewbox` so you'll have to experiment a bit ![enter image description here](https://i.stack.imgur.com/yA0PV.png) **Some sample Xaml** ``` <Canvas Background="Black"> <Viewbox Canvas.Left="10" Canvas.Top="10" Stretch="Fill" Width="200" Height="50"> <Border Background="Red"> <local:StretchText Text="Text" Foreground="Green" FontSize="100"/> </Border> </Viewbox> <Viewbox Canvas.Left="230" Canvas.Top="10" Stretch="Fill" Width="200" Height="50"> <Border Background="Red"> <local:StretchText Text="B" Foreground="Green" FontSize="500"/> </Border> </Viewbox> </Canvas> ``` **StretchText.cs** ``` public class StretchText : Control { protected override void OnRender(DrawingContext drawingContext) { FormattedText formattedText = new FormattedText( Text, CultureInfo.GetCultureInfo("en-us"), FlowDirection.LeftToRight, new Typeface(FontFamily, FontStyle, FontWeight, FontStretches.Normal), FontSize, Foreground); Geometry textGeometry = formattedText.BuildGeometry(new Point(0, 0)); this.MinWidth = textGeometry.Bounds.Width; this.MinHeight = textGeometry.Bounds.Height; TranslateTransform translateTransform = new TranslateTransform(); translateTransform.X = -textGeometry.Bounds.Left; translateTransform.Y = -textGeometry.Bounds.Top; drawingContext.PushTransform(translateTransform); drawingContext.DrawGeometry(Foreground, new Pen(Foreground, 1.0), textGeometry); } public string Text { get { return (string)GetValue(TextProperty); } set { SetValue(TextProperty, value); } } public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(StretchText), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsRender)); } ```
Put the TextBlock inside a Viewbox: <http://msdn.microsoft.com/en-us/library/system.windows.controls.viewbox.aspx>
38,780,207
So I am currently doing this in my Js script: ``` var someObject = require('./stored'); this.makeDuplicates = function(){ var storeDuplicates = []; this.addDuplicates = function(astring){ storeDuplicates[astring] = new someObject(); } this.printDuplicate = function(){ console.log(storeDuplicates["hello"]); } } var input = "hello" var newDupe = new makeDuplicates() newDupe.addDuplicates(input) newDupe.printDuplicate() ``` this will then print undefined. Why isn't this being correctly done? I would assume it would create a hash-like table where "string"->ref to object, but it doesn't seem like it. How can I go about this? Thanks!
2016/08/05
[ "https://Stackoverflow.com/questions/38780207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4557142/" ]
First, if your intention is not to use a list-like thing, don't use arrays, use objects. Unlike other languages, javascript objects are extensible. That is, you can always add new methods and properties to object instances. Therefore javascript don't have hashes since objects behave in a hash-like manner. To make using objects easy javascript has object literal syntax: ``` var storeDuplicates = {}; // object to act as a hash ``` Second, remove the `this` from your constructor: ``` makeDuplicates = function(){ /*... */ }; ``` Everything else should work as you expect them to. See this related question for how `this` works in javascript: [How does the "this" keyword in Javascript act within an object literal?](https://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628) --- Now, the following is just advisory, your code will still work without them but other javascript programmers may find it unconventional. Since constructors (in classical javascript, constructors are like classes in other languages) are just functions there is no syntactic difference between constructors and other functions. To remedy this javascript has evolved a convention where constructor names always start with capital letters: ``` MakeDuplicates = function(){ /* ... */ }; ``` When a javascript programmer sees the above he will understand that the `MakeDuplicates` function is intended to be a constructor.
So I just went back to my code and realized I make an extremely careless mistake. Instead of newDupe.addDuplicates(input), my actual code had newDupe.addDuplicates("anon") hence the undefined. Nevertheless, I am reading the proper use of this. .
156,647
I am building an API platform. I have already ensured that the platform always returns JSON responses. My question is **Should my API platform enforce the rule that all requests must be JSON? What are the benefits of making all requests to be JSON?** I understand the benefits of making all responses to be JSON as this means consistency for the client apps using the API. I fail to see the benefits of making all requests to be JSON as well. I am asking this because [GitHub API v3 appears to be enforcing this rule](http://developer.github.com/v3/#schema). My API platform will involve uploading of files in the requests. As far as I know, JSON requests does not work well with file uploads. Or do I do a hybrid? Enforce that anything NOT to do with file upload should send their requests as JSON? And allow an exception for file upload?
2012/07/13
[ "https://softwareengineering.stackexchange.com/questions/156647", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/16777/" ]
Your API needs to be able to understand the request. How can you do this if you accept random formats. An API consists of the definition of the formats, acceptable values contained within and the sequence in which they are exchanged. If you wish you can specify that your API also accepts XML requests, or perhaps plain url get requests. GitHub has specified a JSON based API and quite rightly rejects any request that is not valid JSON.
I think this is a question of approach, and you are right on "failing to see the benefits" of such restriction. Your service has a defined API; some of the entries require structured data (commands and data objects), others process streams (file upload). If I see it in this way, I see no problem. * If you have to accept something as a stream, you don't force anyone using an improper format (now JSON), but let them send you that file in the most natural way. This is not "breaking" some rule, but the simplest way to do the job. KISS. * If you have to process data hierarchies from the client: commands and objects, yes, it is nice to give one, and perhaps the easiest way to send you hierarchies, JSON is okay. *For your clients.* But for you inside the service, it is not beneficial to actually see JSON, because that is only a stream syntax and the handler components around it (the same exists for XML and perhaps other formats as well). *Your codes don't need JSON, they need data hierarchies.* So my advice here is to hide the fact that now you use JSON format and handlers, from all of your higher level codes. The options: * deserialize to actual object instances within your platform, * convert to a hierarchy of Maps, Dictionaries or alike * or hide the actual JSON node objects behind a simple interface with getAttribute, getChildren, etc. methods. Some time later you might be unable to force a client to use JSON, because their systems communicate through XMLs, can only use plain forms without JavaScript, or their data is actually in a database. Then you will love the concept of having JSON invisible to the rest of your code by any of the above means: you then just write the next wrapper for that XML (or HTTP request parameter package, whatever), and you are done: the same API and code can be reached through another "data language". At least this is how I see it.
37,618,679
I would like to format (round) float (double) numbers to lets say 2 significant digits for example like this: ``` 1 => 1 11 => 11 111 => 110 119 => 120 0.11 => 0.11 0.00011 => 0.00011 0.000111 => 0.00011 ``` So the arbitrary precision remains same I expect there is some nice function for it already built in, but could not find any so far I was pointed to [How to round down to the nearest significant figure in php](https://stackoverflow.com/questions/5834537/how-to-round-down-to-the-nearest-significant-figure-in-php), which is close but doesn't work for N significant digits and I'm not sure what it does with 0.000XXX numbers
2016/06/03
[ "https://Stackoverflow.com/questions/37618679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3358126/" ]
With little modification to possible duplicate, answer by Todd Chaffee: ``` public static function roundRate($rate, $digits) { $mod = pow(10, intval(round(log10($rate)))); $mod = $mod / pow(10, $digits); $answer = ((int)($rate / $mod)) * $mod; return $answer; } ```
To make sigFig(0.9995, 3) output 1.00, use if(floor(log10($value)) !== floor(log10(round($value, $decimalPlaces)))) {$decimalPlaces--;} Said line of code should be placed before declaring $answer. If input $value is negative, set a flag and remove the sign at the beginning of the function, like this: if($value < 0){$flag = 1;} $value = ltrim($value, "-"); Then right before returning $answer, detect if the flag is set and if so restore the negative sign, like this: if(isset($flag)){$answer = "-".$answer;} Finally, for result values with ambiguous number of significant digits (e.g., 1000, 12000,...), express the result in scientific notation to the desired number of significant digits using sprintf or printf.
32,200,108
Note that the question title is: ``` Random math question generation algorithm not working ``` because I can't enter "question" in question title... --- So I am writing an android app that helps little kids learn maths by giving math questions to them. They can change the number of digits and the type of operation as they like. I am now confused with this algorithm that I wrote to generate random questions. It is generating the same question every time if with the same question options. For question options ``` number of digits: 1 operation: + ``` It is always 10 + 10. Question options ``` number of digits: 2 operation: + ``` It is always 11 + 11. Question options ``` number of digits: 3 operation: + ``` It is always 8 + 8. Question options ``` number of digits: 2 operation: + ``` It is always 11 + 11. Although the other operation types (-, +/-, \*) are a bit more random, one of its operands is always the same. 1 digit is 10, 2 digits is 11, 3 digits is 8. Now here is my algorithm: ``` public void generateAQuestion () { switch (options.getOperationType ()) { case ADDITION: current = generateAddition (); break; case SUBTRACTION: current = generateSubtraction (); break; case ADD_AND_SUB: current = generateAddAndSub (); break; case MULTIPLICATION: current = generateMultiplication ();; break; } } private int generateNumberWithDigitCount () { int minValue = 10 ^ (options.getDigitCount () - 1); int maxValue = 10 ^ options.getDigitCount () - 1; Random r = new Random (); return r.nextInt (maxValue - minValue + 1) + minValue; } private Question generateAddition () { int operand1, operand2; operand1 = generateNumberWithDigitCount (); operand2 = generateNumberWithDigitCount (); return new Question (operand1, operand2); } private Question generateSubtraction () { int operand1 = generateNumberWithDigitCount (); Random r = new Random (); int operand2 = -(r.nextInt (operand1)); return new Question (operand1, operand2); } private Question generateAddAndSub () { Question firstPart; if (Math.random () > 0.5) { firstPart = generateAddition (); } else { firstPart = generateSubtraction (); } int[] operands = new int[3]; operands[0] = firstPart.getOperands ()[0]; operands[1] = firstPart.getOperands ()[1]; if (Math.random () > 0.5) { Random r = new Random (); operands[2] = -(r.nextInt (firstPart.getAnswer ())); } else { operands[2] = generateNumberWithDigitCount (); } return new Question (operands); } private MultiplicationQuestion generateMultiplication () { return new MultiplicationQuestion (generateNumberWithDigitCount (), generateNumberWithDigitCount ()); } private int[] generateAnswers (int correctAnswer) { int[] answers = new int[4]; Random r = new Random (); int correctAnswerIndex = r.nextInt (4); answers[correctAnswerIndex] = correctAnswer; for (int i = 0 ; i < answers.length ; i++) { if (i == correctAnswerIndex) { continue; } if (Math.random () > 0.5) { answers[i] = correctAnswer + (i + 1); } else { int candidate = correctAnswer - (i + 1); if (candidate < 0) { candidate = correctAnswer + i + 5; } answers[i] = candidate; } } return answers; } ``` Notes: `options` is the question options, its methods are self explanatory, you can get it.Don't care about the `Question` and `MultiplicationQuestion`'s constructors, they are irrelevant. And I don't know what I did wrong, everything makes sense to me. What did I do wrong?
2015/08/25
[ "https://Stackoverflow.com/questions/32200108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5133585/" ]
what is wrong here is where you use 10 ^ options.get... that isnt the same as power, you can in turn use Math.pow(10, options.get...) The problem you have is that the ^ operator does not act as a exponent mod in this case :) edited code ``` int minValue = (int)(Math.pow(10, (options.getDigitCount () - 1)); int maxValue = (int)(Math.pow(10, options.getDigitCount ())-1; ``` I completely understand why you got this wrong, as it is taught in many math classes that the ^ symbol means power
`^` is the XOR operator in Java. Given that, your expressions for max and min value do not make sense.
148,636
I need to run a scheduled job every few hours to refresh my API token for a 3rd party source. I want to store that API token in a global variable so I can access it from my controller. (I'm building a SPA within a single Visualforce page so there's only one controller that will be using it). Is there a standard place where I can store this API token so I can dynamically make the headers?
2016/11/14
[ "https://salesforce.stackexchange.com/questions/148636", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/38084/" ]
This is a bug inside the framework where dynamically created components are not getting properly indexed to their parents. Doesn't look like anyone is actively working on it right now. If you'd like to put some pressure on the devs who own this you can file a case and tell them to link the case to internal bug **W-2529066**.
as @[techbusinessman](https://salesforce.stackexchange.com/users/8359/techbusinessman) stated, the only **workaround** (so far) to get the value from a dynamically created component is to use : ``` var value = component.get("v.*attributeName*").get("v.value");// for type="Aura.Component" ``` or ``` var value = component.get("v.*attributeName*")[0].get("v.value"); // for type="Aura.Component[]" ``` posting it again so that it would help somebody. This small piece of bug has already eaten half of day when I found his comment.
51,921
I am a logic circuits beginner. We are asked to draw a circuit which takes a four-bit word as input, and outputs true if the word is greater than or equal to 10. Symbolizing the word as (b1b2b3b4), this translates to (b1 | b2 | b3). Now b4 is completely useless in the circuit. What is the drawing convention for a completely useless input? Do I leave it utterly disconnected, which feels weird, or do I have to go through the hassle of inverting it, ORing itself with its inversion, and ANDing that to the rest of the circuit? Or something else I haven't thought of? Thanks!
2012/12/21
[ "https://electronics.stackexchange.com/questions/51921", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/17146/" ]
Firstly, it's conventional to number bits like digits, from the right, and from zero: ``` b3 b2 b1 b0 ``` Secondly, you should test your circuit with some testcases, as it doesn't act as a >=10 comparator. For example, it reports true for 9 (1001 binary). Thirdly, you can just leave things disconnected. I've sometimes seen the convention of drawing an X on the end to indicate "deliberately disconnected output". Disconnected *inputs* are considered bad and should be tied to 1 or 0.
You don't say if your 10 is a decimal Ten or a Binary value = decimal two. I'll assume the former. Ten = 1010 which DOES require the 4th input. If the questions was greater than or equal to 7 you'd be right in not needing that input. b<3:0> is another representation. a 4 bit value is also known as a nybble
11,498,616
I am trying to send bulk of mails but i only receive 500 mails not matter how many mails i send.I am sending mails in loop.Here is a sample. ``` foreach (EmailInfo data in emaildata.ToArray()) { SmtpClient smtpClient = new SmtpClient(); MailMessage mailMsg = new MailMessage(); smtpClient.Send(mailMsg); smtpClient.Dispose(); } ``` I am using `.net framework 4.0`. I get this exception after 500 mails are sent `Service not available, closing transmission channel. The server response was: too many connections`.
2012/07/16
[ "https://Stackoverflow.com/questions/11498616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1405921/" ]
Use *boundary* `\b`: ``` \b The match must occur on a boundary between a \w (alphanumeric) and a \W (nonalphanumeric) character. ``` for example: ``` \b\w+\s\w+\b ``` result is ``` "them theme" "them them" in "them theme them them" ``` so that use: ``` Regex.Replace(inputString, @"(\bb\b)", "20"); Regex.Replace(inputString, @"(\ba\b)", "10"); ```
Try to be more specific in your regex rather than just replacing the values. Here are some rules which describes whether a character captured is variable or not 1. Variable must have binary operator(+,-,\*,/) and optinally spaces to its right(if start) ,to its left(if end) or on both side. It can also have paranethis around it if passed in function. So create a regex which satisfies these all conditions
247,373
I'm importing data from another system to MySQL, its a CSV file. The "Date" field however contains cryptic of 3-digit time entries, here's a random sample set: ``` > 540 > 780 > 620 > 965 ``` What's this? obviously its not 5:40 and 6:20. But it's not UNIX either (I tried 1225295**XXX** before I realized the time range this represents is about 16 minutes) Anyone recognize these? **Update**: I just noticed that further down in the replies, a coworker who's closer to the data just [opened a new SO account and added some more data](https://stackoverflow.com/questions/247373/what-time-format-is-this-not-unix-not-utc-nothing#247456). It seems like these numeric entries are just time entries (not date). Still clueless. IMHO, if no one can recognise this, then it probably isn't some (if obscure) standard time format and is more likely that these entries are foreign keys. **Update 2**: Many thanks to all! [we found the answer visually](https://stackoverflow.com/questions/247373/what-time-format-is-this-not-unix-not-utc-nothing#248123), but as usual, [SO pulled through clutch](https://stackoverflow.com/questions/247373/what-time-format-is-this-not-unix-not-utc-nothing#248070).
2008/10/29
[ "https://Stackoverflow.com/questions/247373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547/" ]
[swatch internet time](http://en.wikipedia.org/wiki/Swatch_Internet_Time) day is divided into 1,000 equal parts. very metric altogether.
I've seen some systems where the date is stored in a special table and elsewhere as an id to it. This might be one of them
2,780,076
I used asp.net in a project in an old company. The vs was licensed etc. Right now, I am planning to use mono since my new company is using linux based stuff and I heard that mono uses the .net framework etc. I just want to know if I need to purchase anything or is it ok to create a webapp using mono?
2010/05/06
[ "https://Stackoverflow.com/questions/2780076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194283/" ]
You can create a webapp using mono wihtout buying anything, of course. You only buy from Microsoft the license of Visual Studio, not the .Net compiler nor the Framework.
@SoMoS has the right answer. If you want more detail, and a better explanation of the patent situation, check out the [Mono Licensing page](http://www.mono-project.com/Licensing).
20,212,665
Defining a function in c using this structures of data: ``` typedef struct { int number; char name[25]; } person; person rep[100]; int key=0; ``` Is there any problem with memory allocation when defining this function: (i'm just a beginner: i don't know what memory allocation means) ``` void add_person(int num, char *name){ if (key<100){ rep[key].number = num; strcpy(rep[key].name, name); key++; } } ```
2013/11/26
[ "https://Stackoverflow.com/questions/20212665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2727656/" ]
A function's pointer is something completely different than this. What you have is a function with a `char *` (`char` pointer). If you call this function, you pass it the contents for a "new" `person` struct. This `person` struct contains a (rather small) array where the name can be held, so memory allocation (which means reserving a memory area for dedicated use) is implied there. But be warned: what do you think will happen if the caller passes a string with more than 25 characters? Right, it will "destroy" the contents of the memory area behind it. So you'll have to pay attention and use `strncpy(rep[key].name, name, sizeof rep[key].name)`. As the creator of `strncpy()` seems to have slept ("No null-character is implicitly appended at the end of destination if source is longer than num"), you'll have to add this null-character - which indicates the end of a string in C - by yourself: ``` rep[key].name[sizeof rep[key].name - 1] = '\0' ``` If the string was shorter, `strcpy()` has added its own `'\0'`, if not, we cut it here.
your function definition is good just a thing concerning the `key` variable: It should be defined as global variable
31,063,962
I'm trying to use toolbar for my project. Here is the code I am using: ``` <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:layout_alignParentTop="true" android:background="?attr/colorPrimary" android:contentInsetLeft="0dp" android:elevation="@dimen/margin_padding_8dp" android:contentInsetStart="0dp"> <RelativeLayout android:id="@+id/rlToolbar" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tvTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:paddingRight="@dimen/margin_padding_16dp" android:text="AppBar" android:textAppearance="@style/TextAppearance.AppCompat" android:textColor="@color/white" android:textSize="@dimen/text_size_20sp" /> </RelativeLayout> ``` ![toolbar](https://i.imgur.com/d5PX5bZ.png) I want to remove left margin, Here I set **android:contentInsetLeft="0dp"** and **android:contentInsetStart="0dp"** but it's **not** working..Please help me !
2015/06/26
[ "https://Stackoverflow.com/questions/31063962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3901323/" ]
See the below code and here I added `app:contentInsetStart="0dp"`. You need to add that to your code because before API 21 (i.e. Lollipop) you need to add that line. ``` <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="64dp" android:background="@color/colorPrimary" android:minHeight="?attr/actionBarSize" android:contentInsetStart="0dp" app:contentInsetStart="0dp" > </android.support.v7.widget.Toolbar> ```
**Add below xml code to your Toolbar** ``` <android:contentInsetLeft="0dp" android:contentInsetStart="0dp" app:contentInsetLeft="0dp" app:contentInsetStart="0dp" android:contentInsetRight="0dp" android:contentInsetEnd="0dp" app:contentInsetRight="0dp" app:contentInsetEnd="0dp"> ```
2,933,391
I have read a lot of threads about the joys and awesome points of unit testing. Is there have a good argument against unit testing?
2010/05/29
[ "https://Stackoverflow.com/questions/2933391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/202184/" ]
In the places I have previously worked, unit testing is usually used as a reason to run with a smaller testing department; the logic is **"we have UNIT TESTS!! Our code can't possibly fail!! Because we have unit tests, we don't need real testers!!"** Of course that logic is flawed. I have seen many cases where you cannot trust the tests. I have also seen many cases where the tests become out of date due to tight time schedules - when you have a week to do a big job, most developers would spend the week doing the real code and shipping the product, rather than refactoring the unit tests for that first week, then pleading for at least another week to do the real code, and then spending a final week bringing the unit tests up to date with what they actually wrote. I have also seen cases where the business logic involved in the unit test was more monstrous and hard to understand than the logic buried in the application. When these tests fail, you have to spend twice as long trying to work out the problem - is the test flawed, or the real code? Now the zealots are not going to like this bit: the place where I work has largely escaped using unit tests because the developers are of a high enough calibre that it is hard to justify the time and resource to write unit tests (not to mention we use REAL testers). For real. Writing unit tests would have only given us minimal value, and the return on investment is just not there. Sure it would give people a nice warm fuzzy feeling - *"I can sleep at night because my code is PROTECTED by unit tests and consequently the universe is at a nice equilibrium"*, but the reality is we are in the business of writing software, not giving managers warm fuzzy feelings. Sure, there absolutely are good reasons for having unit tests. The trouble with unit testing and TDD is: * Too many people bet the family farm on it. * Too many people use it as a religion rather than just a tool or another methodology. * Too many people have tried to make money out of it, which has skewed *how* it should be used. In reality, it should be used as **one** of the tools or methodologies that you use on a day to day basis, and it should never become **the** single methodology.
* It can discourage experimenting with several variations, especially in early stages of a project. (But it can also encourage experimenting in later stages!) * It can't replace system testing, because it doesn't cover the relationship between components. So if you have to split up the available testing time between system testing and unit testing, then too much unit testing can have a negative impact on the amount of system tests. I want to add, that I usually encourage unit testing!
36,000,867
Is there a way to change the responder or select another text view by pressing tab on the keyboard, in Swift? [![enter image description here](https://i.stack.imgur.com/xnwwN.png)](https://i.stack.imgur.com/xnwwN.png) Notes: It's for a fill in the blank type application. My VC creates a list of Words [Word], and each of those words has its own WordView - word.wordView. The WordView is what is displayed. WordView is a child of NSTextView. I tried to override keydown but it doesn't allow me to type anything in the text view.
2016/03/15
[ "https://Stackoverflow.com/questions/36000867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4093643/" ]
Assuming you want to go from textView1 to textView2. First set the delegate: ``` self.textView1.delegate = self ``` Then implement the delegate method: ``` func textView(textView: NSTextView, doCommandBySelector commandSelector: Selector) -> Bool { if commandSelector == "insertTab:" && textView == self.textView1 { self.window.makeFirstResponder(self.textView2) return true } return false } ```
If you want some control over how your field tabs or moves with arrow keys between fields in Swift, you can add this to your delegate along with some move meaningful code to do the actual moving like move next by finding the control on the superview visibly displayed below or just to the right of the control and can accept focus. ``` public func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool { switch commandSelector { case #selector(NSResponder.insertTab(_:)), #selector(NSResponder.moveDown(_:)): // Move to the next field Swift.print("Move next") return true case #selector(NSResponder.moveUp(_:)): // Move to the previous field Swift.print("Move previous") return true default: return false } return false // I didn't do anything } ```
49
To improve upon traditional democracy, various alternatives to the normal up down voting have been put forth such as [range voting](http://en.wikipedia.org/wiki/Range_voting). (Range voting is a voting method for one-seat elections under which voters score each candidate, the scores are added up, and the candidate with the highest score wins.) For example [RangeVoting.org](http://RangeVoting.org) describes how range voting could work. I believe that San Francisco has experimented with something akin to this for their mayoral races. What are the largest elections that have had some variant of range voting applied and how successful were the results? Were the constituents happy with the outcomes and did range voting remain in place or was it repealed?
2012/12/05
[ "https://politics.stackexchange.com/questions/49", "https://politics.stackexchange.com", "https://politics.stackexchange.com/users/21/" ]
[This](https://www.rangevoting.org/VenHist.html) isn't the best source, but supposedly the [Doge](https://en.wikipedia.org/wiki/Doge_of_Venice) of Venice was elected using a 3-point Score/Range system for over 500 years, by placing balls in colored urns. (Actually it might also be [Combined approval voting](https://en.wikipedia.org/wiki/Combined_approval_voting), since the votes includes a connotation of "for" and "against".) The Green Party of Utah used Range Voting on a 0-9 scale to elect officers in 2017. There's an [analysis on Electowiki](https://electowiki.org/wiki/2017_Green_Party_of_Utah_officer_election). They said: > > We fully intend to utilize this system again next year, and would encourage other state parties to consider doing the same. I have heard concerns that it could be "too complicated". I feel that rating something on a scale of 1-10 (or 0-9 in this case) is a pretty basic concept. There was little to no confusion about how to do it. As far as complications tabulating the results... the spreadsheet did all of the dirty work. We just transposed the numbers from the ballot into the spreadsheet, and let the program do the math. We double-checked the results, and had a result very quickly. > > > It's not clear whether they've continued to use it, though.
Having researched this topic and having found no examples I would like to answer the question: **No**.
39,506,642
I am trying to solve a problem in Topcoder, where I need to find the number of rectangles(excluding squares) when the width and length are provided. My code works perfect for all test cases, but for one final test case, ie `592X964` I need to return `81508708664` , which is greater than `2^32-1` , which is greater than the value long can hold, but the compiler demands the value must be returned in `long` . I've added the problem statement and my code below, kindly go through, and let me know if its possible to return the above value using long in java. ``` /* Problem Statement Given the width and height of a rectangular grid, return the total number of rectangles (NOT counting squares) that can be found on this grid. For example, width = 3, height = 3 (see diagram below): __ __ __ |__|__|__| |__|__|__| |__|__|__| In this grid, there are 4 2x3 rectangles, 6 1x3 rectangles and 12 1x2 rectangles. Thus there is a total of 4 + 6 + 12 = 22 rectangles. Note we don't count 1x1, 2x2 and 3x3 rectangles because they are squares. Definition Class: RectangularGrid Method: countRectangles Parameters: int, int Returns: long Method signature: long countRectangles(int width, int height) (be sure your method is public) Limits Time limit (s): 2.000 Memory limit (MB): 64 Notes - rectangles with equals sides (squares) should not be counted. Constraints - width and height will be between 1 and 1000 inclusive. Examples 0) 3 3 Returns: 22 See above 1) 5 2 Returns: 31 __ __ __ __ __ |__|__|__|__|__| |__|__|__|__|__| In this grid, there is one 2x5 rectangle, 2 2x4 rectangles, 2 1x5 rectangles, 3 2x3 rectangles, 4 1x4 rectangles, 6 1x3 rectangles and 13 1x2 rectangles. Thus there is a total of 1 + 2 + 2 + 3 + 4 + 6 + 13 = 31 rectangles. 2) 10 10 Returns: 2640 3) 1 1 Returns: 0 4) 592 964 Returns: 81508708664 This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved. */ public class RectangularGrid { public static void main(String[] args) { System.out.println(countRectangles(592,964)); } public static long countRectangles(int m, int n) { long tot_rect = (long)(((m*m)+m)*((n*n)+n))/4; long tot_square = 0; boolean status = true; while(status) { if(m>0 && n>0) { tot_square+=(long)m*n; --m; --n; } else { status = false; } } return tot_rect-tot_square; } } ```
2016/09/15
[ "https://Stackoverflow.com/questions/39506642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4738175/" ]
> > running this code returns garbage values, I cant see why it does that if the value can be hold by long > > > Because you're doing `int` multiplication: ``` public static long countRectangles(int m, int n) // Note ---------------------------^^^----^^^ { long tot_rect = (long)(((m*m)+m)*((n*n)+n))/4; // Note -----------------^^^-------^^^ ``` If you want those to use `long`, you'll need casts: ``` public static long countRectangles(int m, int n) { long tot_rect = ((((long)m*m)+m)*(((long)n*n)+n))/4; // Note -----------^^^^^^----------^^^^^^ ``` Casting the end result doesn't do anything for losses in intermediate results.
Long is 8 bytes which means its range is -2^63 to 2^63 - 1; So it is by far greater then 2^32-1. It is Integer type that is 4 bytes and its range is -2^31 to 2^31-1. So you are perfectly fine with long as you are within range.
4,338,024
So I have this contact script which works great in firefox but whenever anyone tries it in ie 7 or 8 the plan always returns array and for the life of me I cant figure out what I did wrong. Any help would be greatly appreciated. ``` <?php if(!$_POST) exit; $name = $_POST['name']; $email = $_POST['email']; $phone = $_POST['phone']; $cname = $_POST['cname']; $address1 = $_POST['address']; $address2 = $_POST['address2']; $city = $_POST['city']; $state = $_POST['state']; $zip = $_POST['zip']; $plan = $_POST['plan']; $verify = $_POST['verify']; if(trim($name) == '') { echo '<div class="error_message">Attention! You must enter your name.</div>'; exit(); } else if(trim($email) == '') { echo '<div class="error_message">Attention! Please enter a valid email address.</div>'; exit(); } else if(trim($phone) == '') { echo '<div class="error_message">Attention! Please enter a valid phone number.</div>'; exit(); } else if(!is_numeric($phone)) { echo '<div class="error_message">Attention! Phone number can only contain digits.</div>'; exit(); } else if(!isEmail($email)) { echo '<div class="error_message">Attention! You have enter an invalid e-mail address, try again.</div>'; exit(); } if(trim($cname) == '') { echo '<div class="error_message">Attention! Please enter your Company Name.</div>'; exit(); } if(trim($address1) == '') { echo '<div class="error_message">Attention! Please enter your Address.</div>'; exit(); } if(trim($city) == '') { echo '<div class="error_message">Attention! Please enter your city.</div>'; exit(); } if(trim($state) == '') { echo '<div class="error_message">Attention! Please enter your state.</div>'; exit(); } if(trim($zip) == '') { echo '<div class="error_message">Attention! Please enter your zip code.</div>'; exit(); } else if(trim($verify) == '') { echo '<div class="error_message">Attention! Please enter the verification number.</div>'; exit(); } else if(trim($verify) != '4') { echo '<div class="error_message">Attention! The verification number you entered is incorrect.</div>'; exit(); } if($error == '') { if(get_magic_quotes_gpc()) { $comments = stripslashes($comments); } // Configuration option. // Enter the email address that you want to emails to be sent to. // Example $address = "joe.doe@yourdomain.com"; $address = "email@email.com"; // Configuration option. // i.e. The standard subject will appear as, "You've been contacted by John Doe." // Example, $e_subject = '$name . ' has contacted you via Your Website.'; $e_subject = 'Veterans Career Fair: You\'ve been contacted by ' . $name . '.'; // Configuration option. // You can change this if you feel that you need to. // Developers, you may wish to add more fields to the form, in which case you must be sure to add them here. $e_body = "You have been contacted by $name from $cname, they wish to sign up for the $plan Plan. Their additional information is as follows:\r\n\n"; $e_reply = "Contact $name via email, $email or via phone $phone. \r\n\n"; $e_mail = "Address of $name is: $address1 $address2, $city, $state $zip"; $msg = $e_body . $e_reply . $e_mail; if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n")) { // Email has sent successfully, echo a success page. echo "<fieldset>"; echo "<div id='success_page'>"; echo "<h1>Email Sent Successfully.</h1>"; echo "<p>Thank you <strong>$name</strong>, your message has been submitted to us.</p>"; echo "<p>You should hear from us in 48 hours</p>"; echo "</div>"; echo "</fieldset>"; } else { echo 'ERROR!'; } } function isEmail($email) { // Email address verification, do not edit. return(preg_match("/^[-_.[:alnum:]]+@((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email)); } ?> ``` The Html ``` <form method="post" action="bin/sendme.php" name="contactform" id="contactform"> <label>Full Name</label> <input name="name" type="text" id="name" size="30" value="" /><br /> <label>Email</label> <input name="email" type="text" id="email" size="30" value="" /><br /> <label>Phone</label> <input name="phone" type="text" id="phone" size="30" value="" /><br /> <label>Company Name</label> <input name="cname" type="text" id="cname" size="30" value="" /><br /> <label>Address 1</label> <input name="address" type="text" id="address" size="30" value="" /><br /> <label>Address 2</label> <input name="address2" type="text" id="address2" size="30" value="" /><br /> <label>City</label> <input name="city" type="text" id="city" size="30" value="" /><br /> <label>State</label> <input name="state" type="text" id="state" size="30" value="" /><br /> <label>Zip Code</label> <input name="zip" type="text" id="zip" size="30" value="" /><br /> <label>Plan</label> <select name="plan" type="text" id="plan"> <option value="Platinum">Platinum Sponsorship</option> <option value="Gold">Gold Sponsorship</option> <option value="Silver">Silver Sponsorship</option> <option value="Survey">Survey Sponsorship</option> <option value="Marquee">Marquee Sponsorship</option> </select> <label>3 + 1 =</label> <input name="verify" type="text" id="verify" size="4" value="" style="width: 30px;" /><br /><br /> <input type="submit" class="submit" id="submit" value="REGISTER NOW" /> </form> ``` The Jquery ``` jQuery(document).ready(function(){ $('#contactform').submit(function(){ var action = $(this).attr('action'); $("#message").slideUp(750,function() { $('#message').hide(); $('#submit') .after('<img src="assets/ajax-loader.gif" class="loader" />') .attr('disabled','disabled'); $.post(action, { name: $('#name').val(), email: $('#email').val(), phone: $('#phone').val(), cname: $('#cname').val(), address: $('#address').val(), city: $('#city').val(), state: $('#state').val(), zip: $('#zip').val(), plan: $('#plan').val(), verify: $('#verify').val() }, function(data){ document.getElementById('message').innerHTML = data; $('#message').slideDown('slow'); $('#contactform img.loader').fadeOut('slow',function(){$(this).remove()}); $('#contactform #submit').attr('disabled',''); if(data.match('success') != null) $('#contactform').slideUp('slow'); } ); }); return false; }); ```
2010/12/02
[ "https://Stackoverflow.com/questions/4338024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/348843/" ]
`<select name="plan" type="text" id="plan">` should be `<select name="plan" id="plan">`
The html `select` element does not have an attribute `type` so perhaps that's confusing IE
57,328,560
There's a table storing the time that users listened to music which looks like the follow: ``` +-------+-------+---------------------+ | user | music | listen_time | +-------+-------+---------------------+ | A | m | 2019-07-01 16:00:00 | +-------+-------+---------------------+ | A | n | 2019-07-01 16:05:00 | +-------+-------+---------------------+ | A | x | 2019-07-01 16:10:00 | +-------+-------+---------------------+ | A | y | 2019-07-01 17:10:00 | +-------+-------+---------------------+ | A | z | 2019-07-02 18:10:00 | +-------+-------+---------------------+ | A | m | 2019-07-02 18:15:00 | +-------+-------+---------------------+ | B | t | 2019-07-02 18:15:00 | +-------+-------+---------------------+ | B | s | 2019-07-02 18:20:00 | +-------+-------+---------------------+ ``` The calculation result should be the list of music every user has listened with interval less than 30min, which should looks like (music\_list should be ArrayType column): ``` +-------+------------+ | user | music_list | +-------+------------+ | A | m, n, x | +-------+------------+ | A | y | +-------+------------+ | A | z, m | +-------+------------+ | B | t, s | +-------+------------+ ``` How could I possibly implement it in scala spark dataframe?
2019/08/02
[ "https://Stackoverflow.com/questions/57328560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1755317/" ]
This is a hint. ``` df.groupBy($"user", window($"listen_time", "30 minutes")).agg(collect_list($"music")) ``` The result is ``` +----+------------------------------------------+-------------------+ |user|window |collect_list(music)| +----+------------------------------------------+-------------------+ |A |[2019-07-01 16:00:00, 2019-07-01 16:30:00]|[m, n, x] | |B |[2019-07-02 18:00:00, 2019-07-02 18:30:00]|[t, s] | |A |[2019-07-02 18:00:00, 2019-07-02 18:30:00]|[z, m] | |A |[2019-07-01 17:00:00, 2019-07-01 17:30:00]|[y] | +----+------------------------------------------+-------------------+ ``` which is similar result but not exactly same. Use `concat_ws` after `collect_list` then you can obtain `m, n, x`.
This will work for you ``` val data = Seq(("A", "m", "2019-07-01 16:00:00"), ("A", "n", "2019-07-01 16:05:00"), ("A", "x", "2019-07-01 16:10:00"), ("A", "y", "2019-07-01 17:10:00"), ("A", "z", "2019-07-02 18:10:00"), ("A", "m", "2019-07-02 18:15:00"), ("B", "t", "2019-07-02 18:15:00"), ("B", "s", "2019-07-02 18:20:00")) val getinterval = udf((time: Long) => { (time / 1800) * 1800 }) val df = data.toDF("user", "music", "listen") .withColumn("unixtime", unix_timestamp(col("listen"))) .withColumn("interval", getinterval(col("unixtime"))) val res = df.groupBy(col("user"), col("interval")) .agg(collect_list(col("music")).as("music_list")).drop("interval") ```
7,524
If a photo is over or under exposed but not to the point of clipping (histogram does not reach the left or right side) is there any reason you couldn't just fix the exposure in Photoshop or Lightroom? Obviously you wouldn't ultimately want a photo that is to bright or too dark, but is any actual information lost if the original digital file is not at the correct exposure?
2011/01/23
[ "https://photo.stackexchange.com/questions/7524", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/1431/" ]
Yes, you can correct a little bit; That's what the exposure sliders in Aperture/Photoshop/Lightroom are for, and it's one of the reasons RAW can be a better choice than JPEG. However, some information is hidden by noise, and you're better off changing ISO in camera to get a proper exposure than underexposing and correcting in post. A 1/100, f/8, ISO 800 picture adjusted +2 stops in post will have more noise than a 1/100, f/8, ISO 3200 picture straight out of camera. Also see [How is ISO implemented in digital cameras?](https://photo.stackexchange.com/questions/2946/how-is-iso-implemented-in-digital-cameras) for similar discussion.
You can, but there is only so much data, at some point you are going to hit the case where the light colors are all the same or the dark colors are all the same. To really understand this go look an Ansel Adam's "The Zone System" and understand what he was doing in B&W film 60 years ago.
11,017,655
CSS: Is it possible to specify a style to a fieldset before another fieldset? When Two fieldset follow in my code I would like to apply them a specific style. EDIT Without using class and id of course... Here is my code ``` <div id="tabs"> <fieldset class="one"> <legend>One</legend> Text </fieldset> <fieldset class="two"> <legend>Two</legend> Text </fieldset> </div> ``` Ths give me this : ![enter image description here](https://i.stack.imgur.com/tonAe.jpg) And I would like this : ![enter image description here](https://i.stack.imgur.com/BkKDo.jpg)
2012/06/13
[ "https://Stackoverflow.com/questions/11017655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/196526/" ]
Without using any classes or id's you can use `first-child` to target the first one and then use the default styling for second. e.g. ``` form fieldset{ background: green; } form fieldset:first-child{ background: red; } ``` First fieldset will have a red background, any others will have a green background. Note though this is for fieldsets within the same form. If they are in separate forms, then you can apply the same principle using the `form:first-child`
If you don't want to use classes or id's but still want them to have different styles, how about using inline CSS for each fieldset? Is there a particularly good reason to avoid classes and id's while still wanting to use CSS? With a little more detail, we can probably give you a better answer.
25,485
I want to be able to record band practices and then quickly create mp3s and send them out. Fidelity doesn't matter so much, right now I'm using garage band, creating an m4a from garage band and then using ITunes to convert that file to mp3. The last step is emailing out the mp3s (or uploading them to ftp server). Is there any software that can help me reduce the number of steps I'm taking ?
2011/01/03
[ "https://sound.stackexchange.com/questions/25485", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/-1/" ]
[Audacity](http://audacity.sourceforge.net/) is a nice open source audio editor that can record, edit and export to mp3.
Have you tried automating some of the steps with [Automator](http://support.apple.com/kb/HT2488)?
45,080,142
I've been trying to vectorize a for loop in Matlab because it bottlenecks the whole program but I have no clue about how to do it when iterating on different rows or columns of a single matrix inside of the loop. Here's the code : ``` // X is an n*k matrix, W is n*n // W(i,j) stores the norm of the vector resulting from subtracting // the j-th line of X from its i-th line. for i = 1:n for j = 1:n W(i,j) = norm(X(i,:) - X(j,:)) end end ``` Edit : ====== I chose Luis Mendo's answer as it was the most convenient for me and the one that's closer to the mathematical concept behind my algorithm, yet all three answers were correct and I'd advise to use the one that's the most convenient depending on which Matlab Toolboxes you have or the way you want to code. I also noticed that the common point of all answers was to use a different format, for example : using an array that would store the indices, reshaping current arrays, using one more dimension... So I think that's the right thing to explore if you have a similar problem.
2017/07/13
[ "https://Stackoverflow.com/questions/45080142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4513390/" ]
Using combinatory: ``` % sample data X = randi(9,5,4); n = size(X,1); % row index combinations combIdx = combvec(1:n,1:n); % difference between row combinations D = X(combIdx(1,:),:)-X(combIdx(2,:),:); % norm of each row W = diag(sqrt(D*D')); % reshape W = reshape(W,n,[]); ```
* If you have the Statistics Toolbox, use [`pdist`](https://es.mathworks.com/help/stats/pdist.html): ``` W = squareform(pdist(X)); ``` * No toolbox: good old [`bsxfun`](https://es.mathworks.com/help/matlab/ref/bsxfun.html): ``` W = sqrt(sum(bsxfun(@minus, permute(X, [1 3 2]), permute(X, [3 1 2])).^2, 3)); ```
14,893,043
I'm working on a custom provider that works exactly like a classical user form, however I have to give a second parameter to identify the user: a websiteId (I'm creating a dynamic website plateform). So a username is no more unique, but the combinaison of username and websiteId it is. I successfully created my custom authentication, the last problem I have is to get the websiteId from the domain thanks to a listener, it works, but infortunately the method that get the website id from the domain is loaded after my authentication provider, so I can't get the websiteId in time :( I tried to change the listener priority (test 9999, 1024, 255 and 0, and negative numbers -9999, -1024, -255 etc...), in vain, it's loaded always after. Here my code: **services.yml:** ``` services: # Listeners _________________ website_listener: class: Sybio\Bundle\WebsiteBundle\Services\Listener\WebsiteListener arguments: - @doctrine - @sybio.website_manager - @translator - %sybio.states% tags: - { name: kernel.event_listener, event: kernel.request, method: onDomainParse, priority: 255 } # Security _________________ sybio_website.user_provider: class: Sybio\Bundle\WebsiteBundle\Security\Authentication\Provider\WebsiteUserProvider arguments: [@website_listener, @doctrine.orm.entity_manager] ``` My listener is "website\_listener", and you can see i use it for my sybio\_website.user\_provider as argument. **WebsiteListener:** ``` // ... class WebsiteListener extends Controller { protected $doctrine; protected $websiteManager; protected $translator; protected $websiteId; /** * @var array */ protected $entityStates; public function __construct($doctrine, $websiteManager, $translator, $entityStates) { $this->doctrine = $doctrine; $this->websiteManager = $websiteManager; $this->translator = $translator; $this->entityStates = $entityStates; } /** * @param Event $event */ public function onDomainParse(Event $event) { $request = $event->getRequest(); $website = $this->websiteManager->findOne(array( 'domain' => $request->getHost(), 'state' => $this->entityStates['website']['activated'], )); if (!$website) { throw $this->createNotFoundException($this->translator->trans('page.not.found')); } $this->websiteId = $website->getId(); } /** * @param integer $websiteId */ public function getWebsiteId() { return $this->websiteId; } } ``` $websiteId is hydrated, not in time as you will see in my provider... **WebsiteUserProvider:** ``` <?php namespace Sybio\Bundle\WebsiteBundle\Security\Authentication\Provider; // ... class WebsiteUserProvider implements UserProviderInterface { private $em; private $websiteId; private $userEntity; public function __construct($websiteListener, EntityManager $em) { $this->em = $em; $this->websiteId = $websiteListener->getWebsiteId(); // Try to get the website id from my listener, but it's method onDomainParse is not called in time $this->userEntity = 'Sybio\Bundle\CoreBundle\Entity\User'; } public function loadUserByUsername($username) { // I need the websiteId here to identify the user by its username and the website: if ($user = $this->findUserBy(array('username' => $username, 'website' => $this->websiteId))) { return $user; } throw new UsernameNotFoundException(sprintf('No record found for user %s', $username)); } // ... } ``` So any idea will be appreciate ;) I spent a lot of time to set up my authentication configuration, but now I can't get the websiteId in time, too bad :( Thanks for your anwsers ! **EDIT:** I had also other files of my authentication system to understand, I don't think I can control the provider position when loading, because they're witten in the security.yml config: **WebsiteAuthenticationProvider:** ``` // ... class WebsiteAuthenticationProvider extends UserAuthenticationProvider { private $encoderFactory; private $userProvider; /** * @param \Symfony\Component\Security\Core\User\UserProviderInterface $userProvider * @param UserCheckerInterface $userChecker * @param $providerKey * @param EncoderFactoryInterface $encoderFactory * @param bool $hideUserNotFoundExceptions */ public function __construct(UserProviderInterface $userProvider, UserCheckerInterface $userChecker, $providerKey, EncoderFactoryInterface $encoderFactory, $hideUserNotFoundExceptions = true) { parent::__construct($userChecker, $providerKey, $hideUserNotFoundExceptions); $this->encoderFactory = $encoderFactory; $this->userProvider = $userProvider; } /** * {@inheritdoc} */ protected function retrieveUser($username, UsernamePasswordToken $token) { $user = $token->getUser(); if ($user instanceof UserInterface) { return $user; } try { $user = $this->userProvider->loadUserByUsername($username); if (!$user instanceof UserInterface) { throw new AuthenticationServiceException('The user provider must return a UserInterface object.'); } return $user; } catch (UsernameNotFoundException $notFound) { throw $notFound; } catch (\Exception $repositoryProblem) { throw new AuthenticationServiceException($repositoryProblem->getMessage(), $token, 0, $repositoryProblem); } } // ... } ``` **The factory:** ``` // ... class WebsiteFactory extends FormLoginFactory { public function getKey() { return 'website_form_login'; } protected function getListenerId() { return 'security.authentication.listener.form'; } protected function createAuthProvider(ContainerBuilder $container, $id, $config, $userProviderId) { $provider = 'security.authentication_provider.sybio_website.'.$id; $container ->setDefinition($provider, new DefinitionDecorator('security.authentication_provider.sybio_website')) ->replaceArgument(0, new Reference($userProviderId)) ->replaceArgument(2, $id) ; return $provider; } } ``` **SybioWebsiteBundle (dependency):** ``` // ... class SybioWebsiteBundle extends Bundle { public function build(ContainerBuilder $container) { parent::build($container); $extension = $container->getExtension('security'); $extension->addSecurityListenerFactory(new WebsiteFactory()); } } ``` **Security:** ``` security: firewalls: main: provider: website_provider pattern: ^/ anonymous: ~ website_form_login: login_path: /login.html check_path: /login logout: path: /logout.html target: / providers: website_provider: id: sybio_website.user_provider ```
2013/02/15
[ "https://Stackoverflow.com/questions/14893043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/875519/" ]
Firewall::onKernelRequest is registered with a priority of 8 (sf2.2). A priority of 9 should ensure that your listener is called first (works for me). I had a similar problem, which was to create subdomain-specific "Campaign" sites within a single sf2.2 app: {campaign}.{domain} . Every User has many Campaigns and I, like you, wanted to prevent a User without the given Campaign from logging in. My solution was to create a Doctrine filter to add my campaign criteria to every relevant query made under {campaign}.{domain}. A kernel.request listener (with priority 9!) is responsible for activating the filter before my generic user provider tries to loadUserByUsername. I use mongodb, but the idea is similar for ORM. The best part is that I'm still using stock authentication classes. This is basically all there is to it: config.yml: ``` doctrine_mongodb: document_managers: default: filters: campaign: class: My\Filter\CampaignFilter enabled: false ``` CampaignFilter.php: ``` class CampaignFilter extends BsonFilter { public function addFilterCriteria(ClassMetadata $targetMetadata) { $class = $targetMetadata->name; $campaign = $this->parameters['campaign']; $campaign = $campaign instanceof Campaign ? $campaign->getId() : $campaign; if ($targetMetadata->hasField('campaign')) { return array('campaign' => $this->parameters['campaign']); } if ($targetMetadata->hasField('campaigns')) { return array('campaigns' => $this->parameters['campaign']); } return array(); } } ``` My listener is declared as: ``` <service id="my.campaign_listener" class="My\EventListener\CampaignListener"> <tag name="kernel.event_listener" event="kernel.request" method="onKernelRequest" priority="9" /> <argument type="service" id="doctrine.odm.mongodb.document_manager" /> </service> ``` The listener class: ``` class CampaignListener { private $dm; public function __construct(DocumentManager $dm) { $this->dm = $dm; } public function onKernelRequest(GetResponseEvent $event) { if (HttpKernelInterface::MASTER_REQUEST != $event->getRequestType()) { return; } $request = $event->getRequest(); if ($campaign = $request->attributes->get('campaign', false)) { $filters = $this->dm->getFilterCollection(); $filter = $filters->enable('campaign'); $filter->setParameter('campaign', $campaign); } } } ``` 'campaign' is available in the request here thanks to my routing configuration: ``` campaign: resource: "@My/Controller/CampaignController.php" type: annotation host: "{campaign}.{domain}" defaults: campaign: test domain: %domain% requirements: domain: %domain% ``` .. and %domain% is a parameter from config.yml or config\_dev.yml
As you can see in the SecurityExtension.php The factories used do not have any sort of priority system. It just adds your factory to the end of the array, that's it. Therefore it is impossible to put your custom authentication before that of symfony's security component. An option may be to override the DaoAuthenticationProvider class paramater with your class. I hope that symfony2 will change from factories to a registry where you can add your custom authentication with a tag and a priority because this is not open/closed enough for me.
2,431,365
This is more a use-case question, but I generate static files for a personal website using txt2tags. I was thinking of maybe storing this information in a git repository. Normally I use RCS since it's simplest, and I'm only a single user. But there just seems to be a large trend of people using git/svn/cvs/etc. for personal data, and I thought this may also be a good way to at least learn some of the basics of the tool. Obviously most of the learning is done in an environment where you collaborate. So back to the question: how would you use use a version control system such as git, to manage a personal website?
2010/03/12
[ "https://Stackoverflow.com/questions/2431365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/421924/" ]
I version all of my data. I commit each time I change it. Versionning my code allow a backup too.
Use git. Git gives you the convenience of offline commits plus the ability to push changes to other machines. I keep my configuration files (screen, shell, emacs,...) in git to have them synchronized between my machines. Also makes it dead-easy to get your custom setup on a machine you're only temporarily using. Split up projects into separate repositories (don't commit your home folder) as you can only pull whole repositories with git.
5,199,296
In eclipse I have created a .target file where I add features from remote eclipse p2 sites. Now I would like to create a local p2 site which is a copy of the aggregated features defined in the target definition (and preferably for all environments). I need this local p2 site to be used with a build system using maven3/tycho but have not found a "stable" way to do this. I have tried the following: 1) Export the target file to local directory. Problem: Does not create a p2 site just a folder with features/plugins. 2) Export the target file to local directory AND run the eclipse FeaturesAndBundlesPublisher application on the directory. Problem: This creates a p2 site but some of the original features/bundles are missing. 3) Used buckmeister to create a p2 site from a feature initialized from a .target file: [p2.site using buckmeister](http://nirmalsasidharan.wordpress.com/2010/10/09/provisioning-your-target-platform-as-local-p2-site) Problem: The original features from the content of the .target file are not preserved in the resulting p2 site. Especially this is a problem if the target file contains the feature: org.eclipse.equinox.executable.feature this feature will be missing in the resulting p2 site. 4) Copy the content of: workspace.metadata.plugins\org.eclipse.pde.core.bundle\_pool Problem: Is not a valid p2 site. Any suggestion on how to create a working (with intact features) local p2 site from remote p2 sites?
2011/03/04
[ "https://Stackoverflow.com/questions/5199296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/363603/" ]
`#!/usr/bin/env rvm 1.9.3@mygemset do ruby`
Check out this gist : <https://gist.github.com/343545> HTH
33,916,538
``` import java.util.Scanner; public class abc { public static void main(String[] args) { char[] ch = str.toCharArray(); int len = ch.length; for (int i = 0; i < len; i++) { int counte = 0; char c = str.charAt(i); for (int j = 0; j < len; j++) { if (c == ch[j]) { counte++; ch[j] = '\u0000'; } } if (counte > 0) System.out.print(c + "-" + counte + ","); } } } ``` Input: > > BBBBBbbbbbbCCooooPPPu > > > Output: > > 5-B,6-b,2-C,4-o,3-P,1-u > > > But I want the output to be: > > 6-b,5-B,4-o,3-P,2-C,1-u > > > How can I solve this?
2015/11/25
[ "https://Stackoverflow.com/questions/33916538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5604102/" ]
``` Try this below code. It may help you to generate the random date. --Creation of dummy table CREATE TABLE RANDOM_TEST ( num NUMBER, DATE_COL DATE ); --IOnsertion of dummy data INSERT INTO RANDOM_TEST SELECT LEVEL,NULL FROM DUAL CONNECT BY LEVEL < 10; -- Updating values with some random data MERGE INTO RANDOM_TEST rt USING (SELECT NUM FROM RANDOM_TEST )A ON (rt.num = a.num) WHEN MATCHED THEN UPDATE SET DATE_COL = SYSDATE+A.num; COMMIT; ```
for insert you can use ``` insert into test_table SELECT level,TO_DATE( TRUNC( DBMS_RANDOM.VALUE(TO_CHAR(DATE '2015-12-01','J'),TO_CHAR(DATE '2016-08-01','J'))),'J') FROM DUAL connect by level<100; ``` for update you can try this... ``` UPDATE vish_test a SET a.idate = (SELECT TO_DATE( TRUNC( DBMS_RANDOM.VALUE(TO_CHAR(DATE '2015-12-01','J'),TO_CHAR(DATE '2016-08-01','J'))),'J') FROM DUAL) where rank_id in(select rank_id from vish_test); ```
38,091,542
More of a curious question rather than solving an actual problem. How do frameworks like angular contain CSS within a component and prevent the CSS from leaking all over the page?
2016/06/29
[ "https://Stackoverflow.com/questions/38091542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4093621/" ]
One thing you have to be clear is that HTML loaded sequentially. In your code ``` ........................... <script src="index.js"></script> ................ .................... <h1 id="test">Should this change?!</h1> ``` Here the JavaScript loaded first then the remaining html. As the JavScript will execute when it is loaded for the way you write it, it will not find the later html tags. So it will not get that element (`<h1 id="test">Should this change?!</h1>`). But if you load the JS later then it will work as expected. ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Design All</title> </head> <body> <h2>------------------------</h2> <h1 id="test">Should this change?!</h1> <h2>------------------------</h2> </body> <script src="index.js"></script> ``` That's why experts suggest to load JS at the end.
``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Design All</title> <script src="index.js"></script> </head> <body onload = "chng()"> <h2>------------------------</h2> <h1 id="test">Should this change?!</h1> <h2>------------------------</h2> </body> </html> ``` **index.js** ``` // JavaScript function chng(){ var product = "Camera"; var price = 130; var introduction = document.getElementById("test"); introduction.innerHTML = product + " " + price; } ```
46,747
I've tried a few time to roast gammon, typically my method is to soak the gammon and then roast for a few hours. The result is typically just this side of editable. I've even tried boiling it first (after a suggestion that this removes the salt), but to no avail. Does anyone have any suggestions?
2014/08/30
[ "https://cooking.stackexchange.com/questions/46747", "https://cooking.stackexchange.com", "https://cooking.stackexchange.com/users/1710/" ]
Soak at least overnight. In addition to that, consider a sweet glaze like apricot, or an acidic one like one that includes cider vinegar. Best yet might be all three, an overnight soak (change the water a few times) and a sweet, acidic glaze. If you *still* find it too salty, go ahead and try boiling briefly in fresh water (blanching) after soaking, and then plunging in ice water before you continue to glaze and roast. If all of that isn't enough, and you are choosing the lowest salt gammon available to you, then gammon isn't your thing. Try a fresh ham instead.
Heavily salted meats, like gammon, speck, country ham, proscuito di parma and such aren't intended to be eaten as a steak or roast. They're typically used in small amounts as flavoring in other dishes. If you're looking to roast a ham, you'll want to find a different variety that isn't as heavily salted. There are 'fresh hams' which isn't cured at all, and 'city hams' which are cured, but still need refrigeration for long-term storage.
266,009
I have a function called `USB()`, that will observe a [USB stick's](https://en.wikipedia.org/wiki/USB_flash_drive) insertion and delete files inside of it, if there are some: ``` import os import shutil # 1. Check and clean USB def USB(): usb_inserted = os.path.isdir("F:") # <-- returns boolean...checks whether a directory exists if usb_inserted == False: print("\n\nUSB stick is not plugged in. Waiting for connection...") while usb_inserted == False: # wait """ updating variable, because it takes only the return value of function 'isdir()' and stays the same regardless of the fact, that 'isdir()' changed """ usb_inserted = os.path.isdir("F:") continue SECURITY_FILE = "System Volume Information" if os.listdir("F:") == [SECURITY_FILE] or os.listdir("F:") == []: # if list of files contains only the security file (is empty) print("\nUSB flash is already empty.") # send a message and continue else: files = os.listdir("F:") # list of names of files in the usb flash, that will be deleted if SECURITY_FILE in files: """ taking out the security file from the list, because attempting to delete it causes 'PermissionError [WinError 5]' exception """ files.remove(SECURITY_FILE) for file in files: # Loop through the file list if os.path.isfile(f"F:\\{file}"): # if it's a file os.remove(f"F:\\{file}") # Delete the file elif os.path.isdir(f"F:\\{file}"): # if it's a directory/folder shutil.rmtree(f"F:\\{file}") # remove the folder print("\nAll files/folders are deleted from USB.") USB() ``` Is there anything, that can be improved in terms of cleaner code or things that I could have missed while testing?
2021/08/12
[ "https://codereview.stackexchange.com/questions/266009", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/231109/" ]
A production-grade solution would not have a polling loop at all, and would rely on a filesystem change notification hook. There are [many, many ways](https://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes) to do this with varying degrees of portability and ease of use; if I were you I'd use something portable and off-the-shelf like [watchdog](https://pythonhosted.org/watchdog/).
Making a program to delete everything on a USB stick is dangerous. Consider listing current contents and asking for confirmation, to make sure you don't accidentally wipe the wrong stick or drive.
65,332,141
After upgrading my MacBook Pro to OS X 11.1 Big Sur, I am unable to get compilation of c++ programs using gcc to work. I am using CLion with CMake, and I get the following error when reloading the CMake configuration ``` ld: library not found for -lgcc_s.10.4 ``` The things that I have tried are installing Xcode, it installed without error. I have tried to create a symlink as suggested here <https://github.com/Paxa/fast_excel/issues/33> ``` $ cd /usr/local/lib $ sudo ln -s ../../lib/libSystem.B.dylib libgcc_s.10.4.dylib ``` It appears that the library `libSystem.B.dylib` is not present. Some sites mention that the libraries starting with Big Sur reside in some "shared cache", which I have no idea of what it is and how to access it, let alone make ld access it on its own. Any suggestions on how to solve this are very welcome. Thank you!
2020/12/16
[ "https://Stackoverflow.com/questions/65332141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4567066/" ]
[According to this answer](https://stackoverflow.com/questions/40034457/os-x-installed-gcc-links-to-clang) you should use: `g++-10 -o main main.cpp` * The correct path of brew installed g++ in MacOS is: ``` $ which g++-10 > /usr/local/bin/g++-10 -- $ which g++ > /usr/bin/g++ //this is alias of clang (same for lyb) ``` --- If you use `CMakeLists.txt` file you will configure it like this: ``` set(CMAKE_CXX_COMPILER "/usr/local/bin/g++-10" CACHE STRING "C compiler" FORCE) set(CMAKE_C_COMPILER "/usr/local/bin/gcc-10" CACHE STRING "C++ compiler" FORCE) set(CMAKE_CXX_STANDARD 17) ```
I spent hours trying to solve this compilation problem with cmake, the original statement in `CMakeLists.txt` for library linkage is! ``` link_directories(/usr/local/lib) target_link_libraries(Program libsndfile.dylib) ``` With error message after make: > > ld: library not found for -lsndfile > > > The solution that works is to add the entire path like this: ``` target_link_libraries(Program /usr/local/lib/libsndfile.dylib) ``` There is no need to have this in Ubuntu, but somehow the new MacOS requires it.