qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
29,175
I'm trying to write a SQL Server script to iterate through .bak files in a directory and then restore them to our server. In doing so, I've created three temp tables: #Files to keep track of the file-list returned by running xp\_dirtree, #HeaderInfo to hold data returned when querying restore headeronly to get the database names and #FileListInfo to hold data returned from querying restore filelistonly to get the logical file names. My question is regarding the #HeaderInfo table. Consulting the [MSDN definition](http://msdn.microsoft.com/en-us/library/ms178536%28v=sql.100%29.aspx) of the resultset returned from restore header only, I find that the fifth column (Compressed) and the last column (CompressedBackupSize) have 'invalid data types' (BYTE(1) and uint64, respectively). This, obviously, gives me an error when I try to execute the query. To get around this, I have used tinyint and bigint, respectively, and the code now runs fine. My question(s) is/are this/these: * Is using tinyint/bigint the 'correct' work around for this? Or is there a better way to do it? * Is using them likely to cause any undesired behaviour? * If SQL is expecting BYTE(1) and uint64s, why does using different data types not cause an error? * And why does MSDN specify BYTE(1) and uint64 if they're not what gets returned? What are these used for and where? * Bonus question, for anyone who's interested, is there a more elegant/efficient way of automating a restore script? Many thanks EDIT: SQL Server 2008
2012/11/23
[ "https://dba.stackexchange.com/questions/29175", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/15382/" ]
**First your first questions** 1. I would use tinyint for the `BYTE(1)` in this case they told us the possible values are 1 or 0. `BIT` may also work. You could also try `BIT`. But `uint64` is an unsigned 64 Byte integer. BIGINT is signed, so the max value is lower. So technically speaking a DECIMAL(20,0) or greater precision would be used here. But in later versions of that same article this is a BIGINT (For SQL Server 2008 R2 and SQL Server 2012) so I am sure you are fine with BIGINT here. If you get enough disk space and time to create a database big enough to compress to a value that blows BIGINT you can test this theory out someday ;-) 2. No undesired behavior if you go with `SMALLINT`/`BIGINT/DECIMAL(20,0)` 3. I am not sure I understand your question, but I believe the answer is conversion if you are asking what I think you are asking but this is potentially just an oops 4. I'm not sure why those datatypes are in the documentation but you've chosen good logical approximations. **Then the last question** I hate to shove off on this one, but I'm kind of going to do that. There are a lot of great restore scripts out there on the internet for different scenarios. You haven't fully described yours so not sure I can comment on the efficiency/elegance but you are right to read the headers to determine what you do next. Some questions to ask yourself: Are you looking at things like the date to ensure you restore the latest? Are you looking at things like full/diff/log backups and accounting for them in the restore? What purpose is this for? Restoring a dev environment? Or for a production restore? If a dev restore, I like to go more automated. If a prod restore I like to have a script that eliminates some "oops" factor from a critical production restore but not automate so much of it that it makes it easy to forget to do a critical step or do something like backup the tail of the log. I'd search for restore scripts and see what others have done, ask yourself these questions and incorporate what you like. I also am not sure you need to know if the file is compressed or what the compressed size is. Those facts shouldn't be terribly necessary for a restore script since SQL just handles the restore of a compressed backup for you. You don't have to tell SQL it is compressed. So you may just drop those columns altogether and only take what you require from the header to perform you restore.
654,953
I have often see ball grid array (BGA) chips, mostly those from CPUs or GPUs, being glued around in the corners with some red glue or to the perimeter with a translucent one. Having to manually solder BGA chips using hot air, should I glue the chips to the board before heating? In their answers to a quite similar question about soldering small electronic parts (but not specifically BGA chips), some users mention that glue can cause additional problems when it is not applied properly: [adhesive glue before soldering](https://electronics.stackexchange.com/questions/71682/adhesive-glue-before-soldering) Not having an assistant, such soldering process remains currently challenging for me, as I hold the hot air gun (from a rework station) in one hand and the tweezers in the other one. Without using glue, I see at least three difficulties: * positioning and aligning the chips precisely * maintaining the surface of the chips parallel to thus of the PCB when bringing them to it * remaining stable during the soldering, without false move nor trembling So, my questions are: 1. Is the use of glue recommended, given the context? 2. Are there possibly alternative compounds to help keeping the chips into place during the soldering, like a kind of "butter" that would progressively melt when reaching high temperatures? 3. Are there other improvements that I can make to facilitate the soldering of the BGA chips?
2023/02/21
[ "https://electronics.stackexchange.com/questions/654953", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/199752/" ]
To add on to the other excellent answers, and to answer your third question: the red glue you see is likely to be some kind of **corner staking** or **underfilling**. After soldering, an adhesive compound is added to mitigate in-the-field failure, particularly when packages are subjected to thermal or physical stresses. It's not intended to improve solderability. See [the ANSYS website](https://www.ansys.com/blog/bga-and-qfn-failure-mitigation-underfilling-edge-bonds-and-corner-staking-physics-of-failure) for more info.
68,783,622
Hi everyone i'm noob at this, <https://decisoesesolucoes.com/agencias/albergaria/consultores> In the url above, i want to count the number of 'consultor imobiliario' and 'Consultora Imobiliaria' , both the text has spaces, so why im using the normalize-space . [The text i want to get](https://i.stack.imgur.com/kkTGk.png) Example: `"//*[text()[normalize-space() = 'consultor imobiliario']]"` - this works But if i want to count also the 'Consultora Imobiliaria' doesn't work: ``` "//*[text()[normalize-space() = 'consultor imobiliario' and 'Consultora Imobiliária']]" ``` > > (if I user OR instead AND the counting = bad count) > > > My intire code is : ``` $current_page = 1; $max_page = 999999999999; $countTotalConsultores=0; while($max_page >= $current_page){ $url = "https://decisoesesolucoes.com/agencias/albergaria/consultores?page="; $url .= $current_page; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $res = curl_exec($ch); curl_close($ch); $dom = new DomDocument(); @ $dom->loadHTML($res); $xpath = new DOMXpath($dom); $body = $xpath->query("//*[text()[normalize-space() = 'consultor imobiliario' and 'Consultora Imobiliária']]"); $count = $body->length; $countTotalConsultores = $countTotalConsultores+$count; echo " Página atual:" .$current_page . "No. of agents " . $countTotalConsultores; $current_page = $current_page+1; if ($count < 1){ break; ``` Anyone can help me please?
2021/08/14
[ "https://Stackoverflow.com/questions/68783622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16665895/" ]
**EDITED:** You are trying to find text-nodes that are both equal to have 2 different values. That wil never match anything. It is like saying give me all days in summer that are both 100% sunny and 100% rainy. Use `or` in stead of `and` like this: ``` "//*[text()[normalize-space() = 'consultor imobiliario' or normalize-space() ='Consultora Imobiliária']]" ```
56,444,790
Why do I need to bind () a function inside a constructor? ``` constructor (props){ super(props); this.funcao = this.funcao.bind(this); } ``` could not bind () without using a constructor?
2019/06/04
[ "https://Stackoverflow.com/questions/56444790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11599057/" ]
You don't have to bind the methods in the constructor, have a look at the the explanation below. ```js // Setup (mock) class MyValue { constructor(value) { this.value = value; } log() { console.log(this.value); } bindMethods() { this.log = this.log.bind(this); } } const value = new MyValue("Hello World!"); var onclick; // Explanation console.log("==== 1. ===="); // Normally when you call a function, you call it with // a receiver. Meaning that it is called upon an object. // The receiver is used to fill the `this` keyword. // // «receiver».«method name»(«params») // value.log(); // In the line above `value` is the receiver and is used // when you reference `this` in the `log` function. console.log("==== 2. ===="); // However in React a function is often provided to an // handler. For example: // // onclick={this.log} // // This could be compared to the following: onclick = value.log; // When the event is triggered the function is executed. try { onclick(); } catch (error) { console.error(error.message); } // The above throws an error because the function is // called without receiver. Meaning that `this` is // `undefined`. console.log("==== 3. ===="); // Binding a function pre-fills the `this` keywords. // Allowing you to call the function without receiver. onclick = value.log.bind(value); onclick(); console.log("==== 4. ===="); // Another option is using an anonymous function to // call the function with receiver. onclick = () => value.log(); onclick(); console.log("==== 5. ===="); // Binding doesn't have to occur in the constructor, // this can also be done by any other instance function. // a.k.a. a method. value.bindMethods(); // After binding the functions to the receiver you're // able to call the method without receiver. (Since all // `this` keywords are pre-filled.) onclick = value.log; onclick(); ``` For more details about the `this` keyword you should have a look through the [MDN `this` documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this). Methods that don't make use of the `this` keyword don't have to be bound.
34,624
I am about to upgrade the hard disk of my MacBook. (From 60GB to 320GB, which I know is below the limit of 500GB). I was both able to install an OS X on the new drive and also to transfer the old hard disks partition to the new one with a [sysresccd](http://www.sysresccd.org/Main_Page) (linux live disk) and `dd` (`dd if=/dev/sdb of=/dev/sda`, so entire disk). So it's not a problem of hardware, limitations or restrictions. So, after having transferred the 60 GB-disk to the new one, every partition manager would show me that there is about 260GB left on the disk, but none would allow me to resize the partition. The `Disk Utility` on the OS X installation cd allowes to resize, but also erases the data. I tried to copy (`dd`) the old partition into the new, bigger one (`dd if=/dev/sdb2 of=/dev/sda2`), but then the system would refuse to boot. What I have not yet tried is creating manually a partition, then copying all the contents (with hfsplus-support on the linux live disk), because I suppose this partition would not boot either. Is there a way to either resize the partition after having copied the entire disk, or to render the manually resized partition bootable ?
2009/07/01
[ "https://serverfault.com/questions/34624", "https://serverfault.com", "https://serverfault.com/users/1509/" ]
Just cleanly partition the new disk to any size you like and copy the data over with [Carbon Copy Cloner.](http://www.bombich.com/) It will be bootable and have the size you want. You can do that on a running system, and don't need any live cd's or anything, just an usb or firewire interface for the new/second harddisk.
14,741,859
I have 2 tables: * **Table1** = names of gas stations (in pairs) * **Table2** = has co-ordinate information (longitude and latitude amongst other things) Example of **Table1**: ``` StationID1 StationID2 Name1 Name2 Lattitude1 Longitude1 Lattitude2 Longitude2 Distance ------------------------------------------------------------------------------------------------ 93353477 52452 FOO BAR NULL NULL NULL NULL NULL 93353527 52452 HENRY BENNY NULL NULL NULL NULL NULL 93353551 52452 GALE SAM NULL NULL NULL NULL NULL ``` Example of **Table2**: ``` IDInfo Name Lattitude Longitude ------------------------------------------- 93353477 BAR 37.929654 -87.029622 ``` I want to update this table with the coordinate information which resides in `tableA`. I tried to do the following as per [SQL Server 2005: The multi-part identifier … could not be bound](https://stackoverflow.com/questions/4933888/sql-server-2005-the-multi-part-identifier-could-not-be-bound) ``` update table1 set t1.[Lattitude1] = t2.[Lattitude] from table1 t1 left join table2 t2 on (t1.StationID1 = t2.IDInfo) ``` I get the following error message: > > *Msg 4104, Level 16, State 1, Line 1 > > The multi-part identifier "t1.Lattitude1" could not be bound.* > > > However, if I do the following it works which I can then store into another table. ``` SELECT t1.[StationID1] ,t1.[StationID2] ,t1.[Name1] ,t1.[Name2] ,t2.[Lattitude] AS [Lattitude1] ,t2.[Longitude] AS [Longitude1] ,t3.[Lattitude] AS [Lattitude2] ,t3.[Longitude] AS [Longitude2] from table1 t1 left join table2 t2 on (t1.StationID1 = t2.IDInfo) left join table2 t3 on (t1.StationID2 = t2.IDInfo) ``` I am very new to SQL and am having a difficult time understanding why some things work and others don't. Based on the link I posted above my initial query should have worked - no? Perhaps I'm not thinking straight as I have spent many hours trying this and I finally got help from a co-worker (she suggested the approach I mention above).
2013/02/07
[ "https://Stackoverflow.com/questions/14741859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/668624/" ]
I think you can modify your UPDATE statement to reference the table alias in the UPDATE line. ``` update t1 set t1.[Lattitude1] = t2.[Lattitude] from table1 t1 left join table2 t2 on (t1.StationID1 = t2.IDInfo) ```
56,637,126
I'm testing a tableview the cell content in XCUItest. In my case, I don't know the order of the cell text, nor am I allowed to set an accessibility id for the text. How can I get the index of a cell given the text inside? [![enter image description here](https://i.stack.imgur.com/J6a9R.png)](https://i.stack.imgur.com/J6a9R.png) For instance, if I wanted to get the index of the cell containing text "Cell 2 Text" I would try something like this: ``` func testSample() { let app = XCUIApplication() let table = app.tables let cells = table.cells let indexOfCell2Text = cells.containing(.staticText, identifier: "Cell 2 Text").element.index(ofAccessibilityElement: "I dunno") print(indexOfCell2Text) } ``` I feel like I'm close, but I'm unsure. Can anyone suggest a solution? I apologize if this question has been asked before. I wasn't able to find anything specific about this. References I visited beforehand: <https://developer.apple.com/documentation/xctest/xcuielementquery/1500842-element> [How can I verify existence of text inside a table view row given its index in an XCTest UI Test?](https://stackoverflow.com/questions/32365327/how-can-i-verify-existence-of-text-inside-a-table-view-row-given-its-index-in-an/32389031) [iOS UI Testing tap on first index of the table](https://stackoverflow.com/questions/36566558/ios-ui-testing-tap-on-first-index-of-the-table)
2019/06/17
[ "https://Stackoverflow.com/questions/56637126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8234508/" ]
The most reliable way really is to add the index into the accessibility identifier. But, you can't. Can you change the accessibility identifier of the cell instead of the text ? Anyway, if you don't scroll your table view, you can handle it like that : ``` let idx = 0 for cell in table.cells.allElementsBoundByIndex { if cell.staticTexts["Text you are looking for"].exists { return idx } idx = idx + 1 } ``` Otherwise, the index you will use is related to cells which are displayed on the screen. So, after scrolling, the new first visible cell would become the cell at index 0 and would screw up your search.
132,698
I used linear interpolation between points: ``` T = 1; w = 0.05; num = 1000; A = 1; pulse[x_] := A*(UnitStep[x + w*T/2] - UnitStep[x - w*T/2]) fun = Table[pulse[x] + 0.2*(RandomReal[] - 0.5), {x, -T/2, T/2, T/(num - 1)}]; funX = Table[i, {i, -T/2, T/2, T/(num - 1)}]; funINT = Interpolation[Transpose[{funX[[All]], fun[[All]]}], InterpolationOrder -> 1]; ListPlot[Transpose[{funX[[All]], fun[[All]]}], PlotRange -> All, Filling -> Axis, Frame -> True, FrameLabel -> {"Time [s]", "Amplitude [V]"}, PlotLegends -> {"Pulse"}, ImageSize -> Large] ``` This produces exactly what I want: [![plot](https://i.stack.imgur.com/2fVP4.png)](https://i.stack.imgur.com/2fVP4.png) But in order to calculate the coefficients of complex Fourier series, I have to calculate the following integral: ``` cn[k_] = NIntegrate[funINT[t]*Exp[-I*2*Pi*k*t/T]/T, {t, -T/2, T/2}, Method -> "Trapezoidal"]; ``` which is not working. I get an error saying that the integrand has evaluated to non-numerical values. Any ideas on what the problem is? EDIT: If there is a method to calculate the integral between the discrete points, that might be even better in my case. However, I couldn't find one.
2016/12/03
[ "https://mathematica.stackexchange.com/questions/132698", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/19601/" ]
You could find a general symbolic Fourier coefficient for a linear polynomial and use the formula to integrate the interpolating function piecewise. If you're content with machine precision (double precision), then you can `Compile` it for really great speed. ``` (* Basic integral formulas *) ClearAll[cn0]; cn0[0][{t0_, t1_}, {x0_, x1_}] = (* k == 0 is a special case *) Integrate[(x0 + (x1 - x0)/(t1 - t0) (t - t0)) * Exp[-I*2*Pi*k*t/T]/T /. k -> 0, {t, t0, t1}]; cn0[k_][{t0_, t1_}, {x0_, x1_}] = Integrate[(x0 + (x1 - x0)/(t1 - t0) (t - t0)) * Exp[-I*2*Pi*k*t/T]/T, {t, t0, t1}]; (* Coefficient function *) Clear[cn]; cn[0] = Total@ MapThread[ (* map over interpolation segments *) cn0[0], {Partition[funX, 2, 1], Partition[fun, 2, 1]}]; cn[k_] = Total@ MapThread[ cn0[k], {Partition[funX, 2, 1], Partition[fun, 2, 1]}]; (* Compiled version *) cnC = With[ (* basic integrals *) {i0 = Function[{t0, t1, x0, x1}, (* k == 0 is a special case *) Evaluate@ Integrate[ (x0 + (x1 - x0)/(t1 - t0) (t - t0)) * Exp[-I*2*Pi*k*t/T]/T /. k -> 0, {t, t0, t1}]], i = Function[{t0, t1, x0, x1}, Evaluate@ Integrate[ (x0 + (x1 - x0)/(t1 - t0) (t - t0)) * Exp[-I*2*Pi*k*t/T]/T, {t, t0, t1}]]}, Compile[{{k, _Integer}, {t, _Real, 1}, {x, _Real, 1}}, Total@If[k == 0, i0[Most[t], Rest[t], Most[x], Rest[x]], (* vectorized for speed *) i[Most[t], Rest[t], Most[x], Rest[x]]] ]]; ``` Checks and comparison of speeds: ``` (* OP's method for comparison *) cn1[k_] := NIntegrate[funINT[t]*Exp[-I*2*Pi*k*t/T]/T, {t, -T/2, T/2}, Method -> "Trapezoidal"]; res1 = Table[cn1[k], {k, 0, 5}] // AbsoluteTiming res2 = Table[cn[k], {k, 0, 5}] // AbsoluteTiming res3 = Table[cnC[k, funX, fun], {k, 0, 5}] // AbsoluteTiming (* {6.41549, {0.0509924, 0.0485667 + 0.000384561 I, 0.0489479 + 0.000373475 I, 0.0489737 + 0.000976852 I, 0.0459565 + 0.00132399 I, 0.0452069 + 0.000833868 I}} {0.154046, {0.0509924, 0.0485667 + 0.000384561 I, 0.0489479 + 0.000373475 I, 0.0489737 + 0.000976852 I, 0.0459565 + 0.00132399 I, 0.0452069 + 0.000833868 I}} {0.001207, {0.0509924 + 0. I, 0.0485667 + 0.000384561 I, 0.0489479 + 0.000373475 I, 0.0489737 + 0.000976852 I, 0.0459565 + 0.00132399 I, 0.0452069 + 0.000833868 I}} *) res1 - res2 res2 - res3 (* {6.26145, {-6.245*10^-17, -1.27026*10^-10 - 3.56074*10^-10 I, 5.71595*10^-12 - 8.24057*10^-11 I, -5.08276*10^-10 - 1.50366*10^-11 I, 8.25427*10^-11 - 4.73669*10^-10 I, -3.07932*10^-10 + 1.72791*10^-10 I}} {0.152839, {-1.38778*10^-17 + 0. I, -3.7817*10^-15 - 1.49451*10^-14 I, 1.1019*10^-14 - 3.11627*10^-15 I, -1.10328*10^-15 - 2.62073*10^-15 I, -3.42781*10^-15 - 8.26162*10^-17 I, 1.88738*10^-15 - 1.13711*10^-15 I}} *) ``` So `cn` is almost 50 times faster than `NIntegrate` and `cnC` is over 100 times faster than `cn`.
13,003,257
If I have some kind of tree, and I need to find a specific node in that tree which is essentially null (the struct is not initialised / malloc'ed yet). If I want to return that very specific uninitialised struct place to be able to initialise it, would something like: ``` if (parentNode->childNode == NULL) return parentNode->childNode; ``` work? Or would it return NULL? Would I need to return the parent node instead? The problem I have is that this specific node may be a child of multiple different struct types. I'm not sure how to overcome this in C, since it does not support generics. Does anyone have any ideas?
2012/10/21
[ "https://Stackoverflow.com/questions/13003257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680441/" ]
You can not return NULL. It will not be an identifiable location. What you can do however is: * `malloc` the node at the point where you find it and return the pointer returned by malloc, * you can `return &(parentNode->childNode)` (a pointer to the childNode pointer) which the caller of the function can use to set it to the new node, or * `return parentNode` I don't see how that problem could be mitigated by generics.
17,268,287
I am developing a website and currently I am stick in the registration process. When I ask users to register to my website, they need to choose the number of people that a team will have. When I select the number of people in the selection box, my website displays input fields according to the number of people that I selected. This works fine in Mozilla Firefox (Mozilla/5.0 (X11; U; Linux x86\_64; en-US; rv:1.9.2.24) Gecko/20111109 CentOS/3.6.24-3.el6.centos Firefox/3.6.24). Nonetheless, the other web browsers do not display the input fields according to the number of people that I selected. This is the following code: ``` <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script> <script> $(document).ready(function(){ $("#muestra1").click(function(){ $("#loscuatro").hide(); }); }); $(document).ready(function(){ $("#muestra2").click(function(){ $("#loscuatro").show(); }); }); </script> </head> <body> <div id="container" class="ltr"> <li><span> <div id="container" class="ltr"> <h2>Please give us your name</h2> <ul> <li> <span> Number of team members <select name="integrantes" id="integrantes" > <option name="member1" value="1" id="muestra1" >1</option> <option name="member2" value="2" id="muestra2">2</option> </li><hr /></span> <b><h3>Leader</h3></b> <li> <span> Name* <input id="Field0" /></span> </li><hr /> <div id="loscuatro"> <b><h3>Volunteer</h3></b> <li> <span> Name* <input id="Field0" /></span> </li><hr /> </div><!--end of volunteer loscuatros--> </div> </body> </html> ``` Please, I would be very glad to receive support to this code because I've looked at it several times and I can't find the bug. I remark that this is not the final design of my registration part. Cheers.
2013/06/24
[ "https://Stackoverflow.com/questions/17268287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2514936/" ]
Here is a [**Live demo**](http://jsfiddle.net/mplungjan/EyG6g/) You need to change your option click to the change event of the select. You can also drop the name and ID of the options: ``` $(function(){ $("#integrantes").on("change",function(){ $("#loscuatro").toggle(this.selectedIndex==1); // second option is option 1 }); $("#integrantes").change(); // set to whatever it is at load time }); ``` and close the select ``` <select name="integrantes" id="integrantes" > <option value="1">1</option> <option value="2">2</option> </select> ``` Lastly run your code through a [validator](http://validator.w3.org/) You have unwrapped LIs and two divs with the same ID and as far as I can tell without seeing the CSS, useless spans. Here is a cleaned up version [**Live demo**](http://jsfiddle.net/mplungjan/eTcUH/) ``` <div id="container" class="ltr"> <h2>Please give us your name</h2> <ul> <li> Number of team members <select name="integrantes" id="integrantes" > <option value="1">1</option> <option value="2">2</option> </select> </li> </ul> <h3>Leader</h3> <ul> <li> Name* <input id="Field0" /><hr /> </li> </ul> <div id="loscuatro"> <h3>Volunteer</h3> <ul> <li> Name* <input id="Field0" /><hr /> </li> </ul> </div><!--end of volunteer loscuatros--> </div> ```
3,935,641
How can I add a close button to a draggable/resizable div? I understand that I am essentially describing a dialog, but I have to be able to take advantage of a few of the properties of resizable/draggable (such as containment) that are not a part of dialog. Any ideas?
2010/10/14
[ "https://Stackoverflow.com/questions/3935641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476055/" ]
You can use multiple class names (a perfectly normal thing to do), but are only allowed one class attribute on your HTML element. Do this instead: ``` <a href="#" class="paren defaul">text</a> ```
511,515
We have a scenario One Main e-commerce website - currently attracting a lot of visitors. Three sub "brand specific" sites which will hang off this site - each of these sites will potentiall have the same level of traffic over time. The client requires order processing for each brand site to happen in one place (i.e. one backoffice). What topology should we choose? We think that perhaps having a main sql server with both reads and writes from the backoffice, and replicate that data to "brand specific" sql server instances might work. Each brand specific site would have its own dedicated sql server for Frontoffice "reads". Any writes we perform would go back to the main database to keep stock concurrent Any thoughts? Future scalability is a major factor.
2009/02/04
[ "https://Stackoverflow.com/questions/511515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42446/" ]
Without having a more detailed understanding of how your application is to function it is difficult to provide you with clear direction. Your proposed implementation of having a central server (Publisher) supporting reads and writes, with a number of additional site specific servers (subscribers) for reads only, is certainly plausible. This has the added benefit of giving you the flexibility to replicate only the tables that would be required for read queries i.e. your central server will likely manage data such as supplier information, billing etc. that may not need to be pushed to subscribers. Your central server is likely going to be your sticking point if any, as all other servers will directing write activity back to it. The location of your distributed sites i.e. how far they are from the central server will also affect the transactional latency of your replicated environment. If you wish to present all of your database data as read only at the distributed sites then you may wish to consider using Log Shipping for this. The disadvantage of this implementation if that your application needs to be aware that only read activity can be processed on the local server and all write activity needs to be routed to the central server. I hope this helps but please feel free to pose additional questions. Cheers, John
67,359,673
I'm using *Entity Framework* and *Dynamic Linq Core* to perform some dynamic queries at run time. I have a question on how to write dynamic linq statements to output columns of counts where each column is a field item of another field. Say I have a table with 3 columns: ID, Gender, and Age (assuming they are only in the 10s). ``` ID | Gender | Age 01 | male | 20 02 | female | 30 ... some thousands of rows ``` I would like to count the number of people in each gender (groupBy Gender), by their age group. ``` [{Gender:"male", "20": 120, "30": 200, "40": 300}, {Gender:"female", "20": 300, "30": 200, "40": 1000 }] ``` I tried to group by age, but this doesn't give exactly what i wanted in the above format, because each gender and age combo becomes a new array item. ``` var query = db.someDB .GroupBy("new(Gender, Age)") .Select("new(Key.Gender as Gender, Key.Age as Age, Count() as value)"); ``` I'm restricted to use dynamic linq core because in my real application, the gender and age fields is up to the user to decide, so their field name will change at run-time. How would you do it?
2021/05/02
[ "https://Stackoverflow.com/questions/67359673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11735492/" ]
let's say your query returns a list of object of the following class ``` public class Data { public string Gender { get; set;} public int Age { get; set;} public int Value { get; set;} } ``` ```cs Data results = //query result var resultsV2 = results.GroupBy(r => r.Gender); var list = new List<IDictionary<string, object>>(); foreach(var g in resultsV2) { IDictionary<string, object> obj = new ExpandoObject(); var data = g.Select(x => x); obj["Gender"] = $"{g.Key}"; foreach(var d in data) { var propName = $"{d.Age}"; obj[propName] = $"{d.Value}"; } list.Add(obj); } string jsonString = JsonConvert.SerializeObject(list); ``` [Fiddler](https://dotnetfiddle.net/rPMYN1) input: ``` new List<Data> { new Data() { Gender = "Male", Age = 20, Value = 5 }, new Data() { Gender = "Male", Age = 30, Value = 3 }, new Data() { Gender = "Female", Age = 20, Value = 9 } }; ``` output: ``` [{"Gender":"Male","20":"5","30":"3"},{"Gender":"Female","20":"9"}] ```
2,436,542
I know that on MacOSX / PosiX systems, there is atomic-compare-and-swap for C/C++ code via g++. However, I don't need the compare -- I just want to atomically swap two values. Is there an atomic swap operation available? [Everythign I can find is atomic\_compare\_and\_swap ... and I just want to do the swap, without comparing]. Thanks!
2010/03/12
[ "https://Stackoverflow.com/questions/2436542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/247265/" ]
the "lock xchg" intel assembly instruction probably achieves what you want but i dont think there is a GCC wrapper function to make it portable. Therefor your stuck using inline assembly(not portable) or using compare and swap and forcing the compare to be true(inneficient). Hope this helps :-)
45,888
I use tabs in C/C++ but want to convert those tabs to spaces when copying code that I'm going to paste into an external program. However, I want the original code to retain tabs. Additionally (if possible), I'd like to keep the tabs when copying/pasting within Emacs. I sort of adapted the code at [this link](https://emacs.stackexchange.com/a/18425/20317) and tried: ``` (advice-add 'kill-ring-save :before 'untabify) (advice-add 'kill-ring-save :after 'tabify) ``` but it doesn't copy all the text and converts away from tabs when copying and pasting within Emacs. For instance, if I use the above setup on ``` int main() { int i = 5; } ``` it only copies ``` int main() { int i ``` I'm not a Lisp programmer and am relatively new to Emacs, so forgive me if I'm missing something obvious here.
2018/11/10
[ "https://emacs.stackexchange.com/questions/45888", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/20317/" ]
It's not documented well enough, and possibly poorly named, but the `hideshow` function `hs-hide-level` will collapse all the blocks within the current block. That is, if your cursor is on the `class ...` line (or below it) in your example input, it will give you something very similar to your desired output. Since `hideshow` works with indentation I've found that it works best with *well formated* code or text. Given: ```python class LongClassIDidNotWrite(): def method1(): print("") print("") print("") def method2(): print("") print("") print("") def method3(): print("") print("") print("") ``` Placing the cursor in "Long" on the `class ...` line and calling `M-x hs-hide-level` or `C-c @ C-l` will give you: ```python class LongClassIDidNotWrite(): def method1():...) def method2():...) def method3():...) ``` This works on any point that is part of the `class ...` block. That is, that line, on the blank lines, and on the `def ...` lines. If you try it on the `print ...` lines it won't work, as you're in a new block, and there are no child blocks to fold. `hs-hide-level` also runs a hook `hs-hide-hook` which could prove useful. There is also a `hs-hide-level-recursive` which will recursively hide blocks in a region. It does not run `hs-hide-hook`, according to its documentation.
53,242
How do I check if a partition is encrypted? In particular I would like to know how I check if `/home` and swap is encrypted.
2011/07/15
[ "https://askubuntu.com/questions/53242", "https://askubuntu.com", "https://askubuntu.com/users/19490/" ]
Regarding the standard home encryption provided by Ubuntu, you can ``` sudo ls -lA /home/username/ ``` and if you get something like ``` totale 0 lrwxrwxrwx 1 username username 56 2011-05-08 18:12 Access-Your-Private-Data.desktop -> /usr/share/ecryptfs-utils/ecryptfs-mount-private.desktop lrwxrwxrwx 1 username username 38 2011-05-08 18:12 .ecryptfs -> /home/.ecryptfs/username/.ecryptfs lrwxrwxrwx 1 username username 37 2011-05-08 18:12 .Private -> /home/.ecryptfs/username/.Private lrwxrwxrwx 1 username username 52 2011-05-08 18:12 README.txt -> /usr/share/ecryptfs-utils/ecryptfs-mount-private.txt ``` then the username's home directory is encrypted. This works when username is not logged in, so the partition is not mounted. Otherwise you can look at `mount` output. About the swap, do ``` sudo blkid | grep swap ``` and should check for an output similar to ``` /dev/mapper/cryptswap1: UUID="95f3d64d-6c46-411f-92f7-867e92991fd0" TYPE="swap" ```
105,877
So I'm making a game using love2d where the player will find himself in an zombie infested city but I don't want the city/map to be just the same all the time, so I want to create a random map/city generator, but I don't know where to start, I maybe can make my own but the result would probably be not what I wanted, as I don't want tiles getting placed all over the place messily(it won't look like a city then), I want random set of tiles getting placed in the world/map like buildings get placed randomly throughout the world/map, I hope someone can help me with this as this is really hard for me...
2015/08/19
[ "https://gamedev.stackexchange.com/questions/105877", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/70087/" ]
Like stated by Shiro in a comment , it's difficult to give a precise answer. I can suggest a possible starting point. Use random [voronoi](https://it.wikipedia.org/wiki/Diagramma_di_Voronoi) generation where , given a set of random points P , each point in space is weighted relative to the distance from the nearest p in P. [![enter image description here](https://i.stack.imgur.com/JWgJh.png)](https://i.stack.imgur.com/JWgJh.png) Now , instead of considering euclidean distance use [Manhattan distance](https://en.wikipedia.org/wiki/Taxicab_geometry) and you get something like this : [![enter image description here](https://i.stack.imgur.com/koXjs.png)](https://i.stack.imgur.com/koXjs.png) then adjoust the gradient to obtain this [![enter image description here](https://i.stack.imgur.com/83aDs.png)](https://i.stack.imgur.com/83aDs.png)
46,287,904
I was reading about [value types](https://en.wikipedia.org/wiki/Value_type) and *values* and *objects* were mentioned as if they meant something different, so I assume they do. I then tried to do some research but without luck. I know that a value is an expression that cannot be evaluated further, but isn't an object just the "container" for a value? Also, based on my terminological understanding of expressions, would it be weird to say that an object holds an expression(since a value is an expression)? I will not start making too many guesses because that could will probably just complicate it all and might redirect the focus away from the **difference between values and objects.** Edit: To the people who have marked this as "too-broad", isn't the following question just as broad if not broader [What are rvalues, lvalues, xvalues, glvalues, and prvalues](https://stackoverflow.com/questions/3601602/what-are-rvalues-lvalues-xvalues-glvalues-and-prvalues)? Also, there are so many other "difference between" questions out there on SO, and many of them are as broad as the one I linked.. So why is this particular question not valid?
2017/09/18
[ "https://Stackoverflow.com/questions/46287904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A **value** is a more abstract concept than an **object**. Like those mentioned in comments, the difference/relationship between a value and an object is similar to that between water and a cup. You need a container, which in this case is a cup, to hold the water, or it will leak. Likewise, you need an object to hold values so they don't get lost or overwritten very soon. An object always has its dedicated storage area (in memory), whereas a value's life span can be as little as a single instruction (`movl %eax, $1`).
951,981
Expanding on [How can I make Windows 8 use the classic theme?](https://superuser.com/questions/513492/how-can-i-make-windows-8-use-the-classic-theme) and [Windows 10 TenForums: Windows Classic Look Theme in Windows 10](http://www.tenforums.com/customization/11432-windows-classic-look-theme-windows-10-a.html) -- how does one use Windows 10 with the old classic theme? [![enter image description here](https://i.stack.imgur.com/cwmlt.png)](https://i.stack.imgur.com/cwmlt.png) There's a [Windows 10 theme over at DeviantArt](http://kizo2703.deviantart.com/art/Windows-classic-theme-for-Windows-8-RTM-8-1-10-325642288) but it does not work with the final RTM: [![enter image description here](https://i.stack.imgur.com/dUZHw.jpg)](https://i.stack.imgur.com/dUZHw.jpg) Also, your vote over at [Windows 10 UserVoice: Windows Classic Look Theme in Windows 10](https://windows.uservoice.com/forums/265757-windows-feature-suggestions/suggestions/9193677-windows-classic-look-theme-in-windows-10) would be much appreciated.
2015/08/06
[ "https://superuser.com/questions/951981", "https://superuser.com", "https://superuser.com/users/327566/" ]
Have a look at this thread: <http://forum.thinkpads.com/viewtopic.php?f=67&t=113024&p=777781&hilit=classictheme#p777781> They're discussing/testing how to modify windows binary files to "get back" to classic interface by "unusual" methods, rather than just turning colors into gray! But it appears to be very complex due to totally different structure of explorer, windows manager and whatelse in Windows 10 w.r.t. previous versions. Note: be sure to create a restore point before running ClassicTheme.exe for testing! It can screw up whole interface! For the start menu, things are easier thanks to ClassicShell: <http://www.classicshell.net/gallery/> Additionally, try googling for: Classic AE by Saarineames (download from deviantart) Aero Lite Theme (among other things, make windows border larger than one pixel, for better resize and better visibility) You can also play (carefully) with registry keys: * HKEY\_CURRENT\_USER\SOFTWARE\Microsoft\Windows\DWM *(you can add **AccentColorInactive** key here, or edit existing keys)* * KEY\_CURRENT\_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize <http://www.thewindowsclub.com/get-colored-window-title-bar-windows-10> Ultimate Windows Tweaker is also an amazing tool: <http://www.thewindowsclub.com/image-gallery-for-uwt4>
10,569,321
In Spring WS, endpoints are typically annotated with the @Endpoint annotation. e.g. ``` @Endpoint public class HolidayEndpoint { ... } ``` My question is: is there any way to deifine schema-based endpoint (based on XML configuration)? Thanks...
2012/05/13
[ "https://Stackoverflow.com/questions/10569321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/379814/" ]
In your spring-ws-servlet.xml configuration,add the following: ``` <?xml version="1.0" encoding="UTF-8"?> <beans> <context:annotation-config /> <sws:annotation-driven /> <sws:dynamic-wsdl id="holidayEndPoint" portTypeName="HolidayEndpoint" ............ ...... ``` More info can be had from here [Unable to access web service endpoint: Spring-WS 2](https://stackoverflow.com/questions/7718257/unable-to-access-web-service-endpoint-spring-ws-2) May be this will help you.
40,012,211
The question reads "Just as it is possible to multiply by adding over and over, it is possible to divide by subtracting over and over. Write a program with a procedure to compute how many times a number N1 goes into another number N2. You will need a loop, and count for how many times that loop is executed". I am really stuck at the subtraction phase. I know I have to create a loop but I don't know where to place it. ``` org 100h .MODEL SMALL .STACK 100H .DATA MSG1 DB 'FIRST > $' MSG2 DB 'SECOND > $' MSG3 DB 'THE SUBTRACTION OF ' VALUE1 DB ? MSG4 DB ' AND ' VALUE2 DB ?, ' IS ' SUM DB ?,'.$' CR DB 0DH, 0AH, '$' .CODE MAIN PROC ;INITIALIZE DS MOV AX, @DATA MOV DS, AX ;PROMPT FOR FIRST INPUT LEA DX, MSG1 MOV AH, 9H INT 21H MOV AH, 1H INT 21H MOV VALUE1, AL MOV BH, AL SUB BH, '0' ;CARRIAGE RETURN FORM FEED LEA DX, CR MOV AH, 9H INT 21H ;PROMPT FOR SECOND INPUT LEA DX, MSG2 MOV AH, 9H INT 21H MOV AH, 1H INT 21H MOV VALUE2, AL MOV BL, AL SUB BL, '0' SUBTRACT: ;SUB THE VALUES CONVERT TO CHARACTER AND SAVE SUB BH, BL ADD BH, '0' MOV SUM, BH ;CARRIAGE RETURN FORM FEED LEA DX, CR MOV AH, 9H INT 21H ;OUTPUT THE RESULT LEA DX, MSG3 MOV AH, 9H INT 21H TERMINATE: ;RETURN TO DOS MOV AH, 4CH INT 21H MAIN ENDP END MAIN ```
2016/10/13
[ "https://Stackoverflow.com/questions/40012211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7011413/" ]
Algorithm for positive N1,N2: 1. prepare `N1`, `N2` and set some `R` to -1 2. increment `R` 3. subtract `N1` from `N2` (update `N2` with result) 4. when result of subtraction is above or equal to zero, go to step 2. 5. `R` has result of integer division `N2`/`N1` Steps 2. to 4. can be written in x86 Assembly by single instruction per step (the `sub` updates "carry flag", which can be used to decide whether the subtraction did "overflow" - used by one of the "Jcc" = jump-condition-code instructions to either jump somewhere else or continue by next instruction).
4,468,310
suppose there is a tree with number of child nodes increasing from 2 to 4 then 8 and so on.how can we write recurrence relation for such a tree.
2010/12/17
[ "https://Stackoverflow.com/questions/4468310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/531802/" ]
* using subtitution method- T(n)=2T(n/2)+n =2[2T(n/2^2)+n/2]+n =2^2T(n/2^2)+n+n =2^2[2T(n/2^3)+n/2^2]+n+n =2^3T(n/2^3)+n+n+n similarly subtituing k times-- we get T(n)=2^k T(n/2^k)+nk the recursion will terminate when n/2^k=1 k=log n base 2. thus T(n)=2^log n(base2)+n(log n) =n+nlogn thus the tight bound for the above recurrence relation will be =n log N (base of log is 2)
34,686,217
``` ggplot(all, aes(x=area, y=nq)) + geom_point(size=0.5) + geom_abline(data = levelnew, aes(intercept=log10(exp(interceptmax)), slope=fslope)) + #shifted regression line scale_y_log10(labels = function(y) format(y, scientific = FALSE)) + scale_x_log10(labels = function(x) format(x, scientific = FALSE)) + facet_wrap(~levels) + theme_bw() + theme(panel.grid.major = element_line(colour = "#808080")) ``` And I get this figure [![enter image description here](https://i.stack.imgur.com/VIMue.png)](https://i.stack.imgur.com/VIMue.png) Now I want to add **one geom\_line** to one of the facets. Basically, I wanted to have a dotted line (Say x=10,000) in only the **major** panel. How can I do this?
2016/01/08
[ "https://Stackoverflow.com/questions/34686217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3942806/" ]
I don't have your data, so I made some up: ``` df <- data.frame(x=rnorm(100),y=rnorm(100),z=rep(letters[1:4],each=25)) ggplot(df,aes(x,y)) + geom_point() + theme_bw() + facet_wrap(~z) ``` [![enter image description here](https://i.stack.imgur.com/uCOR9.png)](https://i.stack.imgur.com/uCOR9.png) To add a vertical line at `x = 1` we can use `geom_vline()` with a dataframe that has the same faceting variable (in my case `z='b'`, but yours will be `levels='major'`): ``` ggplot(df,aes(x,y)) + geom_point() + theme_bw() + facet_wrap(~z) + geom_vline(data = data.frame(xint=1,z="b"), aes(xintercept = xint), linetype = "dotted") ``` [![enter image description here](https://i.stack.imgur.com/0uBOB.png)](https://i.stack.imgur.com/0uBOB.png)
6,117,315
I have three questions regarding SSL that I don't fully understand. 1. If I get it correctly, a server `A` submits a request to a certain CA. Then, it receives (after validation etc.) a digital certificate composed of a public key + identity + an encription of this information using the CA's private key. Later on, a client `B` wants to open an SSL communication with `A`, so `A` sends `B` its digital certificate. My question is can't `B` just take this certificate, thus stealing the identity `A` - which will allow them to authenticate as `A` to `C`, for example. I understand that `C` will decrypt the certificate with the CA's public key, It will then encrypt its symetric key which will only be decryptable by the real `A`. However, I do not see where authentication comes to play if `B` can actually steal `A`'s identity. Unless I am missing something. 2. Second question: Why use hashing on the certificate if a part of it is already encrypted by the CA? Doesn't this mean that no one can mess around with a digital certificate (in high probability) anyway? 3. If I am stackoverflow and I have 3 servers doing the same thing - allowing clients to access, read, identify etc. - do I have to have a different digital certificate for each of the 3 servers. Thank you very much.
2011/05/24
[ "https://Stackoverflow.com/questions/6117315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/764420/" ]
An SSL identity is characterized by four parts: 1. A *private* key, which is not shared with anyone. 2. A *public* key, which you can share with anyone. The private and public key form a matched pair: anything you encrypt with one can be decrypted with the other, but you *cannot* decrypt something encrypted with the public key without the private key or vice versa. This is genuine mathematical magic. 3. *Metadata* attached to the public key that state who it is talking about. For a server key, this would identify the DNS name of the service that is being secured (among other things). Other data in here includes things like the intended uses (mainly used to limit the amount of damage that someone with a stolen certificate can do) and an expiry date (to limit how long a stolen certificate can be used for). 4. A *digital signature* on the combination of public key and metadata so that they can't be messed around with and so that someone else can know how much to trust the metadata. There are multiple ways to handle who does the signature: * Signing with the private key (from part 1, above); a self-signed certificate. Anyone can do this but it doesn't convey much trust (precisely because *anyone* can do this). * Getting a group of people who trust each other to vouch for you by signing the certificate; a web-of-trust (so called because the trust relationship is transitive and often symmetric as people sign each others certificates). * Getting a trusted third party to do the signing; a certificate authority (CA). The identity of the CA is guaranteed by another higher-level CA in a *trust chain* back to some root authority that “everyone” trusts (i.e., there's a list built into your SSL library, which it's possible to update at deployment time).There's no basic technical difference between the three types of authorities above, but the nature of the trust people put in them is extremely variable. The details of why this is would require a very long answer indeed! Items 2–4 are what comprises the digital certificate. When the client, B, starts the SSL protocol with the server, A, the server's digital certificate is communicated to B as part of the protocol. A's private key is *not* sent, but because B can successfully decrypt a message sent by the other end with the public key in the digital certificate, B can know that A has the private key that matches. B can then look at the metadata in the certificate and see that the other end claims to be A, and can examine the signature to see how much to trust that assertion; if the metadata is signed by an authority that B trusts (directly or indirectly) then B can trust that the other end has A's SSL identity. If that identity is the one that they were expecting (i.e., they wanted to talk to A: in practice, this is done by comparing the DNS name in the certificate with the name that they used when looking up the server address) then they can know that they have a secured communications channel: they're good to go. B can't impersonate A with that information though: B doesn't get A's private key and so it would all fall apart at the first stage of verification. In order for some third party to impersonate B, they need to have (at least) two of: * *The private key*. The owner of the identity needs to take care to stop this from happening, but it is ultimately in their hands. * *A trusted authority that makes false statements*. There's occasional weaknesses here — a self-signed authority is never very trustworthy, a web of trust runs into problems because trust is an awkward thing to handle transitively, and some CAs are thoroughly unscrupulous and others too inclined to not exclude the scum — but mostly this works fairly well because most parties are keen to not cause problems, often for financial reasons. * *A way to poison DNS* so that the target believes a different server is really the one being impersonated. Without DNSsec this is somewhat easy unfortunately, but this particular problem is being reduced. As to your other questions… > > Why use hashing on the certificate if a part of it is already encrypted by the CA? Doesn't this mean that no one can mess around with a digital certificate (in high probability) anyway? > > > While keys are fairly long, certificates are longer (for one thing, they include the signers public key anyway, which is typically the same length the key being signed). Hashing is part of the general algorithm for signing documents anyway because nobody wants to be restricted to signing only very short things. Given that the algorithm is required, it makes sense to use it for this purpose. > > If I am stackoverflow and I have 3 servers doing the same thing - allowing clients to access, read, identify etc. - do I have to have a different digital certificate for each of the 3 servers. > > > If you have several servers serving the same DNS name (there's many ways to do this, one of the simplest being round-robin DNS serving) you can put the same identity on each of them. This slightly reduces security, but only very slightly; it's still *one service* that just happens to be implemented by *multiple servers*. In theory you could give each one a different identity (though with the same name) but I can't think of any good reason for actually doing it; it's more likely to worry people than the alternative. Also note that it's possible to have a certificate for more than one service name at once. There are two mechanisms for doing this (adding alternate names to the certificate or using a wildcard in the name in the certificate) but CAs tend to charge quite a lot for signing certificates with them in.
10,017,027
I have a table transaction which has duplicates. i want to keep the record that had minimum id and delete all the duplicates based on four fields DATE, AMOUNT, REFNUMBER, PARENTFOLDERID. I wrote this query but i am not sure if this can be written in an efficient way. Do you think there is a better way? I am asking because i am worried about the run time. ``` DELETE FROM TRANSACTION WHERE ID IN (SELECT FIT2.ID FROM (SELECT MIN(ID) AS ID, FIT.DATE, FIT.AMOUNT, FIT.REFNUMBER, FIT.PARENTFOLDERID FROM EWORK.TRANSACTION FIT GROUP BY FIT.DATE, FIT.AMOUNT , FIT.REFNUMBER, FIT.PARENTFOLDERID HAVING COUNT(1)>1 and FIT.AMOUNT >0) FIT1, EWORK.TRANSACTION FIT2 WHERE FIT1.DATE=FIT2.DATE AND FIT1.AMOUNT=FIT2.AMOUNT AND FIT1.REFNUMBER=FIT2.REFNUMBER AND FIT1.PARENTFOLDERID=FIT2.PARENTFOLDERID AND FIT1.ID<>FIT2.ID) ```
2012/04/04
[ "https://Stackoverflow.com/questions/10017027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/510242/" ]
It would probably be more efficient to do something like ``` DELETE FROM transaction t1 WHERE EXISTS( SELECT 1 FROM transaction t2 WHERE t1.date = t2.date AND t1.refnumber = t2.refnumber AND t1.parentFolderId = t2.parentFolderId AND t2.id > t1.id ) ```
43,339,561
I want to select the number of rows which are greater than 3 by rownum function i\_e "(rownum>3)" for example if there are 25 rows and I want to retrieve the last 22 rows by rownum function. but when I write the ``` select * from test_table where rownum>3; ``` it retrieve no row. can any one help me to solve this problem. thanks in advance
2017/04/11
[ "https://Stackoverflow.com/questions/43339561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7677507/" ]
In RDBMS there is no first or last rows. What you calls "raws" , actually is set(sets), they can be ordered or not. `rownum` is a function, which is just enumerates result set, it makes sense only after set is calculated, to order your set of data (rows) you should do it in your query before `rownum` call, you must tell DB what means for the order in particular select statement.
6,213,814
How to populate form with JSON data using data store? How are the textfields connected with store, model? ``` Ext.define('app.formStore', { extend: 'Ext.data.Model', fields: [ {name: 'naziv', type:'string'}, {name: 'oib', type:'int'}, {name: 'email', type:'string'} ] }); var myStore = Ext.create('Ext.data.Store', { model: 'app.formStore', proxy: { type: 'ajax', url : 'app/myJson.json', reader:{ type:'json' } }, autoLoad:true }); Ext.onReady(function() { var testForm = Ext.create('Ext.form.Panel', { width: 500, renderTo: Ext.getBody(), title: 'testForm', waitMsgTarget: true, fieldDefaults: { labelAlign: 'right', labelWidth: 85, msgTarget: 'side' }, items: [{ xtype: 'fieldset', title: 'Contact Information', items: [{ xtype:'textfield', fieldLabel: 'Name', name: 'naziv' }, { xtype:'textfield', fieldLabel: 'oib', name: 'oib' }, { xtype:'textfield', fieldLabel: 'mail', name: 'email' }] }] }); testForm.getForm().loadRecord(app.formStore); }); ``` JSON ``` [ {"naziv":"Lisa", "oib":"2545898545", "email":"[email protected]"} ] ```
2011/06/02
[ "https://Stackoverflow.com/questions/6213814", "https://Stackoverflow.com", "https://Stackoverflow.com/users/765628/" ]
The field names of your model and form **should match**. Then you can load the form using `loadRecord()`. For example: ``` var record = Ext.create('XYZ',{ name: 'Abc', email: '[email protected]' }); formpanel.getForm().loadRecord(record); ``` or, get the values from already loaded store.
33,864,134
I'm developing an Android Application which is consists of a Navigation drawer and a Google Map. I have successfully developed my Navigation Drawer and connect my Map into it. The thing is I need my Map to Zoom to the current location. Here is the code I used in `MapsActivity.java`. ``` protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); setUpMapIfNeeded(); mMap.setMyLocationEnabled(true); // Identify the current location of the device mMap.setOnMyLocationChangeListener(this); // change the place when the device is moving Location currentLocation = getMyLocation(); // Calling the getMyLocation method if(currentLocation!=null){ LatLng currentCoordinates = new LatLng( currentLocation.getLatitude(), currentLocation.getLongitude()); mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentCoordinates, 13.0f)); } } ``` Here I implemented getMyLocation() method. ``` //Zoom to the current location private Location getMyLocation() { LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // Get location from GPS if it's available Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); // Location wasn't found, check the next most accurate place for the current location if (myLocation == null) { Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); // Finds a provider that matches the criteria String provider = lm.getBestProvider(criteria, true); // Use the provider to get the last known location myLocation = lm.getLastKnownLocation(provider); } return myLocation; } ``` Here is How I gave MapsFragment in to NavigatioDrawerActivity. ``` fragment = new MapFragment(); ``` When I run this alone (Insert intent filter to MapsActivity in Manifest) it works perfect. But, when I'm running the Nvigation Drawer as MainActivity this function is not working. Only the default Map is loading. What should I do? -edit- ``` private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } ``` My Maps.xml is like this. ``` <fragment xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/map" tools:context=".MapsActivity" android:name="com.google.android.gms.maps.SupportMapFragment" /> ``` My whole MapsActivity.java ``` public class MapsActivity extends FragmentActivity implements GoogleMap.OnMyLocationChangeListener { private GoogleMap mMap; // Might be null if Google Play services APK is not available. private MapView mapView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); setUpMapIfNeeded(); mMap.setMyLocationEnabled(true); // Identify the current location of the device mMap.setOnMyLocationChangeListener(this); // change the place when the device is moving initializaMap(rootView, savedInstanceState); } @Override protected void onResume() { super.onResume(); setUpMapIfNeeded(); } private void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { // Try to obtain the map from the SupportMapFragment. mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)) .getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { setUpMap(); } } } private void initializaMap(View rootView, Bundle savedInstanceState){ MapsInitializer.initialize(MapsActivity.this); switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(MapsActivity.this)) { case ConnectionResult.SUCCESS: mapView = (MapView) rootView.findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); if (mapView != null) { mMap = mapView.getMap(); mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); UiSettings mUiSettings = mMap.getUiSettings(); mMap.setMyLocationEnabled(true); mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f)); mUiSettings.setCompassEnabled(true); mUiSettings.setMyLocationButtonEnabled(false); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(6.9270786, 79.861243), 13)); } break; case ConnectionResult.SERVICE_MISSING: break; case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED: break; default: } } /** * This is where we can add markers or lines, add listeners or move the camera. In this case, we * just add a marker near Africa. * <p/> * This should only be called once and when we are sure that {@link #mMap} is not null. */ private void setUpMap() { mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker")); } @Override public void onMyLocationChange(Location location) { } } ``` Here is my NavigationDrawer.java ``` public class NavigationDrawer extends ActionBarActivity { private GoogleMap mMap; String[] menutitles; TypedArray menuIcons; // nav drawer title private CharSequence mDrawerTitle; private CharSequence mTitle; private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private List<RowItem> rowItems; private CustomAdapter adapter; private LinearLayout mLenear; static ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_NavigationDrawer); mTitle = mDrawerTitle = getTitle(); menutitles = getResources().getStringArray(R.array.titles); menuIcons = getResources().obtainTypedArray(R.array.icons); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.slider_list); mLenear = (LinearLayout)findViewById(R.id.left_drawer); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFA500"))); imageView=(ImageView)findViewById(R.id.profPic); Bitmap bitmap= BitmapFactory.decodeResource(getResources(), R.drawable.ic_prof); imageView.setImageBitmap(getCircleBitmap(bitmap)); rowItems = new ArrayList<RowItem>(); for (int i = 0; i < menutitles.length; i++) { RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId( i, -1)); rowItems.add(items); } menuIcons.recycle(); adapter = new CustomAdapter(getApplicationContext(), rowItems); mDrawerList.setAdapter(adapter); mDrawerList.setOnItemClickListener(new SlideitemListener()); // enabling action bar app icon and behaving it as toggle button getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu); mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.app_name,R.string.app_name) { public void onDrawerClosed(View view) { getSupportActionBar().setTitle(mTitle); // calling onPrepareOptionsMenu() to show action bar icons invalidateOptionsMenu(); } public void onDrawerOpened(View drawerView) { getSupportActionBar().setTitle(mDrawerTitle); // calling onPrepareOptionsMenu() to hide action bar icons invalidateOptionsMenu(); } }; mDrawerLayout.setDrawerListener(mDrawerToggle); if (savedInstanceState == null) { // on first time display view for first nav item updateDisplay(0); } initializaMap(savedInstanceState); } private void initializaMap(Bundle savedInstanceState){ MapsInitializer.initialize(Extract.this); switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(Extract.this)) { case ConnectionResult.SUCCESS: MapView mapView = (MapView) findViewById(R.id.mapView); mapView.onCreate(savedInstanceState); if (mapView != null) { mMap = mapView.getMap(); mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); UiSettings mUiSettings = mMap.getUiSettings(); mMap.setMyLocationEnabled(true); mMap.animateCamera(CameraUpdateFactory.zoomTo(15.0f)); mUiSettings.setCompassEnabled(true); mUiSettings.setMyLocationButtonEnabled(false); mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(6.9192, 79.8950), 13)); } break; case ConnectionResult.SERVICE_MISSING: break; case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED: break; default: } } //Circle Image public static Bitmap getCircleBitmap(Bitmap bitmap) { int w = bitmap.getWidth(); int h = bitmap.getHeight(); int radius = Math.min(h / 2, w / 2); Bitmap output = Bitmap.createBitmap(w + 8, h + 8, Bitmap.Config.ARGB_8888); Paint p = new Paint(); p.setAntiAlias(true); Canvas c = new Canvas(output); c.drawARGB(0, 0, 0, 0); p.setStyle(Paint.Style.FILL); c.drawCircle((w / 2) + 4, (h / 2) + 4, radius, p); p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); c.drawBitmap(bitmap, 4, 4, p); p.setXfermode(null); p.setStyle(Paint.Style.STROKE); p.setColor(Color.WHITE); p.setStrokeWidth(3); c.drawCircle((w / 2) + 2, (h / 2) + 2, radius, p); return output; } class SlideitemListener implements ListView.OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { updateDisplay(position); } } private void updateDisplay(int position) { Fragment fragment = null; switch (position) { case 0: // fragment = new MapFragment(); //break; default: break; } if (fragment != null) { FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit(); // update selected item and title, then close the drawer setTitle(menutitles[position]); mDrawerLayout.closeDrawer(mLenear); } else { // error in creating fragment Log.e("Extract", "Error in creating fragment"); } } @Override public void setTitle(CharSequence title) { mTitle = title; getSupportActionBar().setTitle(mTitle); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_extract, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // toggle nav drawer on selecting action bar app icon/title if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // Handle action bar actions click switch (item.getItemId()) { case R.id.action_settings: return true; default : return super.onOptionsItemSelected(item); } } /*** * Called when invalidateOptionsMenu() is triggered */ @Override public boolean onPrepareOptionsMenu(Menu menu) { // if nav drawer is opened, hide the action items boolean drawerOpen = mDrawerLayout.isDrawerOpen(mLenear); menu.findItem(R.id.action_settings).setVisible(!drawerOpen); return super.onPrepareOptionsMenu(menu); } /** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggles mDrawerToggle.onConfigurationChanged(newConfig); } } ```
2015/11/23
[ "https://Stackoverflow.com/questions/33864134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
try this .. ``` map.animateCamera(CameraUpdateFactory.newLatLngZoom((sydney), 13.0f)); ``` you have not given by in float. so its not working.. try this..
32,739,103
I have a complex object and I'm trying to set the > > SelectedTransportation > > > property which I manually add in a mapping. The code properly populates the dropdownlist, but I can't figure out how to set SelectedTransportation properly. I've tried setting it during the mapping process and after mapping through a loop but all attempts have failed. Seems like this should be rather easy, but the solution eludes me. ```js var model = {"LoadCarriers":[ { "Id":1, "IsDispatched":false, "IsPrimary":false, "RCNotes":null, "CarrierId":4, "Carrier":{ "Id":4, "Name":"West Chase", "MCNumber":"EPZEPFEEGJAJ", "DOTNumber":"AJSCEXFTFJ", "InternetTruckStopCACCI":"DJOGRBQ", "Phone":"0773283820", "RemitToPhone":null, "AlternatePhone":"4428290470", "Fax":null, "MainAddress":{ "ShortAddress":"Toledo, IN", "Address1":"Lee St", "Address2":"apt 131", "City":"Toledo", "State":"IN", "PostalCode":"07950", "Country":"US" }, "RemitToAddress":{ "ShortAddress":"Fuquay Varina, MO", "Address1":"Manchester Rd", "Address2":"", "City":"Fuquay Varina", "State":"MO", "PostalCode":"23343", "Country":"US" }, "EmailAddress":"[email protected]", "Coverage":null, "CanLoad":false, "InsuranceNumber":"RIQERAIAJBMP", "InsuranceExpirationDate":"\/Date(1442978115587)\/", "AdditionalInsurance":null, "ProNumber":"07643", "URL":"http://www.west-chase.com", "AccountId":1 }, "Dispatcher":"Bob McGill", "DriverId":null, "LoadDriver":{ "Id":1, "Name":"Bobby Pittman", "Phone":"8950121068", "Mobile":null, "MT":false, "Tractor":"OQRNBP", "Trailer":"QTZP", "Location":"Lee St", "TansportationSize":"958424896573544192", "Pallets":null, "IsDispatched":false, "TransportationId":7, "Transportation":{ "Name":"Flatbed or Van", "Id":7 }, "TransportationList":[ { "Name":"Flat", "Id":1 }, { "Name":"Van or Reefer", "Id":2 }, { "Name":"Rail", "Id":3 }, { "Name":"Auto", "Id":4 }, { "Name":"Double Drop", "Id":5 }, { "Name":"Flat with Tarps,", "Id":6 }, { "Name":"Flatbed or Van", "Id":7 }, { "Name":"Flatbed, Van or Reefer", "Id":8 }, { "Name":"Flatbed with Sides", "Id":9 }, { "Name":"Hopper Bottom", "Id":10 }, { "Name":"Hot Shot", "Id":11 }, { "Name":"Lowboy", "Id":12 }, { "Name":"Maxi", "Id":13 }, { "Name":"Power Only", "Id":14 }, { "Name":"Reefer w/ Pallet Exchange", "Id":15 }, { "Name":"Removable Gooseneck", "Id":16 }, { "Name":"Step Deck", "Id":17 }, { "Name":"Tanker", "Id":18 }, { "Name":"Curtain Van", "Id":19 }, { "Name":"Flatbed Hazardous", "Id":20 }, { "Name":"Reefer Hazardous", "Id":21 }, { "Name":"Van Hazardous", "Id":22 }, { "Name":"Vented Van", "Id":23 }, { "Name":"Van w/ Pallet Exchange", "Id":24 }, { "Name":"B-Train", "Id":25 }, { "Name":"Container", "Id":26 }, { "Name":"Double Flat", "Id":27 }, { "Name":"Flatbed or Stepdeck", "Id":28 }, { "Name":"Air", "Id":29 }, { "Name":"Ocean", "Id":30 }, { "Name":"Walking Floor", "Id":31 }, { "Name":"Landoll Flatbed", "Id":32 }, { "Name":"Conestoga", "Id":33 }, { "Name":"Load Out", "Id":34 }, { "Name":"Van Air-Ride", "Id":35 }, { "Name":"Container Hazardous", "Id":36 } ], "CarrierId":0, "Carrier":null }, "Carriers":null, "LoadId":1 } ]}; var loadDriverModel = function (data) { ko.mapping.fromJS(data, {}, this); this.SelectedTransportation = ko.observable(); }; var loadDriverMapping = { 'LoadDriver': { key: function (data) { return data.Id; }, create: function (options) { return new loadDriverModel(options.data); } } }; var carrierModel = function (data) { ko.mapping.fromJS(data, loadDriverMapping, this); }; var carrierMapping = { 'LoadCarriers': { key: function (data) { return data.Id; }, create: function (options) { return new carrierModel(options.data); } } }; var model = ko.mapping.fromJS(model); ko.applyBindings(model); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.js"></script> <!-- ko foreach: LoadCarriers --> <select class="form-control" data-bind="options:LoadDriver.TransportationList, optionsText:'Name', value:$data.LoadDriver.SelectedTransportation"></select> <!-- /ko --> ```
2015/09/23
[ "https://Stackoverflow.com/questions/32739103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2855467/" ]
Your idea of creating a proxy is good imo, however, if you have access to ES6, why not looking into [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy)? I think it does what you want out-of-the-box. The MDN provides good examples on how do traps for value validation in a setter, etc. **EDIT :** **Possible trap** I have imagined : `document.currentScript` is not supported in IE. So if you care about it and decide to polyfill it/use a pre-exisiting polyfill, make sure it is secure. Or it could be used to modify on the fly the external script url returned by `document.currentScript` and skew the proxy. I don't know if this could happen in real life tho.
5,100,229
So I have set up a mysql database that holds an image (more specifically a path to an image) and the images rank (starting at 0). I then created a web page that displays two images at random at a time. [Up till here everything works fine] I want my users to be able to click on one of the images that they like better and for that images rank to increase by +1 in the database. How would I set that up? Please be as detailed as possible in your explanation. I am new to php and mysql.
2011/02/24
[ "https://Stackoverflow.com/questions/5100229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518080/" ]
Well i wasn't able to solve why the Between function didn't work - but mysql doesn't allow BETWEEN on floating point numbers either. So i'm going to assume that it's a similar reason. I changed my code to merely create it's own between statement. ``` NSPredicate *longPredicate = nil; NSPredicate *latPredicate = nil; if ([neCoordLong floatValue] > [swCoordLong floatValue]) { longPredicate = [NSPredicate predicateWithFormat: @" longitude <= %@ AND longitude >= %@", neCoordLong, swCoordLong]; }else { longPredicate = [NSPredicate predicateWithFormat: @" longitude <= %@ AND longitude >= %@", swCoordLong, neCoordLong]; } if ([neCoordLat floatValue] > [swCoordLat floatValue]) { latPredicate = [NSPredicate predicateWithFormat: @" latitude <= %@ AND latitude >= %@", neCoordLat, swCoordLat]; }else { latPredicate = [NSPredicate predicateWithFormat: @" latitude <= %@ AND latitude >= %@", swCoordLat, neCoordLat]; } ``` Hopefully this helps someone else
357,141
I am struck in finding the solution for the below requirements Assume drop down#1 and drop down#2 selection box in the Magento2 admin UI grid filters. If we select option in one drop down#1 then we have to filter option in drop down#2 based on drop down#1 selection value. If anyone aware of the solution / any alternate to achieve this requirement, please help to share your feedback / suggestion. [![enter image description here](https://i.stack.imgur.com/vThDa.png)](https://i.stack.imgur.com/vThDa.png) Thanks is advance
2022/06/23
[ "https://magento.stackexchange.com/questions/357141", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/12392/" ]
The answer just a concept and i don't have enough time to provide full example, but hope this will help to understand a concept. **1. Custom Column Ui Component** You need to create a custom column element for your second filter and extend for example `Magento_Ui/js/grid/columns/select`. You still can use native template. ```js define([ 'Magento_Ui/js/grid/columns/select', 'uiRegistry', 'underscore' ], function (Select, registry, _) { 'use strict'; return Select.extend({ defaults: { sourceFilter: '', // the name of primary filter sourceFilterUi: null, allOptions: [], // all available options }, initConfig: function () { this._super(); // maybe in some cases need to use defer for wait for element this.sourceFilterUi = registry.get(this.parent + '.' + this.sourceFilter); // store all options and reset applicable this.allOptions = this.options; this.options = []; // track source changes if (this.sourceFilterUi) { this.sourceFilterUi.value.subscribe(this.sourceChanged.bind(this)); } // here you can add logic check source value and rebuild options (loaded from bookmark, etc) }, sourceChanged: function(value) { // value might be undefined, string or array depends on parent source // store current value let old_value = this.values(), value; // generate applicable options let new options = []; _.each(this.allOptions, function(option) { if (option.parent == value) { options.push(option); } if (old_value == option.value) { value = option.value; } }); // update options this.options(options); // restore value after update options if (value) { this.value(value); } } }); }); ``` **2. Filter in listing** You need to define custom filter for listing and disable original filter ```xml <?xml version="1.0"?> <listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"> <listingToolbar name="listing_top"> <filters name="listing_filters"> <filterSelect name="second_filter" provider="${ $.parentName }" component="Acme_StackExchange/js/grid/filters/elements/select-deps"> <argument name="data" xsi:type="array"> <item name="config" xsi:type="array"> <item name="sourceFilter" xsi:type="string" translate="true">first_filter</item> </item> </argument> <settings> <options class="Acme\StackExchange\Ui\Component\Listing\Columns\Second\Options"/> <!-- ... --> </settings> </filters> </listingToolbar> </listing> ``` **3. Create custom options with relations** ```php // ... class Options implements OptionSourceInterface { // ... public function toOptionArray(): array { return [ [ 'label' => __('Label'), 'value' => 'value', 'parent' => 'parent', ], // ... ]; } } ```
34,798,757
I am working on an app written in Polymer. I have some CSS variables defined like this: ``` :root { --my-option-1: #ff8a80; --my-option-2: #4a148c; --my-option-3: #8c9eff; } ``` The user literally chooses "1", "2", or "3". I have a function that looks like this: ``` // The v parameter will be 1, 2, or 3 function getOptionColor(v) { var name = '--my-option-' + v; return ?; } ``` I need `getOptionColor` to return `#ff8a80`, `#4a148c`, or `#8c9eff` based on the value entered into the function. However, I do not know how to get the value of a CSS variable at runtime. Is there a way to do this? If so, how?
2016/01/14
[ "https://Stackoverflow.com/questions/34798757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1185425/" ]
You can use a constructor, I don't see a need for inheritance ``` function Config(key, name, icon, values, filterFn) { this.key = key; this.name = name; this.icon = icon; this.values = values; this.filterFn = filterFn; } var cfg = {}; // Don't want to repeat "someKey"? put it in a variable. var myKey = 'someKey'; cfg[myKey] = new Config(myKey, 'someName', 'icon', [1,2], function(obj){ return obj + myKey}); myKey = 'otherKey'; cfg[myKey] = new Config(myKey, 'anotherName', 'anotherIcon', [3,4], function(obj){ return obj + '_' + myKey}); // Or create a method to help, may be overdoing it... function addConfig(key, name, icon, values, filterFn) { cfg[myKey] = new Config(key, name, icon, values, filterFn]; } addConfig('someKey', 'thatName', 'thisIcon', [6,7], o => o); ``` In EcmaScript 6, you can save some typing ``` function Config(key, name, icon, values, filterFn) { Object.assign(this, {key, name, icon, values, filterFn}); } ```
16,637,051
I'm trying to make a number input. I've made so my textbox only accepts numbers via this code: ``` function isNumber(evt) { evt = (evt) ? evt : window.event; var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; } return true; } ``` But now the question comes to, how would I create spaces as the user is typing in their number, much like the iPhone's telephone spacing thing, but with numbers so for example if they type in: 1000 it will become 1 000; ``` 1 10 100 1 000 10 000 100 000 1 000 000 10 000 000 100 000 000 1 000 000 000 ``` Etc... I've tried to read the input from the right for each 3 characters and add a space. But my way is inefficient and when I'm changing the value from 1000 to 1 000 in the textbox, it selects it for some reason, making any key press after that, erase the whole thing. If you know how to do this, please refrain from using javascript plugins like jQuery. Thank You.
2013/05/19
[ "https://Stackoverflow.com/questions/16637051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768788/" ]
For integers use ``` function numberWithSpaces(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " "); } ``` For floating point numbers you can use ``` function numberWithSpaces(x) { var parts = x.toString().split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " "); return parts.join("."); } ``` This is a simple regex work. <https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions> << Find more about Regex here. If you are not sure about whether the number would be integer or float, just use 2nd one...
72,120,997
Let's say I have a data frame like this: ``` dat<- data.frame(ID= c("A","A","A","A","B","B", "B", "B"), test= rep(c("pre","post"),4), item= c(rep("item1",2), rep("item2",2), rep("item1",2), rep("item2",2)), answer= c("1_2_3_4", "1_2_3_4","2_4_3_1","4_3_2_1", "2_4_3_1","2_4_3_1","4_3_2_1","4_3_2_1")) ``` For each group of `ID` and `item`, I want to determine if the levels of `answer` match. The result data frame would look like this: ``` res<- data.frame(ID= c("A","A","B","B"), item= c("item1","item2","item1","item2"), match=c("TRUE","FALSE", "TRUE", "TRUE")) ```
2022/05/05
[ "https://Stackoverflow.com/questions/72120997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8061255/" ]
```r dat<- data.frame(ID= c("A","A","A","A","B","B", "B", "B"), test= rep(c("pre","post"),4), item= c(rep("item1",2), rep("item2",2), rep("item1",2), rep("item2",2)), answer= c("1_2_3_4", "1_2_3_4","2_4_3_1","4_3_2_1", "2_4_3_1","2_4_3_1","4_3_2_1","4_3_2_1")) library(data.table) setDT(dat) dat[, .(match = all(answer == answer[1])), by = .(ID, item)] #> ID item match #> <char> <char> <lgcl> #> 1: A item1 TRUE #> 2: A item2 FALSE #> 3: B item1 TRUE #> 4: B item2 TRUE ``` Created on 2022-05-04 by the [reprex package](https://reprex.tidyverse.org) (v2.0.1)
49,320,845
<https://colab.research.google.com/notebooks/io.ipynb#scrollTo=KHeruhacFpSU> In this notebook help it explains how to upload a file to drive and then download to Colaboratory but my files are already in drive. Where can I find the file ID ? ``` # Download the file we just uploaded. # # Replace the assignment below with your file ID # to download a different file. # # A file ID looks like: 1uBtlaggVyWshwcyP6kEI-y_W3P8D26sz file_id = 'target_file_id' ```
2018/03/16
[ "https://Stackoverflow.com/questions/49320845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8833943/" ]
If the parameter is definitely unused, `[[maybe_unused]]` is not particularly useful, unnamed parameters and comments work just fine for that. `[[maybe_unused]]` is mostly useful for things that are *potentially* unused, like in ``` void fun(int i, int j) { assert(i < j); // j not used here anymore } ``` This can't be handled with unnamed parameters, but if `NDEBUG` is defined, will produce a warning because `j` is unused. Similar situations can occur when a parameter is only used for (potentially disabled) logging.
33,001,985
I have started using Webpack when developing usual web sites consisting of a number pages and of different pages types. I'm used to the RequireJs script loader that loads all dependencies on demand when needed. Just a small piece of javascript is downloaded when page loads. What I want to achieve is this: * A small initial javascript file that loads dependencies asynchronous * Each page type can have their own javascript, which also may have dependencies. * Common modules, vendor scripts should be bundled in common scripts I have tried many configurations to achieve this but with no success. ```js entry: { main: 'main.js', //Used on all pages, e.g. mobile menu 'standard-page': 'pages/standard-page.js', 'start-page': 'pages/start-page.js', 'vendor': ['jquery'] }, alias: { jquery: 'jquery/dist/jquery.js' }, plugins: [ new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js"), new webpack.optimize.CommonsChunkPlugin('common.js') ] ``` In the html I want to load the javascripts like this: ```html <script src="/Static/js/dist/common.js"></script> <script src="/Static/js/dist/main.js" async></script> ``` And on a specific page type (start page) ```html <script src="/Static/js/dist/start-page.js" async></script> ``` common.js should be a tiny file for fast loading of the page. main.js loads async and require('jquery') inside. The output from Webpack looks promising but I can't get the vendors bundle to load asynchronously. Other dependencies (my own modules and domReady) is loaded in ther autogenerated chunks, but not jquery. I can find plenty of examples that does almost this but not the important part of loading vendors asynchronously. Output from webpack build: ``` Asset Size Chunks Chunk Names main.js.map 570 bytes 0, 7 [emitted] main main.js 399 bytes 0, 7 [emitted] main standard-page.js 355 bytes 2, 7 [emitted] standard-page c6ff6378688eba5a294f.js 348 bytes 3, 7 [emitted] start-page.js 361 bytes 4, 7 [emitted] start-page 8986b3741c0dddb9c762.js 387 bytes 5, 7 [emitted] vendor.js 257 kB 6, 7 [emitted] vendor common.js 3.86 kB 7 [emitted] common.js 2876de041eaa501e23a2.js 1.3 kB 1, 7 [emitted] ```
2015/10/07
[ "https://Stackoverflow.com/questions/33001985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4886214/" ]
The solution to this problem is two-fold: 1. First you need to understand [how code-splitting works in webpack](https://webpack.github.io/docs/code-splitting.html) 2. Secondly, you need to use something like the `CommonsChunkPlugin` to generate that shared bundle. ### Code Splitting Before you start using webpack you need to unlearn to be dependent on configuration. Require.js was all about configuration files. This mindset made it difficult for me to transition into webpack which is modeled more closely after CommonJS in node.js, which relies on no configuration. With that in mind consider the following. If you have an app and you want it to asynchronously load some other parts of javascript you need to use one of the following paradigms. **Require.ensure** `require.ensure` is one way that you can create a "split point" in your application. Again, you may have thought you'd need to do this with configuration, but that is not the case. In the example when I hit `require.ensure` in my file webpack will automatically create a second bundle and load it on-demand. Any code executed inside of that split-point will be bundled together in a separate file. ``` require.ensure(['jquery'], function() { var $ = require('jquery'); /* ... */ }); ``` **Require([])** You can also achieve the same thing with the AMD-version of `require()`, the one that takes an array of dependencies. This will also create the same split point: ``` require(['jquery'], function($) { /* ... */ }); ``` ### Shared Bundles In your example above you use `entry` to create a `vendor` bundle which has jQuery. You don't need to manually specify these dependency bundles. Instead, using the split points above you webpack will generate this automatically. *Use `entry` only for separate `<script>` tags you want in your pages*. Now that you've done all of that you can use the `CommonsChunkPlugin` to additional optimize your chunks, but again most of the magic is done for you and outside of specifying which dependencies should be shared you won't need to do anything else. `webpack` will pull in the shared chunks automatically without the need for additional `<script>` tags or `entry` configuration. ### Conclusion The scenario you describe (multiple `<script>` tags) may not actually be what you want. With webpack all of the dependencies and bundles can be managed automatically starting with only a single `<script>` tag. Having gone through several iterations of re-factoring from require.js to webpack, I've found that's usually the simplest and best way to manage your dependencies. All the best!
510,152
Quite often, the script I want to execute is not located in my current working directory and I don't really want to leave it. Is it a good practice to run scripts (BASH, Perl etc.) from another directory? Will they usually find all the stuff they need to run properly? If so, what is the best way to run a "distant" script? Is it ``` . /path/to/script ``` or ``` sh /path/to/script ``` and how to use `sudo` in such cases? This, for example, doesn't work: ``` sudo . /path/to/script ```
2012/11/24
[ "https://superuser.com/questions/510152", "https://superuser.com", "https://superuser.com/users/105968/" ]
sh /path/to/script will spawn a new shell and run she script independent of your current shell. The `source` (.) command will call all the commands in the script in the current shell. If the script happens to call `exit` for example, then you'll lose the current shell. Because of this it is usually safer to call scripts in a separate shell with sh or to execute them as binaries using either the full (starting with `/`) or relative path (`./`). If called as binaries, they will be executed with the specified interpreter (`#!/bin/bash`, for example). As for knowing whether or not a script will find the files it needs, there is no good answer, other than looking at the script to see what it does. As an option, you could always go to the script's folder in a sub-process without leaving your current folder: ``` (cd /wherever/ ; sh script.sh) ```
75,214
I copied 3.62 GB of data on to a re-writable DVD instead of erasing it. Now there is no data on the disc but it shows used space as 3.62 GB and 690 MB of free space. Now I am unable to erase my disc. What should I do to erase the disc and get the space back?
2009/11/25
[ "https://superuser.com/questions/75214", "https://superuser.com", "https://superuser.com/users/96938/" ]
You aren't supposed to format a DVD-RW. Use something like [CDBurnerXP](http://cdburnerxp.se/)'s erase function: ![alt text](https://i.stack.imgur.com/N3NwX.png)
150,258
Someone moved a very important page on my website into the trash, and I do not know who did it! It was not deleted permanently so I don't need to worry, in that sense. The revisions, when I restored it, show that someone edited it 3 days prior to today, so it could have been them, but I can't be sure. Does WP keep track of who clicks the trash button? If not, I presume I'd have to write a custom script to hook onto the trash button, when clicked.
2014/06/20
[ "https://wordpress.stackexchange.com/questions/150258", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/15209/" ]
By default, no, WordPress doesn't keep track of who changes post statuses (at least that I can see). you can hook into `transition_post_status` and log the user id. ``` add_action( 'transition_post_status', 'wwm_transition_post_status', 10, 3 ); function wwm_transition_post_status( $new_status, $old_status, $post ) { if ( 'trash' == $new_status ) { $uid = get_current_user_id(); //somehow or another log the $uid with the $post->ID } } ```
28,958,290
We have recently switched over to React + Flux from Angular to build a rather complex business application. Taking the approach of having one container component that passes all state as properties down the component tree isn't a practical way to develop the app for us as the app makes use of large page-like modals. Enough state does get passed down to the modals for them to load their data into their stores. The problem I have is I need to get some initial state (passed down as props) into the modal component's store. In [this post](http://facebook.github.io/react/tips/props-in-getInitialState-as-anti-pattern.html) the good guys over at Facebook say it's ok to use props for initial state when synchronization is not the goal. This is how I get the initial state into my store currently: ``` var ABC = React.createClass({ ... getInitialState: function() { return ABCStore.getInitialABCState(this.props.initialA); }, ... var ABCStore = Reflux.createStore({ ... init: function() { _state = { a: null, b: 'B init', c: 'C init' }; }, getInitialABCState: function(initialA) { _state.a = initialA; return _state; }, getABCState: function() { return _state; } ... ``` I am unsure what the best practice is to do this, or whether this is a Flux anti-pattern?
2015/03/10
[ "https://Stackoverflow.com/questions/28958290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/525096/" ]
It feels wrong to me that you are using `getInitialState()` to change the state of your store. You should at least be doing that in [`componentWillMount`](http://facebook.github.io/react/docs/component-specs.html#mounting-componentwillmount). I would trigger an action in `componentWillMount` and have the store handler update the internal state of the store (this should always be the case in flux). Then your component's change handler for the store can consume whatever data that you are currently calling your "initial state"
35,281,379
I have ElasticSearch 2.2 running on a linux VM. I'm running ManifoldCF 2.3 on another VM in the same netowrk. Using ManifoldCF's browser UI I added the ElasticSearch output connector and when I save it I get an error in the connector status: ``` Name: Elastic Description: Elastic search Connection type: ElasticSearch Max connections: 10 Server Location (URL): http://<IP_ADDRESS>:9200 Index name: index Index type: sharepoint Use mapper-attachments: false Content field name: contentfield Connection status: ERROR "root_cause":["type":"illegal_argument_exception" ``` Any ideas?
2016/02/08
[ "https://Stackoverflow.com/questions/35281379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/151200/" ]
You are passing an `array` of strings to jQuery's `append` method. Simply join it first: ``` jQuery('.place').append(top.join('')); ``` When you call `toString()` on an array (which is what jQuery is doing here when you try to `append` an array of strings) it casts each array element to a string and puts a comma between them: ``` [1,2,3].toString(); //"1,2,3" [{a:"b"},2,3].toString(); //"[object Object],2,3" ```
25,288
We have made a installation of Sitecore Experience Platform v9.3.0 (rev. 003498) (details below): * 2 servers as Content Management role * 2 servers as Content Delivery role * 2 servers as others roles (Processing, Reporting, Identity Server, XConnect, Identity Server, Marketing, Reference Data, Cortex) * 3 servers as Solr The application has been running for approximately 45 days, however, Experience Analytics and Experience Profile are not recording data (no data is displayed). we have checked the logs of all roles and found no errors that could help us fix the issue. After some research we have changed the **"IndexAnonymousContactData"** tag to **true** in the **"{XCONNECT\_PATH}\App\_Data\jobs\continuous\IndexWorker\App\_Data\config\sitecore\SearchIndexer\sc.Xdb.Collection.IndexerSettings"** configuration file and rebuilt the indexes. However, it did not work. Would anyone have any suggestions on what we could do to fix this issue? Thank you in advance for your help
2020/05/18
[ "https://sitecore.stackexchange.com/questions/25288", "https://sitecore.stackexchange.com", "https://sitecore.stackexchange.com/users/6980/" ]
It turns out to be that the device detection rule config in sitecore 9.3 doesn't include Content Management Role by default so by patching this role solves the problem. ``` <?xml version="1.0" encoding="utf-8" ?> <!-- Purpose: This include file configures the device detection rules component. --> <configuration xmlns:x="http://www.sitecore.net/xmlconfig/" xmlns:role="http://www.sitecore.net/xmlconfig/role/"> **<sitecore role:require="Standalone or ContentDelivery or Processing">** <services> <register serviceType="Sitecore.CES.DeviceDetection.Rules.IRuleDeviceInformationManager, Sitecore.CES.DeviceDetection.Rules" implementationType="Sitecore.CES.DeviceDetection.Rules.RuleDeviceInformationManager, Sitecore.CES.DeviceDetection.Rules" lifetime="Singleton" /> </services> </sitecore> </configuration> ```
33,307,860
I have a list of years, as follows: ``` year = ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013'] ``` I am trying to create a series of XML tags enclosed within another pre-existing tag, like so: ``` <intro> <exposures> <exposure year = "2005"></exposure> <exposure year = "2006"></exposure> <exposure year = "2007"></exposure> <exposure year = "2008"></exposure> etc. <exposures> </intro> ``` Later on I'll populate things within the tags. Right now I'm trying to loop through `year` and add them to the tag and then enclose it within the tag. I've been trying to loop through the 'year' list and append each value to the tag as an attribute: ``` testsoup = BeautifulSoup(testxml, 'xml') intro_tag = testsoup.intro('intro') exp_tag = testsoup.exposures('exposures') year = ['2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013'] exposure_tag = testsoup.new_tag('exposure', year = '') for x in year: exposure_tag['year'] = x exp_tag.append(exposure_tag) intro_tag.append(exp_tag) ``` Unfortunately this only seems to append the last value in the list: ``` <intro><exposures><exposure year="2013"/></exposures></intro> ``` Is this just a feature of BeautifulSoup? Can you only add one tag and not multiple ones? I'm using BeautifulSoup 4.4.0. Incidentally, is BeautifulSoup the best way to do this? I see a lot of posts praising BS4 and lxml for their webscraping abilities but neither seem to be useful for generating XML (that's not a bad thing, just something I've noticed). Is there a better package for automating XML generation?
2015/10/23
[ "https://Stackoverflow.com/questions/33307860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5199451/" ]
I suspect that the issue is this line: `exposure_tag = testsoup.new_tag('exposure', year = '')`. You have one tag and you are trying to append it to the same parent multiple times. Try this instead. ``` for x in year: exposure_tag = testsoup.new_tag('exposure', year = x) exp_tag.append(exposure_tag) intro_tag.append(exp_tag) ```
21,239
I'm setting up a projection map for a non-profit that will have images projected onto angular and unusually shaped walls. I use modul8 on my mac in the past, but this case is different. They use PC (in fact their whole show runs off of a laptop) and they want the ability to change the images based on the theme of the show. They have an A/V guy, but I don't want to suggest complex software that is going to be hard for a beginner to use. What software should I recommend and then use to set up their show so they don't have to keep calling little old expensive me? EDIT: I should also mention that this is a small non-profit, so free or really cheap would benefit them greatly.
2017/04/20
[ "https://avp.stackexchange.com/questions/21239", "https://avp.stackexchange.com", "https://avp.stackexchange.com/users/18709/" ]
It is certainly possible to use FCPX and AfterEffects as part of the same workflow. To do this effectively, you will need to use an intermediate codec that preserves image quality across successive generations. ProRes HQ 422 is a good baseline as an intermediate codec. There are higher quality ProRes codecs (XQ 4444) and lower quality ones (ProRes LT 422). But ProRes HQ should be a good starting place.
6,262,319
I'm making a tool that can do some operations on a transition system and also need to visualise them. Though there isn't much documentation on the ruby-gem (this was the best I could get: <http://www.omninerd.com/articles/Automating_Data_Visualization_with_Ruby_and_Graphviz> ), I managed to make a graph from my transition system. (Feel free to use it, there ain't much example code around. comments/questions are also welcome) ``` # note: model is something of my own datatype, # having states, labels, transitions, start_state and a name # I hope the code is self-explaining @graph = GraphViz::new(model.name, "type" => "graph" ) #settings @graph.edge[:dir] = "forward" @graph.edge[:arrowsize]= "0.5" #make the graph model.states.each do |cur_state| @graph.add_node(cur_state.name).label = cur_state.name cur_state.out_transitions.each do |cur_transition| @graph.add_edge(cur_transition.from.name, cur_transition.to.name).label = cur_transition.label.to_s end end #make a .pdf output (can also be changed to .eps, .png or whatever) @graph.output("pdf" => File.join(".")+"/" + @graph.name + ".pdf") #it's really not that hard :-) ``` Only one thing that I can't do: draw an arrow 'out of nothing' to the start state. Suggestions anyone?
2011/06/07
[ "https://Stackoverflow.com/questions/6262319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317275/" ]
I would try to add a node of shape `none` or `point` and draw the arrow from there. ``` @graph.add_node("Start", "shape" => "point", "label" => "" ) ``` And something like this in your loop ``` if cur_transition.from.name.nil? @graph.add_edge("Start", cur_transition.to.name) else @graph.add_edge(cur_transition.from.name, cur_transition.to.name).label = cur_transition.label.to_s end ```
74,240,319
I am trying to set my machines javac version to 11 from 18.0.2 and I'm doing the following steps 1. open ~/.zshenv 2. export JAVA\_HOME=$(/usr/libexec/java\_home -v11) 3. source ~/.zshenv When I check the version, I still get it as 18.0.2. Not sure what I am doing wrong here. Could someone please help me with this? Been stuck on this forever.
2022/10/28
[ "https://Stackoverflow.com/questions/74240319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6466023/" ]
What works like a charme for me is using jenv: <https://www.jenv.be/> With jenv you can also switch between different Java versions. Before using jenv, I relied on the Maven toolchains plugin: <https://maven.apache.org/plugins/maven-toolchains-plugin/> Thus, I actually never really worried about `JAVA_HOME` on MacOS. Maybe one of these options also is an alternative for you.
33,068,428
Consider the following function for finding the second-to-last element of a list: ``` myButLast (x:xs) = if length xs > 1 then myButLast xs else x ``` This is an O(n^2) algorithm, because `length xs` is O(n) and is called O(n) times. What is the most elegant way to write this in Haskell such that `length` stops once it gets past 1, so that the algorithm is O(n)?
2015/10/11
[ "https://Stackoverflow.com/questions/33068428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3154996/" ]
The easiest way is to avoid `length`: ``` myButLast (x : _ : []) = x -- base case myButLast (_ : xs) = myButLast xs ``` The definitive reference on patterns in Haskell is the language report: <https://www.haskell.org/onlinereport/haskell2010/haskellch3.html#x8-580003.17> GHC implements a few extensions described at <https://downloads.haskell.org/~ghc/latest/docs/html/users_guide/syntax-extns.html#pattern-guards>.
7,756,437
Is that possible to get notification when Home button is pressed or Home Screen is launched? In [Android Overriding home key](https://stackoverflow.com/questions/5039500/android-overriding-home-key) thread i read that "it will be notified when the home screen is about to be launched". So is that possible, if yes how? Thank you
2011/10/13
[ "https://Stackoverflow.com/questions/7756437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/992888/" ]
> > Is that possible to get notification when Home button is pressed or Home Screen is launched? > > > Only by being a home screen.
2,347,497
> > Let $R$ be a ring. If $I\_1,\ldots, I\_k$ are ideals of $R$ and for all $i$: > > > $$I\_i + \bigcap\_{j\neq i} I\_j = R$$ > > > then for all $a\_1,\ldots,a\_k \in R$, there exists some $a \in R$ such that for all $i$, $a \equiv a\_i \pmod{I\_i}$ > > > I could prove this for $k=2$: for $a\_1,a\_2 \in R$, $a\_1 - a\_2 \in I\_1 + I\_2$, so there are $i\_i \in I\_i$ such that $a\_1 - a\_2 = -i\_1 + i\_2$. Hence $a\_1 + i\_1 = a\_2 + i\_2 = a$, and $a \equiv a\_i \pmod{I\_i}$ for $i=1,2$. I couldn't prove the general case. Any help?
2017/07/05
[ "https://math.stackexchange.com/questions/2347497", "https://math.stackexchange.com", "https://math.stackexchange.com/users/360858/" ]
**Hint for the inductive step:** Suppose $I\_1,\dots, I\_k,I\_{k+1}$ are ideals in $R$ such that for any $1\le i \le k+1$, $$I\_i+\bigcap\_{\substack{1\le j \le k+1\\j\ne i}}I\_j=R. $$ Then, *a fortiori*, we have for any $1\le i \le k$, $$I\_i+\bigcap\_{\substack{1\le j \le k\\j\ne i}}I\_j=R. $$ So, given $a\_1, \dots, a\_k, a\_{k+1}\in R$, there exists some $a\in R$ such that $$a\equiv a\_i\mod I\_i\quad(1\le i\le k)$$ and $a$ is unique mod. $\displaystyle\bigcap\_{j=1}^k I\_j$. Can you end the inductive step? *Some more details*: Note that if $J=\displaystyle\bigcap\_{j=1}^k I\_j $, we have $J+I\_{k+1}=R$. So we have to find $A\in R$ such that \begin{cases}A\equiv a& \mkern-12mu\bmod J\\A\equiv a\_{k+1},&\mkern-12mu\bmod I\_{k+1}.\end{cases} which is possible by the case $k=2$, and the solution is unique modulo $J\cap I\_{k+1} =\displaystyle\bigcap\_{j=1}^{k+1} I\_j$.
6,637,219
Let's say I accidentally evaluate an enormous variable--a list with a ba-jillion elements, or whatever. As they scroll down my screen and my computer crawls to a halt, is there a good way to interrupt this *without* killing my `*Python*` buffer? I'm using IPython via `python-mode.el` and `ipython.el` in emacs24 on Mac OS X Leopard-- Thoughts appreciated, a.
2011/07/09
[ "https://Stackoverflow.com/questions/6637219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37772/" ]
Could you not just use the [DisplayAttribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.aspx "DisplayAttribute")?
44,091,666
I set up my app to be able to send Apple Notifications using firebase and I verified that it works using the console. Now I want to do phone authentication which is built on top of APN. So I wrote this: ``` PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber) { verificationID, error in if error != nil { print("Verification code not sent \(error!)") } else { print ("Successful.") } ``` And I get: ``` Error Domain=FIRAuthErrorDomain Code=17999 "An internal error has occurred, print and inspect the error details for more information." UserInfo={NSUnderlyingError=0x170046db0 {Error Domain=FIRAuthInternalErrorDomain Code=3 "(null)" UserInfo={FIRAuthErrorUserInfoDeserializedResponseKey={ code = 500; message = "<null>"; }}}, error_name=ERROR_INTERNAL_ERROR, NSLocalizedDescription=An internal error has occurred, print and inspect the error details for more information.} ``` Any idea? Should I file a bug against firebase? I am using iOS SDK 4.0.0 (latest zip I could find.) **UPDATE:** I disabled method swizzling by adding `FirebaseAppDelegateProxyEnabled` to `info.plist` and set it to `NO` ``` func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // Pass device token to auth. Auth.auth().setAPNSToken(deviceToken, type: .prod) } ```
2017/05/20
[ "https://Stackoverflow.com/questions/44091666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/666818/" ]
Tested with latest **Firebase iOS SDK i.e. 4.0.0** and **Xcode 8.3** Firstly , remove this key `FirebaseAppDelegateProxyEnabled` from info.plist. This is not needed. Now in **AppDelegate.swift** add following functions ``` import Firebase import UserNotifications @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate , UNUserNotificationCenterDelegate{ var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if #available(iOS 10.0, *) { // For iOS 10 display notification (sent via APNS) UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: {_, _ in }) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() FirebaseApp.configure() return true } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // Pass device token to auth. let firebaseAuth = Auth.auth() //At development time we use .sandbox firebaseAuth.setAPNSToken(deviceToken, type: AuthAPNSTokenType.sandbox) //At time of production it will be set to .prod } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { let firebaseAuth = Auth.auth() if (firebaseAuth.canHandleNotification(userInfo)){ print(userInfo) return } }* ``` **Send a verification code to the user's phone:** In the class where you want to integrate Phone Authentication write : **Note** : I have added `+91` as its country code for India. You can add country code according to your region. ``` PhoneAuthProvider.provider().verifyPhoneNumber("+919876543210") { (verificationID, error) in if ((error) != nil) { // Verification code not sent. print(error) } else { // Successful. User gets verification code // Save verificationID in UserDefaults UserDefaults.standard.set(verificationID, forKey: "firebase_verification") UserDefaults.standard.synchronize() //And show the Screen to enter the Code. } ``` **Sign in the user with the verification code**: ``` let verificationID = UserDefaults.standard.value(forKey: "firebase_verification") let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID! as! String, verificationCode: self.txtEmailID.text!) Auth.auth().signIn(with: credential, completion: {(_ user: User, _ error: Error?) -> Void in if error != nil { // Error }else { print("Phone number: \(user.phoneNumber)") var userInfo: Any? = user.providerData[0] print(userInfo) } } as! AuthResultCallback) ```
50,488,521
I am looking for a solution to convert my string to `camelcaps` by the `dot` it contains. here is my string: `'sender.state'` I am expecting the result as : `'senderState'`; I tried this: `'sender.state'.replace(/\./g, '');` it removes the `.` but how to handle the `camel caps` stuff?
2018/05/23
[ "https://Stackoverflow.com/questions/50488521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/218349/" ]
You can pass a function to `.replace()`: ``` 'sender.state'.replace(/\.([a-z])/g, (match, letter) => letter.toUpperCase()); ```
51,094,339
I need to measure the execution time of a Python program having the following structure: ``` import numpy import pandas def func1(): code def func2(): code if __name__ == '__main__': func1() func2() ``` If I want to use "time.time()", where should I put them in the code? I want to get the execution time for the whole program. Alternative 1: ``` import time start = time.time() import numpy import pandas def func1(): code def func2(): code if __name__ == '__main__': func1() func2() end = time.time() print("The execution time is", end - start) ``` Alternative 2: ``` import numpy import pandas def func1(): code def func2(): code if __name__ == '__main__': import time start = time.time() func1() func2() end = time.time() print("The execution time is", end - start) ```
2018/06/29
[ "https://Stackoverflow.com/questions/51094339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9668218/" ]
In linux: you could run this file test.py using the time command > > time python3 test.py > > > After your program runs it will give you the following output: real 0m0.074s user 0m0.004s sys 0m0.000s [this link](https://stackoverflow.com/questions/556405/what-do-real-user-and-sys-mean-in-the-output-of-time1) will tell the difference between the three times you get
38,659,379
I've been experiencing an irritating issue that I cant get around. I am trying to `vagrant up` a centos7 system in this environment: * Windows 10 * Hyper-V (not anniversary update version) * Docker image "serveit/centos-7" or "bluefedora/hyperv-alpha-centos7" * OpenSSH installed, private key configured The contents of my Vagrantfile: ``` Vagrant.configure("2") do |config| #config.vm.box = "serveit/centos-7" config.vm.box = "bluefedora/hyperv-alpha-centos7" config.ssh.private_key_path = "~/.vagrant.d/insecure_private_key" config.ssh.forward_agent = true end ``` I am getting this error when doing a `vagrant up`: ``` PS C:\Programs\vagrant_stuff\centos7> vagrant up Bringing machine 'default' up with 'hyperv' provider... ==> default: Verifying Hyper-V is enabled... ==> default: Importing a Hyper-V instance default: Cloning virtual hard drive... default: Creating and registering the VM... default: Successfully imported a VM with name: vagrantbox ==> default: Starting the machine... ==> default: Waiting for the machine to report its IP address... default: Timeout: 120 seconds default: IP: 192.168.137.6 ==> default: Waiting for machine to boot. This may take a few minutes... default: SSH address: 192.168.137.6:22 default: SSH username: vagrant default: SSH auth method: private key default: default: Vagrant insecure key detected. Vagrant will automatically replace default: this with a newly generated keypair for better security. default: default: Inserting generated public key within guest... default: Removing insecure key from the guest if it's present... default: Key inserted! Disconnecting and reconnecting using new SSH key... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... default: Warning: Authentication failure. Retrying... Timed out while waiting for the machine to boot. This means that Vagrant was unable to communicate with the guest machine within the configured ("config.vm.boot_timeout" value) time period. If you look above, you should be able to see the error(s) that Vagrant had when attempting to connect to the machine. These errors are usually good hints as to what may be wrong. If you're using a custom box, make sure that networking is properly working and you're able to connect to the machine. It is a common problem that networking isn't setup properly in these boxes. Verify that authentication configurations are also setup properly, as well. If the box appears to be booting properly, you may want to increase the timeout ("config.vm.boot_timeout") value. ``` I can do an `vagrant ssh-config`: ``` Host default HostName 192.168.137.6 User vagrant Port 22 UserKnownHostsFile /dev/null StrictHostKeyChecking no PasswordAuthentication no IdentityFile C:/Users/Kareem/.vagrant.d/insecure_private_key IdentitiesOnly yes LogLevel FATAL ForwardAgent yes ``` I saw elsewhere that I should try `vagrant halt` and `vagrant up` to fix the issue. This didn't work. I also deleted the `.vagrant.d/insecure_private_key` file and saw it was recreated. No problem, that's also expected. Also `vagrant ssh` works with password: ``` PS C:\Programs\vagrant_stuff\centos7> vagrant ssh [email protected]'s password: [vagrant@localhost ~]$ ``` So because I could SSH, I decided to check the `.ssh/authorized_keys` file: [vagrant@localhost ~]$ cat .ssh/authorized\_keys ``` [vagrant@localhost ~]$ cat /home/vagrant/.ssh/authorized_keys ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDIRcYs0HBn/BOjiKg9fGnoraVxRnnZk+6sM3waFFE1+U3aO8GQjRKxQsYgJNoyRmNVymzpP13kOoLodDsz UKhdcO6dL+zAtmhsFTgmADMXxVzM3mfRWfPG2HdsU13Pof77A68Ln6z6X4jVG4cnsclYvz67Gudl7lZ9VI2TOdDn1V+7ZANlkGnqejIwA2RVWtYLgLQHU9p4 47nvRqId71XaG8BZpbONRzzrL49wWyjfc4h6SdaHVJZJB6kY+vkr31xw6TPIIlo2UHH7Ihlk6KADNo4wFJYF+ozIA7C792omzjN1zu1SayvCYNG21yZy/cCd n2Hr158Jy83A9CslQPbT vagrant ``` ***Dafuq is this key?!?!*** I'm quite sure this is not the public key that corresponds to Vagrant. This is also not my system public key. When I check the [Vagrant Public key](https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub) I get this: ``` ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9H ZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHi lFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRd K8jlqm8tehUc9c9WhQ== vagrant insecure public key ``` Furthermore, if I update my `Vagrantfile` to use my system private key: ``` #config.ssh.private_key_path = "~/.vagrant.d/insecure_private_key" config.ssh.private_key_path = "~/.ssh/id_rsa" ``` I get a different public key in the VM, which is the [Vagrant Public key](https://raw.githubusercontent.com/mitchellh/vagrant/master/keys/vagrant.pub): ``` [vagrant@localhost ~]$ cat /home/vagrant/.ssh/authorized_keys ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA6NF8iallvQVp22WDkTkyrtvp9eWW6A8YVr+kz4TjGYe7gHzIw+niNltGEFHzD8+v1I2YJ6oXevct1YeS0o9H ZyN1Q9qgCgzUFtdOKLv6IedplqoPkcmF0aYet2PkEDo3MlTBckFXPITAMzF8dJSIFo9D8HfdOV0IAdx4O7PtixWKn5y2hMNG0zQPyUecp4pzC6kivAIhyfHi lFR61RGL+GPXQ2MWZWFYbAGjyiYJnAmCP3NOTd0jMZEnDkbUvxhMmBYSdETk1rRgm+R4LOzFUGaHqHDLKLX+FIPKcF96hrucXzcWyLbIbEgE98OHlnVYCzRd K8jlqm8tehUc9c9WhQ== vagrant insecure public key ``` I also see that the provisioning process does not insert a new key. This all seems backwards, I thought that the key should only be updated if I use my private key, and that it should use my own. ***HELP!*** Can anyone help me find out why this is happening?
2016/07/29
[ "https://Stackoverflow.com/questions/38659379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2951942/" ]
Turns out, there is a known bug in Vagrant 1.8.5 (Will be fixed in 1.8.6): Details [here](https://github.com/mitchellh/vagrant/issues/7610) If you are using 1.8.5, you can download the updated version from PR [#7611](https://github.com/mitchellh/vagrant/pull/7611) using PowerShell: `[IO.File]::WriteAllLines("C:\HashiCorp\Vagrant\embedded\gems\gems\vagrant-1.8.5\plugins\guests\linux\cap\public_key.rb", (Invoke-WebRequest -Uri https://raw.githubusercontent.com/Poohblah/vagrant/41063204ca540c44f9555bd11ba9e76c7307bec5/plugins/guests/linux/cap/public_key.rb).Content)`
4,778,743
I created a wordpress blog (http://raptor.hk), but i am unable to set the right sidebar into correct position. i think i have missed something in CSS. the DIV is named "rightbar". I would like the DIV to be positioned right next to the content, within the white wrapper. Also, support of fluid layout (not moving on browser resize) is needed. the problem is solved (see my answer), but anybody can give better solutions?
2011/01/24
[ "https://Stackoverflow.com/questions/4778743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/188331/" ]
You can use the [Users API](http://code.google.com/appengine/docs/python/users/) to authenticate users - either using Google accounts, or OpenID. If you want sessions without user login, there are a number of libraries, such as [gaesessions](https://github.com/dound/gae-sessions).
36,967,907
i have a string array that contains 20 words. I made a function that take 1 random word from the array. But i want to know how can i return that word from array. Right now i am using void function, i had used char type but it wont work. Little help here ? Need to make word guessing game. CODE: ``` #include <iostream> #include <time.h> #include <cstdlib> #include <stdlib.h> #include <algorithm>///lai izmantotu random shuffle funckiju #include <string> using namespace std; void random(string names[]); int main() { char a; string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba", "kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi", "saule", "parks", "svece", "diegs", "migla", "virve"}; random(names); cout<<"VARDU MINESANAS SPELE"<<endl; cin>>a; return 0; } void random(string names[]){ int randNum; for (int i = 0; i < 20; i++) { /// makes this program iterate 20 times; giving you 20 random names. srand( time(NULL) ); /// seed for the random number generator. randNum = rand() % 20 + 1; /// gets a random number between 1, and 20. names[i] = names[randNum]; } //for (int i = 0; i < 1; i++) { //cout << names[i] << endl; /// outputs one name. //} } ```
2016/05/01
[ "https://Stackoverflow.com/questions/36967907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5058648/" ]
Make `random` return `string`. You also only need to seed the number generator once. Since you only want to get 1 random word from the array, you don't need a `for` loop. ``` string random(string names[]){ int randNum = 0; randNum = rand() % 20 + 1; return names[randNum]; } ``` Then, in the `main` function, assign a `string` variable to the return value of the `random` function. ``` int main() { srand( time(NULL) ); // seed number generator once char a; string names[] = {"vergs", "rokas", "metrs", "zebra", "uguns", "tiesa", "bumba", "kakls", "kalns", "skola", "siers", "svari", "lelle", "cimdi", "saule", "parks", "svece", "diegs", "migla", "virve"}; string randomWord = random(names); cout<<"VARDU MINESANAS SPELE"<<endl; cin>>a; return 0; } ```
24,587,704
So am trying to do some end to end testing in specflow using entity framework 6. I have code migrations enabled and my seed method written. I have a context factory to generate my context with a connection string that in influenced by a step definition. What I want to be able to do is in a Feature I want to create a background step like the following ``` Given I create a database "Admin-Test" ``` In this test i want to drop all connections to a database and then drop it, followed by leaning on EF6 code migration to then recreate it and seed it with a known set of data (the default data for the application). This all works great for the first scenario in the feature but for the rest when the database is droppde the code migrations do not run to repopulate it. I have tried inheriting from `DropCreateDatabaseAlways<DbContext>` And this gets hit in the first but not subsequent. The first problem i was getting was the database not getting created, if i do that manually the seed stuff is still not being run (I read something on msdn about ef not creating the db anymore as it was confusing users). so my question is this: How can i get code migrations to trigger per scenario? I suspect the question people may be able to answer easier is: how can i trigger the automatic code migration stuff manually in a unit test to force it to run? The bonus question is this: recreating the database each scenario is inefficient - i noticed the migration generates a lot of db up and down methods. How can i run those manually and then the seed code?
2014/07/05
[ "https://Stackoverflow.com/questions/24587704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109347/" ]
I personally see your bonus question as part of a potential overall approach. I dont see why `SEED` and `Migration` need to be so tightly coupled. A basic pattern that works with Multiple DBs. a) By default Use Context against a DB with No initializer ``` Database.SetInitializer(new ContextInitializerNone<MYDbContext>()); var context = new MYDbContext((Tools.GetDbConnection(DataSource,DbName )),true); // pass in connection to db ``` b) on demand Migrate. For me this means adminsitrative trigger ``` public override void MigrateDb() { Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, MyMigrationConfiguration>()); Context.Database.Initialize(true); } ``` c) Control Drops separately - Admin trigger You can use EF for this. I personally prefer SQL script triggered from code. d) Trigger seed routines - Admin trigger. Using a rountine that can be called by a tool that just called Migrate for example. I dont like trying to launch this from inside EF migrations. Some scenarios for me that it caused headaches having EF orchestrating when seed got called. A single Admin step could of course combine as required. I use a custom built Migration Workbench (WPF) that can do any or all of the above on any DB. Including New DBs.
9,272,270
Hi I've an input button like ``` <input id="btnDelete" type="button" value="Delete" name="btnDelete" runat="server" onclick="return confirm('Are you sure you wish to delete these records?');" /> and my serverside code is Private Sub btnDelete_ServerClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.ServerClick ' my code here End Sub ``` but when I click on delete button I'm getting confirm msg box, but after that it is not going to server side event. Anything wrong in this? Thank you
2012/02/14
[ "https://Stackoverflow.com/questions/9272270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225264/" ]
USE [OnClientClick](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx#Y570) for your client side javascript validation ``` <asp:BUTTON id="btnDelete" name="btnDelete" value="Delete" onclick="btnDelete_ServerClick" OnClientClick="return confirm('Are you sure you wish to delete these records?');"/> ``` IF you are using HTML control then this may be helpful: [How to call code behind server method from a client side javascript function?](https://stackoverflow.com/questions/5828803/how-to-call-code-behind-server-method-from-a-client-side-javascript-function) CHECK THIS OUT ALSO [\_doPostBack()](http://wiki.asp.net/404.aspx?aspxerrorpath=/themes/fan/pages/page.aspx/1082/dopostback-function/)
53,834,396
Assuming that I have a QPushButton named `button`, I successfully do the following to allow **click** event: ``` class UI(object): def setupUi(self, Dialog): # ... self.button.clicked.connect(self.do_something) def do_something(self): # Something here ``` My question is: how can I call `do_something()` when `the tab` key is pressed? For instance, if I have a QlineEdit named `tb_id`, after entering a value and press tab key, `do_something()` method should be called in the same way as what `clicked` does above. How can I do that using `pyqt5`? Thank you so much.
2018/12/18
[ "https://Stackoverflow.com/questions/53834396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9923495/" ]
To get what you want there are many methods but before pointing it by observing your code I see that you have generated it with Qt Designer so that code should not be modified but create another class that uses that code so I will place the base code: ``` from PyQt5 import QtCore, QtWidgets class UI(object): def setupUi(self, Dialog): self.button = QtWidgets.QPushButton("Press Me") lay = QtWidgets.QVBoxLayout(Dialog) lay.addWidget(self.button) class Dialog(QtWidgets.QDialog, UI): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.setupUi(self) self.button.clicked.connect(self.do_something) @QtCore.pyqtSlot() def do_something(self): print("do_something") if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) w = Dialog() w.resize(640, 480) w.show() sys.exit(app.exec_()) ``` Also, I recommend you read the difference between event and signal in the world of Qt in [What are the differences between event and signal in Qt](https://stackoverflow.com/questions/9323888/what-are-the-differences-between-event-and-signal-in-qt) since you speak of *click event* but in the world of Qt one must say *clicked signal*. Now if going to the point there are the following options: * Using keyPressEvent: --- ``` class Dialog(QtWidgets.QDialog, UI): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.setupUi(self) self.button.clicked.connect(self.do_something) @QtCore.pyqtSlot() def do_something(self): print("do_something") def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Tab: self.do_something() ``` * Using an event filter: --- ``` class Dialog(QtWidgets.QDialog, UI): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.setupUi(self) self.button.clicked.connect(self.do_something) @QtCore.pyqtSlot() def do_something(self): print("do_something") def eventFilter(self, obj, event): if obj is self and event.type() == QtCore.QEvent.KeyPress: if event.key() == QtCore.Qt.Key_Tab: self.do_something() return super(Dialog, self).eventFilter(obj, event) ``` * Using activated signal of QShorcut: --- ``` class Dialog(QtWidgets.QDialog, UI): def __init__(self, parent=None): super(Dialog, self).__init__(parent) self.setupUi(self) self.button.clicked.connect(self.do_something) shortcut = QtWidgets.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Tab), self) shortcut.activated.connect(self.do_something) @QtCore.pyqtSlot() def do_something(self): print("do_something") ``` From the previous methods I prefer the latter because you do not need to overwrite anything and you can connect to several functions. On the other hand, only events are detected when the focus is in the Qt window.
62,910,520
I tried to run `flutter pub get` and I got this error: ``` Error on line 1, column 1 of pubspec.lock: Unexpected character ╷ 1 │ │ ^ ╵ pub upgrade failed (65; ╵) ```
2020/07/15
[ "https://Stackoverflow.com/questions/62910520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13753831/" ]
The file pubspec.lock is a generated file, so you can delete it and then regenerate it. Delete **pubspec.lock**. Run the following command: ``` flutter pub get ``` or ``` flutter pub upgrade ``` Notes on [pub upgrade](https://dart.dev/tools/pub/cmd/pub-upgrade) (you could probably skip the delete step).
3,788,859
let's say I have two xml strings: String logToSearch = "<abc><number>123456789012</number></abc>" String logToSearch2 = "<abc><number xsi:type=\"soapenc:string\" /></abc>" String logToSearch3 = "<abc><number /></abc>"; I need a pattern which finds the number tag if the tag contains value, i.e. the match should be found only in the logToSearch. I'm not saying i'm looking for the number itself, but rather that the matcher.find method should return true only for the first string. For now i have this: Pattern pattern = Pattern.compile("<(" + pattrenString + ").\*?>", Pattern.CASE\_INSENSITIVE); where the patternString is simply "number". I tried to add "<(" + pattrenString + ")[^/>].\*?> but it didn't work because in [^/>] each character is treated separately. Thanks
2010/09/24
[ "https://Stackoverflow.com/questions/3788859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/457493/" ]
This is absolutely the wrong way to parse XML. In fact, if you need more than just the basic example given here, there's provably no way to solve the more complex cases with regex. Use an easy XML parser, like [XOM](http://www.xom.nu). Now, using xpath, query for the elements and filter those without data. I can only imagine that this question is a precursor to future headaches unless you modify your approach right now.
877,690
How does a 3D model handled unit wise ? When i have a random model that i want to fit in my view port i dunno if it is too big or not, if i need to translate it to be in the middle... I think a 3d object might have it's own origine.
2009/05/18
[ "https://Stackoverflow.com/questions/877690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2566/" ]
You need to find a bounding volume, a shape that encloses all the object's vertices, for your object that is easier to work with than the object itself. Spheres are often used for this. Either the artist can define the sphere as part of the model information or you can work it out at run time. Calculating the optimal sphere is very hard, but you can get a good approximation using the following: ``` determine the min and max value of each point's x, y and z for each vertex min_x = min (min_x, vertex.x) max_x = max (max_x, vertex.x) min_y = min (min_y, vertex.y) max_y = max (max_y, vertex.y) min_z = min (min_z, vertex.z) max_z = max (max_z, vertex.z) sphere centre = (max_x + min_x) / 2, (max_y + min_y) / 2, (max_z + min_z) / 2 sphere radius = distance from centre to (max_x, max_y, max_z) ``` Using this sphere, determine the a world position that allows the sphere to be viewed in full - simple geometry will determine this.
32,747,720
I have a table called Product. I need to select all product records that have the MAX ManufatureDate. Here is a sample of the table data: ``` Id ProductName ManufactureDate 1 Car 01-01-2015 2 Truck 05-01-2015 3 Computer 05-01-2015 4 Phone 02-01-2015 5 Chair 03-01-2015 ``` This is what the result should be since the max date of all the records is 05-01-2015 and these 2 records have this max date: ``` Id ProductName ManufactureDate 2 Truck 05-01-2015 3 Computer 05-01-2015 ``` The only way I can think of doing this is by first doing a query on the entire table to find out what the max date is and then store it in a variable @MaxManufatureDate. Then do a second query where ManufactureDate=@MaxManufactureDate. Something tells me there is a better way. There are 1 million+ records in this table: **Here is the way I am currently doing it:** ``` @MaxManufactureDate = select max(ManufactureDate) from Product select * from Product where ManufactureDate = @MaxManufactureDate ``` If figure this is a lot better then doing a subselect in a where clause. Or is this the same exact thing as doing a subselect in a where clause? I am not sure if the query gets ran for each row regardless or if sqlserver stored the variable value in memory.
2015/09/23
[ "https://Stackoverflow.com/questions/32747720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5150565/" ]
``` select * from product where manufactureDate = (select max(manufactureDate) from product) ``` The inner select-statements selects the maximum date, the outer all products which have the date.
68,118,208
``` CREATE TABLE mydataset.newtable (transaction_id INT64, transaction_date DATE) PARTITION BY transaction_date AS SELECT transaction_id, transaction_date FROM mydataset.mytable ``` The docs don't specify whether the PARTITION BY clause supports "required".
2021/06/24
[ "https://Stackoverflow.com/questions/68118208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3381013/" ]
Solved it finally by displaying more logs on the error message. The key action is to update Gradle in my project level build.gradle file, I changed: ``` classpath 'com.android.tools.build:gradle:4.0.2' ``` To: ``` classpath 'com.android.tools.build:gradle:4.2.1' ```
29,808,109
So, I am trying to read in a text file using VB.NET and add the values of each line into a SQL Server database table. The code I have this far reads in the first line but keeps trying to read in the same line and fails. It adds the first, but like I stated it fails after the first one. I am quite sure the problem is in my loop and/or mysplit() array values. Any help in the right direction would be greatly appreciated. Thank you ``` Public Sub addTxtMember() 'Dim fileName As String ' fileName = Application.StartupPath + "c:\users\james needham\documents\visual studio 2013\projects\textfiletutorial1\textfiletutorial1\textfile1.txt" Dim fileName As Integer = FreeFile() 'If File.Exists(fileName) Then 'Dim iofile As New StreamReader(fileName) FileOpen(fileName, "TextFile1.txt", OpenMode.Input) Dim ioline As String 'Dim iolines() As String Dim eID, fName, lName, email, phone Dim i As Integer = 0 ioline = LineInput(fileName) 'Do Until EOF(fileName) While Not ioline = "" ' Dim endsplit = Split(ioline, "") Dim mysplit = Split(ioline, ",") eID = mysplit(0) fName = mysplit(1) lName = mysplit(2) phone = mysplit(3) email = mysplit(4) ' try Dim strInsert As String = "INSERT INTO Employees1 (eID, fName, lName, phone, email) " & _ "VALUES (" & _ "'" & eID & "'," & _ "'" & fName & "', " & _ "'" & lName & "', " & _ "'" & phone & "', " & _ "'" & email & "')" 'MsgBox(strInsert) SQLCon.Open() SQLCmd = New SqlCommand(strInsert, SQLCon) 'has to be non when inserting, updating, or deleting SQLCmd.ExecuteNonQuery() SQLCon.Close() ' Catch ex As Exception 'MsgBox(ex.Message) 'End Try End While FileClose(fileName) 'Else 'MsgBox("fILE NOT FOUND") ' FileClose(fileName) 'End If End Sub ```
2015/04/22
[ "https://Stackoverflow.com/questions/29808109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3889163/" ]
Do the selection of the friend ID in a subquery, then join that with `users`. ``` SELECT u.firstname, u.lastname FROM users as u JOIN (SELECT DISTINCT IF(friends.sender = 75, friends.recipient, friends.sender) AS friend FROM friends WHERE 75 in (sender, recipient)) AS f ON f.friend = u.id ```
2,937,395
I have a JavaScript class that has a method: ``` function someClass() { this.someMethod = someClass_someMethod; } function someClass_someMethod() { // make an AJAX request } ``` The problem is that `someClass_someMethod()` needs to return the value of the AJAX request. I'm using jQuery's `$.getJSON()` method to fetch the data. The data needs to be returned but it seems the only way to get the data is through a callback. How can this be done?
2010/05/30
[ "https://Stackoverflow.com/questions/2937395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/193619/" ]
Make your special view its own UIWindow. Set the UIWindow's windowLevel to UIWindowLevelStatusBar. If it still isn't on top, you can use bringSubviewToFront: on the UIWindow (remember, a UIWindow is a UIView) to bring it to the top of that level.
276,080
Given all variables are in $\mathbb{R}$, and $\{ a, d\} \neq 0$, solve for $\theta$: $$a \sin^2 \theta + b \sin \theta + c + d \cos^2 \theta + e \cos \theta + f = 0$$ as posed in [this question](https://math.stackexchange.com/questions/4577312/solving-quadratic-function-of-sine-and-cosine#4577312). The straightforward approach does not work: ``` Assuming[a != 0 \[And] b != 0, Solve[a Sin[\[Theta]]^2 + b Sin[\[Theta]] + c + d Cos[\[Theta]]^2 + e Cos[\[Theta]] + f == 0, \[Theta]]] ``` One can force "smart" substitutions, as given in the solution to the linked source problem. Is there a direct way to get the solution using *Mathematica*?
2022/11/15
[ "https://mathematica.stackexchange.com/questions/276080", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/9735/" ]
Mathematica has no trouble solving ``` eqn = a Sin[θ]^2 + b Sin[θ] + c + d Cos[θ]^2 + e Cos[θ] + f == 0; subs = {Sin[θ] -> sin, Cos[θ] -> cos}; solution = Solve[(eqn /. subs) && sin^2 + cos^2 == 1, {sin, cos}]; ``` though the solution is rather large, and may not be useful to you.
49,124,177
I have a class where written is a function creating my button: LoginButton.swift ``` func createButton() { let myButton: UIButton = { let button = UIButton() button.addTarget(self, action: #selector(Foo().buttonPressed(_:)), for: .touchUpInside) }() } ``` Now in my second class, Foo.swift, I have a function that just prints a statement Foo.swift ``` @objc func buttonPressed(_ sender: UIButton) { print("button was pressed") } ``` When ran I get no errors except when I try to press the button, nothing happens. Nothing prints, the `UIButton` doesn't react in any way. Really not sure where the error occurs because Xcode isn't printing out any type of error or warning message.
2018/03/06
[ "https://Stackoverflow.com/questions/49124177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9449419/" ]
The action method is called in the target object. Thus, you have either to move `buttonPressed` to the class which contains `createButton` or to pass an instance of `Foo` as a target object. But note that a button is not the owner of its targets. So, if you just write: ``` button.addTarget(Foo(), action: #selector(buttonPressed(_:)), for: .touchUpInside) ``` This will not work, because the `Foo` object is immediately released after that line. You must have a strong reference (e.g. a property) to `Foo()` like ``` let foo = Foo() func createButton() { let myButton: UIButton = { let button = UIButton() button.addTarget(foo, action: #selector(buttonPressed(_:)), for: .touchUpInside) }() } ```
32,173,907
I am new to Apache. I have 2 jboss (Jboss as 7.1.1) and apache httpd server. I am using mod\_cluster for load balancing. I wish to hide the jboss url from user and wish to show the user clean urls. for e.g. www.mydomain.com will be having my static website. subdomain.mydomain.com should go to mydomain.com:8080/myapp subdomain.mydomain.com/mypage.xhtml should go to mydomain.com:8080/myapp/mypage.xhtml sumdomain.mydomain.com/myservice should go to mydomain.com:8080/myapp/service.xhtml?name=myservice I have tried many things with no success. Can some one tell me if it is possible or not. And if possible what are the things I should do. Thanks a lot in advance. Regards.
2015/08/24
[ "https://Stackoverflow.com/questions/32173907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2392795/" ]
You could roll your own without too much coding using `do.call`: ``` partial <- function(f, ...) { l <- list(...) function(...) { do.call(f, c(l, list(...))) } } ``` Basically `partial` returns a function that stores `f` as well as the originally provided arguments (stored in list `l`). When this function is called, it is passed both the arguments in `l` and any additional arguments. Here it is in action: ``` f <- function(a, b, c, d) a+b+c+d p <- partial(f, a=2, c=3) p(b=0, d=1) # [1] 6 ```
22,162,560
How to make a button be at the bottom of div and at the center of it at the same time? ```css .Center { width: 200px; height: 200px; background: #0088cc; margin: auto; padding: 2%; position: absolute; top: 0; left: 0; bottom: 0; right: 0; } .btn-bot { position: absolute; bottom: 0px; } ``` ```html <div class=Center align='center'> <button class='btn-bot'>Bottom button</button> </div> ```
2014/03/04
[ "https://Stackoverflow.com/questions/22162560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2789810/" ]
Give the parent element… ``` display: table; text-align: center; ``` …and its child element… ``` display: table-cell; vertical-align: bottom; ``` This way you do not need to know the width of the child element in case it changes, thus requiring no negative margins or workarounds.
60,878,489
When I generate the production version of my PWA built with VueJS I got this error in Google Chrome after deploying it to my server: * `Uncaught SyntaxError: Unexpected token '<'` in app.21fde857.js:1 * `Uncaught SyntaxError: Unexpected token '<'` in chunk-vendors.d1f8f63f.js:1 I take a look in the Network tab of the console and in both files `chunk-vendors.d1f8f63f.js` and `app.21fde857.js` the `index.html` is coming back with a status 200. Why this occurs? **OBS:** Locally this works perfectly.
2020/03/27
[ "https://Stackoverflow.com/questions/60878489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12542704/" ]
Here is a solution that doesn't require hand-editing your dist assets. Simply add the following property to the exports of your vue.config.js: `publicPath: './'`
22,094,668
I have a database, I mapped it via Ado.net entity model, now I want to expose a single class from my model via WCF service. How can it be achieved?
2014/02/28
[ "https://Stackoverflow.com/questions/22094668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2606389/" ]
Just use specifc CSS rules as: ``` .yellow:hover ~ #slider { background: yellow !important; } ``` [SEE jsFiddle](http://jsfiddle.net/GJQA5/1/)
30,546,943
``` <form id="jtable-edit-form" class="jtable-dialog-form jtable-edit-form"> <div class="jtable-input-field-container"> <div class="jtable-input-label">Type</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configType" type="text" name="configType"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Key</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configKey" type="text" name="configKey"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Value</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-configValue" type="text" name="configValue"> </div> </div> <div class="jtable-input-field-container"> <div class="jtable-input-label">Description</div> <div class="jtable-input jtable-text-input"> <input class="" id="Edit-description" type="text" name="description"> </div> </div> ``` I need to hide 1 div out of 4 div. I want to hide only div which has inner div as value 'Key'. Please note that I am not allowed to changed HTML content. I can just write Jquery for it.
2015/05/30
[ "https://Stackoverflow.com/questions/30546943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1993534/" ]
You can try this: ``` $( "div.jtable-input-label:contains('Key')" ) .closest( "div.jtable-input-field-container" ) .css( "display", "none" ); ```
33,904,005
I'm trying to modify elements of an array in a function. This works fine when kept in main but when I port it to a function it segfaults after accessing the first member of the array. The code below is just a reduced version of my actual code to show where I'm getting the segfault. ``` #include <stdio.h> #include <stdlib.h> typedef struct { unsigned short id; } voter; void initialise(voter** votersPtr, unsigned short *numOfVoters) { *votersPtr = malloc(sizeof(voter)*(*numOfVoters)); for(int i = 0; i < *numOfVoters; i++) { votersPtr[i]->id = (unsigned short) i; printf("%hu \n", votersPtr[i]->id); } } int main(void) { unsigned short numOfVoters = 480; voter* voters = NULL; initialise(&voters, &numOfVoters); return EXIT_SUCCESS; } ``` Any help would be greatly appreciated, thank you.
2015/11/24
[ "https://Stackoverflow.com/questions/33904005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5601548/" ]
`votersPtr[i]->id`, which is the same as `(*votersPtr[i]).id` should be `(*votersPtr)[i].id`.
397,446
I want to draw complete binary tree with some portion highlighted. I am able to draw the complete binary tree, but not able to highlight the specified portion. I want to draw the digram given below: [![enter image description here](https://i.stack.imgur.com/mj9OZ.jpg)](https://i.stack.imgur.com/mj9OZ.jpg) Till now I'm able to do this much: ``` \documentclass[border=2pt]{standalone} \usepackage{forest} \begin{document} \begin{forest} for tree={l+=0.07cm} % increase level distance [1 [2[4][5]] [3[6][7]] ] \end{forest} \end{document} ```
2017/10/22
[ "https://tex.stackexchange.com/questions/397446", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/142684/" ]
I think, in theory, that this should be possible by adding ``` tikz={\node[draw,circle,red,fit=()(!1)(!2)} ``` to the root of the node that you want to circle. Here `()` refers to the node and `(!1)` and `(!2)` its children. Unfortunately, this doesn't quite work because it gives: [![enter image description here](https://i.stack.imgur.com/KCO35.png)](https://i.stack.imgur.com/KCO35.png) So, in practice, it looks better with a little extra tweaking: [![enter image description here](https://i.stack.imgur.com/sDvdp.png)](https://i.stack.imgur.com/sDvdp.png) See section 2.3 of the manual for more details. Here is the full code: ``` \documentclass[border=4pt]{standalone} \usepackage{forest} \begin{document} \begin{forest} for tree={l+=0.08cm} % increase level distance [1 [2,tikz={\node[draw,circle,red,fit=()(!1),inner sep=0mm,xshift=1mm]{};} [4][5] ] [3 [6][7] ] ] \end{forest} \end{document} ``` Another option, which might be preferable, is to use ``` tikz={\node[draw,circle,red,fit=()(!1)(!2),inner sep=0mm]{};} ``` giving [![enter image description here](https://i.stack.imgur.com/grkG9.png)](https://i.stack.imgur.com/grkG9.png)
67,715,975
I have a website for a project that needs to summarize all of the budget categories in one column. For example I have a column which contains: Categories: Water,Electricity,Gas,Rentals,Hospital Fees,Medicine,Personal Care,Fitness, I want to select the sum of water,electricity,gas,rentals and name it as utility bills. Same as sum of hospital fees, medicine, personal care, fitness as healthcare. What sql statement should i use? Any help will be appreciated
2021/05/27
[ "https://Stackoverflow.com/questions/67715975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16044580/" ]
You'd have some other table perhaps, or another column on this table, that maps the specific bills to a general group or category You would then run a query like (if you put the category group in the main table) ``` SELECT categorygroup, sum(amount) FROM bills GROUP BY categorygroup ``` Or (if you have a separate table you join in) ``` SELECT bcg.categorygroup, sum(amount) FROM bills b INNER JOIN billcategorygroups bcg ON b.category=bcg.category GROUP BY bcg.categorygroup ``` You would then maintain the tables, either like (category in main table style): ``` Bills Category, CategoryGroup, Amount --- Electricity, Utility, 123 Water, Utility, 456 ``` Or (separate table to map categories with groups style) ``` BillCategoryGroups Category, CategoryGroup --- Water, Utility Electricity, Utility ``` Etc Something has to map electricity -> utility, water -> utility etc. I'd probably have a separate table because it is easy to reorganize. If you decide that Cellular is no longer Utility but instead Personal then just changing it in the mapping table will change all the reporting. It also helps prevent typos and data entry errors affecting reports - if you use the single table route and put even one Electricity bill down as Utitily then it gets its own line on the report. Adding new categories is easy with a separate table too. All these things can be done with single table and big update statements etc but we have "normalization" of data for good reasons
381,278
Since I have osxfuse installed it would be nice if I could use it. There are a [lot of](https://apple.stackexchange.com/questions/73156/) (heavily) outdated [articles](https://apple.stackexchange.com/questions/140536/) here, saying that it is not [possible](https://apple.stackexchange.com/questions/128060/). Is this still the case?
2020/02/04
[ "https://apple.stackexchange.com/questions/381278", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/66939/" ]
> > **Update**: According to this [document in homebrew-core](https://github.com/Homebrew/homebrew-core/pull/64491) from November 2020, Homebrew maintainers no longer update or support macFUSE formulae, and Homebrew's continuous integration doesn't test them. macFUSE formulae will eventually be removed in the indeterminate future. > > > Specifically, `ext4fuse` (mentioned below in the post) is disabled: > > > > ``` > brew install ext4fuse > Error: ext4fuse has been disabled because it requires closed-source macFUSE! > > ``` > > The reason for this is that FUSE for macOS does not have a license that is compatible with Homebrew. > > > Mac does not support ext4 file system. If you plug in a hard drive, Mac won't recognize it. Fortunately, there are several ways to handle this situation. **1. Temporary options: Use VM** Just install a version of Ubuntu, or whatever your Linux distribution of choice is, in a virtual machine host like VirtualBox, then mount the drive as you would any other and read away. **2. Add ext4 support for macOS** If you regularly use ext4 formatted drives and / or need to copy multiple files from there to the macOS drive, you need a better option. You need to install [macFUSE](https://osxfuse.github.io/) (`osxfuse` has been succeeded by `macfuse` as of version 4.0.0) and `ext4fuse`. The easiest way to install `ext4fuse` is to use Homebrew. Note that `ext4fuse` us a read-only implementation of ext4 for FUSE to browse ext4 volumes and it cannot be used to write into ext4 volumes. First, download and install macFUSE from their [releases page](https://github.com/osxfuse/osxfuse/releases) or install it using Homebrew. ```bash brew install --cask macfuse ``` Then use Homebrew to install `ext4fuse`. ```bash brew install ext4fuse ``` After installing the ext4 support software, you now need to determine the hard drive you want to mount. To do this, run the following command: ```bash diskutil list ``` Save the partition ID (will look like `/dev/disk3s1`). Then, run the following command to mount the hard drive: ```bash sudo ext4fuse /dev/disk3s1 ~/tmp/ext4_support_PARTITION -o allow_other ``` `ext4_support` above can be any name you choose. Now, navigate to the '/ tmp /' directory in the Finder and you will see the contents of the partition listed. If your drive has multiple partitions, you can mount them using the same steps as above. Just make sure to use different directory names to mount them. **Update** Attempting to install `ext4fuse` with brew results in an error. (See [issue #66 on GitHub](https://github.com/gerard/ext4fuse/issues/66)), so instead use the following commands to install it: ```bash curl -s -o ext4fuse.rb https://gist.githubusercontent.com/n-stone/413e407c8fd73683e7e926e10e27dd4e/raw/12b463eb0be3421bdda5db8ef967bfafbaa915c5/ext4fuse.rb brew install --formula --build-from-source ./ext4fuse.rb rm ./ext4fuse.rb ``` **Warning** Although these tools can help you read ext4 formatted hard drives, they are not stable. As long as you are mounting read-only drives, as what is being done in this solution, you will not have many risks. If you try to use these tools to *write* to an ext4 drive, you may lose data. If you need to move files back and forth on a shared drive with Linux, this method is not recommended. Instead, use another file system like ExFAT or try the commercial option listed below **3. Use Paid Software** Software such as [Paragon](https://www.paragon-software.com/home/extfs-mac/) offers a free trial version, but to be safe, you should back up your hard drive first, in case there is a problem. If you want to buy software, it is available for 40$ **Note**: I haven't used this tool and can't say anything about what they have promised. Although reading ext4 format on macOS is no longer an impossible task, it is frustrating when Apple does not support this format. Try it on your own risk but I strongly recommend the first solution which is easy and convenient.
584,665
In Excel, if I have two lines in A1: ``` Hello World ``` but if I go over to A2 and type `=lower(A1)`, I get: ``` helloworld ``` How can I preserve the newline between *Hello* and *World*?
2013/04/18
[ "https://superuser.com/questions/584665", "https://superuser.com", "https://superuser.com/users/210559/" ]
Use `=lower(A1)` and then turn on `Wrap Text` for that cell.
49,572,567
I'm trying to filter a simple `HTML` table with the filter being determined by multiple radio buttons. The goal is to show/hide any rows that contain/don't contain the words in the filter. For example if I select "**yes**" on the "`auto`" filter and "**no**" on the "manually" filter it should look in the column named "auto" for the "yes" value and on the "manually" column for the "no" value. I tried it with [this question](https://stackoverflow.com/questions/19420792/filter-table-with-multiple-radio-inputs) but it filters with the logical OR and not the logical AND. Also i don't quite know how to set the filter inactive when the user wants to deactivate the according filter. Here is my HTML code: ``` <html> <head> <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script> </head> <body> <form name="FilterForm" id="FilterForm" action="" method=""> <label>Auto:</label> <input type="radio" name="auto" value="yes" /> <label>yes</label> <input type="radio" name="auto" value="no" /> <label>no</label> <input type="radio" name="auto" value="inactive" /> <label>inactive</label> <br> <label>Manually:</label> <input type="radio" name="manually" value="yes" /> <label>yes</label> <input type="radio" name="manually" value="no" /> <label>no</label> <input type="radio" name="manually" value="inactive" /> <label>inactive</label> <br> <label>Downgrade:</label> <input type="radio" name="downgrade" value="yes" /> <label>yes</label> <input type="radio" name="downgrade" value="no" /> <label>no</label> <input type="radio" name="downgrade" value="inactive" /> <label>inactive</label> <br> </form> <table border="1" id="ExampleTable"> <thead> <tr> <th>name</th> <th>auto</th> <th>manually</th> <th>downgrade</th> </tr> </thead> <tbody> <tr> <td class="name">Name1</td> <td class="auto">yes</td> <td class="manually">yes</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name2</td> <td class="auto">no</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name3</td> <td class="auto">no</td> <td class="manually">yes</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name4</td> <td class="auto">yes</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> </tbody> </table> </body> </html> ``` And here is the Javascript i did with the help of the previous mentioned question: ``` <script> $('input[type="radio"]').change(function () { var firstRow = 'name'; var auto = $('input[name="auto"]:checked').prop('value') || ''; var manually = $('input[name="manually"]:checked').prop('value') || ''; var downgrade = $('input[name="downgrade"]:checked').prop('value') || ''; $('tr').hide(); $('tr:contains(' + firstRow + ')').show(); $('tr:contains(' + auto + ')').show(); $('tr').not(':contains(' + manually + ')').hide(); $('tr').not(':contains(' + downgrade + ')').hide(); }); </script> ``` Here is also an image for better understanding: [![project_image](https://i.stack.imgur.com/l9uAx.jpg)](https://i.stack.imgur.com/l9uAx.jpg) Since i usually don't use JS and JQuery I couldn't quite figure out the problem and the time is short. I would be very grateful for a push in the right direction, thanks in advance.
2018/03/30
[ "https://Stackoverflow.com/questions/49572567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8641691/" ]
Try this, I think this is what you want: ```js $(document).ready(function(){ $('input[type="radio"]').change(function () { var firstRow = 'name'; var auto = $('input[name="auto"]:checked').prop('value') || ''; var manually = $('input[name="manually"]:checked').prop('value') || ''; var downgrade = $('input[name="downgrade"]:checked').prop('value') || ''; var trs = $('tr:not(:first)'); $(trs).hide(); if(auto == 'inactive' || manually == 'inactive' || downgrade == 'inactive'){ // Do nothing as any of three condition says show all // And currently we all rows selected in trs } else { if(auto != '' && auto != 'inactive'){ var chkdName = $('input[name="auto"]:checked').prop('name'); trs = $(trs).find("."+chkdName+':contains('+auto+')').parent(); } if(manually != '' && manually != 'inactive'){ var chkdName = $('input[name="manually"]:checked').prop('name'); trs = $(trs).find("."+chkdName+':contains('+manually+')').parent(); } if(downgrade != '' && downgrade != 'inactive'){ var chkdName = $('input[name="downgrade"]:checked').prop('name'); trs = $(trs).find("."+chkdName+':contains('+downgrade+')').parent(); } } $(trs).show(); }); $("#reset").on('click', function(){ $(':radio').prop('checked', false); $('tr').show(); }); }); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form name="FilterForm" id="FilterForm" action="" method=""> <label>Auto:</label> <input type="radio" name="auto" value="yes" /> <label>Yes</label> <input type="radio" name="auto" value="no" /> <label>No</label> <input type="radio" name="auto" value="inactive" /> <label>All</label> <br> <label>Manually:</label> <input type="radio" name="manually" value="yes" /> <label>Yes</label> <input type="radio" name="manually" value="no" /> <label>No</label> <input type="radio" name="manually" value="inactive" /> <label>All</label> <br> <label>Downgrade:</label> <input type="radio" name="downgrade" value="yes" /> <label>Yes</label> <input type="radio" name="downgrade" value="no" /> <label>No</label> <input type="radio" name="downgrade" value="inactive" /> <label>All</label> <br> </form> <br><button id="reset">Reset</button><br><br><br><br> <table border="1" id="ExampleTable"> <thead> <tr> <th>Name</th> <th>Auto</th> <th>Manually</th> <th>Downgrade</th> </tr> </thead> <tbody> <tr> <td class="name">Name1</td> <td class="auto">no</td> <td class="manually">no</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name2</td> <td class="auto">no</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name3</td> <td class="auto">no</td> <td class="manually">yes</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name4</td> <td class="auto">yes</td> <td class="manually">no</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name5</td> <td class="auto">yes</td> <td class="manually">no</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name6</td> <td class="auto">yes</td> <td class="manually">yes</td> <td class="downgrade">no</td> </tr> <tr> <td class="name">Name7</td> <td class="auto">no</td> <td class="manually">yes</td> <td class="downgrade">yes</td> </tr> <tr> <td class="name">Name8</td> <td class="auto">yes</td> <td class="manually">yes</td> <td class="downgrade">yes</td> </tr> </tbody> </table> ``` Here is the working copy: [fiddle url](https://plnkr.co/edit/PyaHur2a1wquT6t79ixX?p=preview)
13,726,429
I am trying to do a basic string replace using a regex expression, but the answers I have found do not seem to help - they are directly answering each persons unique requirement with little or no explanation. I am using `str = str.replace(/[^a-z0-9+]/g, '');` at the moment. But what I would like to do is allow all alphanumeric characters (a-z and 0-9) and also the '-' character. Could you please answer this and explain how you concatenate expressions.
2012/12/05
[ "https://Stackoverflow.com/questions/13726429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359306/" ]
This should work : ``` str = str.replace(/[^a-z0-9-]/g, ''); ``` Everything between the indicates what your are looking for 1. `/` is here to delimit your pattern so you have one to start and one to end 2. `[]` indicates the pattern your are looking for on one specific character 3. `^` indicates that you want every character NOT corresponding to what follows 4. `a-z` matches any character between 'a' and 'z' included 5. `0-9` matches any digit between '0' and '9' included (meaning any digit) 6. `-` the '-' character 7. `g` at the end is a special parameter saying that you do not want you regex to stop on the first character matching your pattern but to continue on the whole string Then your expression is delimited by `/` before and after. So here you say "every character not being a letter, a digit or a '-' will be removed from the string".
5,223,716
I am trying to insensitive replace string, so I'm using str\_ireplace() but it does something I dont want and I have no clue how to overcome this problem. so this is my code: ``` $q = "pArty"; $str = "PARty all day long"; echo str_ireplace($q,'<b>' . $q . '</b>',$str); ``` The output will be like that: `"<b>pArty</b> all day long"`. The output looks like that because I replace insenitive variable `$q` with its sensitive. How can I overcome this so the output will be `"<b>PARty</b> all day long"`?
2011/03/07
[ "https://Stackoverflow.com/questions/5223716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/519002/" ]
You could do this with `preg_replace`, e.g.: ``` $q = preg_quote($q, '/'); // in case it has characters of significance to PCRE echo preg_replace('/' . $q . '/i', '<b>$0</b>', $str); ```
34,160
I'm making a malware software in my final thesis at the university. I won't use it ever, and it was made by educational and scientific purposes only. But my university will publish it, giving the opportunity for everyone to use it. If someone commit a crime with my software, can I get in trouble?
2018/12/07
[ "https://law.stackexchange.com/questions/34160", "https://law.stackexchange.com", "https://law.stackexchange.com/users/-1/" ]
> > my university will publish it, giving the opportunity for everyone to > use it. If someone commit a crime with my software, can I get in > trouble? > > > I would say "No" for three reasons. I will assume that you are in a jurisdiction of the U.S. or reasonably similar thereto. First, the malware code is part of your thesis, which in turn is a prerequisite (already [approved by the university](https://law.stackexchange.com/questions/34160/can-i-get-in-trouble-for-making-a-malware/34197#comment62964_34160)) for graduation. If anything, the entity that would be knowingly broadcasting the material is the university, not you. Any liability in the vein of [MCL 750.540f](http://www.legislature.mi.gov/(S(2ubfmtd5hibnrarwrhdecvcs))/mileg.aspx?page=getobject&objectname=mcl-750-540f) would fall on the university, as it knows better than you about the presumed "risks" as to whether third-parties might abuse your research. In the context of a *public* university with its typical status of "arm of the state", it would be untenable if one arm of the state (the university) authorizes you to proceed, and subsequently another governmental agency prosecutes *you* once your thesis reaches completion. Second, your thesis with all the source code therein expresses ideas which are protected by the First Amendment. A serious discussion of malware necessarily requires that these ideas be expressed in assembly code (often intertwined with excerpts in machine code) of the architecture for which it is devised. Anything short of that makes a discussion of malware meaningless because this topic depends so heavily on the particulars of the targeted family of processors. Furthermore, the academic context evidences your pursuit of educational & scientific advancement rather than a direct or indirect intent to encourage criminal activity. A person whose ultimate purpose is to promote computer crimes has many alternatives which are quicker and more effective than enrolling in a university, pay tuition, and undergo years of academic study. Third, (without minimizing your merits) it is doubtful that no solution could ever exist for the malware you devise, or that no one else from a "clandestine" setting would ever come up independently with an akin variant of that malware. Thus, publications of malware made with the openness and formalities of a university thesis are likelier to be viewed as a heads up to IT security companies about enhancements they might need to make on products & services they offer.
2,009,437
How can I get the @@IDENTITY for a specific table? I have been doing ``` select * from myTable ``` as I assume this sets the scope, from the same window SQL query window in SSMS I then run ``` select @@IDENTITY as identt ``` It returns identt as null which is not expected since myTable has many entrie in it already.. I expect it to return the next available ID integer. myTable has a ID column set to Primary key and auto increment.
2010/01/05
[ "https://Stackoverflow.com/questions/2009437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127257/" ]
You can use [IDENT\_CURRENT](http://msdn.microsoft.com/en-us/library/ms175098.aspx) ``` IDENT_CURRENT( 'table_name' ) ``` Note that IDENT\_CURRENT returns the last identity value for the table **in any session and any scope**. This means, that if another identity value was inserted after your identity value then you will not retrieve the identity value that you inserted.
14,225,659
I have found that one of the Microsoft Reporting controls (the Chart) is inadequate for my needs. Since these controls aren't extensible, I've extended the functionality of a WPF control and am saving the control as a graphic. Unfortunately, ReportViewer's image control doesn't support vector graphics, either. Therefore my goal is to generate the PDF from ReportViewer with certain "placeholders" (e.g. a rectangle item), and then come behind with iTextSharp and add the vector graphic on top of these placeholders. Since the report length flows based on the input data, I can't know the coordinates of these placeholders before getting them. I can't think of a way to include a PDF field in the RDLC, which would be nice since iText has the GetFieldPosition() method. Furthermore I know there is iText's PDFWriter.GetVerticalPosition() method, but this is really only useful if you've moved the cursor to that location in the PDFWriter. Truth is, I'm still trying to get my head around iText and PDF. It is *vast*. So my two questions that refer to each other: 1. What kind of placeholder should I use in the RDLC designer that can be systematically identified afterwards and have its position queried? 2. How would I go about getting this position? Thanks in advance! -Brandon
2013/01/08
[ "https://Stackoverflow.com/questions/14225659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1435756/" ]
My imperfect, but working solution is to use text item placeholders that match the background to mark the positions in the .RDLC report. After generating the PDF, these are identified by way of inheriting iTextSharp's LocationTextExtractionStrategy (as per [this entry by greenhat](https://stackoverflow.com/questions/4577789/extract-text-and-text-rectangle-coordinates-from-a-pdf-file-using-itextsharp/8825884#8825884)). In my current test environment the above is copy-pasted verbatim and only deviates in the RenderText() override, which does not add the TextChunk to the list unless `info.GetText()` is an appropriate placeholder string. Snippet of placeholder extraction: ``` PdfReader reader = new PdfReader(fileName); LocationTextExtractionStrategyEx strat = new LocationTextExtractionStrategyEx(); for (int i = 1; i <= reader.NumberOfPages; i++) PdfTextExtractor.GetTextFromPage(reader, i, strat); ``` The native vector image type is WMF, and can be inserted at the absolute location of the placeholder text. To do so for the first placeholder in the list, then: ``` using (FileStream fs = new FileStream("output.pdf", FileMode.Create, FileAccess.Write, FileShare.None)) { using (PdfStamper stamper = new PdfStamper(reader, fs)) { using (Stream wmfStream = new FileStream(@"C:\Paint.wmf", FileMode.Open, FileAccess.Read, FileShare.Read)) { Image replacementVectorImage = Image.GetInstance(wmfStream); replacementVectorImage.SetAbsolutePosition(strat.TextLocationInfo[0].TopLeft[0], strat.TextLocationInfo[0].BottomRight[1]); PdfContentByte cb = stamper.GetOverContent(1); cb.AddImage(replacementVectorImage); } } } ``` Thanks to mkl and VahidN for your valuable input!
25,428,870
I'm trying to figure out how to write a decorator to check if the function was called with specific optional argument. This may not be the pythonic way of checking for arguments, but I'd like to know the solution using decorators regardless. Here is an example of what I'm looking for: ``` @require_arguments("N", "p") # Question here def g(x,*args,**kwargs): if "N" not in kwargs: raise SyntaxError("missing N") if "p" not in kwargs: raise SyntaxError("missing p") print x g(3,N=2) # Raise "missing p" ``` How do I write the decorator `@require_arguments(*args)` that will raise the appropriate error?
2014/08/21
[ "https://Stackoverflow.com/questions/25428870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/249341/" ]
Here you go: ``` def require_arguments(*reqargs): def decorator(func): def wrapper(*args, **kwargs): for arg in reqargs: if not arg in kwargs: raise TypeError("Missing %s" % arg) return func(*args, **kwargs) return wrapper return decorator @require_arguments("N", "p") # Question here def g(x,*args,**kwargs): print x g(3,N=2) # Raise "missing p" ``` Output: ``` Traceback (most recent call last): File "arg.py", line 19, in <module> g(3,N=2) # Raise "missing p" File "arg.py", line 7, in wrapper raise ValueError("Missing %s" % arg) ValueError: Missing p ```
71,165,098
What is an appropriate way to solve the following example with swift? I know because of type erasure that you cannot assign `StructB` to `item2` in the constructor. In other languages like *Java* I would solve the problem by not having a generic class parameter `T` in the `Container` struct but let vars `item` and `item2` just be the type of `ProtocolA` (like `var item2: ProtocolA`). This is not allowed by swift: *Protocol 'ProtocolA' can only be used as a generic constraint because it has Self or associated type requirements* I worked through [this](https://docs.swift.org/swift-book/LanguageGuide/Generics.html) section of swifts documentation about generics but so far I was not able to adapt a solution for my simple problem: ```swift protocol ProtocolA { associatedtype B func foo() -> B } struct StructA: ProtocolA { typealias B = String func foo() -> String { "Hello" } } struct StructB: ProtocolA { typealias B = Double func foo() -> Double { 0.0 } } struct Container<T: ProtocolA> { var item: T var item2: T init(item: T) { self.item = item self.item2 = StructB() // err: Cannot assign value of type 'StructB' to type 'T' } } ``` I also want to know how a solution could look if I do not want to specify a generic type parameter at all for the container struct. So that I could write the following: ```swift func test() { let container = Container(StructA()) // no type given } ```
2022/02/17
[ "https://Stackoverflow.com/questions/71165098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3477946/" ]
For the problem as described, the answer is very straightforward: ``` struct Container<T: ProtocolA> { var item: T var item2: StructB // This isn't T; you hard-coded it to StructB in init init(item: T) { self.item = item self.item2 = StructB() } } let container = Container(item: StructA()) // works as described ``` I get the feeling that there's something deeper to this question, which is why Alexander was asking for more context. As written, the question's answer seems too simple, so some of us assume that there's more that you didn't explain, and we want to avoid a round of "here's the answer" followed by "that's not what I meant." As you wrote it, you try to force `item` and `item2` to have the same type. That's obviously not what you mean because `T` is given by the caller, and `item2` is always StructB (which does not have to equal `T`, as the error explains). Is there another way you intend to call this code? It's unclear what code that calls `foo()` would look like. Do you have some other way you intend to initialize Container that you didn't explain in your question? Maybe you want two different types, and you just want StructB to be the default? In that case, it would look like (based on Ptit Xav's answer): ``` struct Container<T: ProtocolA, U: ProtocolA> { var item: T var item2: U // Regular init where the caller decides T and U init(item: T, item2: U) { self.item = item self.item2 = item2 } // Convenience where the caller just decides T and U is default init(item: T) where U == StructB { self.init(item: item, item2: StructB()) } } ``` The `where U == StructB` allows you to make a default type for U.
44,386,174
``` class Node: def __init__(self, data = None, next = None): self.data = data self.next = next class LinkedList(Node): def __init__(self, l_size = 0, head = None, tail = None): Node.__init__(self) self.l_size = 0 self.head = head self.tail = tail def add(self, data): n = Node(data, None) if(self.l_size == 0): self.head.next = n self.head.data = n.data else: self.tail.next = n self.tail.data = n.data n = n.next print(n) self.tail = n self.l_size += 1 return True l = LinkedList() l.add(7) l.add(8) l.add(2) ``` I'm just trying to achieve `(h)-> 7 -> 8 -> 2 <- (l)` Where (h) and (l) are the head and tail pointers respectively. The way I'm implementing this the LL is basically the head and the tail pointers, the Nodes chain together on their own, that's why I made Node a super class.
2017/06/06
[ "https://Stackoverflow.com/questions/44386174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4982544/" ]
Simply aggregate your table per `user_id` and use `HAVING` to ensure both conditions are met for the user. ``` select user_id from settings group by user_id having count(case when token = 'language' and value = 'en' then 1 end) > 0 and count(case when token = 'newsletter' AND value = 1 then 1 end) > 0 ``` You can add a `WHERE` clause to speed this up, if you like: ``` where (token = 'language' and value = 'en') or (token = 'newsletter' AND value = 1) ```
69,984,598
I tried using a lambda expression and `count_if()` to find the same string value in a `vector`, but it didn't work. The error message is: > > variable 'str' cannot be implicitly captured in a lambda with no capture-default specified > > > ```cpp std::vector<std::string> hello{"Mon","Tue", "Wes", "perfect","Sun"}; for (unsigned int i = 0; i < hello.size(); i++) { int n=0; std::string str=hello[i]; n=std::count_if(hello.begin(),hello.end(),[](std::string s){return s==str;}); std::cout<<n; } ```
2021/11/16
[ "https://Stackoverflow.com/questions/69984598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16188928/" ]
@Steven The brackets `[]` of lambda functions, are called a *capture list*. They define the scope of variables that the lambda function uses. See [this reference](https://en.cppreference.com/w/cpp/language/lambda). When you use this formatting `[&]`, it means you can see all the variables (by reference) of the current scope in your lambda function. So the type of variables doesn't matter. For your example, when you write: ``` s == str ``` The lambda function only knows about the variable `s`, which is passed as an argument. To see the `str`, you can use either of these: 1. `[&]`, pass everything by reference 2. `[&str]`, pass only the variable `str` as reference Note, there are also ways to pass by value.
11,573,562
In my current project, I am making a sticky-note type application in which the user can have multiple instances open of the same form. However, I was wondering if there was a way in C# where I can create a new instance of form1 however have the new form's title/text/heading to be form2. If this is achievable, I would like a nudge into the correct direction of how to code that part of my app. Thanks everyone. --EDIT-- I realized I forgot to add something important: I need to be able to calculate how many instances are currently open. From there I will add +1 to the form text.
2012/07/20
[ "https://Stackoverflow.com/questions/11573562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1539802/" ]
Try accessing the forms properties from the class: ``` MyForm newForm = new MyForm(); newForm.Show(); newForm.Text = "Form2"; ``` Or call a method from the current form to set the text: ``` // In MyForm public void SetTitle(string text) { this.Text = text; } // Call the Method MyForm newForm = new MyForm(); newForm.Show(); newForm.SetTitle("Form2"); ``` Hope this helps! To check the amount of forms open you could try something like this: ``` // In MyForm private int counter = 1; public void Counter(int count) { counter = count; } // Example MyForm newForm = new MyForm(); counter++; newForm.Counter(counter); ``` It may be confusing to use, but lets say you have a button that opens a new instance of the same form. Since you have one form open at the start `counter = 1`. Every time you click on the button, it will send `counter++` or `2` to the form. If you open another form, it will send `counter = 3` and so on. There might be a better way to do this but I am not sure.
29,709,291
Chromecast session status returns undefined on Chrome mobile ios. The session exists and has other properties defined, like sessionID. On the desktop, the session status returns "connected", "disconnected", or "stopped" as expected. Is this a bug with Chrome ios? Is there another way to detect the session status?
2015/04/17
[ "https://Stackoverflow.com/questions/29709291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4634213/" ]
Here's one alternative using `ifelse` ``` > transform(df, NewSize=ifelse(Month==1, Size*Month1, ifelse(Month==2, Size*Month2, Size*Month3))) Orig Dest Month Size Month1 Month2 Month3 NewSize 1 A B 1 30 1.0 0.6 0.0 30 2 B A 1 20 0.2 1.0 1.0 4 3 A C 1 10 0.0 0.0 0.6 0 4 A B 2 10 1.0 0.6 0.0 6 5 B A 2 20 0.2 1.0 1.0 20 6 A C 2 20 0.0 0.0 0.6 0 7 A B 3 30 1.0 0.6 0.0 0 8 B A 3 50 0.2 1.0 1.0 50 9 A C 3 20 0.0 0.0 0.6 12 ```
1,148,807
How would I solve this differential eqn $$xdy - ydx = (x^2 + y^2)^{1/2} dx$$ I tried bringing the sq root term to the left and it looked like a trigonometric substitution might do the trick, but apparently no. Any help would be appreciated.
2015/02/15
[ "https://math.stackexchange.com/questions/1148807", "https://math.stackexchange.com", "https://math.stackexchange.com/users/117251/" ]
$$x\frac{dy}{dx} - y = (x^2 + y^2)^{1/2} $$ is an ODE of the homogeneous kind. The usual method to solve it is to let $y(x)=x\:f(x)$ This leads to an ODE of the separable kind easy to solve. The final result is $y=c\:x^2-\frac{1}{4\:c}$
21,772,974
I am coding a PHP script, but I can't really seem to get it to work. I am testing out the basics, but I don't really understand what GET and POST means, what's the difference? All the definitions I've seen on the web make not much sense to me, what I've coded so far (but since I don't understand POST and GET, I don't know how to get it to work: ``` <form name="mail_sub" method="get"> Name: <input type="text" name="theirname"> <br /> Email:&nbsp; <input type="text" name="theirpass"> <br /> <input type="submit" value="Join!" style="width:200px"> </form> <?php if (isset($_POST['mail_sub'])) { echo $_POST['theirname']; } ?> ```
2014/02/14
[ "https://Stackoverflow.com/questions/21772974", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3077765/" ]
$\_POST isn't working for you because you have the form method set to get. ``` <form name="mail_sub" method="post"> ``` There's plenty of better info online as to the difference between post and get so I won't go into that but this will fix the issue for you. Change your PHP as well. ``` if ( isset( $_POST['theirname'] ) ) { echo $_POST['theirname']; } ```
39,350,744
I created a custom Lucene index in a Sitecore 8.1 environment like this: ```xml <?xml version="1.0"?> <configuration xmlns:x="http://www.sitecore.net/xmlconfig/"> <sitecore> <contentSearch> <configuration type="Sitecore.ContentSearch.ContentSearchConfiguration, Sitecore.ContentSearch"> <indexes hint="list:AddIndex"> <index id="Products_index" type="Sitecore.ContentSearch.LuceneProvider.LuceneIndex, Sitecore.ContentSearch.LuceneProvider"> <param desc="name">$(id)</param> <param desc="folder">$(id)</param> <param desc="propertyStore" ref="contentSearch/indexConfigurations/databasePropertyStore" param1="$(id)" /> <configuration ref="contentSearch/indexConfigurations/ProductIndexConfiguration" /> <strategies hint="list:AddStrategy"> <strategy ref="contentSearch/indexConfigurations/indexUpdateStrategies/onPublishEndAsync" /> </strategies> <commitPolicyExecutor type="Sitecore.ContentSearch.CommitPolicyExecutor, Sitecore.ContentSearch"> <policies hint="list:AddCommitPolicy"> <policy type="Sitecore.ContentSearch.TimeIntervalCommitPolicy, Sitecore.ContentSearch" /> </policies> </commitPolicyExecutor> <locations hint="list:AddCrawler"> <crawler type="Sitecore.ContentSearch.SitecoreItemCrawler, Sitecore.ContentSearch"> <Database>master</Database> <Root>/sitecore/content/General/Product Repository</Root> </crawler> </locations> <enableItemLanguageFallback>false</enableItemLanguageFallback> <enableFieldLanguageFallback>false</enableFieldLanguageFallback> </index> </indexes> </configuration> <indexConfigurations> <ProductIndexConfiguration type="Sitecore.ContentSearch.LuceneProvider.LuceneIndexConfiguration, Sitecore.ContentSearch.LuceneProvider"> <initializeOnAdd>true</initializeOnAdd> <analyzer ref="contentSearch/indexConfigurations/defaultLuceneIndexConfiguration/analyzer" /> <documentBuilderType>Sitecore.ContentSearch.LuceneProvider.LuceneDocumentBuilder, Sitecore.ContentSearch.LuceneProvider</documentBuilderType> <fieldMap type="Sitecore.ContentSearch.FieldMap, Sitecore.ContentSearch"> <fieldNames hint="raw:AddFieldByFieldName"> <field fieldName="_uniqueid" storageType="YES" indexType="TOKENIZED" vectorType="NO" boost="1f" type="System.String" settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider"> <analyzer type="Sitecore.ContentSearch.LuceneProvider.Analyzers.LowerCaseKeywordAnalyzer, Sitecore.ContentSearch.LuceneProvider" /> </field> <field fieldName="key" storageType="YES" indexType="UNTOKENIZED" vectorType="NO" boost="1f" type="System.String" settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider"/> </fieldNames> </fieldMap> <documentOptions type="Sitecore.ContentSearch.LuceneProvider.LuceneDocumentBuilderOptions, Sitecore.ContentSearch.LuceneProvider"> <indexAllFields>true</indexAllFields> <include hint="list:AddIncludedTemplate"> <Product>{843B9598-318D-4AFA-B8C8-07E3DF5C6738}</Product> </include> </documentOptions> <fieldReaders ref="contentSearch/indexConfigurations/defaultLuceneIndexConfiguration/fieldReaders"/> <indexFieldStorageValueFormatter ref="contentSearch/indexConfigurations/defaultLuceneIndexConfiguration/indexFieldStorageValueFormatter"/> <indexDocumentPropertyMapper ref="contentSearch/indexConfigurations/defaultLuceneIndexConfiguration/indexDocumentPropertyMapper"/> </ProductIndexConfiguration> </indexConfigurations> </contentSearch> </sitecore> </configuration> ``` Actually a quite straightforward index that points to a root, includes a template and stores a field. It all works. But I need something extra: * Limit the entries in the index to the latest version * Limit the entries in the index to one language (English) I know this can be easily triggered in the query as well, but I want to get my indexes smaller so they will (re)build faster. The first one could be solved by indexing web instead of master, but I actually also want the unpublished ones in this case. I'm quite sure I will need a custom crawler for this. The second one (limit the languages) is actually more important as I will also need this in other indexes. The easy answer is probably also to use a custom crawler but I was hoping there would be a way to configure this without custom code. Is it possible to configure an custom index to only include a defined set of languages (one or more) instead of all?
2016/09/06
[ "https://Stackoverflow.com/questions/39350744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6144330/" ]
After some research I came to the conclusion that to match all the requirements a custom crawler was the only solution. Blogged the code: <http://ggullentops.blogspot.be/2016/10/custom-sitecore-index-crawler.html> The main reason was that we really had to be able to set this per index - which is not possible with the filter approach. Also, when we added a new version the previous version had to be deleted from the index - also not possible without the crawler... There is quite some code so I won't copy it all here but we had to override the DoAdd and DoUpdate methods of the SitecoreItemCrawler, and for the languages we also had to make a small override of the Update method.
39,386,415
I wrote a piece of code to learn more about `Comparator` function of java collection. I have two sets having 3 elements in each. and i want to compare. I post my code below and output of counter variable. Can anyone explain why variable `i` gives this weird output ?? I could not understand flow. ``` public class TestProductBundle { public static void main(String args[]) { TestProductBundle productBundle = new TestProductBundle(); Set<ClassA> hashSetA = new HashSet<ClassA>() { { add(new ClassA("name", 1, "desc")); add(new ClassA("name", 2, "desc")); add(new ClassA("name", 3, "desc")); } }; Set<ClassA> hashSetB = new HashSet<ClassA>() { { add(new ClassA("name1", 2, "desc1")); //"name" & "desc" are different than previous add(new ClassA("name2", 1, "desc2")); add(new ClassA("name3", 3, "desc3")); } }; if (productBundle.compareCollection(hashSetA, hashSetB)) { System.out.println("Equal set of tree"); } else { System.out.println("Unequal set of tree"); } } @SuppressWarnings("serial") public boolean compareCollection(Set<ClassA> collection1, Set<ClassA> collection2) { TreeSet<ClassA> treeSetA = new TreeSet<ClassA>(new CompareID()) { { addAll(collection1); } }; TreeSet<ClassA> treeSetB = new TreeSet<ClassA>(new CompareID()) { { addAll(collection2); } }; if (treeSetA.containsAll(treeSetB) && treeSetB.containsAll(treeSetA)) return true; else return false; } } ``` code for ClassA and class that implements Comparator. ``` class ClassA { String name; int id; String desc; public ClassA(String name, int id, String desc) { this.name = name; this.id = id; this.desc = desc; } int getId() { return id; } } ``` & ``` class CompareID implements Comparator<ClassA> { int i = 0; @Override public int compare(ClassA o1, ClassA o2) { System.out.println(i++); // Counter variable if (o1.getId() > o2.getId()) return 1; else if (o1.getId() < o2.getId()) return -1; else return 0; } } ``` output is (cross verified in debugger also) ``` 0 1 2 3 0 // why started from 0 again ? 1 2 3 4 5 6 7 8 4 // What the hell !!! 5 6 7 8 Equal set of tree // is that correct output ? ```
2016/09/08
[ "https://Stackoverflow.com/questions/39386415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3042916/" ]
I'm not sure what you are finding strange. You have **two** TreeSet instances, each having its own `CompareID` instance serving as `Comparator`, and each `CompareID` instance maintains it's own counter. Therefore it's not a surprise to see each counter values (0,1,2,etc...) appearing twice. As for the order of appearance of the counter values, that depends on the internal implementation of `TreeSet`. As for > > Equal set of tree // is that correct output ? > > > Yes, both sets contain the same elements. The order doesn't matter. To clarify - the methods `contains` and `containsAll` of `TreeSet` consider an element `x` to be contained in the `TreeSet` if `compare(x,y)==0` for some element `y` of the `TreeSet`, where `compare` is the `compare` method of the supplied `Comparator`. Therefore, in your example, only the `id` property determines if two elements are equal. The following scenario explains the output : ``` 0 // compare method of 1st CompareID object executed 1 // compare method of 1st CompareID object executed 2 // compare method of 1st CompareID object executed 3 // compare method of 1st CompareID object executed 0 // compare method of 2nd CompareID object executed 1 // compare method of 2nd CompareID object executed 2 // compare method of 2nd CompareID object executed 3 // compare method of 2nd CompareID object executed 4 // compare method of 1st CompareID object executed 5 // compare method of 1st CompareID object executed 6 // compare method of 1st CompareID object executed 7 // compare method of 1st CompareID object executed 8 // compare method of 1st CompareID object executed 4 // compare method of 2nd CompareID object executed 5 // compare method of 2nd CompareID object executed 6 // compare method of 2nd CompareID object executed 7 // compare method of 2nd CompareID object executed 8 // compare method of 2nd CompareID object executed ``` EDIT : First you are adding elements to the first `TreeSet` (hence `compare` of the first `Comparator` is called several times in a row), then you are adding elements to the second `TreeSet` (hence `compare` of the second `Comparator` is called several times in a row), then you call `treeSetA.containsAll(treeSetB)` which causes `compare` of the first `Comparator` to be called several times in a row, and finally you call `treeSetB.containsAll(treeSetA)` which causes `compare` of the second `Comparator` to be called several times in a row.
26,504,553
I have 5 imageviews and I am updating them based on value but the problem is for updating all of them I have redundant code for eacg image updation expect the specific imageView object. Here is example, I have such 5 methods to update each imageview which I guess is not optimal solution. ``` public void imageThird(int value){ third.setVisibility(View.VISIBLE); if(value >= 1000 && value <= 800) { third.setImageResource(R.drawable.sa); } else if(value >= 800 && value <= 500) { third.setImageResource(R.drawable.sb); } else if(value >= 500 && value <= 300) { third.setImageResource(R.drawable.sc); } else if(value >= 300 && value <= 150) { third.setImageResource(R.drawable.sd); } else if(value >= 150 && value <= 50) { third.setImageResource(R.drawable.se); } else { third.setImageResource(R.drawable.sa); } } ``` So I have 5 like this method, which is not good I guess, the only difference is the imageview object for each image. May be it is silly question I am not much aware about how images works in Andorid.
2014/10/22
[ "https://Stackoverflow.com/questions/26504553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4132634/" ]
I just tested it with a sample project. It works fine. There must be something wrong with your wiring up the cell. Here is my code. Only indicating changes from plain vanilla tab bar project template. ![enter image description here](https://i.stack.imgur.com/fAKkQ.png) ``` // FirstViewController.swift func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell cell.textLabel?.text = "Cell \(indexPath.row + 1)" return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let detail = segue.destinationViewController as DetailController let cell = sender as UITableViewCell let indexPath = self.tableView.indexPathForCell(cell) detail.detailItem = "Cell \(indexPath!.row + 1)" } //DetailController.swift class DetailController: UIViewController { var detailItem : String! @IBOutlet var label : UILabel! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) label.text = detailItem } } ```
1,787,006
I am working to integrate data from an external web service in the client side of my appliction. Someone asked me to test the condition when the service is unavailable or down. Anyone have any tips on how to block this site temporarily while we run the test to see how the service degrades? For those curious we are testing against Virtual Earth, but Google Maps but this would apply to any equally complicated external service. any thoughts and suggestions are welcome
2009/11/24
[ "https://Stackoverflow.com/questions/1787006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10676/" ]
Create some Mock-Webservice class or interface (and [inject](http://martinfowler.com/articles/injection.html) [it](http://www.youtube.com/watch?v=hBVJbzAagfs)). In there, you could test the response of your system to webservice failures and also what happens, if a web-service request take longer than expected or actually time-out. DeveloperWorks article on mock testing: <http://www.ibm.com/developerworks/library/j-mocktest.html>
56,761,464
I need to pick a random number from 31 to 359. ``` rand(31, 359); ``` I need the number is not part from this array of numbers: ``` $badNumbers = array(30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360); ``` How can I do this please? Thanks.
2019/06/25
[ "https://Stackoverflow.com/questions/56761464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10296344/" ]
I would probably do this as it completes when one is found: ``` while(in_array($rand = rand(31, 359), $badNumbers)); echo $rand; ``` Here is another way using an array: ``` $good = array_diff(range(31, 359), $badNumbers); echo $good[array_rand($good)]; ``` Or randomize and choose one: ``` shuffle($good); echo array_pop($good); ``` The array approaches are useful if you need to pick more than one random number. Think `array_rand` again or `array_slice` for the second one.
35,349
I'm making a game with target (orbit camera). I want to limit camera movements when in room. So that camera don't go through walls when moving around target and along the ground. What are common approaches? Any good links with tutorials? I use Unity3D, nevertheless I'm good with a general solution to the problem
2012/08/31
[ "https://gamedev.stackexchange.com/questions/35349", "https://gamedev.stackexchange.com", "https://gamedev.stackexchange.com/users/19462/" ]
Make a snake game with it. Make a shooter game with it. Make some simple well known games to start off. Once you've done this, you should be more confident with your engine, and making these games will give you ideas on where to keep going.
40,655,245
I'm trying to remove gray color outline of images. I saw that that outline means error because image tags don't have source properties. but if i add `src="image.jpg"`, hovering doesn't work. how to fix it? so confused.... this is my code ```css #item1 { background-image: url('cushion01.jpg'); height: 300px; width: 300px; background-repeat: no-repeat; background-size: cover; } #item1:hover { background-image: url('cushion-01.jpeg'); height: 300px; width: 300px; } ``` ```html <div class="secondary__item" style="width: 100%; height : 850px;"> <ul class="item-images"> <li class="item-image"> <img class="item" id="item1" src="image.jpg" /> </li> <li class="item-image"> <img class="item" id="item2" /> </li> </ul> <ul class="item-images"> <li class="item-image"> <img class="item" id="item3" /> </li> <li class="item-image"> <img class="item" id="item4" /> </li> </ul> </div> ```
2016/11/17
[ "https://Stackoverflow.com/questions/40655245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6650139/" ]
Strange thing is that you are trying to set background to `<img>` tag. If I were you I'd use `<div>` instead. Then It would be very simple: HTML: ``` <div class= "secondary__item" style="width: 100%; height : 850px;"> <ul class="item-images"> <li class="item-image"><div class="item" id="item1" ></div></li> <li class="item-image"><div class="item" id="item2" ></div></li> </ul> <ul class="item-images"> <li class="item-image"><div class="item" id="item3" ></div></li> <li class="item-image"><div class="item" id="item4" ></div></li> </ul> </div> ``` CSS: ``` .item { height:300px; width :300px; background-repeat: no-repeat; background-size : cover; /*you can remove it*/ border: 1px solid; } .item:hover { background-image: url('http://shushi168.com/data/out/114/36276270-image.png'); height:300px; width :300px; } ``` Here is a Fiddle: <https://jsfiddle.net/7kzu5qcy/2/>
37,546,012
I trying to build a Simon game but I'm messing with CSS. [![simon game](https://i.stack.imgur.com/xWinG.jpg)](https://i.stack.imgur.com/xWinG.jpg) (source: [walmartimages.com](http://i5.walmartimages.com/dfw/dce07b8c-837a/k2-_c8eba155-7ff4-45e8-86ab-704862d4a446.v1.jpg)) I don't know my mistakes but inline-block isn't working as expected: ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; float: left; left: 0px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; position: absolute; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <body> <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> </body> ``` <https://jsfiddle.net/gbs4320m/> I tried to mix things up with different settings and consulted online resources but i couldn't figure out the problem. Please help!! Thanks in advance.
2016/05/31
[ "https://Stackoverflow.com/questions/37546012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3531612/" ]
Remove the position absolute: ```css body { text-align: center; } #box { width: 500px; height: 500px; border-radius: 100%; position: relative; margin: auto; background-color: #333; top: 10vh; box-shadow: 0px 0px 12px #222; } #box .pad { width: 240px; height: 240px; float: left; left: 0px; border: 5px solid #333; box-shadow: 0px 0px 2px #222; display: inline-block; } #topLeft { background-color: green; border-top-left-radius: 100%; } #topRight { background-color: red; border-top-right-radius: 100%; /*right: 0;*/ } #bottomLeft { background-color: yellow; border-bottom-left-radius: 100%; } #bottomRight { background-color: blue; border-bottom-right-radius: 100%; } ``` ```html <h1 id="header">freeCodeCamp JS Simon Game</h1> <div id="box"> <div class="pad" id="topLeft"></div> <div class="pad" id="topRight"></div> <div class="pad" id="bottomLeft"></div> <div class="pad" id="bottomRight"></div> </div> ```