qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
16,972,295
So i'm trying to create a simple String struct which will contain the text of the string and the size of it, at least for now. However I'm having issues allocating my struct. Right now i'm simply trying to get a size of 1 character to work, but its simply crashing at this point and i don't know what i'm doing wrong with the allocation, please help. ``` #include <stdio.h> #include <stdlib.h> typedef struct{ char* text; int size; }String; String* getString(); int main(int argc, char** argv){ String* str1 = getString(); printf("%s",str1->text); free(str1); return 0; } String* getString(){ String* str = (String*)malloc(sizeof(String)); scanf("%s",str->text); str->size++; return str; } ```
2013/06/06
[ "https://Stackoverflow.com/questions/16972295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1998810/" ]
You need to allocate memory for the structure but also for `text` string. ``` scanf("%s",str->text); ``` `str->text` is an uninitialized pointer.
1,614,501
> > Find the last $4$ digits of $2016^{2016}$. > > > Technically I was able to solve this question by I used Wolfram Alpha and modular arithmetic so the worst I had to do was raise a $4$ digit number to the $9$th power. I would do $2016^2 \equiv 4256^2 \equiv \cdots$ and then continue using the prime factorization of $2016$. I am wondering if there is a better way to solve this.
2016/01/16
[ "https://math.stackexchange.com/questions/1614501", "https://math.stackexchange.com", "https://math.stackexchange.com/users/297795/" ]
$$\begin{align}(2000+16)^{2016}&\equiv 2016\cdot 2000\cdot 16^{2015} + 16^{2016}&\pmod{10000}\\ &\equiv 2000+16^{2016}&\pmod{10000} \end{align}$$ So you need to find the last four digits of $16^{2016}$ and add $2000$. You can actually reduce the exponent modulo $500$, because $16^{2016}\equiv 16^{16}\pmod{625}$ and $16^{2016}\equiv 0\equiv 16^{16}\pmod{16}$. So you need to compute $16^{16}\mod{10000}$. This can be done by repeated squaring: $$16^2=256\\ 16^4=256^2\equiv 5536\pmod{10000}\\ 16^8\equiv 5536^2\equiv 7296\pmod{10000}\\ 16^{16}\equiv 7276^2\equiv 1616\pmod{10000}\\ $$ So the result is $2000+1616=3616$.
7,757,506
I have the following code: ``` <tr> <td class="add_border_bold" nowrap="nowrap">Schedule Saved (days)</td> <td width="100%" class="add_border"> <%# Eval("schedule_saved_days", "{0:0,0}")%> &nbsp; </td> </tr> <tr> <td class="add_border_bold" nowrap="nowrap">Scheduled Saved in Months</td> <td width="100%" class="add_border"> <%# Eval("schedule_saved_days", "{0:0,0}")%> &nbsp; </td> </tr> ``` What the requirement is, is to display the second 'schedule saved' in months, rather than days (for some reason they can't figure it out based on days). previously in coldfusion i had just been dividing the number by 30. i had tried a couple different things like `<%# Eval("schedule_saved_days"/30, "{0:0,0.00}")%>` and `<%# Eval("schedule_saved_days/30)%>` just to get something to work. i'm sure this is a quick fix and my google-fu is failing me. Thanks in advance.
2011/10/13
[ "https://Stackoverflow.com/questions/7757506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/397344/" ]
Try something like this: ``` <%#(Convert.ToDecimal(Eval("schedule_saved_days")) / 30).ToString("0,0")%> ```
58,909,925
I need to call a function when modal close. My code as follows, ``` function openModal(divName) { $("#"+divName+"Modal").modal({ overlayClose: false, closeHTML: "<a href='#' title='Close' class='modal-close'>X</a>", onShow: function (dialog) { $('#simplemodal-container').css({ 'width': 'auto', 'height': 'auto', 'padding-bottom': '1000px' }); var tmpW = $('#simplemodal-container').width() / 2 var tmpH = $('#simplemodal-container').height() / 2 $('#simplemodal-container').css({ 'margin-left': tmpW * -1, 'margin-top': tmpH * -1 }); }, close:onClose, onClose: ModalClose(), opacity: 50, persist: true }); } ``` I tried two ways to call a function as follows, but both not working 1st way ``` function onClose() { alert('called'); } ``` 2nd way ``` $('.resetbutton').click(function () { alert('called'); } ```
2019/11/18
[ "https://Stackoverflow.com/questions/58909925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3703534/" ]
For `Grouper` need datetimes, so format of datetimes is changed by [`MultiIndex.set_levels`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.MultiIndex.set_levels.html) after aggregation and also added `closed='left'` for left closing bins: ``` df1['date'] = pd.to_datetime(df1['date']) df2 = df1.groupby([pd.Grouper(key='date', freq='W-MON', closed='left'), 'Company', 'Email'])['Email'].count() new = ((df2.index.levels[0] - pd.to_timedelta(7, unit='d')).strftime('%B%d') + ' - '+ df2.index.levels[0].strftime('%B%d') ) df2.index = df2.index.set_levels(new, level=0) print (df2) date Company Email October07 - October14 abc [email protected] 2 [email protected] 1 def [email protected] 1 xyz [email protected] 1 October14 - October21 abc [email protected] 1 def [email protected] 1 xyz [email protected] 1 [email protected] 1 Name: Email, dtype: int64 ``` For first DataFrame use `sum` per first and second levels and reshape by [`Series.unstack`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unstack.html): ``` df3 = df2.sum(level=[0,1]).unstack(fill_value=0) print (df3) Company abc def xyz date October07 - October14 3 1 1 October14 - October21 1 1 2 ```
1,996,482
I thought I would write some quick code to download the number of "fans" a Facebook page has. For some reason, despite a fair number of iterations I've tried, I can't get the following code to pick out the number of fans in the HTML. None of the other solutions I found on the web correctly match the regex in this case either. Surely it is possible to have some wildcard between the two matching bits? The text I'd like to match against is "**6 of X fans**", where X is an arbitrary number of fans a page has - I would like to get this number. I was thinking of polling this data intermittently and writing to a file but I haven't gotten around to that yet. I'm also wondering if this is headed in the right direction, as the code seems pretty clunky. :) ``` import urllib import re fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft') pattern = "6 of(.*)fans" #this wild card doesnt appear to work? compiled = re.compile(pattern) for lines in fbhandle.readlines(): ms = compiled.match(lines) print ms #debugging if ms: break #ms.group() print ms fbhandle.close() ```
2010/01/03
[ "https://Stackoverflow.com/questions/1996482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207201/" ]
``` import urllib import re fbhandle = urllib.urlopen('http://www.facebook.com/Microsoft') pattern = "6 of(.*)fans" #this wild card doesnt appear to work? compiled = re.compile(pattern) ms = compiled.search(fbhandle.read()) print ms.group(1).strip() fbhandle.close() ``` You needed to use `re.search()` instead. Using `re.match()` tries to match the pattern against the *whole* document, but really you're just trying to match a piece inside the document. The code above prints: `79,110`. Of course, this will probably be a different number by the time it gets run by someone else.
28,664,098
I'm extremely new to code writing, so please forgive any ignorance on my part. I have a simple bit of code in which I would like to make the visibility of a couple of "outerCircle" divs turn off when the user clicks anywhere on the page. I have tried several ways, but it's just not working. If anyone has a suggestion, I would greatly appreciate it. Here is what I have so far: ``` <body onload = "startBlink()" onclick = "onOff()"> <p id = "title">Click anywhere to turn the outer circles on or off.</p> <div class = "container" onclick = "onOff()"> <div class = "outerCircle" id = "outerLeftCircle"> <div class = "innerCircle" id = "innerLeftCircle"> </div> </div> <div class = "outerCircle" id = "outerRightCircle"> <div class = "innerCircle" id = "innerRightCircle"> </div> </div> </div><!-- Closes the container div --> <script> // This function blinks the innerCircle div // function startBlink(){ var colors = ["white","black"]; var i = 0; setInterval(function() { $(".innerCircle").css("background-color", colors[i]); i = (i+1)%colors.length; }, 400); } // This function turns the outerCircle divs on or off // function onOff() { alert("Entering function now"); if (getElementById(".outerCircle").style.visibility = "visible") { getElementById(".outerCircle").style.visibility = "hidden"; getElementById(".outerLeftCircle").style.visibility = "hidden"; getElementById(".outerRightCircle").style.visibility = "hidden"; } else { getElementById(".outerCircle").style.visibility = "visible"; getElementById(".outerLeftCircle").style.visibility = "visible"; getElementById(".outerRightCircle").style.visibility = "visible"; } } </script> ```
2015/02/22
[ "https://Stackoverflow.com/questions/28664098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4484550/" ]
edited my answer since I've been learning a thing or two these last couple of weeks ;) you need an apostrophe around to: and cc: lists with more than one recipient you also need an apostrophe around any main body text or attachments you're going to send if you put an apostrophe into your VBA editor, it just comments it out, so you can get away with that by using Chr(39) also, as the documentation suggests, you need attachment='file:///c:/test.txt' which includes the file:/// I've included an example from something I've been working on below ``` Dim reportTB As Object Set reportTB = VBA.CreateObject("WScript.Shell") Dim waitOnReturn As Boolean: waitOnReturn = True Dim windowStyle As Integer: windowStyle = 1 reportTB.Run "thunderbird.exe -compose to=bfx_" & LCase(show) & "[email protected],subject=[" & show & "] EOD Report " _ & prjDate & ",body=" & Chr(39) & "Hi " & UCase(show) & "ers,<br><br>Today's end of day report is attached.<br>" & _ "Any questions let me know.<br><br>Edi " & Chr(39) & ",attachment=" & Chr(39) & reportPath & Chr(39), windowStyle, waitOnReturn ``` Hope that helps :)
13,357,583
Which Platforms are supported for the IBM Social Business Toolkit SDK? Can I run the SDK on an IBM Domino/XWork server?
2012/11/13
[ "https://Stackoverflow.com/questions/13357583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1167759/" ]
The following platforms are supported: * WebSphere Application Server 7 * WebSphere Portal 8 * Domino Server 8.5 * Tomcat 7 So yes, you can use the SDK on an IBM Domino/XWork Server.
2,535,958
I have obtained the crosshair cursor from NSCursor crosshairCursor. Then, how can i change to it. I don't want to call enclosingScrollView to setDocumentCursor as [[view enclosingScrollView] setDocumentCursor:crosshaircursor ];
2010/03/29
[ "https://Stackoverflow.com/questions/2535958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/276989/" ]
I found out an easy way to do this: setStyle("arrowButtonWidth", 0); In my custom combobox, I set the initial width of the arrow button to 0. Then in the List change event, ``` addEventListener(ListEvent.CHANGE, changeHandler); ``` if the size of the dataprovider is greater than 1, the arrow width is set back to (say) 20 ``` setStyle("arrowButtonWidth", 20); ``` This approach is much simpler than the above approaches. If you know any pitfall of my approach, please share.
274,229
How can we convert a .tif with .tfw .htm into a raster KML/KMZ file to open in google earth? I have a .tif file along with a .tfw and .htm files. I wanted to open it in Google Earth. Converting the .tif into a raster in KML/KMZ format will solve the problem. I was working in MATLAB mapping toolbox and did not find a solution in there. A Matlab or any opensource solution will work.
2018/03/09
[ "https://gis.stackexchange.com/questions/274229", "https://gis.stackexchange.com", "https://gis.stackexchange.com/users/116129/" ]
You can use [`ST_Dimension`](https://postgis.net/docs/ST_Dimension.html), which returns the largest dimension of a GeometryCollection's components. For an undoubtedly excellent reason that's well-rooted in thoughtfully-drafted specifications, [`ST_Dimension`](https://postgis.net/docs/ST_Dimension.html) produces dimensions starting at `0`, while [`ST_CollectionExtract`](https://postgis.net/docs/ST_CollectionExtract.html) accepts dimensions beginning with `1`. (In other words, [`ST_Dimension`](https://postgis.net/docs/ST_Dimension.html) uses `2` to indicate a polygon, while [`ST_CollectionExtract`](https://postgis.net/docs/ST_CollectionExtract.html) uses `3` to indicate a polygon.) So to extract the highest-dimension geometries from a GeometryCollection, you would use: ``` SELECT ST_CollectionExtract(geom, 1 + ST_Dimension(geom)) FROM my_data; ```
41,505,806
``` create table abc(name character(n), name1 character varying(n), name2 text); ``` In the above query what is the limit of 'n'? ``` create table abc(name character(), name1 character varying(), name2 text); ``` In the above query what it will take if we not specify any value to 'n'?
2017/01/06
[ "https://Stackoverflow.com/questions/41505806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6853242/" ]
[Quote from the manual](https://www.postgresql.org/docs/current/static/datatype-character.html) > > The notations `varchar(n)` and `char(n)` are aliases for `character varying(n)` and `character(n)`, respectively. `character` without length specifier is equivalent to `character(1)`. If `character varying` is used without length specifier, the type accepts strings of any size. > > > and further down: > > In any case, the longest possible character string that can be stored is about 1 GB > > >
5,333,734
I am messing around trying to write a small web crawler. I parse out a url from some html and sometimes I get a php redirect page. I am looking for a way to get the uri of the redirected page. I am trying to use System.Net.WebRequest to get a a stream using code like this ``` WebRequest req = WebRequest.Create(link); Stream s = req.GetResponse().GetResponseStream(); StreamReader st = new StreamReader(WebRequest.Create(link).GetResponse().GetResponseStream()); ``` The problem is that the link is a PHP redirect, so the stream is always null. How would I get the URI to the page the php is redirecting?
2011/03/17
[ "https://Stackoverflow.com/questions/5333734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/582080/" ]
``` HttpWebRequest req = (HttpWebRequest)WebRequest.Create(link); req.AllowAutoRedirect = true; reg.AutomaticDecompression = DecompressionMethods.GZip; StreamReader _st = new StreamReader(_req.GetResponseStream(), System.Text.Encoding.GetEncoding(req.CharacterSet)); ``` the AllowAutoRedirect will automatically take you to the new URI; if that is you're desired effect. The AutomaticDecompression will auto decompress compressed responses. Also you should be executing the get response stream part in a try catch block. I my exp it throws alot of WebExceptions. Since you're experimenting with this technology make sure you read the data with the correct encoding. If you attempt to get data from a japanese site without using Unicode then the data will be invalid.
2,921,389
I am creating a doc file and writing a text containing ^m in it and facing issue. Does this ^m is a special character for doc file ? If I replace ^m with some other characters (like ^m with >m or any other) then It works fine. I faced this issue with other characters too like ^a and few other. What could be the solution ?
2010/05/27
[ "https://Stackoverflow.com/questions/2921389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/276279/" ]
^M -- as in: Control-M -- is often used to type a 'carriage return' character (ASCII-code 13 in decimal, 0D in hex).
53,774,145
``` public class Demo { public static void main(String[] args) { int a=10,b=20; short c = (a<b)?a:b; System.out.println(c); } } ``` **this is my program and I got below error why I'm not getting** ``` "Demo.java:6: error: incompatible types: possible lossy conversion from int to short short c = (a<b)?a:b; 1 error" ``` **And I write "final" with variable declaration and it works fine. But why does this happen?** ``` public class Demo { public static void main(String[] args) { final int a=10,b=20; short c = (a<b)?a:b; System.out.println(c); } } ```
2018/12/14
[ "https://Stackoverflow.com/questions/53774145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10563008/" ]
This is specified in the Java Language Specification [§5.2 Assignment Contexts](https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.2): > > Assignment contexts allow the use of one of the following: > > > ... > > > In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int: > > > * A narrowing primitive conversion may be used if the type of the variable is `byte`, `short`, or `char`, and the value of the constant expression is representable in the type of the variable. > > > The expression with ternary operator that you have used in the second snippet is a constant expression, because all the variables used in that expression are `final`. In addition, `10` is representable in `short`. Therefore, a narrowing primitive conversion from `int` to `short` is allowed. This makes sense, doesn't it? The compiler knows all about the values of the final variables, so this can surely be allowed. In the first case however, `a` and `b` are not constant variables, so `(a<b)?a:b` is not a constant expression, so an explicit cast is needed: ``` short c = (short)((a<b)?a:b); ```
53,773,278
I created two Rectangles. I want to add events on them. For example when mouse hover on one, the hovered one will change color, can do resize or drag them(rectangles) to other place... I was just wondering if I could control the drawn graphic, or it will like *Microsoft Paint* that after you painted, the object can not be operate unless you clear canvas and do redraw. Is it possible to control a drawn graphic, thanks for any suggestion. **Simple code of my drawn graphics** ``` private void Form1_Paint(object sender, PaintEventArgs e) { // Create pen. Pen blackPen = new Pen(Color.Black, 3); // Create rectangle. Rectangle rect1 = new Rectangle(20, 20, 250, 250); Rectangle rect2 = new Rectangle(70, 70, 150, 150); // Draw rectangle to screen. e.Graphics.FillRectangle(Brushes.DeepSkyBlue, rect1); e.Graphics.FillRectangle(Brushes.LightBlue, rect2); } ```
2018/12/14
[ "https://Stackoverflow.com/questions/53773278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10309167/" ]
Also, you can create your own control like: ``` class RectangleControl : Control { public void FillRectangle(Color color) { this.BackColor = color; } } ``` Then : ``` private void Form1_Paint(object sender, PaintEventArgs e) { RectangleControl rect1 = new RectangleControl() { Parent = this, Left = 20, Top = 20, Width = 250, Height = 250 }; rect1.FillRectangle(Color.DeepSkyBlue); RectangleControl rect2 = new RectangleControl() { Parent = rect1, Left = 50, Top = 50, Width = 150, Height = 150 }; rect2.FillRectangle(Color.LightBlue); rect1.MouseHover += Rect1_MouseHover; rect2.MouseLeave += Rect2_MouseLeave; } private void Rect2_MouseLeave(object sender, EventArgs e) { (sender as RectangleControl).BackColor = Color.Yellow; } private void Rect1_MouseHover(object sender, EventArgs e) { (sender as RectangleControl).BackColor = Color.LightBlue; } ```
68,683,848
I have a question. I am new and still learning :) I want to create a review block with gutenberg. And the rating has to be stars. But for some reason i dont get it worked. Maybe i am doing it wrong, maybe it isn't possible. I hope some on could explain it to me. For now i have created a selectcontrol and this works. When selecting A i get A. But i want to replace value: A for a star: What i have > > > ``` > <SelectControl > multiple > label={ __( 'Select some users:' ) } > value={ testimonial.selectcontrol } // e.g: value = [ 'a', 'c' ] > onChange={ (value) => handleTestimonialChange('selectcontrol', value, index ) } > options={ [ > { value: null, label: 'Select a User', disabled: true }, > { value: 'a', label: 'User A' }, > { value: 'b', label: 'User B' }, > { value: 'c', label: 'User c' }, > ] } > /> > > ``` > > What i want > > > ``` > <SelectControl > multiple > label={ __( 'Select some users:' ) } > value={ testimonial.selectcontrol } // e.g: value = [ 'a', 'c' ] > onChange={ (value) => handleTestimonialChange('selectcontrol', value, index ) } > options={ [ > { value: null, label: 'Select a User', disabled: true }, > { value: <i class="fas fa-star"></i>, label: 'User A' }, > { value: 'b', label: 'User B' }, > { value: 'c', label: 'User c' }, > ] } > /> > > ``` > > The value returns in this code: > > selectcontrolDisplay =props.attributes.testimonial.map( ( testimonial, index ) => { > return <span key={ index }>{testimonial.selectcontrol}; > } ); > > > What i get back in the backed from Wordpress is object object. Like mentiond above, i am not sure or it possible. If some on could explain something different with the same result. I am happy to. If the full code is needed please let me know.
2021/08/06
[ "https://Stackoverflow.com/questions/68683848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15984384/" ]
From `console.log` it seems data are just fine. Do not get distracted by any `__ob__` stuff in the console. It is [normal Vue reactivity](https://v2.vuejs.org/v2/guide/reactivity.html#How-Changes-Are-Tracked) When I inspect your example site, all seems fine - Vue Dev tools shows `:options` are bound just fine. My theory is this is not problem of data or `v-select` (mis)configuration (there is one error but not significant - `v-select` has no `code` prop) but rather problem with conflicting CSS (maybe because of JQuery but it is hard to say for sure) See example below ....works just fine ```js Vue.component('v-select', VueSelect.VueSelect); const vm = new Vue({ el: '#app', data() { return { categorySelectionItems: [{ "code": 1, "label": "Broadcast" }, { "code": 2, "label": "Classroom" }, { "code": 3, "label": "Collaboration" }, { "code": 5, "label": "Entertainment" }, { "code": 4, "label": "Esports" }, { "code": 6, "label": "Experimental" }, { "code": 7, "label": "Marketing" }, { "code": 8, "label": "Music" }, { "code": 12, "label": "Other" }, { "code": 9, "label": "Radio" }, { "code": 10, "label": "Venue" }, { "code": 11, "label": "Worship" }], selection_category_id: null, platforms: [{ label: 'Canada', code: 'ca' }], selection_platform_id: null, }; }, }) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.14/vue.js"></script> <!-- use the latest vue-select release --> <script src="https://unpkg.com/vue-select@latest"></script> <link rel="stylesheet" href="https://unpkg.com/vue-select@latest/dist/vue-select.css"> <div id="app"> <div> <div class="row"> <div class="form-group col-md-6"> <label>Select category</label> <div class="select-container"> <v-select v-model="selection_category_id" label="label" :options="categorySelectionItems" class="form-control" placeholder="Select option"></v-select> </div> <pre>selection_category_id: {{ selection_category_id }}</pre> </div> </div> <div class="form-group col-md-6"> <label>Platform</label> <div class="select-container"> <div class="select-container"> <v-select v-model="selection_platform_id" label="label" :options="platforms" class="form-control" placeholder="Select option"></v-select> </div> <pre>selection_platform_id: {{ selection_platform_id }}</pre> </div> </div> </div> </div> ```
17,519,572
Can not figure out why this error keeps getting thrown: ``` -[__NSCFString bytes]: unrecognized selector sent to instance 0xc3eb200 ``` for this code: ``` - (void)parser:(SBJsonStreamParser *)parser foundObject:(NSDictionary *)dict { empty = NO; for (NSDictionary *valueDictionary in [dict objectForKey:@"Contacts"]) { if ([[valueDictionary objectForKey:@"Empty"] isEqualToString:@"YES"]){ empty = YES; contactsArray = [[NSMutableArray alloc] init]; }else{ Thecontacts = [valueDictionary objectForKey:@"Contacts"]; } dataRepresentingSavedArray = Thecontacts; if (dataRepresentingSavedArray != nil) { **Causes Error->** NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray]; contactsArray = [[NSMutableArray alloc] initWithArray:oldSavedArray]; } } [table reloadData]; } ``` The value for [valueDictionary objectForKey:@"Contacts"] is ``` <62706c69 73743030 d4010203 0405082b 2c542474 6f705824 6f626a65 63747358 24766572 73696f6e 59246172 63686976 6572d106 0754726f 6f748001 ab090a11 1718191a 2228292a 55246e75 6c6cd20b 0c0d0e56 24636c61 73735a4e 532e6f62 6a656374 738006a2 0f108002 8007d20b 0c0d1380 06a31415 16800380 0480055b 416e6472 65772044 756e6e5f 1018616e 64726577 4064756e 6e2d6361 72616261 6c692e63 6f6d5661 63636570 74d21b1c 1d215824 636c6173 7365735a 24636c61 73736e61 6d65a31e 1f205e4e 534d7574 61626c65 41727261 79574e53 41727261 79584e53 4f626a65 63745e4e 534d7574 61626c65 41727261 79d20b0c 0d248006 a3252627 80088009 800a5e4a 6f686e20 4170706c 65736565 645f1016 4a6f686e 2d417070 6c657365 6564406d 61632e63 6f6d5561 6c657274 12000186 a05f100f 4e534b65 79656441 72636869 76657200 08001100 16001f00 28003200 35003a00 3c004800 4e005300 5a006500 67006a00 6c006e00 73007500 79007b00 7d007f00 8b00a600 ad00b200 bb00c600 ca00d900 e100ea00 f900fe01 00010401 06010801 0a011901 32013801 3d000000 00000002 01000000 00000000 2d000000 00000000 00000000 00000001 4f> ``` I have been playing with the code and are close to final resolution it is nasty, but it will work until i find a work around. SO oldSavedArray prints the array but when i go to print this ``` contactsArray = [[NSMutableArray alloc] initWithArray:oldSavedArray]; ``` i receive this. ``` [__NSCFString count]: unrecognized selector sent to instance 0xabab970 ``` the output of oldSavedArray is ( ( "John Appleseed", "[email protected]", alert ), ( "Andrew Dunn", "[email protected]", accept ) ) ``` url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; [AsyncURLConnection request:url completeBlock:^(NSData *data) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ dispatch_async(dispatch_get_main_queue(), ^{ NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; if (![myString isEqualToString:@"0"]) { [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:myString] forKey:@"savedArray"]; NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"savedArray"]]; contactsArray = [[NSMutableArray alloc] initWithArray:oldSavedArray]; [table reloadData]; }else{ contactsArray = [[NSMutableArray alloc] init]; } }); }); } errorBlock:^(NSError *errorss) { }]; ```
2013/07/08
[ "https://Stackoverflow.com/questions/17519572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/663192/" ]
The error message shows that ``` Thecontacts = [valueDictionary objectForKey:@"Contacts"]; ``` returns a `NSString` object, not a `NSData` object as you expected. I assume that you created the JSON using something like ``` [NSString stringWithFormat:@"%@", Contacts] ``` which uses the `description` method of `NSData` and returns a string like ``` <62706c69 73743030 d4010203 0405082b ... > ``` or perhaps SBJson does that implicitly. You *could* parse that string and convert it back to `NSData`. But that would be a fragile approach because the actual `description` format of `NSData` is not documented and might change in the future. Note that JSON does not know "raw binary data", only dictionaries, arrays, strings and numbers. You should convert the `NSData` to `NSString` (using one of the publicly available Base64 converters) and store the Base64 string in the JSON.
38,896,260
I am trying to fill my webpage with content based on content stored in a database. However, I would like to skip the first item; I want to start looping from the second item. How can I achieve this? ``` @foreach($aboutcontent as $about) <div class="col-md-4 text-center"> <div class="thumbnail"> <img id="" class="img-responsive" src="images/{{ $about->aboutimg }}" alt=""> <div class="caption"> <h3>{{ $about->aboutname }}</h3> <p>{{ $about->aboutinfo }}</p> </div> </div> </div> @endforeach ```
2016/08/11
[ "https://Stackoverflow.com/questions/38896260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5875799/" ]
As of Laravel 5.4, whenever you use `foreach` or `for` within blade files you will now have access to a [$loop variable](https://laravel.com/docs/5.4/blade#the-loop-variable). The $loop variable provides many useful properties and methods, one of them being useful here, for skipping the first iteration. See the example below, which is a much cleaner way of achieving the same result as the other older answers here: ``` @foreach ($rows as $row) @if ($loop->first) @continue @endif {{ $row->name }}<br/> @endforeach ```
13,828,661
I am having trouble with an hw problem in my CS class. The problem has to do with creating a class in python. Heres the prompt Your class should be named Student, and you should define the following methods: `__init__`: This method initializes a Student object. Parameters: a name, a GPA, and a number of units taken • Should initialize instance variables for name, GPA, and units based on the information that was passed in. If the GPA or number of units is negative, sets it to 0. (Donʼt worry about non-numeric values in this method.) update: This method updates the instance variables of the Student object if the Student takes a new class. • Parameters: units for the new class, grade points earned (as a number) in the new class. • Should modify the instance variable for units to add the units for the new class • Should modify the GPA to incorporate the grade earned in the new class. (Note that this will be a weighted average using both the unit counts and both sets of GPAs.) get\_gpa: This method should return the studentʼs GPA. get\_name: This method should return the studentʼs name. **Heres what i have** ``` class Student: def__init__(self,name,GPA,units): if units <0: units=0 if GPA<0: GPA=0 self.name=name self.GPA=GPA self.units=units def update(newunits,GPE): ``` thats all i can come up with
2012/12/11
[ "https://Stackoverflow.com/questions/13828661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786698/" ]
Let’s go through some points which will hopefully help you: ### Constructor (`__init__`) > > If the GPA or number of units is negative, sets it to 0. > > > So you probably want to check each separately: ``` if units < 0: units = 0 if GPA < 0: GPA = 0 ``` ### Update method Methods in general take a reference to the current object as the first argument, named `self` per convention (just as in `__init__`). So your update method declaration should look like this: ``` def update(self, newunits, GPE): ... ``` > > Should modify the instance variable for units to add the units for the new class > > > Just as you did in the constructor, you can access instance variables using `self.varname`. So you probably want to do something like this: ``` self.units += newunits ``` > > Should modify the GPA to incorporate the grade earned in the new class. (Note that this will be a weighted average using both the unit counts and both sets of GPAs.) > > > Just as you update `self.units` you have to update `self.GPA` here. Unfortunately, I have no idea what a GPA is and how it is calculated, so I can only guess: ``` self.GPA = ((self.GPA * oldunits) + (GPE * newunits)) / self.units ``` Note that I introduced a new local variable `oldunits` here that simply stores the units temporarily from *before* it was updated (so `oldunits = self.units - newunits` after updating). ### get\_gpa and get\_name These are simple getters that just return a value from the object. Here you have an example for the **units**, i.e. you should figure it out for the actual wanted values yourself: ``` def get_units (self): return self.units ``` Note that it’s rather unpythonic to have getters (`get_x` methods), as you would just expect people to access the properties directly (while handling them with care).
10,830,183
I have a working node.js / express based server and am using jade for templating. Usually there is no problem but a couple of times every day I get an error message when requsting any page. The error is 'failed to locate view'. I don't know why i get this error since it worked fine just minutes before. The question however is how I can force a crash on this event, for example: ``` res.render('index.jade', {info: 'msg'}, function(error, ok) { if (error) throw new Error(''); // Proceed with response }; ``` How would I do this? And how would I proceed with the response? thank you.
2012/05/31
[ "https://Stackoverflow.com/questions/10830183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1306716/" ]
You can add an error handling middleware. ``` app.use(function handleJadeErrors(err, req, res, next) { // identify the errors you care about if (err.message === 'failed to locate view') { // do something sensible, such as logging and then crashing // or returning something more useful to the client } else { // just pass it on to other error middleware next(err); } }); ```
10,965,285
I am trying to loop over an array. However, I would like to add a 15 second delay between each array value. This will write value 1 to console, then count down 15 seconds and write value 2 to console, and so on. I'm not sure exactly how to do this. My code as of now just outputs the numbers 15 all the way to 1 on the console at once with no actual count down and no array values. array ``` ["l3", "l4", "l5", "l6", "l7", "l8", "l9", "l10", "l11", "l12", "l13", "l14", "l15", "l16"] ``` code ``` var adArray = []; // get links with class adfu var adfuClass = document.getElementsByClassName('adfu'); for (var i = 0; i < adfuClass.length; i++) { var ids = adfuClass[i].id var newIds = ids.replace(/tg_/i, "l"); adArray.push(newIds); } // get links with class ad30 var ad30Class = document.getElementsByClassName('ad30'); for (var i = 0; i < ad30Class.length; i++) { var ids = ad30Class[i].id; var newIds = ids.replace(/tg_/i, "l"); adArray.push(newIds); } // get links with class adf var adfClass = document.getElementsByClassName('adf'); for (var i = 0; i < adfClass.length; i++) { var ids = adfClass[i].id; var newIds = ids.replace(/tg_/i, "l"); adArray.push(newIds); } // loop through array with all new ids for (var i = 0, l = adArray.length; i < l; i++) { var counter = 15; var countDown = setTimeout(function() { console.log(counter); if (counter == 0) { console.log(adArray[i]); } counter--; }, 1000); } ```
2012/06/09
[ "https://Stackoverflow.com/questions/10965285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1320596/" ]
``` // loop through array with all new ids var i = 0, l = adArray.length; (function iterator() { console.log(adArray[i]); if(++i<l) { setTimeout(iterator, 15000); } })(); ``` Something like this?
20,319,104
In my C++ code I use templates a lot.. that might be an understatement. The end result is that the type names take more than 4096 characters and watching the GCC output is painful to say the least. In several debugging packages like GDB or Valgrind one can request that C++ types not be demangled. Is there a similar way to force G++ to output **only** mangled type names, cutting on all the unecessary output? Clarification ------------- Because of the first answer that was given I see that the question isn't clear. Consider the following MWE: ``` template <typename T> class A { public: T foo; }; template <typename T> class B { }; template <typename T> class C { public: void f(void) { this->foo = T(1); this->bar = T(2); } }; typedef C< B< B< B< B< A<int> > > > > > myType; int main(int argc, char** argv) { myType err; err.f(); return 0; }; ``` The error in the line `this->bar = T(2);` is an error only when an object of type `C<myType>` is instantiated and the method `C::f()` called. Therefore, G++ returns an error message along these lines: ``` test.cpp: In instantiation of ‘void C<T>::f() [with T = B<B<B<B<A<int> > > > >]’: test.cpp:33:8: required from here test.cpp:21:14: error: no matching function for call to ‘B<B<B<B<A<int> > > > >::B(int)’ this->foo = T(1); ^ test.cpp:21:14: note: candidates are: test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B() class B ^ test.cpp:11:7: note: candidate expects 0 arguments, 1 provided test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B(const B<B<B<B<A<int> > > > >&) test.cpp:11:7: note: no known conversion for argument 1 from ‘int’ to ‘const B<B<B<B<A<int> > > > >&’ test.cpp:21:14: error: ‘class C<B<B<B<B<A<int> > > > > >’ has no member named ‘foo’ this->foo = T(1); ^ test.cpp:23:14: error: no matching function for call to ‘B<B<B<B<A<int> > > > >::B(int)’ this->bar = T(2); ^ test.cpp:23:14: note: candidates are: test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B() class B ^ test.cpp:11:7: note: candidate expects 0 arguments, 1 provided test.cpp:11:7: note: B<B<B<B<A<int> > > > >::B(const B<B<B<B<A<int> > > > >&) test.cpp:11:7: note: no known conversion for argument 1 from ‘int’ to ‘const B<B<B<B<A<int> > > > >&’ test.cpp:23:14: error: ‘class C<B<B<B<B<A<int> > > > > >’ has no member named ‘bar’ this->bar = T(2); ``` The type names are irritating here, but make it impossible to read when the complete type name takes hundreds of characters. Is there a way to ask GCC for mangled type names instead of the full names, or to limit their length somehow? STLFilt ------- Unfortunately, `STLFilt` only makes the output prettier; the length doesn't change. In fact, the fact that the output is broken into multiple lines makes the whole thing worse, because the output takes more space.
2013/12/02
[ "https://Stackoverflow.com/questions/20319104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3055685/" ]
People are suffering from this particular shortcoming of C++ error reporting for ages. :) However, more verbose error reports are generally better for complex problem solving. Thus, a better approach is to let g++ to spit out the long and verbose error message and then use a stand alone error parser to make the output more readable. There used to be a decent error parser here: <http://www.bdsoft.com/tools/stlfilt.html> (unfortunately, no longer in development). See also this near duplicate: [Deciphering C++ template error messages](https://stackoverflow.com/questions/47980/deciphering-c-template-error-messages)
18,240,320
i just started coding with Symfony 2. On my local machine i setup my database using app/console doctrine:database:create and doctrine:schema:create which works great. The problem i have is, local i have diffrent parameters defined in parameters.yml than on my production environment. How can i define paramters for dev and for prod? I've already tried to create a parameters\_dev.yml but this did not work. Should i maybe create a paramters.yml on my prod server and copy it after deployment so i dont have my DB password in version control?
2013/08/14
[ "https://Stackoverflow.com/questions/18240320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1785272/" ]
parameters.yml should't be handled by version control. You have to set it on ignore in .gitignore. Only parameters.yml.dist has to be versioned more over if you use symfony 2.3 and install vendors using composer on prod you will be prompt to enter all the setting from parameters.yml.dist so parameters.yml will be generated automatically
336,838
I was just wondering, what's the difference between these file formats? Shouldn't there be just one or two that generally tend to perform superior to most others?
2011/09/17
[ "https://superuser.com/questions/336838", "https://superuser.com", "https://superuser.com/users/97637/" ]
[`compress`](http://en.wikipedia.org/wiki/Compress) (the Unix command, ported to Linux and others) itself only has one file extension that is used for its output, and that is `.z` There are other compression algorithms (and their associated programs) that compress files differently for different results. Some popular programs include: * [Gzip](http://en.wikipedia.org/wiki/Gzip) which has the extension `.gz` * [Bzip](http://en.wikipedia.org/wiki/Bzip2) which has the extension `.bz2` * [Rar](http://en.wikipedia.org/wiki/Rar) which has the extension `.rar` * [Zip](http://en.wikipedia.org/wiki/ZIP_%28file_format%29) which has the extension `.zip` * [7-zip](http://en.wikipedia.org/wiki/7z) which has the extension `.7z` * and many more... Generally newer archivers will use better compression algorithms, usually at the cost of taking longer (requiring more CPU time) to compress or requiring more memory or both. As a general rule though, the newer the program, the newer it's algorithms and therefore the better its compression will be. `compress` is as old as the hills and its compression ratios tend to be a lot worse than more modern programs like 7-zip.
1,124,217
This is the answer I can come up with. I get the complete opposite of what I'm supposed to get. My mistake is probably in the first part, could anyone help me out? $$\left|x^2+x+1\right|\:\ge \left|x^2+x\right|-\left|1\right|\ge \left|x^2\right|-\left|x\right|-\left|1\right|\:=\:x^2\:-\left|x\right|-1 $$ and $$ \frac{1}{\left|x^2+x+1\right|}\:=\:\:\:\frac{x^2\:-\left|x\right|-1}{\left|x^2+x+1\right|\left(x^2\:-\left|x\right|-1\right)}\:\:\:\le \:\frac{\left|x^2+x+1\right|}{\left|x^2+x+1\right|\left(x^2\:-\left|x\right|-1\right)}\:=\:\frac{1}{x^2\:-\left|x\right|-1} $$
2015/01/28
[ "https://math.stackexchange.com/questions/1124217", "https://math.stackexchange.com", "https://math.stackexchange.com/users/174613/" ]
If $f(g(b))=b$ for all $b$, then in particular for $b:=f(a)$ we also have $f(g(f(a))=f(a)$ for all $a$. Now, using that $f$ is injective we arrive at $g(f(a)=a$.
2,689,794
I'm currently building an Excel 2003 app that requires a horribly complex form and am worried about limitations on the number of controls. It currently has 154 controls (counted using `Me.Controls.Count` - this should be accurate, right?) but is probably only about a third complete. The workflow really fits a single form, but I guess I can split it up if I really have to. I see evidence in a Google search that VB6 (this usually includes VBA) has a hard limit of 254 controls in a form. However, I created a dummy form with well over 1200 controls which still loaded and appeared to work just fine. I did get some 'out of memory' errors when trying to add specific combinations of controls though, say 800 buttons and 150 labels, leading me to think that any limit might be affected by the memory requirements of each type of control. Does anyone have any information that might help ensure that I or, more importantly, other users with differing environments don't run into any memory issues with such a large form?
2010/04/22
[ "https://Stackoverflow.com/questions/2689794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67361/" ]
Most MSForms controls are windowless (as in they are not true windows, rather they are drawn directly by the VBA Forms engine as graphical objects) which are "light-weight" by comparison. This means you can dump more onto a Userform than you could using equivalent non-MSForms controls on a VB6 form. I don't know what the upper limit is, but it will either be an absolute limit or a limit imposed by available resources, so if you can add 1,200 without encountering either of those & excel is behaving itself in terms of memory use you should be ok. That said, that number of controls still seems an awful lot to present to the user at once!
21,376,200
I am using open cv and C++. I have 2 face images which contain marker points on them. I have already found the coordinates of the marker points. Now I need to align those 2 face images based on those coordinates. The 2 images may not be necessarily of the same height, that is why I can't figure out how to start aligning them, what should be done etc.
2014/01/27
[ "https://Stackoverflow.com/questions/21376200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3217694/" ]
In your case, you cannot apply the homography based alignment procedure. Why not? Because it does not fit in this use case. It was designed to align flat surfaces. Faces (3D objects) with markers at different places and depths are clearly no planar surface. Instead, you can: 1. try to match the markers between images then interpolate the displacement field of the other pixels. Classical ways of doing it will include [moving least squares](http://faculty.cs.tamu.edu/schaefer/research/mls.pdf) interpolation or [RBF](http://hal.archives-ouvertes.fr/docs/00/09/47/64/PDF/Bartoli_Zisserman_BMVC04.pdf)'s; 2. otherwise, a more "Face Processing" way of doing it would be to use the decomposition of faces images between a texture and a face model (like [AAM](http://en.wikipedia.org/wiki/Active_appearance_model) does) and work using the decomposition of your faces in this setup.
1,400,937
Suppose there is a bash file named "`uploadme`" in the `/usr/bin` folder. *I am using that file as a command*, and passing the **file names** as a **command line argument**, in any subdirectory of my home directory. Suppose I am in the directory directory`/home/John/documents/`. In that directory, there is only one file that exists, named "Hello.txt". I will use the command as: ``` uploadme Hello.txt ``` So, the bash file will get one argument as "Hello.txt", but **I want the full path of the file without mentioning it in the argument.** How can we do that?
2022/04/05
[ "https://askubuntu.com/questions/1400937", "https://askubuntu.com", "https://askubuntu.com/users/1584541/" ]
The tool `realpath` does that: ``` echo $(realpath "$1") ```
54,140,610
I have a `<ul>`, which has many `<li>` , each of which contains an anchor tag. The xpath of the list elements looks like the one: `String xpath = "//*[@id='page']/section[8]/div/div/div[2]/div/ul/li[";` `String part2 = "]/a";` My task involves clicking on each of those links, coming back to the homepage, and then clicking on another link. At this moment, my webpage contains 5 such elements. To click on each element, I repeat the following inside a for loop: `driver.findElement(By.xpath(part1 + i + part2)).click();` followed by `driver.navigate().back();` The problem is I have hardcoded the value 5. It can be 6 some other day, or can have any number of links anyday. What logic can I use to check the size of the ul? **The problem is that I cannot use a `java.util.List` to store the links beforehand.**
2019/01/11
[ "https://Stackoverflow.com/questions/54140610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2451763/" ]
Are you allowed to store their count? :) ``` int len = driver.findElements(By.xpath("//*[@id='page']/section[8]/div/div/div[2]/div/ul/li/a").size() ``` `findElements` will find all elements matching the locator (note the plural), return as a List, on which you you get the size (length). So now you'll know the upper bound of the loop.
67,920,614
So I have read mutliple articles regarding this issue, but none worked for my case. What happens: When you toggle the keyboard by clicking an entry, on Android the whole layout is shifted up by as much as the keyboard is big. iOS simply renderes the keyboard on top. This is ofc terrible, and especially for the chat application I am building right now completely hiding the entry editor field where the user types on. Inacceptable. There are some solutions (allthoug I really wonder why such a basic thing isnt included into xamarin.ios already) **1.) Putting your layout into a scrollview.** This works. Simply wrap everything into a scrollview, and the keyboard will push everything up. Great, right? No. In some instances you cannot wrap things into a scrollview: My chat is one example. Since the chat view is a scrollview itself, the outter layers cannot be a scrollview. I mean, they can: but then you have two scrollviews on top of each other leading to scroll issues and both interfering with one another. ALSO: values like `height="180"` dont work inside a scrollview anymore because the height isnt a fixed value. **2) Using a plugin** There are many nuget plugins that should work but with the newest iOS they just dont anymore. Some still do, but on few occasions (when the enter button is pressed to disable keyboard) the layout doesnt scroll back down well enough leaving a blank space. So these do not work at all or well enough. **3) Adding a layout that is inflated when the keyboard is triggered** This is what I did as a workaround (that isnt good either): At the bottom of my layout where my entry field for the chat is I added this layout: ``` <Grid Grid.Column="1" Grid.Row="2" x:Name="keyboardLayout" IsVisible="false" > <Grid.RowDefinitions> <RowDefinition Height="300"/> </Grid.RowDefinitions> <BoxView BackgroundColor="Transparent"/> </Grid> ``` It is a fixed layout with a height of 300. Now I can listen to keyboard change events: ``` if (Device.RuntimePlatform == Device.iOS) { // Android does it well by itself, iOS is special again var keyboardService = Xamarin.Forms.DependencyService.Get<IKeyboardService>(); keyboardService.KeyboardIsHidden += delegate { keyboardLayout.IsVisible = false; }; keyboardService.KeyboardIsShown += delegate { keyboardLayout.IsVisible = true; }; } ``` With a complicated interface (that I am posting if someone wants it), I can listen to change keyboard events. If the keyboard is visible, I simply update the UI with the layout. This works, but the fixed size of 300 is an issue. To this day I still dont really know how fixed values in XAML work (input wanted...!), for smaller margins they seem to be equal on every phone, but for higher values (> 50) they differ too much. So my solution is just about good enough for older iPhones (6, 7). But leaves a bit of an empty space between the keyboard and the entry filed on newer iPhones with longer screens (11, 12). In summary: no solution is ideal. **What we need** Either an important xamarin update facing this issue (which wont happen anytime soon), or someone who knows how to get the height of the keyboard in pixels, translate that into XAML values, and fill them in in regards to the phone used. Then my solution (number 3) would work always, everywhere (still a workaround, but bulletproof). Is there anybody out there, who knows how to a.) get the height of the shown keyboard in pixels and (and most important) b.) konws how to translate pixels into `Height="xxx"` Thank you for comming to my ted talk ;)
2021/06/10
[ "https://Stackoverflow.com/questions/67920614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15801387/" ]
You can create class that extend grid in shared code firstly. ``` public class KeyboardView: Grid{} ``` Then create a custom renderer to do the resize control. ``` [assembly: ExportRenderer(typeof(KeyboardView), typeof(KeyboardViewRenderer))] namespace KeyboardSample.iOS.Renderers { public class KeyboardViewRenderer : ViewRenderer { NSObject _keyboardShowObserver; NSObject _keyboardHideObserver; protected override void OnElementChanged(ElementChangedEventArgs<View> e) { base.OnElementChanged(e); if (e.NewElement != null) { RegisterForKeyboardNotifications(); } if (e.OldElement != null) { UnregisterForKeyboardNotifications(); } } void RegisterForKeyboardNotifications() { if (_keyboardShowObserver == null) _keyboardShowObserver = UIKeyboard.Notifications.ObserveWillShow(OnKeyboardShow); if (_keyboardHideObserver == null) _keyboardHideObserver = UIKeyboard.Notifications.ObserveWillHide(OnKeyboardHide); } void OnKeyboardShow(object sender, UIKeyboardEventArgs args) { NSValue result = (NSValue)args.Notification.UserInfo.ObjectForKey(new NSString(UIKeyboard.FrameEndUserInfoKey)); CGSize keyboardSize = result.RectangleFValue.Size; if (Element != null) { Element.Margin = new Thickness(0, 0, 0, keyboardSize.Height); //push the entry up to keyboard height when keyboard is activated } } void OnKeyboardHide(object sender, UIKeyboardEventArgs args) { if (Element != null) { Element.Margin = new Thickness(0); //set the margins to zero when keyboard is dismissed } } void UnregisterForKeyboardNotifications() { if (_keyboardShowObserver != null) { _keyboardShowObserver.Dispose(); _keyboardShowObserver = null; } if (_keyboardHideObserver != null) { _keyboardHideObserver.Dispose(); _keyboardHideObserver = null; } } } } ``` Finally, adding content inside KeyboardView. You can take a look this thread: [adjust and move the content of a page up slightly when the keyboard appears in an Entry control Xamarin Forms](https://stackoverflow.com/questions/68103011/adjust-and-move-the-content-of-a-page-up-slightly-when-the-keyboard-appears-in-a/68110827#68110827)
1,978,657
Is there any predefined UIViewController/NavigationController in the IPhone API as same as "Info" in "Phone/Mobile" application? For example, suppose I received a call or dialed a number, which is not stored in address book. Then later I wanna see the details of that number, IPhone navigates me to the "Info" view when I click the "Detail disclosure button" in the calls table view. Exactly I want the same "Info" ViewController. Before going to design my customized UIViewController I just wanna know, is there any predefined ViewController in the API? P:S: I searched the address book API, but unfortunately I didn't notice any such contoller. Regards, Prathap.
2009/12/30
[ "https://Stackoverflow.com/questions/1978657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233177/" ]
no, you don't have something this specific in the API. if you want that kind of viewcontroller, you'll have to roll your own.
28,922,247
I'm working on cleaning up the tags of mp3s that contain the web links. I tried the regular expression that clears up the web-links ``` (\w+)*(\s|\-)(\w+\.(\w+)) with $1 ``` However, when I try using the same on the file, the extension is replaced. How do I make the extension here, .mp3 as an exception with the above regex? I have tried using [this](https://stackoverflow.com/questions/1141848/regex-to-match-url) but the replace takes more time
2015/03/08
[ "https://Stackoverflow.com/questions/28922247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3003393/" ]
based on your examples, use this pattern ``` \s-\s\S+(?=\.) ``` and replace w/ nothing ``` \s # <whitespace character> - # "-" \s # <whitespace character> \S # <not a whitespace character> + # (one or more)(greedy) (?= # Look-Ahead \. # "." ) # End of Look-Ahead ``` [Demo](https://regex101.com/r/yW4aZ3/219)
53,744,017
I have the following User entity that contains list of friends, that is the list of the same entitities. ``` @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String surname; List<User> friends; } ``` How is the correct way to map this relation in the Hibernate? In native SQL tables it is resolved by creating second table that define relation beetwen users.
2018/12/12
[ "https://Stackoverflow.com/questions/53744017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9505054/" ]
Here you can use the following example: ``` @Entity @Table(name = "users") class User implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private String surname; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "user_friends") Set<User> friends; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } public Set<User> getFriends() { return friends; } public void setFriends(Set<User> friends) { this.friends = friends; } public void addFriend(User u) { if (this.friends == null) { this.friends = new HashSet(); } this.friends.add(u); } } ``` persistence.xml : ``` <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"> <persistence-unit name="deneme" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <class>com.deneme.User</class> <properties> <property name="hibernate.hbm2ddl.auto" value="update"/> <property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://127.0.0.1;databaseName=springbootdb"/> <property name="javax.persistence.jdbc.user" value="emre"/> <property name="javax.persistence.jdbc.password" value="asdf_1234"/> <property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/> <property name="hibernate.ddl-generation" value="auto"/> <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect"/> <property name="hibernate.show_sql" value="true"/> </properties> </persistence-unit> </persistence> ``` main : ``` public class Main { public static void main(String[] args) { EntityManagerFactory emfactory = Persistence.createEntityManagerFactory( "deneme"); EntityManager entitymanager = emfactory.createEntityManager(); entitymanager.getTransaction().begin(); User u = new User(); u.setName("test"); u.setSurname("test"); User uf = new User(); uf.setName("fri"); uf.setSurname("fri"); u.addFriend(uf); entitymanager.persist(u); entitymanager.getTransaction().commit(); entitymanager.close(); emfactory.close(); } } ``` Generated sql: ``` Hibernate: insert into users (name, surname) values (?, ?) Hibernate: insert into users (name, surname) values (?, ?) Hibernate: insert into user_friends (User_id, friends_id) values (?, ?) ``` Screenshot from database: [![enter image description here](https://i.stack.imgur.com/lzD2k.png)](https://i.stack.imgur.com/lzD2k.png)
27,351,274
I've got two select queries I need to combine into one result. ``` /* Count of all classes students have passed */ /* A */ SELECT COUNT(TECH_ID) as Number1, ct.SUBJ, ct.COU_NBR FROM [ISRS].[ST_COU] st JOIN [ISRS].[CT_COU_SQL] ct ON st.COU_ID = ct.COU_ID WHERE GRADE = 'A' OR Grade = 'B' or Grade = 'C' GROUP BY ct.SUBJ, ct.COU_NBR /* Total Count of all students who needed to take a course */ /* B */ SELECT COUNT(TECH_ID) as Number2, ec.SUBJ, ec.COU_NBR FROM [dbo].[ST_MAJOR_COMMENT] st JOIN [dbo].[Emphasis_Class] ec ON st.MAJOR = ec.Emphasis GROUP BY ec.SUBJ, ec.COU_NBR ``` I need SUBJ, COU\_NBR, sum(B - A)
2014/12/08
[ "https://Stackoverflow.com/questions/27351274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4335893/" ]
If I understand your requirement correctly, you want the footer to sit at the bottom of the content box. One solution is to make the content box `position:relative` and move the footer inside it, so that its `position:absolute` will bind it to the content box, and the `bottom:0` will achieve the desired effect of having it sit against the bottom of said content box. See <http://jsfiddle.net/wn6uvske/5/>. HTML: ``` <div id="wrapper"> <div id="sidebar"></div> <div id="body-content"> <div class="header"> <div class="navbar navbar-default" role="navigation"> <div class="container"> <ul class="nav navbar-nav navbar-right"> <li><a href="#" class="menu-toggle">Toggle Menu</a> </li> </ul> </div> </div> </div> <div class="main"> <div class="content container"> <p>Content</p> <div class="footer"> <!-- moved up into content container --> <p>Footer</p> </div> </div> </div> </div> </div> ``` (relevant) CSS: ``` .main .content { height: 2000px; background-color: aquamarine; padding-bottom:80px; position:relative; } .footer { position: absolute; bottom: 0; left: 0; right: 0; height: 80px; background-color: beige; } ```
37,161,201
I'm reading a book about java 8 by Richard Warburton. In the section about Primitive stream author gives some explanation about primitives vs references (emphasized mine): > > For algorithms that perform lots of numerical operations, the cost of > boxing an unboxing combined with the ***additional memory bandwidth used*** > ***by allocated boxed objects*** can make the code significantly slower. > > > What is the bandwidth? Is it considered as for primitives we have the actual value of them in memory and can work with them directly. For references, in turn, we work with pointers to the heap and to invoke a method on some object we have to perform indirection by a given pointer and only then we can invoke the method. Is that considered a bandwidth? Do we really have to worry about the bandwidth in practice?
2016/05/11
[ "https://Stackoverflow.com/questions/37161201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2786156/" ]
A realistic computer has a limitation on how quickly it can retrieve bytes/words from memory, with one faster speed for reading from CPU caches, and a slower speed for reading from memory that is not in the L1/L2/L3/... cache. When we're working through a large primitive/boxed stream, we can assume that we don't have elements of the collection in the CPU cache, and they need to be fetched from main memory. In a gross oversimplification applicable to OpenJDK, an object in memory will contain references to its `java.lang.Class` and all superclasses thereof (used for checking casts and related), followed by its fields. This can be fairly sizable, for example with the boxed `java.lang.Integer` where it would likely need to maintain a reference to `Class<Integer>` and `Class<Number>`. Needless to say, this is much larger than the 32 bits needed for a primitive. When one is iterating/streaming a collection of `Integer`s, it's necessary to load these objects into memory, and for simple numerical operations on the elements, the memory becomes the bottleneck.
50,208,502
I had an Angular app with `dev, prod & QA` environments. I build it by ng build --env=QA After building, How do I know, that it is in QA environment without deploying it to the server?
2018/05/07
[ "https://Stackoverflow.com/questions/50208502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7498614/" ]
We can find it in dist/main.bundle.js with variable environment. So, by this, we know which environment it is. ``` var environment = { production: true, envName: 'QA' }; ```
50,637,672
I want to fetch data(the images in each post) stored in <https://www.instagram.com/explore/tags/selfie/?__a=1>, but all I get when I decode and var\_dump this is NULL. ``` $obj = json_decode("https://www.instagram.com/explore/tags/selfie/?__a=1", true); var_dump($obj); ```
2018/06/01
[ "https://Stackoverflow.com/questions/50637672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5909288/" ]
Before decoding json you have to first fetch api response. ``` $obj = json_decode(file_get_contents("https://www.instagram.com/explore/tags/selfie/?__a=1"), true); ```
39,424,559
I quick started with Redis on Windows PC with ``` docker run -p 6379:6379 redis ``` (Redis does not have Windows distribution, [fork for Windows](https://github.com/MSOpenTech/redis) is not the latest version ) ``` 1:C 10 Sep 08:17:03.635 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf _._ _.-``__ ''-._ _.-`` `. `_. ''-._ Redis 3.2.3 (00000000/0) 64 bit .-`` .-```. ```\/ _.,_ ''-._ ( ' , .-` | `, ) Running in standalone mode |`-._`-...-` __...-.``-._|'` _.-'| Port: 6379 | `-._ `._ / _.-' | PID: 1 `-._ `-._ `-./ _.-' _.-' |`-._`-._ `-.__.-' _.-'_.-'| | `-._`-._ _.-'_.-' | http://redis.io `-._ `-._`-.__.-'_.-' _.-' |`-._`-._ `-.__.-' _.-'_.-'| | `-._`-._ _.-'_.-' | `-._ `-._`-.__.-'_.-' _.-' `-._ `-.__.-' _.-' `-._ _.-' `-.__.-' ... 1:M 10 Sep 08:17:03.644 * The server is now ready to accept connections on port 6379 ``` Then however I can't connect from Spring Boot app. With `application.properties` like ``` spring.redis.host=localhost spring.redis.port=6379 ``` got error ``` Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.ConnectException: Connection refused: connect at redis.clients.jedis.Connection.connect(Connection.java:164) ~[jedis-2.8.2.jar:na] at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:80) ~[jedis-2.8.2.jar:na] at redis.clients.jedis.BinaryJedis.connect(BinaryJedis.java:1677) ~[jedis-2.8.2.jar:na] at redis.clients.jedis.JedisFactory.makeObject(JedisFactory.java:87) ~[jedis-2.8.2.jar:na] at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:868) ~[commons-pool2-2.4.2.jar:2.4.2] at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:435) ~[commons-pool2-2.4.2.jar:2.4.2] at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:363) ~[commons-pool2-2.4.2.jar:2.4.2] at redis.clients.util.Pool.getResource(Pool.java:49) ~[jedis-2.8.2.jar:na] ... 23 common frames omitted Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[na:1.8.0_45] at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) ~[na:1.8.0_45] at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:345) ~[na:1.8.0_45] at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_45] at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_45] at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) ~[na:1.8.0_45] at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_45] at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_45] at redis.clients.jedis.Connection.connect(Connection.java:158) ~[jedis-2.8.2.jar:na] ... 30 common frames omitted ``` When trying to use Node.js with [node\_redis](https://github.com/NodeRedis/node_redis) example, I got ``` Error Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED ```
2016/09/10
[ "https://Stackoverflow.com/questions/39424559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/482717/" ]
As you mentioned (in the comments), redis bundled their image with `protected-mode` set to yes ([see here](http://redis.io/topics/security)). **How to go around protected-mode** * 1) Disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. * 2) Alternatively you can disable the protected mode by editing the Redis configuration file, and setting the protected mode option to 'no', and then restarting the server. * 3) If you started the server manually (perhaps for testing), restart it with the '--protected-mode no' option. * 4) Setup a bind address or an authentication password. source: [redis-github](https://github.com/docker-library/redis/issues/58) **Build your own image** * You could create your own image by pulling redis's and ADDing your own redis.conf to the image ? * Or update the start command in the Dockerfile to disable protected-mode: `CMD [ "redis-server", "--protected-mode", "no" ]` **You can also take a look at this Dockerfile which contains the modification suggested above** (last line): <https://github.com/docker-library/redis/blob/23b10607ef1810379d16664bcdb43723aa007266/3.2/Dockerfile> This Dockerfile is provided in a [Redis issue on github](https://github.com/docker-library/redis/issues/58), it replaces the startup command with `CMD [ "redis-server", "--protected-mode", "no" ]`. You could just download this Dockerfile and type: ``` $ docker build -t redis-unprotected:latest . $ docker run -p 6379:6379 redis-unprotected ```
49,255,874
trying executing this code on the group with joins but its giving me error that its not a group by statement code below ``` SELECT sum (quantity), customers.customer_name, states.state_name, regions.region_name FROM sales JOIN customers ON sales.customer_id = customers.customer_id join states on customers.state_id = states.state_id join regions on states.region_id = regions.region_idhaving sum(quantity) >= 10 GROUP BY sales.sale_id, customers.customer_name, states.state_name, regions.region_id ; ``` saying not a group by expression.
2018/03/13
[ "https://Stackoverflow.com/questions/49255874", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8217437/" ]
``` dat <- data.frame(VAR1=c(0,1,0,1,0,0,1,1,0), VAR2=c(1,1,0,1,0,0,1,0,1), VAR3=c(0,1,1,1,1,0,1,1,1)) dat1 <- dat[,names(sort(colSums(dat), decreasing = TRUE))] dat1 VAR3 VAR2 VAR1 1 0 1 0 2 1 1 1 3 1 0 0 4 1 1 1 5 1 0 0 6 0 0 0 7 1 1 1 8 1 0 1 9 1 1 0 ```
65,987
A few days back, I went for a riverside shoot with my Nikon D5300. Unfortunately, moderate rain soon started. I noticed a few photographers, probably with professional grade cameras, were daring enough to shoot the landscape in such weather. The scenic beauty around at that moment was mesmerizing, but I missed capturing any shots, fearing that a single droplet of water would burn out my DSLR. Before trying out taking pictures in rainy condition with my Nikon D5300, I need to know how weather-proof it is. Any suggestions/authentic information is appreciated.
2015/08/02
[ "https://photo.stackexchange.com/questions/65987", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/39813/" ]
The D5300 is an entry-level DSLR and is not weatherproof at all. As most cameras, it will handle a few drops of water or snow but you should not let it get wet. Weatherproof DSLRs and mirrorless exist and they will be able to stand up to strong rain without issues as long as a weatherproof lens is also attached. All camera manufacturers except Pentax/Ricoh reserve such features of higher-end models and pricier lenses, so if you want to get a weather-sealed DSLR and lens for a low cost, you will have to switch systems. There are things called rain-covers which are basically ponchos for a camera which you can buy to use your D5300 in the rain. Its a little cumbersome to work with and you have to be careful because it is not a sealed bag, but can do for occasional rain. These cost $50-$100 the last time I checked. There different sizes are to accommodate different lenses.
9,836,552
I need to perform some code when the user stop scrolling the picker, in other way, when the picker stop scrolling. The logic i want to follow is, once the picker stop scrolling, i get the current value and i do some database queries basing on that value. In the picker view documentation, i don't see a delegate method that can help on such task. Any thoughts? thanx in advance.
2012/03/23
[ "https://Stackoverflow.com/questions/9836552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/734308/" ]
whenever you scroll the picker view, didSelect delegate method call at the end of scroll ``` - (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { NSLog(@"Selected %i. ", row); /// do it here your queries } ``` try with above example and check your console
32,962,528
``` #include <bits/stdc++.h> using namespace std; #define HODOR long long int #define INF 1234567890 #define rep(i, a, b) for(int i = (a); i < (b); ++i) #define dwn(i, a, b) for(int i = (a); i >= (b); --i) #define REP(c, it) for( typeof( (c).begin()) it = (c).begin(); it != (c).end(); ++it) #define DWN(c, it) for( typeof( (c).end()) it = (c).end()-1; it >= (c).begin(); --it) #define ss(n) scanf("%s",n) #define FILL(x,y) memset(x,y,sizeof(x)) #define pb push_back #define mp make_pair #define ALL(v) v.begin(), v.end() #define sz(a) ((int)a.size()) #define SET(v, i) (v | (1 << i)) #define TEST(v, i) (v & (1 << i)) #define TOGGLE(v, i) (v ^ (1 << i)) #define gc getchar #define pc putchar template<typename X> inline void inp(X &n ) { register int ch=gc();int sign=1;n=0; while( ch < '0' || ch > '9' ){if(ch=='-')sign=-1; ch=gc();} while( ch >= '0' && ch <= '9' ) n = (n<<3)+(n<<1) + ch-'0', ch=gc(); n=n*sign; } inline void inps(char *n) { register int ch=gc(); int sign=1; int i=0; while( ch != '\n' ){ n[i]=(char)ch; ++i; ch=gc();} n[i]='\0'; } int MaxPath(int arr[][100],int n) { for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { cout<<arr[i][j]<<" "; } cout<<endl; } } int main() { int t,n; inp(t); while(t--) { inp(n); int arr[n][n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { inp(arr[i][j]); } } float result = MaxPath(arr,n); } return 0; } ``` > > **Error seems like this :** error: cannot convert ‘int (*)[n]’ to ‘int (*)[100]’ for argument ‘1’ to ‘int MaxPath(int (\*)[100], int)’ > > > I have seen many posts on stckoverflow , but none of which seems to be working
2015/10/06
[ "https://Stackoverflow.com/questions/32962528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4914678/" ]
You could pass in as a pointer to a pointer to int like this ``` int MaxPath(int** arr,int n) ``` but for this to work you would have to declare int arr[n][n] differently ``` int main() { int t,n; inp(t); while(t--) { inp(n); int** arr = new int*[n]; for (int i = 0; i < n; i++) arr[i] = new int[n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { inp(arr[i][j]); } } float result = MaxPath(arr,n); } //deallocate arr for (int i = 0; i < n; i++) { delete[] arr[i]; } delete []arr; return 0; } ```
61,936,858
**this is my dataframe:** ``` c_id fname age salary lname 1 abc 21 21.22 yyy 2 def 41 23.4 zzz ``` i need to display the position of the column name with respect to datatype. so my output should be: ``` **FOR INT:** col_name position c_id 0 age 2 **for str:** col_name position fname 1 lname 4 **for float:** col_name position salary 3 ```
2020/05/21
[ "https://Stackoverflow.com/questions/61936858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13343231/" ]
IIUC, you can just create a dataframe from the dtypes and reset the index to get the positional index number. ``` col_df = ( pd.DataFrame(df.dtypes, columns=["DataType"]) .rename_axis("Column") .reset_index() .rename_axis("Position") ) Column DataType Position 0 c_id int64 1 fname object 2 age int64 3 salary float64 4 lname object ``` --- ``` print(col_df[col_df['DataType'] == 'object']) Column DataType Position 1 fname object 4 lname object ```
45,806,172
what is the best way to check whether a stack exists using the AWS Java SDK, given a stack name? I've tried the below code based on - <https://github.com/aws/aws-sdk-java/blob/master/src/samples/AwsCloudFormation/CloudFormationSample.java> ``` DescribeStacksRequest wait = new DescribeStacksRequest(); wait.setStackName(stackName); List<Stack> stacks = awsCFTClient.describeStacks(wait).getStacks(); if (stacks.isEmpty()) { logger.log("NO_SUCH_STACK"); return true; } ``` However, I am getting: AmazonServiceException:com.amazonaws.services.cloudformation.model.AmazonCloudFormationException: Stack with id "stackName" does not exist. Thanks in advance!
2017/08/21
[ "https://Stackoverflow.com/questions/45806172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2817943/" ]
In case someone else is looking for a quick and dirty solution, this works, ``` //returns true if stack exists public boolean stackExists(AmazonCloudFormation awsCFTClient, String stackName) throws Exception{ DescribeStacksRequest describe = new DescribeStacksRequest(); describe.setStackName(stackName); //If stack does not exist we will get an exception with describe stack try { awsCFTClient.describeStacks(describe).getStacks(); } catch (Exception e) { logger.log("Error Message: " + e.getMessage()); if (e.getMessage().matches("(.*)" + stackName + "(.*)does not exist(.*)")) { return false; } else { throw e; } } return true; } ``` If there is a better way for doing this, please let me know.
18,966,169
Is it possible to show a right click menu on table items with SWT? The menu would be different for every item, e.g for some rows, some of the menu items would be enabled, for others, they would be disabled. So, each row would need its own menu, and when setting up the menu i'd need a way to identify which row I was working with. Any ideas?
2013/09/23
[ "https://Stackoverflow.com/questions/18966169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2790209/" ]
Listening for `SWT.MouseDown`, as suggested by @user4793956, is completely useless. The context menu is always brought up, no need to call `setVisible(true)`. Quite contrary, you need to cancel the `SWT.MenuDetect` event, if you do **not** want the menu to pop up. This works for me: ``` // Create context menu Menu menuTable = new Menu(table); table.setMenu(menuTable); // Create menu item MenuItem miTest = new MenuItem(menuTable, SWT.NONE); miTest.setText("Test Item"); // Do not show menu, when no item is selected table.addListener(SWT.MenuDetect, new Listener() { @Override public void handleEvent(Event event) { if (table.getSelectionCount() <= 0) { event.doit = false; } } }); ```
14,326,604
When a user slides the jQuery Slider over, it effects each image. How do I only get the images pertaining to that slider to change? I've tried: `$(this).closest('img.down')` and `$(this).siblings('img.down')` ``` $("#slider").slider({ value:50, min: 0, max: 100, step: 50, slide: function( event, ui ) { $('img.up, img.down').css('opacity','.4'); if (ui.value >= 51) { $('img.up').css('opacity','.8'); } if (ui.value <= 49) { $('img.down').css('opacity','.8'); } } }); ``` [Fiddle here](http://jsfiddle.net/psybJ/5/) Thanks guys!
2013/01/14
[ "https://Stackoverflow.com/questions/14326604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/908392/" ]
You need to make a change to your markup, ***you cannot have three items in a page with the same id***. You can make it ``` class="slider" ``` Move the initialization of the CSS outside of the function then traverse the markup to get the correct image: ``` $('img.up, img.down').css('opacity','.4'); $(".slider").slider({ value:50, min: 0, max: 100, step: 50, slide: function( event, ui ) { if (ui.value == 50) { $(this).parent().find('img.up, img.down').css('opacity','.4'); } if (ui.value >= 51) { $(this).parent().find('img.up').css('opacity','.8'); } if (ui.value <= 49) { $(this).parent().find('img.down').css('opacity','.8'); } } }); ``` <http://jsfiddle.net/psybJ/9/>
396,799
I am trying to set up a part of our network as a linux cluster. Since its a little educational for me, I choose using MAAS with JuJu. However there are some questions that boggle my mind and I was hoping that someone could clarify that for me. The linux cluster I'm about to set up consists of 10 machines. Half of it Dell and the other HP. Both types of machines have a lights-out module (HP=>iLO2, Dell=>DRAC) that support IPMI on a seperate 100Mb NIC. They both support PXE on the first onboard gigabit NIC. I configured the lights out module with a static IP matching the physical layout of the racks and position height. Installing MAAS however didn't ask me on what subnet and vlan the IPMI protocol should be configured. How do I do this? Also I want only the region controller to be able to contact the internet for package management. The other provisioned nodes should only be allowed to connect to the internet via a proxy on the region controller. So the region controller in my case should be configured with 3 subnets; 1 for internet, 1 for client protocol connectivity and 1 for cluster traffic. The region controller itself should also be a node for JuJu. Then at last there is the node configuration that should have a sort of basic layout that can be used within JuJu. As far as I could see there is no possibility to set up cluster subnet configuration. Each machine has at least 4 NIC's that I like to assign the different subnets to; 1 for the IPMI traffic, 1 for the PXE boot traffic, 1 for the cluster traffic and 1 for the storage/client network. What I like to do is to bond all these interfaces together as one big trunk and then use VLAN's to separate the traffic **before** provisioning. Then when provisioning a node, MAAS should automagically configure the network interfaces as the layout suggests above. Maybe what I'm looking for is a advanced configuration tutorial/guide for MAAS and JuJu. Regards, Joham
2013/12/28
[ "https://askubuntu.com/questions/396799", "https://askubuntu.com", "https://askubuntu.com/users/229480/" ]
Maybe if you let install of [Juju GUI](https://juju.ubuntu.com/docs/howto-gui-management.html) to provide adequately more what type of network balancing you need then you could find your answer faster. [**Using Juju with GUI**](https://juju.ubuntu.com/docs/howto-gui-management.html) This advanced guides very close to your problem: [**MAAS: Cluster Configuration**](http://maas.ubuntu.com/docs/cluster-configuration.html) [**Additional Manual Configuration**](http://maas.ubuntu.com/docs/configure.html#installing-additional-clusters)
17,981,284
In this situation, I want to find all records that contain the name steve in one column and [email protected] in another. I know Im missing an operator, but i dont know which ``` SELECT firstname,lastname,middlename,company_name, primary_emailaddress,alternate_emailaddress,personal_address_line1, personal_address_line2,personal_address_city,facebook_username, twitter_username,googleplus_username,linkedin_username, personal_website_url,birthday_month,notes,personal_address_zipcode, company_address_zipcode,home_phonenumber,company_phonenumber, cell_phonenumber,birthday_day,birthday_year,hash,image_file FROM contacts WHERE ( MATCH( firstname,lastname, primary_emailaddress,alternate_emailaddress,personal_address_line1, personal_address_city,company_name, company_address_line1,company_address_city, facebook_username,twitter_username,googleplus_username,linkedin_username, personal_website_url ) AGAINST ('Steve [email protected]' IN BOOLEAN MODE)) ```
2013/07/31
[ "https://Stackoverflow.com/questions/17981284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135605/" ]
Ok, after a lot of searching. I answered my own question. I've discovered finding anything on the angular documentation is incredibly impossible, but sometimes, once it's found, it changes how you were thinking about your problem. I began here: <http://docs.angularjs.org/api/ng>.$location Which took me here: <http://docs.angularjs.org/guide/dev_guide.services>.$location Which took me to this question: [AngularJS Paging with $location.path but no ngView reload](https://stackoverflow.com/questions/12422611/angularjs-paging-with-location-path-but-no-ngview-reload) What I ended up doing: I added `$location.search({name: 'George'});` To where I wanted to change the name (A $scope.$watch). However, this will still reload the page, unless you do what is in that bottom StackOverflow link and add a parameter to the object you pass into `$routeProvider.when`. In my case, it looked like: `$routeProvider.when('/page', {controller: 'MyCtrl', templateUrl:'path/to/template', reloadOnSearch:false})`. I hope this saves someone else a headache.
63,678,928
Suppose a class MyClass implements an interface MyInterface, and it has its own instance method let's say foo(). When i create an instance of MyClass like this: ``` MyInterface myClass = new MyClass(); ``` The compiler wouldn't let me access its instance method without an explicit casting: ``` myClass.foo(); // Can't resolve symbol ((MyClass) myClass).foo(); // this is okay ``` Even though the compiler obviously knows myClass is an instance of MyClass: ``` if(myClass instanceof MyClass) System.out.println(myClass.getClass().getName()); //this will print "MyClass" ``` Why do i need to use cast for compiler to allow me to access the instance method?
2020/08/31
[ "https://Stackoverflow.com/questions/63678928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3554898/" ]
The *meaning* of the line `MyInterface myClass = new MyClass()` is, "Create a new `MyClass`, and then forget about all its features except those defined in the interface `MyInterface`." When you refer to "the compiler obviously knows myClass is an instance of MyClass," you're not actually correct: it's *not* the compiler that knows that, but the *runtime.* The *compiler* was told to forget that information, and it did.
33,528,414
![Here's the Screenshot](https://i.stack.imgur.com/ldDO2.png) I am trying to override the OnLaunched() function in a Template 10 Windows Application, but the problem is that it is sealed in Template 10 BootStrapper class (which inherits from the Application class). Here's my method: ``` using Windows.UI.Xaml; ... namespace Sample { ... sealed partial class App : Template10.Common.BootStrapper { protected override void OnLaunched(LaunchActivatedEventArgs args) { /*************** My stuff ***************** ***********************************************/ } ... } ``` I am using Template10 Blank app for this app, and the OnLaunched() method in BootStrapper class is this: ``` namespace Template10.Common { public abstract class BootStrapper : Application { ... protected sealed override void OnLaunched(LaunchActivatedEventArgs e); ... } ... } ``` I cannot remove the sealed modifier from OnLaunched() in BootStrapper (guess because it is "from metadata"). What's the point of including a sealed method in an abstract class? Do we get some other method to override, like OnResume(), OnStartAsync(), etc, instead of OnLaunched()? Update: For reference, here are all the members in BootStrapper: ``` public abstract class BootStrapper : Application { public const string DefaultTileID = "App"; protected BootStrapper(); public static BootStrapper Current { get; } public TimeSpan CacheMaxDuration { get; set; } public INavigationService NavigationService { get; } public StateItems SessionState { get; set; } public bool ShowShellBackButton { get; set; } protected Func<SplashScreen, UserControl> SplashFactory { get; set; } public event EventHandler<WindowCreatedEventArgs> WindowCreated; public static AdditionalKinds DetermineStartCause(IActivatedEventArgs args); public NavigationService NavigationServiceFactory(BackButton backButton, ExistingContent existingContent); [AsyncStateMachine(typeof(<OnInitializeAsync>d__44))] public virtual Task OnInitializeAsync(IActivatedEventArgs args); public virtual void OnResuming(object s, object e); public abstract Task OnStartAsync(StartKind startKind, IActivatedEventArgs args); [AsyncStateMachine(typeof(<OnSuspendingAsync>d__45))] public virtual Task OnSuspendingAsync(object s, SuspendingEventArgs e); public Dictionary<T, Type> PageKeys<T>() where T : struct, IConvertible; public virtual T Resolve<T>(Type type); public virtual INavigable ResolveForPage(Type page, NavigationService navigationService); public void UpdateShellBackButton(); [AsyncStateMachine(typeof(<OnActivated>d__26))] protected sealed override void OnActivated(IActivatedEventArgs e); [AsyncStateMachine(typeof(<OnCachedFileUpdaterActivated>d__27))] protected sealed override void OnCachedFileUpdaterActivated(CachedFileUpdaterActivatedEventArgs args); [AsyncStateMachine(typeof(<OnFileActivated>d__28))] protected sealed override void OnFileActivated(FileActivatedEventArgs args); [AsyncStateMachine(typeof(<OnFileOpenPickerActivated>d__29))] protected sealed override void OnFileOpenPickerActivated(FileOpenPickerActivatedEventArgs args); [AsyncStateMachine(typeof(<OnFileSavePickerActivated>d__30))] protected sealed override void OnFileSavePickerActivated(FileSavePickerActivatedEventArgs args); protected sealed override void OnLaunched(LaunchActivatedEventArgs e); [AsyncStateMachine(typeof(<OnSearchActivated>d__31))] protected sealed override void OnSearchActivated(SearchActivatedEventArgs args); [AsyncStateMachine(typeof(<OnShareTargetActivated>d__32))] protected sealed override void OnShareTargetActivated(ShareTargetActivatedEventArgs args); protected sealed override void OnWindowCreated(WindowCreatedEventArgs args); public enum AdditionalKinds { Primary, Toast, SecondaryTile, Other } public enum BackButton { Attach, Ignore } public enum ExistingContent { Include, Exclude } public enum StartKind { Launch, Activate } } ``` Please help :}
2015/11/04
[ "https://Stackoverflow.com/questions/33528414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5035469/" ]
Template 10 does not allow us to override OnLaunched() method. Instead we can override the OnInitializeAsync() and OnStartAsync() methods for this purpose. The reason is that Template 10 recommends us to use something called the Single Page Model, which is nothing but using a single instance of the Page class to put in the empty Frame provided by the Framework. How is that benefit to us? Well, if we need to put a menu, say a Hamburger menu, in our app, then we need to copy the code for the menu in each and every page we create in our app. This would lead to things like redundancy, inconsistency, WET code, etc. etc. Therefore, template 10, initially, creates a Page, which they call the Shell, and then contents of each page is loaded into this Shell page, instead of creating new Pages. We can override these methods in the following way: ``` sealed partial class App : BootStrapper { public App() { this.InitializeComponent(); } public override Task OnInitializeAsync(IActivatedEventArgs args) { var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include); Window.Current.Content = new Views.Shell(nav); return Task.FromResult<object>(null); } public override Task OnStartAsync(BootStrapper.StartKind startKind, IActivatedEventArgs args) { NavigationService.Navigate(typeof(Views.MainPage)); return Task.FromResult<object>(null); } } ``` Here's where I figured the answer: <https://github.com/Windows-XAML/Template10/wiki/Docs-%7C-HamburgerMenu> So, long story short, override OnInitializeAsync() or OnStartAsync(), instead of OnLaunched().
17,996,678
I'm trying to find a structural break in my time series using the `breakpoints()` function (in the `strucchange` package). My goal is to find where is "knot" in my dataset. I'm looking for a procedure which would test all possible knots and choose the one who minimize an information criterion such AIC or BIC. `breakpoints()` does a good job but I would like to draw a continuous piecewise linear function. This, I would like the intercept to be the same before and after the breakpoint. Is anyone aware of a function or an option to do this ? On the picture below, the red line is the true model and the blue line is fitted using `breakpoints()`. I would like a procedure which would fit the true model (no jump at the breakpoint). See my [gist file](https://gist.github.com/pachevalier/6132114) to reproduce this example. ![enter image description here](https://i.stack.imgur.com/QXVZK.png)
2013/08/01
[ "https://Stackoverflow.com/questions/17996678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1967500/" ]
The 'strucchange' package seems designed to return discontinuous results. You may want to look at packages that are designed the way you imagine the result to be structured. The 'segmented' package is one such. ``` require(segmented) out.lm<-lm(y~date3,data=df) o<-segmented(out.lm, seg.Z= ~date3, psi=list(date3=c(-10)), control=seg.control(display=FALSE)) slope(o) #$date3 # Est. St.Err. t value CI(95%).l CI(95%).u #slope1 0.3964 0.1802 2.199 0.03531 0.7574 #slope2 -1.6970 0.1802 -9.418 -2.05800 -1.3360 str(fitted(o)) # Named num [1:60] 1.94 2.34 2.74 3.13 3.53 ... # - attr(*, "names")= chr [1:60] "1" "2" "3" "4" ... plot(y ~ date3, data=df) lines(fitted(o) ~ date3, data=df) ``` ![enter image description here](https://i.stack.imgur.com/dMnbL.png)
43,441,231
I have started working with flex box on React native, on CSS you should set the display to flex but on RN, this is set by default. What classifies a container object where you can set alignItems, justifyContent? Does it *only* need to be a view? or is every single component a potential container?
2017/04/16
[ "https://Stackoverflow.com/questions/43441231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457172/" ]
You need to do change in first for loop:- ``` for (i = 1; i < tr.length; i++) { // not start with 0 start with 1. ``` Means leave table `<thead><tr>` and then start searching in rest `<tr>`. Note:- check it and if you are facing any problem. I will create an example for you.
86,788
How do I display a list of values $\{a\_1,a\_2,\ldots,a\_n\}$ in a two column format? > > `--------- > 1 | a_1 > 2 | a_2 > 3 | a_3 > ...... > n | a_n` > > > I tried using TableFormat but this doesn't display the row number.
2015/06/25
[ "https://mathematica.stackexchange.com/questions/86788", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/19923/" ]
**Update** `ciao`'s answer makes the most sense. ``` TableForm[a /@ Range[5], TableHeadings -> Automatic] ``` **Original Post** Try this. If your list of values is ``` a /@ Range[5] (* {a[1], a[2], a[3], a[4], a[5]} *) ``` then you can do something like ``` TableForm@Transpose[{Range[5], a /@ Range[5]}] ``` or ``` TableForm@MapIndexed[{First@#2, #1} &, a /@ Range[5]] ``` (`MapIndexed` is major overkill. I just like using it recently.)
154,329
In Leetcode it states that my runtime is only faster than 38% all of submitted JavaScript solutions. Is there anything I can change to make it more efficient? ``` /** * @param {number} x * @param {number} y * @return {number} */ var hammingDistance = function(x, y) { var resultStr =( x^y); let count =0; while(resultStr>0){ resultStr =(resultStr&resultStr-1) ; count++; } return count; }; ```
2017/02/03
[ "https://codereview.stackexchange.com/questions/154329", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/57142/" ]
A few things could be changed here, non of which I mention are optimisation however. Your solution is almost identical to the [example on the wiki page](https://en.wikipedia.org/wiki/Hamming_distance#Algorithm_example) where you can see hardware optimisations if supported, though the example does not apply to JavaScript. **Naming** The `Str` in `resultStr` seems to imply that it's a string but that's not the case. `result` may be better suited, or `val` which is a common choice for this. While `count` is perfectly fine, `distance` might make it's purpose more obvious (especially since "distance" is in the function name). **Parentheses** There's a bunch of parentheses that aren't needed, adding spacing around operators makes it easier to follow. **Shorthand operators/spacing** You can take advantage of shorthand operators: `resultStr = resultStr & resultStr - 1` can be simplified to `resultStr &= resultStr - 1` Another added benefit is that in this example we don't have to worry about operator precedence. **ES6** Since you're using ES6 features such as `let` you can take advantage additional features such as `const` and `=>` (arrow functions). **ES6 - const/let** Favour `let` and `const` over `var`. You are already declaring `count` with `let` so it would make sense to do the same for `resultStr`. If we declare `const hammingDistance = ...` it means that if we later try and reassign `hammingDistance = ...` we will get a `TypeError`. I recommend using `const` whenever you don't need to reassign a variable. *Note this does not mean the variable is immutable, just that it cannot be reassigned.* **ES6 - arrow functions** I've opted to use [arrow function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions) notation over traditional syntax here. Your example does not benefit from any of the advantages such as lexical `this` so feel free to change back to `function(x, y)` as this is a personal choice. **Solution** Here's your code with the suggested changes: ``` const hammingDistance = (x, y) => { let val = x ^ y; let distance = 0; while (val > 0) { val &= val - 1; distance++; } return distance; }; ``` **For loop solution** If you wanted, you could replace the `while` loop with a `for` loop as follows: ``` const hammingDistance = (x, y) => { let val = x ^ y; let distance; for (distance = 0; val > 0; distance++) { val &= val - 1; } return distance; }; ```
37,395,473
I am having trouble with some code that was given to me. It isn't concatenating the rows as it should be. I am pulling from 3 tables to select which rows to concatenate. I have a `Comment`, `WorkOrderT` and `WorkMaterial_nonFiltered` table. The `Comment` table, obviously, has comments and is linked to the `WorkMaterial_nonFiltered` table. The `WorkMaterial_nonFiltered` table is connected to the `WorkOrderT` table which is where the Work Order ID's are. I am trying to use the Work Order ID to get all the comments for that work order and have them all concatenated into one row per work order id. Here is the code as I currently have it: ``` select wo.WOId as ID, STUFF(cast((select distinct '; ' + c.comments from working.Comment c where c.Instance_InstanceId = wm.id for xml path(''), type) as varchar(max)), 1, 1, ' ') as MaterialComments from working.WorkOrderT wo left join working.WorkMaterial_nonFiltered wm on wm.WorkOrder = wo.WOId where wo.WOId = '00559FB6-4DD2-4762-8DE1-8D1B13962AED' order by [MaterialComments] ``` When I run this I get 11 rows as a result. The first has the `MaterialComments` as `NULL` then the others have data in them. I don't care about the `NULL` row, unless it's what's causing the problem, it's the others that I really need to have concatenated, separated by the ";". I've tried building this out one step at a time, but I've not been able to figure out why I always get 11 rows instead of just the 1. I've looked into the following other questions to try and find a solution: [Concatenate many rows into a single text string?](https://stackoverflow.com/questions/194852/concatenate-many-rows-into-a-single-text-string) [Concatenate Rows using FOR XML PATH() from multiple tables](https://stackoverflow.com/questions/26758458/concatenate-rows-using-for-xml-path-from-multiple-tables) [How to create a SQL Server function to “join” multiple rows from a subquery into a single delimited field?](https://stackoverflow.com/questions/6899/how-to-create-a-sql-server-function-to-join-multiple-rows-from-a-subquery-into) [How to make a query with group\_concat in sql server](https://stackoverflow.com/questions/17591490/how-to-make-a-query-with-group-concat-in-sql-server/17591536#17591536) [String Aggregation in the World of SQL Server](http://www.codeproject.com/Articles/691102/String-Aggregation-in-the-World-of-SQL-Server) So far I've not been able to get any suggestions from these links to work for me I still get 11 rows instead of 1 concatenated row. **EDIT** Here is some sample data from what I have in my tables: (Note sure how to make this an actual table sorry for the sloppy formatting) ``` WorkOrderID Comments 00559FB6-4DD2-4762-8DE1-8D1B13962AED 5/17 caj in transit; expected delivery on 5/18 per ups 1Z25AR580319345668 00559FB6-4DD2-4762-8DE1-8D1B13962AED 5/18 caj updated esd on 6/17 per vendor site 00559FB6-4DD2-4762-8DE1-8D1B13962AED 5/17 caj allocated to ship 00559FB6-4DD2-4762-8DE1-8D1B13962AED 5/17 caj updated esd on 5/27 per vendor site 00559FB6-4DD2-4762-8DE1-8D1B13962AED 5/18 caj processed; no udpated delivery date per estes Tracking #/BOL #: 3SNS31780960 00559FB6-4DD2-4762-8DE1-8D1B13962AED 5/18 caj processed; no updated delivery date per ups 1Z39ER600354622348 008FC1D1-D6A6-4E48-A69F-168DBF8D215A Jun 25 2015 10:22AM;dlb223;6/25 dlb 1Z4370490304215160 to be dlv'd today 008FC1D1-D6A6-4E48-A69F-168DBF8D215A Jun 8 2015 1:11PM;klh323;6/8 klh Reserved to meet 06/30 requested delivery date 008FC1D1-D6A6-4E48-A69F-168DBF8D215A Jun 25 2015 10:23AM;dlb223;6/23/2015 008FC1D1-D6A6-4E48-A69F-168DBF8D215A Jun 25 2015 10:23AM;dlb223;6/5 dlb 1Z4370490304215937 to be dlv'd today 008FC1D1-D6A6-4E48-A69F-168DBF8D215A Jun 25 2015 10:24AM;dlb223;6/25 dlb 1Z4370490304216445 to be dlv'd today 00910B84-486C-4AD4-9B1E-5F8D8B42C841 5/12 jad IN TRANSIT; EXPECTED DELIVERY 5/12 PER UPS 1Z750WA20313280446 00910B84-486C-4AD4-9B1E-5F8D8B42C841 4/29 jad IN TRANSIT; EXPECTED DELIVERY 4/29 PER UPS 1Z39ER600354244542 ``` The results I want to look like this: (again I don't know how to make this a table) ``` WorkOrderID Comments 00559FB6-4DD2-4762-8DE1-8D1B13962AED 5/17 caj in transit; expected delivery on 5/18 per ups 1Z25AR580319345668; 5/18 caj updated esd on 6/17 per vendor site; 5/17 caj allocated to ship; 5/17 caj updated esd on 5/27 per vendor site; 5/18 caj processed; no udpated delivery date per estes Tracking #/BOL #: 3SNS31780960; 5/18 caj processed; no updated delivery date per ups 1Z39ER600354622348 008FC1D1-D6A6-4E48-A69F-168DBF8D215A Jun 25 2015 10:22AM;dlb223;6/25 dlb 1Z4370490304215160 to be dlv'd today; Jun 8 2015 1:11PM;klh323;6/8 klh Reserved to meet 06/30 requested delivery date; Jun 25 2015 10:23AM;dlb223;6/23/2015; Jun 25 2015 10:23AM;dlb223;6/5 dlb 1Z4370490304215937 to be dlv'd today; Jun 25 2015 10:24AM;dlb223;6/25 dlb 1Z4370490304216445 to be dlv'd today 00910B84-486C-4AD4-9B1E-5F8D8B42C841 5/12 jad IN TRANSIT; EXPECTED DELIVERY 5/12 PER UPS 1Z750WA20313280446; 4/29 jad IN TRANSIT; EXPECTED DELIVERY 4/29 PER UPS 1Z39ER600354244542 ``` I hope that this makes it more clear what I'm trying to accomplish.
2016/05/23
[ "https://Stackoverflow.com/questions/37395473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2911241/" ]
I have ended up using pass through queries to a linked server. That is where the problem actually was. With the data coming back from the linked server. Once I figured that out I was able to get the results that I needed. Now I have a really long pass through query that uses the `for xml` and gives me the comments for the WOID's the way that I need them.
5,267,988
I just need a hello world demo to see how machine code actually works. Though windows' **EXE** and linux' **ELF** is near machine code,but it's not **PURE** How can I write/execute **PURE** machine code?
2011/03/11
[ "https://Stackoverflow.com/questions/5267988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631505/" ]
Everyone knows that the application we usually wrote is run on the operating system. And managed by it. It means that the operating system is run on the machine. So I think that is PURE machine code which you said. So, you need to study how an operating system works. Here is some NASM assembly code for a boot sector which can print "Hello world" in PURE. ``` org xor ax, ax mov ds, ax mov si, msg boot_loop:lodsb or al, al jz go_flag mov ah, 0x0E int 0x10 jmp boot_loop go_flag: jmp go_flag msg db 'hello world', 13, 10, 0 times 510-($-$$) db 0 db 0x55 db 0xAA ``` And you can find more resources here: <http://wiki.osdev.org/Main_Page>. END. If you had installed nasm and had a floppy, You can ``` nasm boot.asm -f bin -o boot.bin dd if=boot.bin of=/dev/fd0 ``` Then, you can boot from this floppy and you will see the message. (NOTE: you should make the first boot of your computer the floppy.) In fact, I suggest you run that code in full virtual machine, like: bochs, virtualbox etc. Because it is hard to find a machines with a floppy. So, the steps are First, you should need to install a full virtual machine. Second, create a visual floppy by commend: bximage Third, write bin file to that visual floppy. Last, start your visual machine from that visual floppy. NOTE: In <https://wiki.osdev.org> , there are some basic information about that topic.
1,651
I flagged many, but not all, of the comments on [this question](https://law.stackexchange.com/q/86530/46948) and [associated answer](https://law.stackexchange.com/a/86532/46948) as not needed/conversational. The flags were declined. They are mostly talking about the physical makeup of money, inflation and, whether one of their friends in the 1970s would have purchased a beer or cannabis resin with extra money. Some examples (although I don't want to get bogged down in this specific instance; I'm more interested in flagging practice generally): > > In the 1970s a friend washed, in a launderette, a pair of jeans with a one-pound note in a pocket. It was real money in those days for a young student. Worth around 12 US dollars in today's values. He sent it to the Bank of England and they mailed him a £1 postal order to cash at a post office. > > > > > I don't know where you got that from, but around here, nobody but car dealers and jewelers regularly come in contact with 200 euro bills. Most transactions requiring bills that size are now made electronically. Lots of shops will not accept 500 and 200 bills. > > > > > in fact knowing this guy he would have spent £1 of fun money on cannabis resin, and it would have got him around 2 or 3 grams, and you can't really buy that stuff these days. I don't know what £10 would buy now, as I don't use recreational drugs > > > Can a person who reviews such flags explain how the comments are helpful so that I can be more selective in my flagging (if you even mind that I have over-flagged in this instance)? Or, if it's alright that I might be raising flags that sometimes are declined, let me know that too (i.e. I [should just keep flagging as I see it and you'll just decline what you disagree with and that's all fine](https://law.meta.stackexchange.com/a/939/46948) - I found this other answer after writing this question). I just don't want to be cluttering your queues. I appreciate any insight into how moderators approach these. To be clear, I am not critical of the approach taken by moderators to these particular flags; it just doesn't match my prior understanding, and am looking for understanding of how the moderators view things to help guide my own flagging behaviour. Hopefully this is also helpful to others.
2022/11/23
[ "https://law.meta.stackexchange.com/questions/1651", "https://law.meta.stackexchange.com", "https://law.meta.stackexchange.com/users/46948/" ]
I also flagged the comments after seeing this post. My flag on this comment also got rejected: > > I once ran a pair of blue jeans through the cycles through which a > washing machine puts them and then found that I had left three > twenty-dollar bills in one of the pockets. That is my only experience > of money laundering. > > > I have to say I am quite curious as to how this doesn't quality as being either "outdated, conversational or not relevant to this post.". To me, this is the very definition of conversational.
24,366,091
We receive a file from an external provider. One of the columns contains a timestamp in the form "05/01/2014 09:25:41 AM EDT". I am trying to insert this into a TIMESTAMP WITH TIME ZONE column with the following SQL: `INSERT INTO table VALUES (to_timestamp_tz('05/01/2014 09:25:41 AM EDT', 'MM/DD/YYYY HH12:MI:SS AM TZR TZD'));` That is when I get `ORA-1882: timezone region not found`. I've also tried specifying this like `INSERT INTO table VALUES (to_timestamp_tz('05/01/2014 09:25:41 AM EST EDT', 'MM/DD/YYYY HH12:MI:SS AM TZR TZD'));` but then I get `ORA-1857: not a valid time zone`. Anyone have an idea how I can insert this? We are running Oracle 11.2.0.3. I can see in `v$timezone_names` that EST and EDT both appear to be valid tzabbrev for tzname 'America/New York'. EDIT: It appears that if I substitute EST5EDT for EDT (and CST6CDT, MST7MDT, and PST8PDT for CST, MST, and PST, respectively) , I can get the behavior I need. The problem with this is that I need to know what these substitutions are in advance so I can code around them. I still need to know how to handle potential daylight savings time issues with other timezones.
2014/06/23
[ "https://Stackoverflow.com/questions/24366091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3767403/" ]
> > Are they differ in anything other than the usage ? or Does the syntax and definitions also differ? > > > The language is the same. The environment is different. By "Core JavaScript," Flanagan is talking about *the language* and only the objects and functions defined by the [ECMAScript specification](http://ecma-international.org/ecma-262/5.1/), leaving anything provided by the *environment* out. By "Client-side JavaScript" he's talking about the use of JavaScript, the language, in a browser environemnt. In a browser environment, your code will have access to things provided by the browser, like the `document` object for the current page, the `window`, functions like `alert` that pop up a message, etc. By "Server-side JavaScript" he's talking about the use of JavaScript, the language, in a server environment. In that environment, your code won't have access to browser-related things because, well, it's not in a browser. It'll probably have access to other things, like APIs for dealing with the file system, databases, network, etc.
93,224
> > Use spaces liberally throughout your code. “When in doubt, space it out.” > > > In the above sentence, what does "space it out" mean? Source: <https://make.wordpress.org/core/handbook/best-practices/coding-standards/javascript/#spacing>
2016/06/09
[ "https://ell.stackexchange.com/questions/93224", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/36262/" ]
In your example > > space it out > > > means to add spaces (or whitespaces) to make the code easier for humans to read. Consider the difference between > > def myMethod(a,b,c)if(a==b)t=0;elseif(b==c)t=a;else t=c;end;return t;end > > > and > > def myMethod(a,b,c) > >     if(a==b) > >         t=0; > >     elseif(b==c) > >         t=a; > >     else > >         t=c; > >     end; > >     return t; > > end > > > the nesting, using additional whitespace indentation, more clearly shows how the code will execute given different conditions. In some circumstances, behind the scenes, the additional whitespace is automatically removed (since the computer does not need it) in a process call "minification". Your example also uses the well known construction since "doubt" and "out" rhyme > > when in doubt, *something* it out > > > where *something* can be any verb that goes with "out" as long as the context makes sense > > when in doubt, white it out *(with correction fluid)* > > when in doubt, scream it out > > when in doubt, cut it out *(a possible saying by surgeons)* > > when in doubt, ride it out > > when in doubt, wait it out > > >
43,918,785
I have a data frame with columns I want to reorder. However, in different iterations of my script, the total number of columns may change. ``` >Fruit Vendor A B C D E ... Apples Oranges Otto 4 5 2 5 2 ... 3 4 Fruit2<-Fruit[c(32,33,2:5)] ``` So instead of manually adapting the code (the columns 32 and 33 change) I'd like to do the following: ``` Fruit2<-Fruit[,c("Apples", "Oranges", 2:5)] ``` I tried a couple of syntaxes but could not get it to do what I want. I know, this is a simple syntax issue, but I could not find the solution yet. The idea is to mix the variable name with the vector to reference the columns when writing a new data frame. I don't want to spell out the whole vector in variable names because in reality it's 30 variables.
2017/05/11
[ "https://Stackoverflow.com/questions/43918785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7998091/" ]
Make sure you are "adding" the `mysql-connector-java-5.1.42-bin.jar` file to the classpath when starting your program (obviously it can be a different version number). something like ``` java -cp .;mysql-connector-java-5.0.8-bin.jar JdbcExample ``` or ``` set CLASSPATH=...;mysql-connector-java-5.0.8-bin.jar java JdbcExample ``` assuming: 1. the JAR is in the current folder... if that works, consider putting the JAR in a 'central' place a use the complete path in above commands 2. using Windows, otherwise the separator would be `:` instead of `;` 3. the class is in no package for Ubuntu: ``` java -cp .:mysql-connector-java-5.0.8-bin.jar JdbcExample ```
35,679,477
``` array[obj][obj] = 1; ``` I want to create 2D array whose index is user defined object. How to do this? or there is some other data structure available to do this?
2016/02/28
[ "https://Stackoverflow.com/questions/35679477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5672907/" ]
Android will use `res\values-v21\styles.xml` if the user's device is running Android API level 21+ (Android 5.0+) & will use `res\values\styles.xml` for older versions
1,825,624
I have created a job with the `at` command on Solaris 10. It's working now but I want to kill it but I don't know how I can find the job number and how to kill that job or process.
2009/12/01
[ "https://Stackoverflow.com/questions/1825624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/147352/" ]
You should be able to find your command with a `ps` variant like: ``` ps -ef ps -fubob # if your job's user ID is bob. ``` Then, once located, it should be a simple matter to use `kill` to kill the process (permissions permitting). If you're talking about getting rid of jobs in the `at` queue (that aren't running yet), you can use `atq` to list them and `atrm` to get rid of them.
275,274
There is a challenge involving a lemon floating in a jug of water which seems impossible to beat. I've noticed it in several pubs of Edinburgh. The challenge is as follows: * There is a jug half filled with water. * Floating in the water, there's a lemon. The lemon doesn't touch either the bottom nor the edges of the jug. * The challenge is to successfully balance a coin on the lemon. * Modifying, moving, or more generally touching the lemon are not allowed. Any attempt to balance a coin on the lemon seems to result in the lemon flipping over, and the coin to sink in the water. Why is it so hard to balance the coin while it's extremely easy to balance a coin on a lemon set on a table? How do you beat the lemon challenge?
2016/08/19
[ "https://physics.stackexchange.com/questions/275274", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/67968/" ]
We assume the lemon is rigid, which is reasonably accurate for these small forces. Stability in buoyancy requires a small rotation to create a net restoring torque. This is conceptualized as the [metacenter](https://en.wikipedia.org/wiki/Metacentric_height), which is the "average" point the water pushes upward on. For *small* displacement angles this point remains fixed to the object. If the center of gravity is above the metacenter it's unstable. For the lemon, the metacenter is very close to the center since it's almost cylindrically symmetric. A coin raises the center of mass above the metacenter and makes the system unstable, regardless of exactly where it's positioned. For a lemon on the table, the bumps and/or flat-regions act like a tiny tripod. As long as the center of mass stays above this "tripod" (above a point inside the triangle defined by it's three feet), it is stable. The center of mass depends on the position of the coin, so we can find a location that is stable for an arbitrarily small tripod. As to the water case, it may be possible if the lemon is oddly shaped enough.
48,758,254
I am trying to join two tables: Table1: (900 million rows (106 GB). And, id1, id2, id3, id4 are **clustered primary key**, houseType is string) ``` +-----+-----+-----+------------+--------+ | Id1 | id2 | id3 | id4 | val1 | +-----+-----+-----+------------+--------+ | ac | 15 | 697 | houseType1 | 75.396 | +-----+-----+-----+------------+--------+ | ac | 15 | 697 | houseType2 | 20.97 | +-----+-----+-----+------------+--------+ | ac | 15 | 805 | houseType1 | 112.99 | +-----+-----+-----+------------+--------+ | ac | 15 | 805 | houseType2 | 53.67 | +-----+-----+-----+------------+--------+ | ac | 27 | 697 | houseType1 | 67.28 | +-----+-----+-----+------------+--------+ | ac | 27 | 697 | houseType2 | 55.12 | +-----+-----+-----+------------+--------+ ``` Table 2 is very small with 150 rows. And, val1, val2 are **clustered primary key.** ``` +------+------+---------+ | val1 | val2 | factor1 | +------+------+---------+ | 0 | 10 | 0.82 | +------+------+---------+ | 10 | 20 | 0.77 | +------+------+---------+ | 20 | 30 | 0.15 | +------+------+---------+ ``` **What I need :** For every "val1" in table1, it should be found which range [val1, val2] in table2 it belongs to and its associated "factor1" in table2 should be returned from table2, which will be used for further aggregate calculation. example of my query: ``` Select a.id1, a.id2, a.id3, a.id4, max(case when a.val1 >= b.val1 and a.val1 < b.val2 then b.factor1 * a.val1 else null end ) as result From Table1 as a, Table2 as b Group by a.id1, a.id2, a.id3, a.id4 ``` For example, a row : ``` ac , 15, 697, houseType2, 20.97 in table1 0.15 should be returned from table2 because 20.97 in range [20, 30] in table2. ``` **There is no join action in the query because I do not know how to use join here. I just need to lookup the factors for val1 in table2.** In SQL server, it runs very slow with more than 3 hours. I also got : ``` Warning: Null value is eliminated by an aggregate or other SET operation. ``` Could anyone help me about this ? thanks
2018/02/13
[ "https://Stackoverflow.com/questions/48758254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3448011/" ]
This should reduce your recordset: ``` Select a.id1, a.id2, a.id3, a.id4, b.factor1 * a.val1 as result From Table1 a inner join Table2 b on a.val1 >= b.val1 and a.val1 < b.val2 ``` This way, you will only get a single record from b for each record from a. This is at least a start to improve your performance problem. No need for MAX because you are joining to get a single record.
30,533,846
I am using the Chartist plugin for generating charts. I've noticed that it does different element generations through browsers. In Internet Explorer, it uses the `<text>` element, but it is offset on the left by 70px. I want to move that element on the right 70px, but I can't achieve this. I've tried with the `text-anchor`, `transform`, some letter and word spacing hacks, but none of them work. Here is the code I am trying to modify: ``` <text class="ct-label ct-horizontal ct-end" x="25" y="205" width="179" height="20">FEB-2015</text> ``` So, instead of X-20, I want X-90. [Here is a live demo](http://amarsyla.com/sandbox/hotelkey)
2015/05/29
[ "https://Stackoverflow.com/questions/30533846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1616512/" ]
Correct (but possibly slow) solution ------------------------------------ This **is** a bug of the Chartist library. They are calculating their label position so it is not center-aligned to the category. For the permanent solution, you need to take it up with them, so the bug is fixed on their side. You can find author's contact details on [this GitHub page](https://github.com/gionkunz). Temporary solution ------------------ In the interim, you can apply a dirty fix by shifting the whole labels block to the right. As IE11 ignores `transform` properties applied via CSS, we will need to apply it directly to the SVG node properties. Since you have jQuery on your page, we'll use that for the simplicity sake: ``` <!--[if IE]> <script> $chart.on( 'created', function() { $( '.ct-labels' ).attr( 'transform', 'translate(70)' ); } ); </script> <![endif]--> ``` Needless to say, this needs to go **after** your other chart code.
292,887
Recently I downloaded ubuntu 13.04 (iso). Now after extracting the iso file and running wubi - it says downloading required files though I had already downloaded the iso file (794 MB). So what to do now?
2013/05/09
[ "https://askubuntu.com/questions/292887", "https://askubuntu.com", "https://askubuntu.com/users/101535/" ]
wubi in 13.04 is not in a releasable state. You have to install Ubuntu 12.10 through wubi and then upgrade to 13.04. follow this [steps](http://schoudhury.com/blog/articles/install-ubuntu-13-04-with-ubuntu-wubi-installer/)
67,506,376
I am trying to create a Django application where each User has one model attached to them ( a list of Plants ) and that model is composed of individual plants. I already know I can have the plants connected to the plant list through a many-to-one relationship using foreign key as shown down below: ``` class PlantList(models.Model): plant_list_id = models.AutoField(primary_key=True) class Plant(models.Model): plantlist = models.ForeignKey(PlantList, on_delete = models.CASCADE) name = models.CharField(max_length = 20) wateringInterval = models.PositiveSmallIntegerField() ``` However, I want each user to have a plant list attached to them that can be displayed uniquely for each user, according to the plants that they add to their list. How would I make it so that each user has a plant list? I was trying to have it inside the register form but couldn't figure out how to do it and I wanted each plantlist to have a unique ID so that I can add plants to it easier. ``` class AddNewPlant(forms.Form): name = forms.CharField(label='Name',max_length = 20) wateringInterval = forms.IntegerField(label='Watering Interval') ```
2021/05/12
[ "https://Stackoverflow.com/questions/67506376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10322369/" ]
Actually if all you want is a string representation of `Int` `Float` `Double` or any other standard numeric type you only need to know that they conform to `CustomStringConvertible` and use `String(describing:)`. Or you can use conformance to [`Numeric`](https://developer.apple.com/documentation/swift/numeric) **and** [`CustomStringConvertible`](https://developer.apple.com/documentation/swift/customstringconvertible): ``` struct example { var string: String init<C: CustomStringConvertible & Numeric>(number: C) { string = String(describing: number) } } ``` and maybe even better `example` itself could conform to `CustomStringConvertible` ``` struct example: CustomStringConvertible { var description: String init<C: CustomStringConvertible & Numeric>(number: C) { description = String(describing: number) } } ``` yet another way : ``` struct example<N: Numeric & CustomStringConvertible>: CustomStringConvertible { let number: N init(number: N) { self.number = number } var description: String { String(describing: number) } } ``` ### EDIT I think what you want is a custom [Property Wrapper](https://docs.swift.org/swift-book/LanguageGuide/Properties.html#ID617) not `@Binding`: ``` @propertyWrapper struct CustomStringConversion<Wrapped: CustomStringConvertible> { var wrappedValue: Wrapped init(wrappedValue: Wrapped) { self.wrappedValue = wrappedValue } var projectedValue: String { .init(describing: wrappedValue) } } struct Foo { @CustomStringConversion var number = 5 } let foo = Foo() let number: Int = foo.number // 5 let stringRepresentation: String = foo.$number // "5" ``` But as @LeoDabus pointed out [using `LosslessStringConvertible`](https://stackoverflow.com/questions/65958622/extending-a-type-to-have-multiple-values-for-the-same-associatedtype/65960326#65960326) may be better : ``` struct example<N: Numeric & LosslessStringConvertible>: LosslessStringConvertible { let number: N init(number: N) { self.number = number } init?(_ description: String) { guard let number = N(description) else { return nil } self.number = number } var description: String { .init(number) } } let bar = example(number: Double.greatestFiniteMagnitude) // 1.7976931348623157e+308 let baz: example<Double>? = example("1.7976931348623157e+308") // 1.7976931348623157e+308 ```
44,628,848
I'm trying to create annotations on the MapKit from a `geoJSON` file, but the problem is that the coordinates provided by the `geoJSON` file don't match the coordinate system that `MapKit` uses. **Question** : How do I convert *read* the geoJSON file and *convert* the coordinates from [``](http://spatialreference.org/ref/epsg/sweref99-13-30/) to `WGS84S`? Here is an example of what the `geoJSON` file looks like: ``` {"name":"MAPADDRESSPOINT","type":"FeatureCollection" ,"crs":{"type":"name","properties":{"name":"EPSG:3008"}} ,"features":[ {"type":"Feature","geometry":{ "type":"Point","coordinates": [97973.4655999987,6219081.53249992,0]}, "properties":{ "ADDRESSAREA_resolved":"Sadelvägen", "multi_reader_id":1, "multi_reader_full_id":1, "BALSTATUS_resolved":"Gällande", "REMARKTYPE_resolved":"", "FARMADDRESSAREA_resolved":"", "geodb_type":"geodb_point", "multi_reader_keyword":"GEODATABASE_SDE_2", "DEVIATEFROMSTANDARD_resolved":"", "geodb_feature_is_simple":"yes", "STATUS_resolved":"Ingen information", "ADDRESSEDCONSTRUCTIONTYPE_resolved":"", "SUPPLIER_resolved":"", "multi_reader_type":"GEODATABASE_SDE", "geodb_oid":18396, "STAIRCASEIDENTIFIER_resolved":"", "LOCATIONADDRESSSTATUS_resolved":"Gällande", "POSITIONKIND_resolved":"Byggnad", "BALADDRESSTYPE_resolved":"Gatuadressplats", "COMMENTARY":""," DTYPE":"", "EXTERNALID":2,"GID":"{DEEA1685-2FF3-4BEB-823D-B9FA51E09F71}", "MODIFICATIONDATE":"20170301173751", "MODIFICATIONSIGN":"BAL service", "OBJECTID":18396, "REGDATE":"20110321151134", "REGSIGN":"BAL service", "STATUS":0, "ADDRESSEDCONSTRUCTIONVALUE":"", "LABELROTATIONANGLE":0, "POSTCODE":"25483", "POSITIONKIND":1, "REALPROPERTYKEY":"120320803", "BALSTATUS":2, "BALADDRESSTYPE":1, "BALID":"D5650F0B-EE54-4C4C-9C40-A8162118288C", "DESIGNATIONVALUE":"", "SYNCDATE":"20170301173751", "STREETNAME":"Sadelvägen", "ADDRESSAREA":554, "YARDSNAME":"", "PLACENAMEID":"", "ADDRESSLABEL":"Sadelvägen 6", "DESIGNATIONNUMBERLETTER":"", "LOCATIONADDRESSSTATUS":3, "CITY":"Helsingborg", "ENUMERATOR":"6", "SYMBOLROTATIONANGLE":0, "POPULARNAME":"", "geodb_feature_dataset":"Adress" } } }] } ```
2017/06/19
[ "https://Stackoverflow.com/questions/44628848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8171709/" ]
<https://en.m.wikipedia.org/wiki/Transverse_Mercator_projection> Longitude of natural origin 0° 00' 00.000" N 13° 30' 00.000" E Scale factor at natural origin 1 False easting 150000 meters False northing 0 FINAL (Playground) version ``` //: [Previous](@previous) import Foundation extension Double { var rad: Double { get { return .pi * self / 180.0 } } var deg: Double { get { return 180.0 * self / .pi } } } // SWEREF99 13 30 (GRS80) let φ0 = 0.0 let λ0 = 13.5.rad let N0 = 0.0 let E0 = 150000.0 let k0 = 1.0 // GRS80 let a = k0 * 6378137.0 let b = k0 * 6356752.31414034 let n = (a - b)/(a + b) let n2 = n * n let n3 = n2 * n let n4 = n3 * n let a2 = a * a let b2 = b * b let e2 = (a2 - b2)/a2 let H0 = 1.0 + 1.0/4.0*n2 + 1.0/64.0*n4 let H2 = -3.0/2.0*n + 3.0/16.0*n3 let H4 = 15.0/16.0*n2 - 15.0/64.0*n4 let H6 = -35.0/48.0*n3 let H8 = 315.0/512.0*n4 let ν:(Double)->Double = { φ in return a/(sqrt(1.0 - e2 * sin(φ) * sin(φ))) } let ρ:(Double)->Double = { φ in return ν(φ) * (1.0 - e2) / (1.0 - e2 * sin(φ) * sin(φ)) } let η2:(Double)->Double = { φ in return ν(φ) / ρ(φ) - 1.0 } var arcMeridian1:(Double)->Double = { φ in let m = (a + b) / 2 * (H0 * φ + H2 * sin(2.0 * φ) + H4 * sin(4.0 * φ) + H6 * sin(6.0 * φ) + H8 * sin(8.0 * φ)) return m } var arcMeridian:(Double, Double)->Double = { φ1, φ2 in return arcMeridian1(φ2) - arcMeridian1(φ1) } var cartografic:(Double,Double)->(Double,Double) = { φ, λ in let νφ = ν(φ) let ρφ = ρ(φ) let η2φ = νφ / ρφ - 1.0 let s1 = sin(φ) let s2 = s1 * s1 let c1 = cos(φ) let c2 = c1 * c1 let c3 = c2 * c1 let c5 = c3 * c2 let t2 = s2/c2 let t4 = t2 * t2 let k1 = νφ * c1 let k2 = νφ/2.0 * s1 * c1 let k3 = νφ/6.0 * c3 * (νφ / ρφ - t2) let k4 = νφ/24.0 * s1 * c3 * (5.0 - t2 + 9.0 * η2φ) let k5 = νφ/120.0 * c5 * (5.0 - 18.0 * t2 + t4 + 14.0 * η2φ - 58.0 * t2 * η2φ) let k6 = νφ/720.0 * s1 * c5 * (61.0 - 58.0 * t2 + t4) let Δλ = λ - λ0 let Δλ2 = Δλ * Δλ let Δλ3 = Δλ2 * Δλ let Δλ4 = Δλ3 * Δλ let Δλ5 = Δλ4 * Δλ let Δλ6 = Δλ4 * Δλ let N = arcMeridian(φ0,φ) + N0 + Δλ2 * k2 + Δλ4 * k4 + Δλ6 * k6 let E = E0 + Δλ * k1 + Δλ3 * k3 + Δλ5 * k5 return (N,E) } var geodetic:(Double,Double)->(Double,Double) = { N, E in var φ = (N - N0) / a + φ0 var M = arcMeridian(φ0, φ) var diff = 1.0 repeat { φ += (N - N0 - M) / a M = arcMeridian(φ0, φ) diff = N - N0 - M } while abs(diff) > 0.0000000001 // max 3 - 4 iterations let E1 = E - E0 let E2 = E1 * E1 let E3 = E2 * E1 let E4 = E3 * E1 let E5 = E4 * E1 let E6 = E5 * E1 let E7 = E6 * E1 let νφ = ν(φ) let νφ3 = νφ * νφ * νφ let νφ5 = νφ3 * νφ * νφ let νφ7 = νφ5 * νφ * νφ let ρφ = ρ(φ) let η2φ = νφ / ρφ - 1.0 let s1 = sin(φ) let s2 = s1 * s1 let c1 = cos(φ) let t1 = s1 / c1 let t2 = t1 * t1 let t4 = t2 * t2 let t6 = t4 * t2 let k1 = 1.0 / (c1 * νφ) let k2 = t1 / (2.0 * ρφ * νφ) let k3 = 1.0 / (6.0 * νφ3) * (νφ / ρφ + 2.0 * t2) let k4 = (t1 / (24.0 * ρφ * νφ3)) * (5.0 + 3.0 * t2 + η2φ - 9.0 * t2 * η2φ) let k5 = 1.0 / (120.0 * νφ5) * (5.0 + 28.0 * t2 + 24.0 * t4) let k6 = (t1 / (720.0 * ρφ * νφ5)) * (61.0 + 90.0 * t2 + 45.0 * t4) let k7 = (t1 / (5040.0 * ρφ * νφ7)) * (61.0 + 662.0 * t2 + 1320.0 * t4 + 720.0 * t6) φ = φ - E2 * k2 + E4 * k4 - E6 * k6 let λ = λ0 + E1 * k1 - E3 * k3 + E5 * k5 - E7 * k7 return (φ, λ) } print("pecision check") let carto0 = cartografic(55.0.rad, 12.75.rad) print(carto0,"err:", carto0.0 - 6097487.637, carto0.1 - 102004.871) let carto1 = cartografic(61.0.rad, 14.25.rad) print(carto1,"err:", carto1.0 - 6765725.847, carto1.1 - 190579.995) print() print("given position: N 6219081.53249992, E 97973.4655999987") let geo = geodetic(6219081.53249992, 97973.4655999987) print("geodetic: φ =", geo.0.deg,"λ =", geo.1.deg) //: [Next](@next) ``` prints ``` pecision check (6097487.6372101102, 102004.87085248799) err: 0.00021011009812355 -0.000147512007970363 (6765725.8471242301, 190579.99493182387) err: 0.000124230049550533 -6.81761302985251e-05 given position: N 6219081.53249992, E 97973.4655999987 geodetic: φ = 56.0916410844269 λ = 12.6641326192406 ``` position on map [![enter image description here](https://i.stack.imgur.com/to2xM.jpg)](https://i.stack.imgur.com/to2xM.jpg)
12,220,650
I have a very odd problem related to the Portland Group FORTRAN 90 compiler. I am trying to run a code that *relies* on array overflow to work properly. *I did not write this code!* The originators had to compile it with the flag "-tp=piii" to force the compiler to refrain from optimizations that defeated the array overflow. I guess the idea is that compilers written for the old P3 were too primitive to do this sort of thing. Now, when I try to do the same thing, I get the message "pgf90-Fatal --tp piii is not supported in this installation." So I can't do the same thing. So: Does pgf90 in its default operation defeat the sort of array overflow the code needs? The people I am working with obviously think it does. And, if it does, could there be some other flag(s) I could use to get what I need from the "-tp=piii" flag? Bet you never thought you would get a question like this! Just think how *I* feel. And yes, I will be re-writing it as soon as I can convince my keepers to let me do it.
2012/08/31
[ "https://Stackoverflow.com/questions/12220650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1380285/" ]
I'm no longer familiar with the PGI compiler and don't have its documentation to hand so can't guide you directly to the compiler option you want, but it will be indexed under something like *array bounds* or *bounds checking*. Until Fortran 90 it was common practice to write code which ignored, or was ignorant of, array bounds. Much of the code that was written that way is still out in the wild and I (like most Fortran programmers) come across it regularly. Sadly (that's argumentative) so is the attitude that it is an acceptable way to write code; if I meet the attitude out in the wild I terminate it with extreme prejudice. Rant over ... it is the default behaviour of at least some of the Fortran compilers currently in widespread use to not automatically generate code which, at run-time, has a tantrum when the program steps outside an array's boundaries. However, all of them will have an option to generate code which does include bounds checking at run-time. Not checking array bounds at run time generally means faster code and most Fortran users are very interested in faster code which goes some way to explaining the default behaviour of compilers. So, to conclude, you shouldn't have too much trouble reproducing the required behaviour of the code you've inherited. I'll be a little surprised if the PGI compiler doesn't default to not checking array bounds; but it will definitely have an option for switching the feature on or off.
4,043
Has anyone created a twitter like app in Sharepoint 2007? Would really like to know about your ideas and suggestions.
2010/07/15
[ "https://sharepoint.stackexchange.com/questions/4043", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/-1/" ]
There are a few options for you. Michael Gannotti has this point on how to do it simply with a content editor web part and some javascript: <http://sharepoint.microsoft.com/blogs/mikeg/Lists/Posts/Post.aspx?ID=1202> Aidan Garnish has a solution here: <http://aidangarnish.net/blog/post/2009/02/Twitter-SharePoint-web-part.aspx> There's a CodePlex project called SharePointTwitter here: <http://sharepointtwitter.codeplex.com/> And if you just want to search twitter there's a web part here: <http://www.mattjimison.com/blog/2009/03/04/twitter-search-webpart/> Hope that helps!
14,613,498
See demo: [jsFiddle](http://jsfiddle.net/bVyW5/) * I have a simple form that is being toggled when clicking 'show' / 'cancel' * Everything works fine, but **if you click 'cancel' shortly after the form is revealed, there's a good 2-3 seconds lag before the animation even begins**. * This doesn't happen if you wait a few seconds before clicking 'cancel'. * The lag occures in all tested browsers (ie, ff, chrome). **1. What could cause this lag and how can it be prevented?** **2. Is there a better way of coding this sequence of animations, that might prevent any lags?** **HTML**: ``` <div id="newResFormWrap"> <form id="newResForm" action="" method="post" name="newRes"> <div id="newResFormCont"> <h3>title</h3> <p>form!</p> <div class="button" id="cancelNewRes">Cancel</div> </div> </form> </div> <div class="button" id="addRes">show</div> ``` **jQuery:** ``` $("#newResForm").css({opacity: 0}); $("#addRes").click(function () { toggleNewRes() }); $("#cancelNewRes").click(function () { toggleNewRes() }); //toggleNewRes function toggleNewRes() { if ($("#newResFormWrap").css('display') == "none") {//if hidden $("#addRes").animate({ opacity: 0 }, 'fast', function() { $("#newResFormWrap").toggle('fast', function (){ $("#newResForm").animate({ opacity: 100 },2000); }); }); } else { //if visible $("#newResForm").animate({ opacity: 0 }, 100,function() { $("#newResFormWrap").toggle('fast', function (){ $("#addRes").animate({ opacity: 100 }); }); }); } } ```
2013/01/30
[ "https://Stackoverflow.com/questions/14613498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/806061/" ]
Make sure to clear the queue when starting a new animation with `stop()`: ``` $("#newResForm").stop().animate({ opacity: 0 }, 100,function() { $("#newResFormWrap").toggle('fast', function (){ $("#addRes").animate({ opacity: 100 }); // ... ``` What's causing the lag is the fact that your long 2-second animation `$("#newResForm").animate({ opacity: 100 },2000)` isn't finished yet. JQuery puts animations by default into a queue, waiting for one to finish before the next begins. You clear the queue with `stop()`, which is especially useful if you have two contradicting animations (like an open and close animation, or a mouseover/mouseout animation). In fact you might find it a good practice to begin all your animation chains with `stop()` unless you know you want them to queue with prior animations that may have occurred elsewhere. Getting into more advanced topics, you can even name different queues, so that for example your hover animations and your expand/collapse animations are treated separately for the purposes of `stop()`. See the `queue` option (when given a string) at <http://api.jquery.com/animate/> for more details.
1,602,055
Given a set $X$ and a family $\mathcal{S}$ of subsets of $X$, prove that there exists a topology $\mathcal{T}(\mathcal{S})$ on $X$ which contains $\mathcal{S}$ and is the smallest with this property (Hint: use the axioms to see what other subsets of $X$, besides the ones from $\mathcal{S}$, must $\mathcal{T}(\mathcal{S})$ contain.) I checked the axioms of a topology and I think the other subset $\mathcal{T}(\mathcal{S})$ has to contain is $X$ (for the first axiom). Is this correct? and why is this the smallest topology? How do I prove that?
2016/01/06
[ "https://math.stackexchange.com/questions/1602055", "https://math.stackexchange.com", "https://math.stackexchange.com/users/294640/" ]
The "smallest" topology $\mathcal{T}(S)$ is the topology such that if $T'$ is any other topology containing the subsets in the collection $S$, then $\mathcal{T}(S) \subseteq T'$. As the other answerers have pointed out, consider taking every topology on the set $X$ which contains all of the sets in $S$, and then take the intersection of all of those topologies. We get another topology! To show this: Consider $(\mathcal{T}\_{i})\_{i \in I}$ to be the collection of topologies on $X$ in which each topology $\mathcal{T}\_{i}$ contains the sets in $S$. We are interested in three things: 1. **Is this intersection non-empty?** Yes! Since the power set of $X$, $\mathcal{P}(X)$ is a topology which contains every set in the collection $S$, and also since the set $X$ is an element of every topology, the intersection of the topologies is non-empty. 2. **Is the intersection a topology?** Yes! You should prove this (it's very easy). Suppose $\mathcal{T}\_{i}$ is a topology for each $i \in I$. Suppose the intersection $\cap\_{i \in I} \mathcal{T}\_{i}$ is non-empty. Then this intersection is also a topology. Prove it. 3. **Once we establish that for the topologies $\mathcal{T}\_{i}$ that contain the collection $S$, $\cap\_{i \in I} \mathcal{T}\_{i}$ is a topology, then we want to know if this topology contains the collection $S$. Does it?** Yes! Why? 4. **Finally, do we have that $\cap\_{i \in I} \mathcal{T}\_{i} \subseteq T$ for any topology $T$ which contains the collection of sets $S$?** Yes! Why?
20,604,093
I am stuck with a problem installing Qt5 on OSX. The [Qt Requirements for Mac OSX](http://qt-project.org/doc/qt-5.0/qtdoc/requirements-mac.html) are done - Xcode and command line are installed. Then I followed the steps: ``` # mkdir qt5 # cd qt5 # git clone git://gitorious.org/qt/qtbase.git # cd qt5 # ./configure The test for linking against libxcb and support libraries failed! You might need to install dependency packages, or pass -qt-xcb. ``` Then I also tried ``` # cd qtbase # ./configure -prefix $HOME/development/macosx/qt5 -nomake docs -nomake examples -nomake demos -nomake tests -opensource -confirm-license -release -no-c++11 Unknown part docs passed to -nomake. # ./configure The test for linking against libxcb and support libraries failed! You might need to install dependency packages, or pass -qt-xcb. ``` Some other links on related problems are: * ["Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed](https://stackoverflow.com/questions/17106315/failed-to-load-platform-plugin-xcb-while-launching-qt5-app-on-linux-without) * [Qt5 installation problems](https://stackoverflow.com/questions/14424158/qt5-installation-problems) Then [Xquartz](http://xquartz.macosforge.org/landing/) was also installed, supposing that the problem is because X11 is missing on OSX Mountain Lion, restarted the computer and tried the installation again. It didn't solved the problem a bit. On Linux Qt5 installation was nice with no hustle. But on OSX it doesn't work. I hope someone can give any suggestions.
2013/12/16
[ "https://Stackoverflow.com/questions/20604093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194990/" ]
I just encountered this same problem myself, and I worked around it by specifying the argument -no-xcb (instead of -qt-xcb) to the configure script. That allowed the compilation of the Qt libraries to complete (although some of the Qt example programs failed to compile... but it was enough to get me back on track for now). I suspect this is a Mavericks-specific problem, as the same Qt source tarball (qt-everywhere-enterprise-5.2.0-src.tar.gz) compiled fine with the normal configure invocation under Mountain Lion.
30,373
![enter image description here](https://i.stack.imgur.com/PI2Q5.jpg) Plant :Alstonia Appearance:Blisters (gall) on both sides,cutting galls leaves white fluid. After some time holes apppears in the blisters.so it seems some insect laid eggs. What kind of disease is this? It seems to be some kind of blisters on the leaves of a decorative plant. I'm guessing some insect laid eggs in it for eggs nourishment. Would you please identify them and tell me how to treat them?
2017/01/03
[ "https://gardening.stackexchange.com/questions/30373", "https://gardening.stackexchange.com", "https://gardening.stackexchange.com/users/16473/" ]
Alstonia scholaris (L.) R. Br. is a very beautiful ornamental tree, which is commonly known as pagoda tree because of its pagoda like growing habit. It is commonly infected by the Homopteran, Pauropsylla tuberculata Crawf which leads to unsightly gall formation on the leaves as pictured. The gall is the leaf response to the infection by the parasite which in turn sustains the growing insect. If there is a hole in the gall, the insect has likely already left. <https://www.cabdirect.org/cabdirect/abstract/20083091676>
25,390,936
Not sure if I should use a regex, and if so which, but I'm using SQL (Sequel Pro) For a particular instance in a table (about 200 columns) I want to remove everything that precedes the year (such as for 3/13/2012 I want to remove 3/13/ ). Some entries only have a year, and some have the month and day preceding the year. How can I remove the month and day without removing the year in SQL?
2014/08/19
[ "https://Stackoverflow.com/questions/25390936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3597867/" ]
Try this: ``` SELECT DATEPART(YEAR,CONVERT(DATE,{Your Column Name Here})) ```
56,007,622
In this problem, I am trying to understand when an alert should be generated based on 'value'. If previous 5 values are above 10, then an alert is created. The alert continues to stay active till the value goes below 7.5. Now, once the alert is no longer active and it reaches a stage where previous 5 values are above 10, then an alert is created again. Here is the logic I am using to do this: ``` NUM_PREV_ROWS = 5 PREV_5_THRESHOLD = 10.0 PREV_THRESHOLD = 7.5 d = {'device': ['a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a','a', 'a','a','a','a','a','b','b','b','b','b', 'b','b','b','b','b','b','b','b','b','b','b','b','b','b','b','b','b'] , 'value': [11,11,11,11,11,11,11,8,9,11,11,11,11,11,8,9,6,11,11,11,11,11,11,11,11,11,11,11,11,8,9,11,11,11,11,11,8,9,6,11,11,11,11,11]} df = pd.DataFrame(data=d) df['prev>10'] = df['value']>PREV_5_THRESHOLD df['prev5>10'] = df['prev>10'].rolling(NUM_PREV_ROWS).sum() df['prev>7.5'] = df['value']>PREV_THRESHOLD alert = False alert_series = [] for row in df.iterrows(): if row[1]['prev5>10']==NUM_PREV_ROWS: alert = True if row[1]['prev>7.5']==False: alert = False alert_series.append(alert) df['alert'] = alert_series ``` The problem is that the loop should restart when a new device is encountered (in this case, it should first run for A and then run over B once it comes across that device). How can I do this? This is the output with current logic: ``` print(df) value prev>10 prev5>10 prev>7.5 alert a 11 True NaN True False a 11 True NaN True False a 11 True NaN True False a 11 True NaN True False a 11 True 5.0 True True a 11 True 5.0 True True a 11 True 5.0 True True a 8 False 4.0 True True a 9 False 3.0 True True a 11 True 3.0 True True a 11 True 3.0 True True a 11 True 3.0 True True a 11 True 4.0 True True a 11 True 5.0 True True a 8 False 4.0 True True a 9 False 3.0 True True a 6 False 2.0 False False a 11 True 2.0 True False a 11 True 2.0 True False a 11 True 3.0 True False a 11 True 4.0 True False a 11 True 5.0 True True b 11 True 5.0 True True b 11 True 5.0 True True b 11 True 5.0 True True b 11 True 5.0 True True b 11 True 5.0 True True b 11 True 5.0 True True b 11 True 5.0 True True b 8 False 4.0 True True b 9 False 3.0 True True b 11 True 3.0 True True b 11 True 3.0 True True b 11 True 3.0 True True b 11 True 4.0 True True b 11 True 5.0 True True b 8 False 4.0 True True b 9 False 3.0 True True b 6 False 2.0 False False b 11 True 2.0 True False b 11 True 2.0 True False b 11 True 3.0 True False b 11 True 4.0 True False b 11 True 5.0 True True ``` Appreciate all the help!
2019/05/06
[ "https://Stackoverflow.com/questions/56007622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11035965/" ]
There's a [chapter on Scheduling in the Airflow documentation](https://airflow.apache.org/scheduler.html#scheduling-triggers), which states: > > Note that if you run a DAG on a schedule\_interval of one day, the run stamped 2016-01-01 will be trigger soon after 2016-01-01T23:59. In other words, the job instance is started once the period it covers has ended. > > > **Let’s Repeat That** The scheduler runs your job one schedule\_interval AFTER the start date, at the END of the period. > > > You are experiencing exactly this: today (2019-05-06) a DagRun is created for the latest "completed" interval, meaning the week starting on 2019-04-29. Thinking about it like this might help: if you want to process some data periodically, you need to start processing it *after* the data is ready for that period.
203,266
I need another excuse of "I was very busy" as people became tired of hearing it. So, I thought of expressing the idea of having a very restricted/limited time for all the tasks that I have been assigned to do and therefore I couldn't completely finish this specific one. The thing is I can't get my hands on a suitable phrase. I guess it would be something like: > > I wasn't able to finish it as I **got pretty restricted** in time. > > > Is it correct? Can I achieve that meaning better? It is not necessary to be formal, but I don't want it to be too informal.
2019/03/31
[ "https://ell.stackexchange.com/questions/203266", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/80554/" ]
There are some other good suggestions here. I might also use: > > I got caught up with other work. > > > I got caught up in other work. > > > Either of these means that you were very busy or “tangled up” with other work- like you couldn’t escape the trap of the work, so to speak. EDIT: Sorry, I should have also addressed your own suggestion - > > I got pretty restricted in time. > > > I would not say that, even if the meaning might be understood. The phrasing is awkward - it would sound better to say > > My time was restricted. > > > if you were to use the word *restricted*. *Restricted* is something that *is*, not something that is *gotten*, generally speaking. Also, *restricted* is often used to indicate some specific enforced limit, like "Access was restricted to authorized users", or "My time was restricted to three hours". I think in this case the word doesn't completely fit if nobody was actually forcing you to only spend a certain amount of time on this particular task. I daresay it might come off as rude to tell someone the time you had for this task was *restricted*; they might think you set a limit on the time you were going to spend on it because you didn't think it was that important.
18,772,414
I am working on open-source project on github, and I cloned a the project by doing `git clone [email protected]:project.git` Now, All works fine, I can run the project and working on it. But this was a master branch, and now someone has created a branch called `user_interface` and added some basic HTML, now I need to pull this `user_interface` and merge it to my local working file, so I can immediately start using these additional features from that user. But, the problem is specifying how to explicitly call call that branch `user_interface` and merge it to my local copy. So far, I tried only `git pull`, but it pulls the original data and merges it to my local directory, so I end up with the same copy I got the last time.
2013/09/12
[ "https://Stackoverflow.com/questions/18772414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The problem seems to be that egrep is not resetting captured groups on repeats. Not sure if this is a bug or just ambiguity in what the notation implies. If you manually repeat then it should work: ``` egrep -i "(\w)\1(\w)\2(\w)\3(\w)\4" /usr/share/dict/words ``` However, it is strange that this does not work. This does work in perl: ``` perl -lne "print if /((\w)\2){3}/" /usr/share/dict/words ``` BTW, egrep does support {m,n} syntax. This proves that: ``` egrep -i "a{2}" /usr/share/dict/words ```
233,574
I'm moving a couple of servers to a colo and was wondering what you would recommend for a hardware firewall to sit in front of them? Is it fine to just get the cheapest Cisco/Fortigate/Juniper/whatever firewall? I don't need anything fancy, pretty much just port forwarding.
2011/02/09
[ "https://serverfault.com/questions/233574", "https://serverfault.com", "https://serverfault.com/users/546/" ]
Here's an example for some criteria you'll want to consider when selecting a firewall in the scenario you described: 1. Feature set - Make sure it'll perform your immediate and potential future purposes. 2. Performance - Co-location generally provides good network connectivity and throughput. Make sure the device you pick will handle the anticipated loads you'll be capable of. 3. Form factor - You're paying to put equipment here, the smaller the equipment, the more you can pack in. 4. Management - Some devices offer features that make remote management easier, and give you tools in the event you find yourself unable to access it. I imagine the brand names you've mentioned would have models capable of what you're asking. Most likely it would come down to performance and management of the equipment.
3,308,437
How can I see the version of .net framework which renders my aspx page on remote server?
2010/07/22
[ "https://Stackoverflow.com/questions/3308437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259881/" ]
This outputs your version: ``` System.Environment.Version.ToString() ```
260,924
Assume a multi-line file (`myInput.txt`) with lines comprising one or more words. ``` echo -e "Foo\nFoo bar\nFoo baz\nFoo bar baz\nBar\nBaz\nBaz qux\nBaz qux quux\nQux quux" > myInput.txt ``` I wish to remove all one-word lines that are identical with the first word of any multi-word lines **using Python**. ``` echo -e "Foo bar\nFoo baz\nFoo bar baz\nBar\nBaz qux\nBaz qux quux\nQux quux" > myGoal.txt ``` The following code satisfies my goal but does not appear overtly Pythonic to me. ``` from itertools import compress myList = list() with open("myInput.txt", "r") as myInput: for line in [l.strip() for l in myInput.readlines()]: if not line.startswith("#"): myList.append(line) # Get all lines with more than one word more_than_one = list(compress(myList, [len(e.strip().split(" "))>1 for e in myList])) # Get all lines with only one word only_one_word = list(compress(myList, [len(e.strip().split(" "))==1 for e in myList])) # Keep only unique set of initial words of more_than_one unique_first_words = list(set([e.split(" ")[0] for e in more_than_one])) # Remove all union set words from only_one_word only_one_word_reduced = [e for e in only_one_word if e not in unique_first_words] # Combine more_than_one and only_one_word_reduced combined_list = only_one_word_reduced + more_than_one ``` Do you have any suggestions on making the Python code slimmer and more straightforward?
2021/05/19
[ "https://codereview.stackexchange.com/questions/260924", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/122794/" ]
```py # Get all lines with more than one word more_than_one = list(compress(myList, [len(e.strip().split(" "))>1 for e in myList])) ``` * The function `split` splits by whitespaces by default, there is no need to pass the explicit argument * Lines have been stripped already when reading the file, using `strip` seems unnecessary * Using list comprehension should be enough, without the function `compress` and `list` For example: ```py more_than_one = [line for line in myList if len(line.split()) > 1] ``` Or: ```py more_than_one = [line for line in myList if ' ' in line] ``` * Same observations for `Get all lines with only one word` --- ```py # Keep only unique set of initial words of more_than_one unique_first_words = list(set([e.split(" ")[0] for e in more_than_one])) ``` * Not sure why the `set` is converted to a `list`. Checking for unique words in a set is much faster than in a list --- * **Functions**: would be better to include all the operations in a function, for easier testing and reuse * **PEP 8**: function and variable names should be lowercase, with words separated by underscores as necessary to improve readability. `myList` should be `my_list`. [More info](https://www.python.org/dev/peps/pep-0008/#function-and-variable-names). --- A function that does the same could be the following: ``` def remove_duplicates(lines): seen = set() for line in lines: first_word, *tail = line.split() if tail: seen.add(first_word) return [line for line in lines if line not in seen] ``` An use it like: ``` print(remove_duplicates(['a','a b','b','c','c d','z'])) # Output: ['a b', 'b', 'c d', 'z'] ```
2,582,951
Also I want to know how to add meta data while indexing so that i can boost some parameters
2010/04/06
[ "https://Stackoverflow.com/questions/2582951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150887/" ]
Lucene indexes text not files - you'll need some other process for extracting the text out of the file and running Lucene over that.
2,314,637
All, I am creating a web application and I need to give users the ability to add/edit/delete records in a grid type control. I can't use 3rd party controls so I am restricted to just whats in the box for asp.net (datagrid or gridview) or creating my own. Any thoughts on the best direction to go in. I'd like to keep the complexity level at a dull roar :) thanks in advance daniel
2010/02/22
[ "https://Stackoverflow.com/questions/2314637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/164257/" ]
Gridviews have different item templates that you can use for editing and inserting data. That'd be an easy way to go about it. As long as you set your datakeyid property to the primary key in the database, you should be able to make template fields based off of whether or not you're editing or inserting data. The command name of the button you use to fire the event will handle the statements required for updating/inserting data. [This](http://www.aspdotnetcodes.com/GridView_Insert_Edit_Update_Delete.aspx) is a good site for some examples.
2,088,079
Differentiate $$\:\left(x-1/2\right)^2+\left(y-1/4\right)^2=5/16$$ With respect to $x.$ The above simplifies to $$x^2-x+y^2-\frac{y}{2} = 0$$ I know that you have to take the implicit derivative, such that $$\frac{d}{dx}(x^2-x+y^2-\frac{y}{2}) = \frac{d}{dx}(0)$$ Thus $$2x-1+2y-\frac{1}{2}=0$$ and $$y=-x+\frac{3}{4}$$ So $$y'=-x+\frac{3}{4}$$ Have I made any errors, and where can I improve on this solution? In particular, I am worried because the last two equations are the same except the difference between $y$ and $y'.$ I mean, both can't be assumed to be true, right? And I am asked to find the equation of the tangent of the circle that intersects at the point $(1, 0).$ In this case, do I write the equation in the form $y=mx+b$ (but with numbers replacing $m$ and $b$) as well, in which case I would have two $y$ variables in my solution?
2017/01/07
[ "https://math.stackexchange.com/questions/2088079", "https://math.stackexchange.com", "https://math.stackexchange.com/users/293926/" ]
Your error is first forgetting that $y$ depends on $x$ (I assume because implicit derivatives are mentioned and $x(y)$ would be pretty mean) and then getting confused and solving for $y$ and not $y'$. You are right that you need to take $$ \frac{d}{dx}(x^2-x+y^2-y/2)=0 $$ But $y$ is a function of $x$ so this should be by the chain rule $$ 2x-1+2yy'-1/2y'=0 $$ Can you solve for $y'$ now? Now as for the tangent line to the circle described by this curve, you now have the equation for the slope of the tangent line to the curve at any point and a given point. So your $m=y'(1)$ and you can use precalculus methods to find the equation of the line in point slope form.
68,883,343
I'm trying to only call an axios call once per render from an event handler (onClick basically), so I'm using useEffect and inside that useEffect, I'm using useState. Problem is - when onClick is called, I get the following error: > > Error: Invalid hook call. Hooks can only be called inside of the body of a function component. > > > I understand why I'm getting it, I'm using useState in an event handler - but I don't know what else to do. How else can I handle these variables without useState? HttpRequest.js ```js import {useEffect, useState} from 'react' import axios from 'axios' export function useAxiosGet(path) { const [request, setRequest] = useState({ loading: false, data: null, error: false }); useEffect(() => { setRequest({ loading: true, data: null, error: false }); axios.get(path) .then(response => { setRequest({ loading: false, data: response.data, error: false }) }) .catch((err) => { setRequest({ loading: false, data: null, error: true }); if (err.response) { console.log(err.response.data); console.log(err.response.status); console.log(err.response.headers); } else if (err.request) { console.log(err.request); } else { console.log('Error', err.message); } console.log(err.config); }) }, [path]) return request } ``` RandomItem.js ```js import React, {useCallback, useEffect, useState} from 'react'; import Item from "../components/Item"; import Loader from "../../shared/components/UI/Loader"; import {useAxiosGet} from "../../shared/hooks/HttpRequest"; import {useLongPress} from 'use-long-press'; function collectItem(item) { return useAxiosGet('collection') } function RandomItem() { let content = null; let item; item = useAxiosGet('collection'); console.log(item); const callback = useCallback(event => { console.log("long pressed!"); }, []); const longPressEvent = useLongPress(callback, { onStart: event => console.log('Press started'), onFinish: event => console.log('Long press finished'), onCancel: event => collectItem(), //onMove: event => console.log('Detected mouse or touch movement'), threshold: 500, captureEvent: true, cancelOnMovement: false, detect: 'both', }); if (item.error === true) { content = <p>There was an error retrieving a random item.</p> } if (item.loading === true) { content = <Loader/> } if (item.data) { return ( content = <div {...longPressEvent}> <Item name={item.data.name} image={item.data.filename} description={item.data.description}/> </div> ) } return ( <div> {content} </div> ); } export default RandomItem; ``` [use-long-press](https://github.com/minwork/use-long-press) It works to load up the first item just fine, but when you try to cancel a long click (Basically the onClick event handler), it spits out the error above.
2021/08/22
[ "https://Stackoverflow.com/questions/68883343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/200025/" ]
You need to redo your hook so it would not start loading unconditionally but instead return a callback that might be called to initiate loading at some moment: ``` const [loadCollections, { isLoading, data, error }] = useLazyAxiosGet('collections'); .... onCancel: loadCollections ``` I propose to follow [approach that Apollo uses](https://www.apollographql.com/docs/react/api/react/hooks/#usequery) when there is `useQuery` that starts loading instantly and `useLazyQuery` that returns callback to be called later and conditionally. But both share similar API so could be easily replaced without much updates in code. Just beware that "immediate" and "lazy" version don't just differ by ability to be called conditionally. Say, for "lazy" version you need to decide what will happen on series calls to callback - should next call rely on existing data or reset and send brand new call. For "immediate" version there are no such a dilemma since component will be re-rendered for multiple times per lifetime, so it definitely *should not* send new requests each time.
5,047
I would like to draw a land for a motocross game. I've been thinking of Bezier Curves but I am not sure whether this is the best approach. Can you give me some advice? I want to do it in JavaScript, not very good choice but it's personal project so for time being it's OK.
2010/10/31
[ "https://gamedev.stackexchange.com/questions/5047", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/2938/" ]
I found a couple of links that might be useful for others: Example script of Bezier implementation in JS <http://jsfromhell.com/math/bezier> It can be used from JavaScript or ActionScript to animate along a bezier path. <http://code.google.com/p/javascript-beziers/> Online drawing script/plot, quite useful if you want to make some tests <http://jsdraw2d.jsfiction.com/demo/curvesbezier.htm> A bit of theory and an implementation example <http://13thparallel.com/archive/bezier-curves/>
9,056
I want to implement mutual exclusion for $n$ processes. Critical section code: ``` int turn = 0; /* shared control variable */ Pi: /* i is 0 or 1 */ while (turn != i) ; /* busy wait */ CSi; turn = 1 - i; ``` This solution from [this page](http://phoenix.goucher.edu/~kelliher/cs42/sep27.html) but it is only made for two processes. I tried to adapt it for $n$ processes like this: ``` turn = 0 // shared control variable i = turn; while (turn != i); // CS turn = (turn + 1) % n; ``` Does this work?
2013/01/20
[ "https://cs.stackexchange.com/questions/9056", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/6488/" ]
From my understanding of the 2-processor, if you want to do the same thing you would delete the statement (I truly dont know why you had it. There could be something interesting behind this statement of yours). ``` i = turn ``` and instead, let each of the $n$ processors have an id from $\{1, \dots, n\}$. Then, you would let the processors go *in sequence* to the critical code. That is, assume a processor $i$ takes the token and left it. Then, it has to wait the other $n- 1$ to take the token if it want to take it again. The problem in this solution is the sequential method of taking the token. If you want to have something more efficient, then have a look at the Lamport's bakery algorithm. The pseudocode of the algorithm is available in the site you provided, and it is explained in wikipedia. The idea of this algorithm is very simple in fact. There is a *queue* of processors that want to get the token. These processors enter the queue, and the first come is first served. In regard to the [link](http://phoenix.goucher.edu/~kelliher/cs42/sep27.html) you included in your question, this is done by these lines: ``` number[i] = max(number) + 1; // enter the queue ! ... ... while (number[j] != 0 && (number[j] < number[i] || number[j] == number[i] && j < i) ) // wait until your turn comes. ... Do your critical section ! ... ... number[i] = 0; // go out of the queue .. ``` Obviously, you can play around with this. But it is a neat way of implementing FIFO requests.
5,914,507
Hey all. I need to work on all of the skills that come along with working with web services in Android. Most of the apps I've worked on have used static/local data. Obviously, to create something powerful, I need to learn how to work with web services. To that end, does anyone have any recommendations for an easy API to work with? I don't really have any preference (I'm doing this project just so I can learn), though I'd rather not work with Twitter. So, I'm looking for one of the popular APIs, but something that's relatively simple so that I don't have to be bogged down in an ultra-complex API. I want to be able to focus more on the Android/Java implementation. Thanks a lot!
2011/05/06
[ "https://Stackoverflow.com/questions/5914507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479180/" ]
You have many API that you can use to leverage your skills. Facebook is one of them but you can also have a look at websites such as Read It Later, Instapaper, Delicious or MeeGo that use simple web API with JSON/XML to transmit data.
16,949,444
I added a Blog Archive widget to my [Orchard CMS blog](http://logiczone.me/logically-me/archive/2013/6). It displayed the archive dates as intended and clicking the date displays a list of blog posts that fall under the date. The problem I have is with the list of blog posts that are being shown. They do not seem to follow the regular blog post style. Looking at the source the posts are simply rendered as plain tags without any CSS classes. Using the shape tracing tool tells me that they're simply rendered as the List core shape. I've tried modifying the Blog Archive content part to add a CSS part, but that didn't work. I've create several shape alternates using the tracing tool but none of them worked. Can anyone out there point me to the right direction? Much appreciated.
2013/06/05
[ "https://Stackoverflow.com/questions/16949444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2457314/" ]
You are right, that list should have a class on it. Please file a bug for it. The fix is simple but requires modification of the blog module. In BlogPostController, after the line saying `var list = Shape.List();`, add this: ``` list.Classes.Add("blog-archive"); ```
36,386,213
I am trying to achieve the functionality seen on Google Play where a CardView has an options menu that can be clicked and you can click on the card to view more detail on the card. I have implemented an OnItemTouch listener on my RecyclerView which works fine and responds when touched, taking me to another activity. However, when I now try and add a click listener to an options icon I have added within the RecyclerView item (which is a CardView), the OnItemTouch listener is called. Can anyone help? Activity ``` mRecyclerView.addOnItemTouchListener( new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Intent intent = new Intent(getApplicationContext(), TransactionDetailActivity.class); Bundle bundle = new Bundle(); bundle.putSerializable("transaction_key", mTransactionList.get(position)); intent.putExtras(bundle); startActivity(intent); } }) ); mRecyclerView.setAdapter(mAdapter); ``` Click Listener ``` public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener { private OnItemClickListener mListener; public interface OnItemClickListener { public void onItemClick(View view, int position); } GestureDetector mGestureDetector; public RecyclerItemClickListener(Context context, OnItemClickListener listener) { mListener = listener; mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onSingleTapUp(MotionEvent e) { return true; } }); } @Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) { View childView = view.findChildViewUnder(e.getX(), e.getY()); if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) { mListener.onItemClick(childView, view.getChildPosition(childView)); return true; } return false; } @Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { } @Override public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { } } ```
2016/04/03
[ "https://Stackoverflow.com/questions/36386213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1810110/" ]
If you don't want to handle the clicks of CardView children, OnItemTouchListener is the way. But if you want to handle the cliks of cardview children, you may have to attach OnClickListener (in the Adapter class' DataObjectHolder or onBindViewHolder method) to the CardView or its immediate child (which can be any layout Eg. LinearLayout, RelativeLayout, etc) to handle the card clicks. If done so, the OnClickListener of any view inside the CardView will work. Following is an example: **Adapter** ``` public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.DataObjectHolder>{ Context context; ArrayList<String> list; static String TAG = "ApprovalsRV Adapter"; DeleteListener deleteListener; public RecyclerViewAdapter(Context context, ArrayList<String> list) { this.context = context; this.list = list; deleteListener = (DeleteListener) context; } public static class DataObjectHolder extends RecyclerView.ViewHolder { TextView tName; RelativeLayout rlName; CardView cvName; public DataObjectHolder(View itemView, final Context context) { super(itemView); tName = (TextView) itemView.findViewById(R.id.tName); rlName = (RelativeLayout) itemView.findViewById(R.id.rlName); cvName = (CardView) itemView.findViewById(R.id.cvName); cvName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Handle the card click here deleteListener.deleteName(position); // if handling from activity (explained below) } }); tName.setOnClickListener(new View.OnClickListener() { //You can have similar listeners for subsequent children @Override public void onClick(View view) { //Handle the textview click here } }); } } @Override public DataObjectHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.card_view_layout, parent, false); DataObjectHolder dataObjectHolder = new DataObjectHolder(view, context); return dataObjectHolder; } @Override public void onBindViewHolder(DataObjectHolder holder, int position) { holder.tName.setText(list.get(position)); } @Override public int getItemCount() { return list.size(); } } ``` If you want to handle the card click from the activity, you will need to use an interface here. **DeleteListener.java** ``` public interface DeleteListener { public void deleteName(int position); } ``` Now to use this in your activity: **MyActivity.java** ``` public class MyActivity extends AppCompatActivity implements DeleteListener { @Override public void deleteName(int position) { //Your job } } ``` This will clear your doubt.
29,643,473
So, for my question have a look at my Jmeter setup: ![Jmeter setup](https://i.stack.imgur.com/Wk4Ex.png) Let me explain what's happening and then move on to my question. **Explanation** On the server I have a guava cache (with timeout of 5 seconds) and a DB hooked up to it. Request A sends data (read from csv file) to the server and puts it in cache. It returns a unique ID corresponding with that data. Request B sends a seconds request (with that unique ID) that evicts the item from cache and saves to DB. The third request, C, uses that unique ID again to read from DB and process the data. Now, to share that unique ID (and some other URL params) between thread groups I put them in a queue in Jmeter (using the jp@gc - Inter-Thread Communication PreProcessor and PostProcessor). All works like it should, both Jmeter and Server. **Question** To finish up this setup I need to add one more thing... For each request A only 10% (random) of the unique IDs need to be put in queue A. And again for each request B only 10% (random) of those unique IDs need to be put in queue B. How can I do this last part if Jmeter does not allow if-controllers to be put as part of an http-request?
2015/04/15
[ "https://Stackoverflow.com/questions/29643473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3354890/" ]
If anyone is interested in the answer. I found out that the easiest way to do this is to create a random variable (in variable `rnd`) and a beanshell postprocessor, both under Http request A. The beanshell code is: ``` import kg.apc.jmeter.modifiers.FifoMap; if (vars.get("rnd").equals("1")) { FifoMap.getInstance().put("QUEUE_A", "${uniqueId"); } ``` For Request B, analog to the procedure for Request A. Works perfectly.
36,060
I have read about sakkayaditti <https://www.wisdomlib.org/definition/sakkayaditti> Sakkayaditti means something in Buddhism, Pali. please help me to clarify
2019/11/22
[ "https://buddhism.stackexchange.com/questions/36060", "https://buddhism.stackexchange.com", "https://buddhism.stackexchange.com/users/17327/" ]
This is a key concept in the Early Buddhist Texts: > > [MN 64](https://suttacentral.net/mn64/en/sujato#mn64:3.4): Anusetvevassa sakkāyadiṭṭhānusayo. > > > [MN 64](https://suttacentral.net/mn64/en/sujato#mn64:3.4): Yet the underlying tendency to ***identity view*** still lies within them. > > > Identity View is the view that "I am". For example, we say, "I am Chinese" or "I am educated" or "I am poor", etc. These personal perspectives contribute to suffering. If "I am poor", then "I want to be rich". If "I am ugly" then "I want to be beautiful". Through study and practice, we step away from personal perspectives and abandon Identity View as not satisfying, not conducive to happiness. To be an Arahant, to be a Realized One, Identity View is abandoned entirely. Sakkāyadiṭṭhi is the [heresy of individuality](https://suttacentral.net/define/sakk%C4%81yadi%E1%B9%AD%E1%B9%ADhi) To be clear, that does not mean that Buddhists are all alike. The Buddha in fact insisted that each of us find the truth for ourselves. What it means is that Buddhists are alike in dismissing personal cravings as unskillful and unwholesome.
10,131,464
I am working on some kind of file sharing program which is written in C. There is a function that can read a data file and store the data into a string and return this string to main function and the main function send back to client. Codes are shown below ``` char* ListFiles(){ FILE *fp; char file[30]; char *f; if((fp=fopen("list","r"))==NULL) { ... } while (!feof(fp)) { fgets(file,50,fp); } fclose(fp); f=file; printf("%s",f); //get display!!! return f; } int main(){ char *files; ... ... files=ListFiles(); printf("%s",files); //nothing display!! sent(); } ``` However, this method doesn't work. There is nothing display and of course nothing is sent. But I do get the correct display in function ListFiles(). I don't know what happen. I also use strcpy() and it still fail to work.
2012/04/12
[ "https://Stackoverflow.com/questions/10131464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1113845/" ]
Follow [`George Skoptsov`](https://stackoverflow.com/users/1257977/george-skoptsov) recommendations. But If you don't have the [`strdup()`](http://pubs.opengroup.org/onlinepubs/009695399/functions/strdup.html) function,then use this: ``` char* strdup(const char* org) { if(org == NULL) return NULL; char* newstr = malloc(strlen(org)+1); char* p; if(newstr == NULL) return NULL; p = newstr; while(*org) *p++ = *org++; /* copy the string. */ return newstr; } ``` And then: ``` #include <string.h> /* strlen() call */ #include <stdlib.h> /* NULL, malloc() and free() call */ /* do something... */ char* ListFiles() { /* .... */ return strdup(f); } ``` Or instead of `char file[30];` do a [`dynamic memory allocation`](http://en.wikipedia.org/wiki/C_dynamic_memory_allocation): `char* file = malloc(30);` then you can do `return f;` and it will work fine because `f` now is not a pointer to a local variable.
47,978,833
I'm creating my first bootstrap frontend, and I'm experiencing some issues which I'm not able to solve: [![row](https://i.stack.imgur.com/az6go.png)](https://i.stack.imgur.com/az6go.png) The row expanding to the whole width of the container, the max column width (12 units) will not extend to this width: [![column](https://i.stack.imgur.com/3vMXm.png)](https://i.stack.imgur.com/3vMXm.png) Further on, why is within the container writing over the padding: [![padding](https://i.stack.imgur.com/vx9ne.png)](https://i.stack.imgur.com/vx9ne.png) Any hints appreciated! I already tried to use container-fluid class, but the row seems not to get the max width. Whole HTML: ``` <!DOCTYPE html> <html> <head> <title>Snoo</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="app.css"> </head> <body> <div class="container"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Snoo!</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Reddit!</a> </li> </ul> </div> </nav> </div> <div class="container"> <div class="row"> <div class="col_xl-12"> <div id="content"> <h1>Snoo!</h1> <hr> <h3>A chatbot based on a million reddit comments, quiet salty!</h3> <button class="btn btn-primary btn-lg">Learn more!</button> </div> </div> </div> </div> </body> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script> </html> ``` css: ``` #content { text-align: center; padding-top: 25% } ```
2017/12/26
[ "https://Stackoverflow.com/questions/47978833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7109315/" ]
your class name wrong `col_xl-12` to change class name `col-xl-12` [![enter image description here](https://i.stack.imgur.com/P6IcL.png)](https://i.stack.imgur.com/P6IcL.png) <https://v4-alpha.getbootstrap.com/layout/grid/>
15,385,002
I am using django-cms to design a site,as of now i had to create a basic home page with a menu bar like `About Us`, `Products`, `Contact Us` etc., I had done all the necessary settings of `django` and `django-cms`, activated the admin section and working perfectly. I have created a `Home Page template` that contains the `About Us`, `Products`, `Contact Us` and created a page called `aboutus` through django-cms `admin` with a slug `about-us`. Now i had given that slug `about-us` which is nothing but a url in the anchor tag for `About Us` menu , so when i clicked the link its working fine and redirecting me to the page `aboutus` with the url in the browser as `http://localhost:8080/aboutus`. but the problem is , when i clicked again on the `aboutus` link its generating the url twice that is like `http://localhost:8080/aboutus/aboutus`, i mean for each and every click, the slug `aboutus` is appending to the url. Below are my codes **settings.py** ``` TEMPLATE_CONTEXT_PROCESSORS = ( ....... 'cms.context_processors.media', 'sekizai.context_processors.sekizai', ) CMS_TEMPLATES = ( ('home.html', gettext('Home')), ('aboutus.html', gettext("About Us")), ('management_team.html',gettext('Management Team')), ) ..... .... ``` **urls.py** ``` from django.conf.urls.defaults import * from django.contrib import admin from django.conf import settings admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^', include('cms.urls')), ) ``` **home.html** ``` {% load cms_tags sekizai_tags %} {% load staticfiles %} {% load staticfiles %} <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>{% block head %}{% endblock %}</title> {% render_block "css" %} </head> <body> {% cms_toolbar %} <div class="submenu"> <a href="about-us">About Company Services</a><br /> <a href="management-team">Our Management Team</a> </div> <a href="about-us" class="menu aboutus">About Us</a></div> {% render_block "js" %} </body> </html> ``` So above is my overall code,in which `home.html` displays a home page with the menu as below (by using some css styles) ``` About Us About Company Services Our Management Team ``` So when i clicked on the the link `About Us` the url generating is `http://localhost:8000/about-us/` and immediately when we clicked on `About Company Services` the url generating is `http://localhost:8000/about-us/about-us` and `http://localhost:8000/about-us/about-us/our-management-team/` when clicked on `Our Management Team` immediately . So the url is appending to the previous url instead of appending to the `domain name`. I have created all the pages by using the created templates from django-cms admin as ``` Page Name slug About Us about-us About Company Services about-us Our Management Team our-management-team ``` So whats wrong in the above code, why the urls are appending to the previous urls instead of appending to the domain ? How to create a `childs(About Company Services,Our Management Team )` from the django-cms admin to the `parent(About Us)` Actually i want to create two pages`(About Company Services,Our Management Team )` under `About Us` page , how can we achieve this in django-cms admin Can anyone please let me know the concept of menus in django-cms, i have tried and read the documentation of `django-cms many many many times` but unable to understand the concept of `menus` so approached `SO`
2013/03/13
[ "https://Stackoverflow.com/questions/15385002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1342109/" ]
If this is your page layout in the admin section (`/admin/cms/page`): ``` - Home (level=0) - About Us (level=1) - About Company Services (level=2) - Foo Bar (level=3) - Our Management Team (level=2) - Some Other Section (level=1) - Some Sub Section (level=2) - ... ``` When you print `{% show_menu A B C D %}` you are rendering a `ul` menu, where A,B,C & D are numbers which specify the configuration of the menu. ``` A = Start B = End C = Inactive D = Active ``` So `{% show_menu 1 2 0 100 %}` * `A=1` means start the navigation at level 1, i.e. excluding `Home` which is level 0 * `B=2` means render the navigation down to level 2, i.e. excluding `Foo Bar` * `C=0` means that for inactive trails, show 0 levels. So if we are currently on the `About Us` page, we wont see any links in the menu below `Some Other Section` (as this is an inactive trail), but we will still see `About Company...` and `Out Management...` (as this is an active trail) * `D=100` means that for the currently active trail, show down to 100 levels (this is why we see the `About Company...` and `Our Management` mentioned above) So the result is: ``` - About Us (level=1) - About Company Services (level=2) - Our Management Team (level=2) - Some Other Section (level=1) ```
73,660,460
Using this code I have write/replace data in an excel file. But now i need to do the same thing for csv file. Can someone help me with that? ```py with pd.ExcelWriter('2.xlsx', mode='a', engine='openpyxl', if_sheet_exists='replace') as writer: fm_data.to_excel(writer, sheet_name='Raw Data1') ```
2022/09/09
[ "https://Stackoverflow.com/questions/73660460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19875567/" ]
Assuming you know there are only 2 columns *and* the second column is always a floating-point number (when there are any), you can use this: ``` awk -F, 'NF == 3 { $0 = $1FS$2"."$3 } NF == 4 { $0 = $1"."$2FS$3"."$4 } 1' infile ```
2,243,423
i want the assemblies (\*.dll) files for silverlight charting controls or give me path that where does it stoer when we install the toolkit in our computer
2010/02/11
[ "https://Stackoverflow.com/questions/2243423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/255609/" ]
When you've installed the toolkit you will find the dlls in:- `C:\Program Files (x86)\Microsoft SDKs\Silverlight\v3.0\Toolkit\Nov09\Bin` or on a 32 bit system:- `C:\Program Files\Microsoft SDKs\Silverlight\v3.0\Toolkit\Nov09\Bin` The above is obviously for the November 09 release, no doubt as this answer ages the latest release will be in a similarly named folder. However they should be listed in the .NET tab when you add references.
1,774,129
I'm looking for a good way to find the process ID of a particular Windows Service. In particular, I need to find the pid of the default "WebClient" service that ships with Windows. It's hosted as a "local service" within a svchost.exe process. I see that when I use netstat to see what processes are using what ports it lists [WebClient] under the process name, so I'm hoping that there is some (relatively) simple mechanism to find this information.
2009/11/21
[ "https://Stackoverflow.com/questions/1774129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19404/" ]
[`QueryServiceStatusEx`](http://msdn.microsoft.com/en-us/library/ms684941%28VS.85%29.aspx) returns a [`SERVICE_STATUS_PROCESS`](http://msdn.microsoft.com/en-us/library/ms685992%28VS.85%29.aspx), which contains the process identifier for the process under which the service is running. You can use [`OpenService`](http://msdn.microsoft.com/en-us/library/ms684330%28VS.85%29.aspx) to obtain a handle to a service from its name.
7,229,552
I am trying to create a key/value database with 300,000,000 key/value pairs of 8 bytes each (both for the key and the value). The requirement is to have a very fast key/value mechanism which can query about 500,000 entries per second. I tried BDB, Tokyo DB, Kyoto DB, and levelDB and they all perform very bad when it comes to databases at that size. (Their performance is not even close to their benchmarked rate at 1,000,000 entries). I cannot store my database in memory because of hardware limitations (32 bit software), so memcached is out of the question. I cannot use external server software as well (only a database module), and there is no need for multi-user support at all. Of course server software cannot hold 500,000 queries per second from a single endpoint anyways, so that leaves out Redis, Tokyo tyrant, etc.
2011/08/29
[ "https://Stackoverflow.com/questions/7229552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/741628/" ]
David Segleau, here. Product Manager for Berkeley DB. The most common problem with BDB performance is that people don't configure the cache size, leaving it at the default, which is pretty small. The second most common problem is that people write application behavior emulators that do random look-ups (even though their application is not really completely random) which forces them to read data out of cache. The random I/O then takes them down a path of conclusions about performance that are not based on the simulated application rather than the actual application behavior. From your description, I'm not sure if your running into these common problems or maybe into something else entirely. In any case, our experience is that Berkeley DB tends to perform and scale very well. We'd be happy to help you identify any bottlenecks and improve your BDB application throughput. The best place to get help in this regard would be on the BDB forums at: <http://forums.oracle.com/forums/forum.jspa?forumID=271>. When you post to the forum it would be useful to show the critical query segments of your application code and the db\_stat output showing the performance of the database environment. It's likely that you will want to use BDB HA/Replication in order to load balance the queries across multiple servers. 500K queries/second is probably going to require a larger multi-core server or a series of smaller replicated servers. We've frequently seen BDB applications with 100-200K queries/second on commodity hardware, but 500K queries per second on 300M records in a 32-bit application is likely going to require some careful tuning. I'd suggest focusing on optimizing the performance of a the queries on the BDB application running on a single node, and then use HA to distribute that load across multiple systems in order to scale your query/second throughput. I hope that helps. Good luck with your application. Regards, Dave
378,112
For a while, using the windows explorer search to find files by their file name has been returning no items, even when I know there is a match. I looked into it and it appears that the index contains no items. I've removed and readded the include locations, restarted the windows search service, changed the index location and it still shows 0 items indexed. Does anyone have any idea how to fix this? (Or even an temporary alternative to search the file system, by file attributes only. Not content) Windows 7 Pro 64-bit I'm using Window Security Essentials only for virus protection. (I found internet posts indicating 3rd party virus software appearred to cause this problem for them)
2012/01/13
[ "https://superuser.com/questions/378112", "https://superuser.com", "https://superuser.com/users/106001/" ]
I had the same problem, I feel Microsoft really let me down with the new explorer interface. I am now using a 3rd party software called ["Search Everything"](http://www.voidtools.com/) to search for file names.
36,711,068
My middleware class is in different class library project and controller is in different project. What I am trying to do, if specific condition does not meet then redirect to the Custom Controller/Action method from middleware. However, I am not able to do that with Response.Redirect method. How can I do this in middleware class ? Any help on this appreciated ! Rohit
2016/04/19
[ "https://Stackoverflow.com/questions/36711068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1421482/" ]
It seems you're using a middleware for the wrong reasons. I recommend that you either have the middleware return a (very minimal) 404 by simply writing it to the response stream (instead of forwarding to `Next()`), or don't do this in a middleware at all but instead in a globally registered `IActionFilter` in your MVC app. --- I've explained the rationale for the above advice in the comments, but I think it's important enough to lift into the actual answer: In a middleware pipeline, you want each component to be as independent as possible. A couple of things enable this loose coupling in OWIN: * The input to, and output from, each component has the same format, whether there are 10 other middleware components before it, or none at all * The convention is that each part of the pipeline can do one or more of three things, in this order: 1. Read (and modify) the incoming request. 2. Decide to handle the request entirely, or forward handling to the next component. 3. Write to the response stream. When sticking to these conventions, it becomes very easy to compose, decompose and re-compose pipelines from reusable middleware components. (Want request logging? Just hook up a middleware component at the start of the pipe. Want some general authentication logic across the board? Add a component in the auth stage of the pipe. Want to switch to a different logging framework? Replace the logging component. Want to apply the same logging across an ecosystem of microservices? Re-use the component. Etcetera, ad infinum...) This works so well, because the components both stay within their boundaries, and work with a contract that the web server itself can understand. ASP.NET WebAPI might seem to be a different beast, but in reality it's just another OWIN component which is always configured to handle the request, and never to forward to a next component (and thus they've made it difficult to register a component after WebApi in the pipeline...). What you're trying to do, breaks the contract of the second point there - you want to tell the next component how to handle the request. *But that's not up to you - it's up to the next component.*