text
stringlengths
64
81.1k
meta
dict
Q: Time complexity, proof $\log(n + c) \in O(\log(n))$ I have to prove that for $a \in N, c > 0$ (constants), this statement holds: $\log_a(n + c) \in O(\log_a(n))$ So if I use the definition, the following should hold: $\log_a(n + c) \leq d\log_a(n) = \log_a (n^d), \forall n \geq n_0, d > 0$ I have to find $n_0, d$ now $n + c \leq n^d$ But how can I express $d$ so it depends only on $c$? How to continue from here? Thanks for any help! A: I'm omitting the $a$ from the notations, as the base of the logarithm doesn't change anything. For fixed $c > 0$, and any $n \geq 1$, $$ \log(n+c) = \log\left(n\left(1+\frac{c}{n}\right)\right) = \log n + \log\left(1+\frac{c}{n}\right)\;. $$ But $\log\left(1+\frac{c}{n}\right) \xrightarrow[n\to\infty]{} 0$, so in particular it is less than $\log n$ (which goes to $\infty$) for $n$ "sufficiently large" (i.e., $\exists n_0, \forall n \geq n_0\; \log\left(1+\frac{c}{n}\right)\leq \log n$). Hence, for $n$ sufficiently large $$ \log(n+c) \leq 2\log n $$ proving the result. A: Perhaps first prove $$ \lim_{n\to\infty} \frac{\log(n+c)}{\log n} = 1 $$
{ "pile_set_name": "StackExchange" }
Q: Are bugs necessarily off-topic? Jorge Castro recently commented on one of my questions that it should be filed as a bug instead. And I've seen here that the general view is that questions about bugs should be considered off-topic here and handled on Launchpad instead. My question is whether that stance should be modified somewhat. Obviously, for bugs to be fixed they need to be reported in the appropriate bug tracker(s). However, there are two situations where I think that questions about bugs are relevant here: Sometimes, the user might not have enough understanding of the situation to be able to file a good bug report. An answer here could help provide that data. It has been my experience that vague bugs rarely get fixed, while bugs that provide sufficient detail are more likely to be addressed. In other cases, while a bug report is possible and should be filed (or in some cases, might already exist), there's a need to find a workaround for a particular bug. I've asked several questions of this nature (always being sure to file the appropriate bug report). Ask Ubuntu is a better way to manage workarounds than Launchpad because, frankly, it can be quite time-consuming to find a suitable workaround, especially for bug logs that contain lots of comments. Searching for workarounds is the exact type of Q&A our format works so well for. A: I can touch on both of your points to hopefully help you with these types of situations.. How do I report a bug? There is a wonderful list of answers here..., or when looking for more information you can pop into the Chat room, or post a question asking how to identify the issue. so, No I don't think the current stand on Bugs being reported on AU should change, however if you follow the two points above you should be able to get the answers you are looking for. A: I think our current policy is good. Sometimes, the user might not have enough understanding of the situation to be able to file a good bug report. An answer here could help provide that data. It has been my experience that vague bugs rarely get fixed, while bugs that provide sufficient detail are more likely to be addressed. Vague bugs don't get addressed; neither do vague questions. The advantage of Launchpad is that it automatically collects hardware and package details and relevant logs (with ubuntu-bug), and uses an advanced duplicate detection system for crashes; AskUbuntu has neither of these features. Bugs are more likely to get addressed in Launchpad. Trying to eke answers out of people here is less efficient than doing it there. In other cases, while a bug report is possible and should be filed (or in some cases, might already exist), there's a need to find a workaround for a particular bug. Even when there are workarounds to find, they are inherently too localized for the format. They have an expiration date of whenever the bug gets fixed. Ask Ubuntu is not a customer support site; it is intended to create valuable information for the long term. We are the intersection between support and documentation. Support-only belongs in other channels. And yes, I believe we should do a better job communicating this. In short, my vote is stay the course. A: When should I post such a question? How do I report a bug? should address this for most cases. Of course, in some cases (like a bug for which you don't know the package and there's no specific window you can click on for ubuntu-bug -w), you may have to ask in chat or the forums. This point's a bit more interesting. Go ahead and post a question with a link to the specific bug report (either a pre-existing one or one you filed yourself) and ask for a workaround only if you can't find it there already. That being said, keep in mind that such a question is only valid up until the fix is released, and should then be closed as Too Localized. Thus when doing so, you should probably check that both of the following are true: Such a workaround would be highly useful to a significant number of people until the bug is fixed properly. The fix for the bug is not going to be released soon. If the bug was just reported not too long ago (like, say, a week or two at most), then it's advisable to wait on it. If the bug is quite old though (months or years) and there's no fix being worked on, then it makes more sense to ask if a workaround's available. All that being said, most such posts probably are only a good idea in a few exceptional cases where they will be useful for a non-trivial period of time, and will require your own judgment on whether it's worth making the post despite the risk of closure. What if I find such a question that someone else posted? If they're looking for assistance in filing a bug, point them again to How do I report a bug? and ask in a comment if it answers their question. If it doesn't, check whether you can find the desired solution there; if not, then their question is probably worthy of an answer. In all other cases, flag their question as a dupe of that. If they're seeking a workaround to a problem: If they provide a link to the bug report, see if there's a workaround there which resolves the issue for them. If there is and it works for them, flag as Too Localized. If there isn't, either provide a workaround yourself or wait for someone else to do so; once it is provided and the OP verifies it works for them, encourage them to post it in a comment on the bug report and then flag the question. If no bug report is provided, tell them to file one according to How do I report a bug? and flag as Offtopic. What about reporting/workarounds in Ubuntu+1? It should go without saying that, regardless of who's posting, questions relating to bugs in Ubuntu+1 releases are always offtopic. People looking for help filing bugs for these specifically should refer to There's an issue with an Alpha/Beta Release of Ubuntu, what should I do?, and those looking for workarounds are advised to be patient as Ubuntu+1 bugs are often rapidly fixed.
{ "pile_set_name": "StackExchange" }
Q: How to Convert Codepen to Vue.js? I'm having trouble moving this pen to Vue.js This is what my code looks like for The Vue app - I understand where the HTML, and CSS should go. Should I add the Javascript to the individual component, or add it to the App.vue file? What I want to do is test this code in a view I can route to. This is the Javascript from the pen: var app = new Vue({ el: '#app', mounted() { let vm = this axios .get( 'https://sheets.googleapis.com/v4/spreadsheets/15qFEW97T-9Im9dx5G4KJqRorPDy74wwAvqaQm5Phz4w/values/A2%3AC12?key=AIzaSyBP4OwJmDCdX0rdOdgIa4q79g0XrMGcOSk' ) .then(function (response) { let specials = response.data.values for (let index = 0; index < specials.length; index++) { const element = specials[index] let mitem = { name: element[0], description: element[1], price: element[2] } if (vm.isEven(index)) { vm.menuItems_L = vm.menuItems_L.concat(mitem) } else { vm.menuItems_R = vm.menuItems_R.concat(mitem) } } console.log(response) }) }, data: { menuItems_L: [], menuItems_R: [], menuStyle: { background: '#ffe6d1', color: '#000' }, dotStyle: { backgroundImage: 'radial-gradient(' + this.color + ' 1px, transparent 0px)' } }, computed: {}, methods: { isEven: function (n) { return n % 2 == 0 } } }); This is what my code looks like in the component (with changes from research / guessing), the HTML is in tags above it: <script> import axios from 'axios'; export default { mounted() { let vm = this Vue.axios.get( 'https://sheets.googleapis.com/v4/spreadsheets/15qFEW97T-9Im9dx5G4KJqRorPDy74wwAvqaQm5Phz4w/values/A2%3AC12?key=AIzaSyBP4OwJmDCdX0rdOdgIa4q79g0XrMGcOSk' ) .then(function (response) { let specials = response.data.values for (let index = 0; index < specials.length; index++) { const element = specials[index] let mitem = { name: element[0], description: element[1], price: element[2] } if (vm.isEven(index)) { vm.menuItems_L = vm.menuItems_L.concat(mitem) } else { vm.menuItems_R = vm.menuItems_R.concat(mitem) } } console.log(response) }) }, data: { menuItems_L: [], menuItems_R: [], menuStyle: { background: '#ffe6d1', color: '#000' }, dotStyle: { backgroundImage: 'radial-gradient(#000, 1px, transparent 0px)' } }, computed: {}, methods: { isEven: function (n) { return n % 2 == 0 }, setColor: function (c) { c = menuStyle.color let colorStyle = 'radial-gradient(' + c + ' 1px, transparent 0px)' return colorStyle } } } </script> A: You just need to remove the link on the first of the HTML templets, and make the <div id='#app'> is the root for the whole page as mentioned on Vue Docs Vue will show an error, explaining that every component must have a single root element. You can fix this error by wrapping the template in a parent element Also change data:{} to function data(){return{}} ... because As mentioned on Vue Docs, that Data have to be a function a component’s data option must be a function, so that each instance can maintain an independent copy of the returned data object: import axios from 'axios'; export default { el: '#app', data() { return { menuItems_L: [], menuItems_R: [], menuStyle: { background: '#ffe6d1', color: '#000' }, dotStyle: { backgroundImage: 'radial-gradient(' + this.color + ' 1px, transparent 0px)' } } }, mounted() { let vm = this axios .get( 'https://sheets.googleapis.com/v4/spreadsheets/15qFEW97T-9Im9dx5G4KJqRorPDy74wwAvqaQm5Phz4w/values/A2%3AC12?key=AIzaSyBP4OwJmDCdX0rdOdgIa4q79g0XrMGcOSk' ) .then(function (response) { let specials = response.data.values for (let index = 0; index < specials.length; index++) { const element = specials[index] let mitem = { name: element[0], description: element[1], price: element[2] } if (vm.isEven(index)) { vm.menuItems_L = vm.menuItems_L.concat(mitem) } else { vm.menuItems_R = vm.menuItems_R.concat(mitem) } } console.log(response) }) }, methods: { isEven: function (n) { return n % 2 == 0 } } } <template> <div id="app"> <section id="specialssection" class="specials-container" v-if="menuItems_L" :style="menuStyle"> <div id="special_component" :style="menuStyle"> <h1>Daily Specials</h1> <div class="specials-table-container"> <table> <tbody v-for="item in menuItems_L" :key="`specialmenu-${item.name}`"> <tr class="nameandprice"> <td :style="dotStyle"> <span :style="menuStyle">{{item.name}}</span> </td> <td :style="dotStyle"> <span :style="menuStyle">${{item.price}}</span> </td> </tr> <tr class="description"> <td colspan="2">{{item.description}}</td> </tr> </tbody> </table> <table> <tbody v-for="item in menuItems_R" :key="`specialmenu-${item.name}`"> <tr class="nameandprice"> <td :style="dotStyle"> <span :style="menuStyle">{{item.name}}</span> </td> <td :style="dotStyle"> <span :style="menuStyle">${{item.price}}</span> </td> </tr> <tr class="description"> <td colspan="2">{{item.description}}</td> </tr> </tbody> </table> </div> </div> </section> </div> </template>
{ "pile_set_name": "StackExchange" }
Q: tableview custom cell: use of undeclared type I'm setting up custom cell for a tableview and got it almost work properly except some annoying errors. So I setup a prototype cell in storyboard with identifier: RankingCell and class: RankingCell. I setup a very basic class file : RankingCell.swift import Foundation import UIKit class RankingCell: UITableViewCell { @IBOutlet var firstName: UILabel! @IBOutlet var lastName: UILabel! } The outlets are correctly linked to field inside the custom cell. Now here is the view controller file: class RankingViewController: UIViewController, UITableViewDelegate { var testArray = ["Ben", "rob"] var testArray2 = ["mel", "duval"] func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let cell = tableView.dequeueReusableCellWithIdentifier("RankingCell") as RankingCell //Error I here cell.firstName.text = testArray[indexPath.row] cell.lastName.text = testArray2[indexPath.row] return cell } override func viewDidLoad() { super.viewDidLoad() tableView.reloadData() //Error II here } } The error I outlined by the complier is "use of undeclared type 'RankingCell'". What's weird is that when I compile, it compiles with no problem, and even displays correct data in the cells. Still I would prefer to do things properly and get ride of the outlined error. The second error is in viewdidload. I simplified the code in the example, but I pull data from a backend, and once I have it, I need to reload the table so I put there tableView.reloadData() which trigger error: "(UITableView, numberOfRowsInSection: Int) -> Int' does not have a member named 'reloadData'". Thus I can't have the table reload with appropriate data. Maybe you know how to have data reloaded properly from viewdidload ? Please answer in swift. A: Ok, I finally resolved the issues: The first error of undeclared type.... I spent hours on that..... and all what was needed, was to restart xcode. I couldn't believe that when I read someone with similar problem. The fact that the error was showing in red in xcode, but that the project could still be build and run without error was suspicious.... also the colors for that part of code in xcode were wrong... anyway something got corrupted and restarting xcode fixed it. The second error, to reload the table view: I simply created an iboutlet for the tableview, and then called it in viewdidload after work on the backend to retrieve data. Again, there was a corruption where I couldn't ctrl+drag the tableview from stroyboard into the file: I had to type the outlet, and then link it and it worked, not the other way arround. So instead of invoking tableView.reloadData() I invoke userFriendsTableView.reloadData(), userFriendsTableView being the name of the custom outlet, and now it all works.
{ "pile_set_name": "StackExchange" }
Q: Graph smoothing keeping vertices fixed? Context Given a Graph like this one: skl2 = Get["https://dl.dropboxusercontent.com/u/659996/graph.m"]; skl2 = HighlighVertexDegree[skl2, VertexDegree[skl2]]; skl2 = Graph[skl2, VertexLabels -> "Name"] I am interested in re-arranging the position of some of it vertices. Question I would like to move about (=smooth) all the white vertices while keeping the others fixed. (see also this question) Attempt Let me identify by hand such a branch between two yellow vertices: (vertical branch on the right) cc = {26, 36, 43, 49, 48, 55, 63, 71}; HighlightGraph[skl2, cc] The following allows me to identify the corresponding points: pts = Table[ PropertyValue[{skl2, cc[[i]]}, VertexCoordinates], {i, Length[cc]}]; and move them using a BSplineFunction pts2 = BSplineFunction[pts] /@ (Range[0, Length[pts] - 1]/(Length[pts] - 1)); Do[PropertyValue[{skl2, cc[[i]]}, VertexCoordinates] = pts2[[i]], {i, Length[cc]}]; HighlightGraph[skl2, cc] So in principle all is 'fine and dandy' but I would need to identify the relevant segments automatically. It seems to me this functionality if of interest (?) beyond my specific problem. One could think of this as which are the closest neighbours of a given (say yellow) vertex amongst the non white ones, as one scrolls the graph. A: For the part I would need to identify the relevant segments automatically. you can use vd2 = ConnectedComponents@Subgraph[g0, VertexList[g0, x_ /; (VertexDegree[g0, x] == 2)]] {{36, 43, 49, 48, 55, 63}, {41, 42, 47, 54, 62}, {39, 40, 46, 53}, {94, 95, 96}, {82, 92, 99}, {77, 78, 84}, {38, 45, 52}, {13, 17, 18}, {9, 10, 11}, {104, 105}, {89, 90}, {86, 87}, {76, 81}, {75, 80}, {74, 79}, {69, 70}, {66, 67}, {37, 44}, {23, 24}, {16, 25}, {103}, {101}, {98}, {64}, {61}, {59}, {57}, {34}, {32}, {27}, {15}, {14}, {5}} where g0 is the graph linked in the question. Using the function HighlighVertexDegree from OP's related question: g0b = HighlighVertexDegree[g0, VertexDegree[g0]] HighlightGraph[g0, vd2, ImageSize -> 500, VertexLabels -> "Name"] Update: If you wish to include the immediate neighbors of the nodes in each component, you can use vd2N = Complement[VertexList[NeighborhoodGraph[g0, #]], #] & /@ vd2; vd2Np = FindShortestPath[g0, ##] & @@@ vd2N {{26, 36, 43, 49, 48, 55, 63, 71}, {35, 41, 42, 47, 54, 62, 68}, {33, 40, 39, 46, 53, 60}, {93, 94, 95, 96, 97}, {83, 82, 92, 99, 108}, {73, 77, 78, 84, 93}, {31, 38, 45, 52, 58}, {3, 13, 17, 18, 26}, {8, 9, 10, 11, 12}, {106, 105, 104, 112}, {88, 89, 90, 91}, {85, 86, 87, 88}, {71, 76, 81, 91}, {68, 75, 80, 88}, {65, 74, 79, 85}, {68, 69, 70, 71}, {65, 66, 67, 68}, {29, 37, 44, 51}, {22, 23, 24, 33}, {12, 16, 25, 35}, {97, 103, 111}, {100, 101, 102}, {91, 98, 106}, {56, 64, 73}, {60, 61, 65}, {58, 59, 60}, {56, 57, 58}, {33, 34, 35}, {22, 32, 31}, {26, 27, 28}, {8, 15, 22}, {6, 14, 21}, {4, 5, 6}} or vd2O = Complement[VertexOutComponent[g0, #, 1], #] & /@ vd2; vd2Op = FindShortestPath[g0, ##] & @@@ vd2O; {vd2N == vd2O, vd2Np == vd2Op} (* {True, True *) HighlightGraph[g0, vd2Op, ImageSize -> 500] Update 2: And, for the part I would like to move about (=smooth) all the white vertices while keeping the others fixed. bsF = BSplineFunction[#] /@ (Range[0, Length[#] - 1]/(Length[#] - 1)) &; vc = PropertyValue[{g0, #}, VertexCoordinates] & /@ # & /@ vd2Op; vcb = (bsF /@ vc); (PropertyValue[{g0b, #}, VertexCoordinates] = #2) & @@@ Transpose[{Join @@ vd2Op, Join @@ vcb}]; g0b This can be encapsulated as follows GraphSmooth[skl_] := Module[{skl2, vd1, vd2, vd3, cc, pts, pts2, x}, vd1 = ConnectedComponents@ Subgraph[skl, VertexList[skl, x_ /; (VertexDegree[skl, x] == 2)]]; vd2 = VertexOutComponent[skl, #, 1] & /@ vd1; vd3 = FindShortestPath[skl, #[[1]], #[[-1]]] & /@ vd2; skl2 = skl; Do[cc = vd3[[j]];If[Length[cc] > 2,pts = Table[PropertyValue[{skl2, cc[[i]]}, VertexCoordinates], {i, Length[cc]}]; pts2 = BSplineFunction[pts] /@ (Range[0, Length[pts] - 1]/(Length[pts] - 1)); Do[PropertyValue[{skl2, cc[[i]]}, VertexCoordinates] = pts2[[i]], {i, Length[cc]}]], {j, 1, Length[vd3]}]; skl2] skl2 = GraphSmooth[skl]; A: One can smooth the graph by averaging the position of each degree 2 vertex with its neighborhoods. In addition, if the vertex's original position is included in the average, the vertex will be pulled slightly toward it. (Thus four points are being averaged, hence the 0.25 below.) If one iterates this procedure, nice "curved" paths develop. coords = PropertyValue[skl2, VertexCoordinates]; deg2 = Pick[VertexList[skl2], VertexDegree[skl2], 2]; (* coefficient matrix for the original points: degree-2 vertices get weight 1/4 other vertices get weight 1, which will keep them in place *) fixedM = SparseArray[Thread[deg2 -> 0.25], {113}, 1.]; (* averaging matrix for the degree-2 vertices: degree-2 vertices and their adjacent neighbors get weight 1/4 other vertices get weight 0 via multiplication by SparseArray[Thread[deg2 -> 1], {113}] *) relaxM = SparseArray[{#, #} -> 1 & /@ deg2, {113, 113}] + AdjacencyMatrix[skl2] SparseArray[Thread[deg2 -> 1], {113}]; (* iterate until fixed positions are reached - it's fast, otherwise limit the number of iterations (five is usually enough) *) newcoords = FixedPoint[ fixedM coords + 0.25 relaxM.# &, coords, 100]; (* set the new coordinates *) newgraph = Fold[SetProperty[{#1, #2}, VertexCoordinates -> newcoords[[#2]]] &, skl2, deg2] The procedure above is easily bundled into a function by declaring the variables and placing code in a Module. The technique is similar to the relaxation of surface tension. Update - This is an apparently undocumented way to set all the new coordinates at once: newgraph = SetProperty[{skl2, deg2}, VertexCoordinates -> newcoords[[#]] & /@ deg2] The documentation advises "Use Fold to apply SetProperty repeatedly". Note that the second argument has to be a list of rules.
{ "pile_set_name": "StackExchange" }
Q: Simple architecture design program I'm looking for a very simple architecture design program. If it were open source, that would be awesome! I just want to create a kind of map of rooms, and add only borders of furniture items. A: I have made basic architectural drawings (for work) using CAD software such as Free CAD You can certainly draw floor plans and so on in this type of software, but it takes a bit of practice to use fluently - I don't know if it's the simplest. But it is great for scaling and drawing with measurements. You can get Free CAD from Ubuntu repositories: sudo apt-get install freecad It's open source and you can contribute to development - here's the GitHub page
{ "pile_set_name": "StackExchange" }
Q: Adding options of select dynamically from array from java script I have 2 select input in my HTML page <select id="parent"> <option value="1">One</option> <option value="2">Two</option> </select> And <select name="selectOpt" id="dmSelect"> <option disabled selected >-Select an Option-</option> </select> Now I need add some option depending on the value of parent suppose if one is selected options of selectOpt will be <option value="a1">a1</option> <option value="a2">a2</option> and if two is selected options of selectOpt will be <option value="b1">b1</option> <option value="b2">b2</option> and these options will come from some array for like A=["a1","a2"...] B=["b1","b2"...] A: Two Arrays: A=[{display: "a1", value: "a1" }, {display: "a2", value: "a2" }, ........ ] B=[{display: "b1", value: "b1" }, {display: "b2", value: "b2" }, ........ ] Now on change $('#parent').change(function() { var parent = $(this).val(); $("#dmSelect").html("");` switch(parent) { case 1: $(A).each(function (i) { $("#dmSelect").append("<option value=\""+A[i].value+"\">"+A[i].display+" </option>"); }); break; case 2: $(B).each(function (i) { $("#dmSelect").append("<option value=\""+B[i].value+"\">"+B[i].display+"</option>"); }); break; default: } });
{ "pile_set_name": "StackExchange" }
Q: Pandas choose idxmin+1 (nth to last) values only How can I choose only the nth to last index using idxmin in pandas? df = data.loc[data.groupby("key1")["key2"].idxmin()] only gives me the last value of course. Having a dataframe of the form: key1 key2 a 1 a 2 a 3 b 4 b 5 c 6 the desired result should be: key1 key2 a 2 b 5 A: You could do it like this: df[df.groupby('key1')['key2'].transform(pd.DataFrame.rank) == 2] OR df[df.groupby('key1')['key2'].apply(lambda x: x.rank() == 2)] Output: key1 key2 1 a 2 4 b 5
{ "pile_set_name": "StackExchange" }
Q: Call another class and putting stuff in the constructor I think I'm having trouble understanding the constructor in a class. I have written a class within a wordpress plugin. I now want to use that class in another plugin. This is all fine. Within my function I can do new class blah blah then do my thing. However what I want to be able to do is pass some values into this new classes constructor file and then pass the variables from the constructor. Sooooooooooo something like: class why_wont_you_work { public foo1; public foo2; public function __construct() { $this->foo1= $otherclassfunction['name']; $this->foo2= $otherclassfunction['address']; public function do_stuff() { $otherclass = new $otherclass; $otherclassfunction = $otherclass->otherclassfunction(); echo $this->foo1; } A: You can make a constructor that accepts arguments, and pass them from where you create them, just like normal for a function. class why_wont_you_work { public foo1; public foo2; public function __construct($name, $address) { $this->foo1= $name; $this->foo2= $address; public function do_stuff() { $otherclass = new $otherclass; $otherclassfunction = $otherclass->otherclassfunction(); echo $this->foo1; } $obj = new why_wont_you_work( "some name", "some address" );
{ "pile_set_name": "StackExchange" }
Q: How come I can add objects using appendTo but not append in jQuery? How come this works: var items = []; $.each([1, 2, 3, 4], function () { items.push($('<li />').html('test' + this)); }); // clearing/appending as two seperate calls $('ul').empty(); $(items).appendTo('ul'); but this doesn't? var items = []; $.each([1, 2, 3, 4], function () { items.push($('<li />').html('test' + this)); }); // clearing/appending in one fluent call $('ul').empty().append($(items)); This way throws the following error: No such interface supported. A: I believe it's due to implementation. If you look at the way AppendTo is written, it's essentially taking each item in the items array and running a $("ul").append(items[i]). Append though doesn't seem to work on arrays. You'll notice that even without the empty, your line still won't work. I don't completely understand the workings of append, but I believe what happens is the function chomps through all the arguments sequentially, but never attempts to break the elements out of an array. So what happens is that it attempts to append an array to an element and fails. Ironically, this would work: $("ul").empty().append(items[0], items[1], items[2], items[3]); Anyway you'd have to do something like this to accomplish what you seem to be aiming to do: $("ul").empty(); $(items).each(function(e, elem) {$('ul').append(elem);})
{ "pile_set_name": "StackExchange" }
Q: Save button using SSJS does not open xe:dialog in web xpage but works on mobile xpage The following save button code works well on mobile xpage: var checkBox31:com.ibm.xsp.component.xp.XspInputCheckbox = getComponent("checkBox31"); var customerID1:com.ibm.xsp.component.xp.XspInputText = getComponent("customerID1"); var a = checkBox31.getValue(); var b = customerID1.getValue() if (a == "" || a == null){ if (b == ""){ sessionScope.put("ITDialog","You must enter Customer ID"); var dialog1:com.ibm.xsp.extlib.component.dialog.UIDialog = getComponent("dialog1"); dialog1.show(); } } But it does not work on web xpage. I'm using 8.5.3FP6. I used 8.5.3FP1 and 8.5.3FP5 bu had same issue. Thanks in advance for any help. Here is sample of code which is not working.     ]]></xp:this.script> </xp:executeClientScript> </xp:this.script> </xp:eventHandler> </xp:button> &#160; </xp:panel> </xe:dialog> </xp:panel> <xp:table> <xp:tr> <xp:td style="background-color:rgb(226,226,226)"> <xp:label value="Company:" id="company_Label1" for="company1"> </xp:label> </xp:td> <xp:td> <xp:inputText value="#{document1.Company}" id="company1"> </xp:inputText> </xp:td> </xp:tr> <xp:tr> <xp:td style="background-color:rgb(226,226,226)"> <xp:label value="Address:" id="address_Label1" for="address1"> </xp:label> </xp:td> <xp:td> <xp:inputText value="#{document1.Address}" id="address1"> </xp:inputText> </xp:td> </xp:tr> <xp:tr> <xp:td style="background-color:rgb(226,226,226)"> <xp:label value="Contact person:" id="contactPerson_Label1" for="contactPerson1"> </xp:label> </xp:td> <xp:td> <xp:inputText value="#{document1.ContactPerson}" id="contactPerson1"> </xp:inputText> </xp:td> </xp:tr> </xp:table> </xp:panel> </xp:view> A: A checkbox has a value of either 'false' or 'true' (indicating it is 'deselected' & 'selected'), it shouldn't return a value of "" or null. Therefore, the first if statement is never true, and your dialog will never appear. I believe what you want is that if the checkbox is unselected, there must be a customer ID entered in the input. If so, I think this is the code you want: var checkBox31:com.ibm.xsp.component.xp.XspInputCheckbox = getComponent("checkBox31"); var customerID1:com.ibm.xsp.component.xp.XspInputText = getComponent("customerID1"); var a = checkBox31.getValue(); var b = customerID1.getValue(); if (a == "false") { if (b == "") { sessionScope.put("ITDialog","You must enter Customer ID"); var dialog1:com.ibm.xsp.extlib.component.dialog.UIDialog = getComponent("dialog1"); dialog1.show(); } }
{ "pile_set_name": "StackExchange" }
Q: automatic zoom on iphone safari Is there a way for Mobile Safari to recognize a site meant for mobile phones and automatically zoom in? How does that work on other phones and browsers? I'd like to avoid looking at user_agent and sending a different page for each mobile browser. A: See the configuring the viewport part of the Apple web-app developer guide.
{ "pile_set_name": "StackExchange" }
Q: Jetty Http/2 Client on Android I'm trying to use Jetty HTTP/2 client on Android to talk to a custom HTTP/2 service. I can't see a way to start the android HTTP/2 app using ALPN as boot parameter. Is there a way can I disable ALPN for Jetty client or some workaround to activate ALPN during the boot time? A: As answered in the [jetty-users] mailing list. Not possible. HTTP/2 pretty much requires TLS/ALPN. The way to do that, currently, is to modify the Java SSL classes at bootclasspath time. The Jetty Project has written this modification into the alpn-boot.jar for the standard OpenJDK based Java envs. There's no way for a normal Android application to do xbootclasspath on a normal android device. Options you have. Convince Google to include alpn-boot in the base Android image (AOSP). Convince Google to include xbootclasspath support for Android Apps. Build your own Android image with alpn-boot built-in. Built a native ALPN and/or HTTP/2 processor and use it via JNI with your Android application. Good Luck,
{ "pile_set_name": "StackExchange" }
Q: Python module for storing and querying geographical coordinates Is there a Python module where I can create objects with a geographical location coordinate (latitude and longitude), and query all the objects for ones which are within a 5km distance (i.e. radius) of a given coordinate? I've been trying to store the latitude and longitude as keys in dictionaries (as they're indexed by key) and use some distance finding algorithms to query them. But this feels like a horrible hack. Essentially something like PostGIS for PostgreSQL, but all within my Python app's memory. A: Yes, try geopy. import geopy import geopy.distance pt1 = geopy.Point(48.853, 2.349) pt2 = geopy.Point(52.516, 13.378) dist = geopy.distance.distance(pt1, pt2).km # 878.25 afterwards you can query your lists of points: [pt for pt in points if geopy.distance.distance(orig, pt).km < 5.] A: I know this isn't exactly what you meant, but you could use GeoDjango with an in-memory SQLite database. It's a full set of GIS tools exposed as a Web application, which makes it a Swiss Army knife for rapidly developing GIS applications, especially for small ad hoc queries.
{ "pile_set_name": "StackExchange" }
Q: Lost reputation because “user was removed” I have received several downvotes from unknown users recently. What is it, and am I the only one experiencing that ? A: That is not downvotes. A user that upvoted one of your answers was deleted from the system - with them, the reputation given by them has also gone. This happens to other people too - you are not alone.
{ "pile_set_name": "StackExchange" }
Q: Sort List of List of MyType Thanks to eran, I have the following Lambda which creates a list of list of myType. MyType contains a field named dateOfContainer. My question now would be if there is a possibility to extends the expression in order to sort the List<MyType> of List<List<MyType>> list by dateOfContainer? List<List<MyType>> list = new ArrayList<> ( myList.stream().collect (Collectors.groupingBy(MyType::getDateOfContainer)).values()); [EDIT] Thanks a lot for the suggestions. Iam still fighting witch this expression. My current expression looks like this: List<List<ScheduleIntervalContainer>> list = new ArrayList<>( structuredScheduleIntervalContainers.stream().sorted(Comparator.comparing(ScheduleIntervalContainer::getDateOfContainer)) .collect(Collectors.groupingBy(ScheduleIntervalContainer::getDateOfContainer, LinkedHashMap::new, Collectors.toList())).values()); but I am getting this error in eclipse: The method sorted(Comparator<? super List<ScheduleIntervalContainer>>) in the type Stream<List<ScheduleIntervalContainer>> is not applicable for the arguments (Comparator<ScheduleIntervalContainer>) A: You may sort the stream prior grouping, then use LinkedHashMap which preserves order: List<List<MyType>> list = new ArrayList<> ( myList.stream() .sorted(Comparator.comparing(MyType::getDateOfContainer)) .collect( Collectors.groupingBy(MyType::getDateOfContainer, LinkedHashMap::new, Collectors.toList())) .values());
{ "pile_set_name": "StackExchange" }
Q: Proving that the inverse of an algebraic element is algebraic Let $E$ be an extension of a field $F$. Suppose $c \in E$ is algebraic over $F$ where $c \neq 0$. I want to prove that $c^{-1}$ is also algebraic over $F$. I feel like I'm missing something obvious here and that it shouldn't be very difficult to do. I know that $c^{-1} \in F(c)$, but that's about it. Do I actually need to construct a polynomial over $F$ with root $c^{-1}$ (presumably from the minimum polynomial of $c$)? Any hints would be appreciated. A: Note: If you just want algebraicity, please don't read this and see DonAntonio's answer. If $c\neq 0$ is algebraic over $F$, then $c^{-1}$ is algebraic over $F$. Moreover, $F[c^{-1}]=F[c]=F(c)$ and $c^{-1}$ has the same degree as $c$. Recall, that an element $d\in E$ is algebraic over $F$ if and only if $F[d]$ is a finite-dimensional vector space over $F$, whose dimension is the degree of $d$, i.e. the degree of its minimal polynomial. Indeed, it suffices to consider the evaluation $F[X]\longrightarrow F[d]$ and to mod out, in case $d$ is algebraic, by its kernel which is a principal ideal generated by the minimal polynomial. Let $P(x)$ be the minimal polynomial of $c$. i.e. the monic polynomial of minimal degree such that $P(c)=0$. Then write $P(x)=x^n+\ldots+a_1x+a_0$. If $a_0=0$, we get $$ c^n+\ldots+a_1c=c(c^{n-1}+\ldots+a_1)=0\quad\Rightarrow\quad c^{n-1}+\ldots+a_1=0. $$ This contradicts the minimality of $P$. So $a_0\neq 0$ and we have $$ a_0=-c^n-\ldots-a_1c\qquad\Rightarrow\qquad c^{-1}=-a_0^{-1}c^{n-1}-\ldots-a_0^{-1}a_1\in F[c]. $$ Therefore $F[c^{-1}]\subseteq F[c]$. So $F[c^{-1}]$ has finite dimension. It follows that $c^{-1}$ is algebraic over $F$. Applying the latter to $c^{-1}$ instead of $c$, we get $F[c]\subseteq F[c^{-1}]$, whence the equality. The fact that $F[c]= F[c^{-1}]$ is equal to $F(c)$ and that it is therefore a field follows easily from similar considerations: every nonzero element $d=Q(c)$ in $F[c]$ has $F[d]\subseteq F[c]$ finite dimensional, so it is algebraic and its inverse belongs to $F[d]$, hence to $F[c]$. So $F(c)\subseteq F[c]\subseteq F(c)$. A: Hints: for $\,c\neq 0\,$ (of course) $$0=f(c)=\sum_{k=0}^na_kc^k=c^n\sum_{k=0}^n\frac{a_k}{c^n}c^k\ldots$$
{ "pile_set_name": "StackExchange" }
Q: how to compare two dictionaries to check if a key is present in both of them I am trying to compare two dictionaries and check if each key in dict1 is present(or not) in either of dict2 or dict3 using the below logic? Is there a better way to check if any of the keys in dict1 are present in dict2 or dict3 and get the corresponding value? dict1 = {'1234': 'john','5678': 'james'}; dict2 = {'1234': 'technician'}; dict3 = {'5678': '50.23'}; shared_keys1 = set(dict1).intersection(dict2) shared_keys2 = set(dict1).intersection(dict3) for key in shared_keys1: print( "Found Shared Key:{0}".format(key) ) print( "dict1['{0}']={1}".format(key,dict2[key]) ) for key in shared_keys2: print( "Found Shared Key:{0}".format(key) ) print( "dict1['{0}']={1}".format(key,dict3[key]) ) OUTPUT:- Found Shared Key:1234 dict1['1234']=technici Found Shared Key:5678 dict1['5678']=50.23 A: in on a dict will return if a key is present in a dictionary: >>> a = {'b': 1, 'c': '2'} >>> 'b' in a True >>> 'd' in a False So your code could be written as: dict1 = {'1234': 'john','5678': 'james'}; dict2 = {'1234': 'technician'}; for key in dict1.keys(): print key if key in dict2: print dict1[key] + dict2[key] else: print dict1[key] If you just want to check that the two are equal, you can do: set(dict1) == set(dict2) A: shared_keys = set(dict1).intersection(dict2) is how I would do it >>> dict1 = {'1234': 'john','5678': 'james'} >>> dict2 = {'1234': 'technician'}; >>> set(dict1).intersection(dict2) set(['1234']) >>> if set(dict1).intersection(dict2): ... print "there is at least one key that is present in both dictionaries..." ... there is at least one key that is present in both dictionaries... if you wanted to check more dicts you just add them shared_keys = set(dict1).intersection(dict2).intersection(dict3) for key in shared_keys: print( "Found Shared Key:{0}".format(key) ) print( "dict1['{0}']={1}".format(key,dict1[key]) ) print( "dict2['{0}']={1}".format(key,dict2[key]) ) print( "dict3['{0}']={1}".format(key,dict3[key]) )
{ "pile_set_name": "StackExchange" }
Q: No error window in Dev cpp I am sorry for this silly doubt. But when I compile this program, it only shows error line. It does not show error window. (I have purposely made an error here, I know the correct solution in code ). I tried view section in menu bar, but couldn't find the solution. Any settings help will be appreciated. A: No need to be sorry.. it happens.. Right click the status bar Click on floating report window. A movable window will come up. Click on the inner tabbed close button. (You may have to right-click the report window to resize it and see the close button) After that just randomly resize the window so that it doesn't hide again. Happy Coding..!!! Edit - As @Alex suggested in one comment below - You probably hid Error window while you were changing it's size. So it's hidden between Editor window and Statusbar. Try to close Statusbar first (right mouse click -> Statusbar) and then stretch Error window to normal size (click and pull lower window bound up). This also works. :) A: Click the "View" at the top of the window. Then Click on the "Floating Report Window". A floating window will appear at the botton of the screen. Then Resize that floating Window. At last click on the inner tabbed close button. A: I had same problem. If you restart your devcpp you will see report bar(including compile log). But if you try to click it it will dissapear. The problem is that this window is shrunk in size to a bar. All you need is just after restarting devcpp click and stretch this bar to small size window.
{ "pile_set_name": "StackExchange" }
Q: Asp.Net Mvc4 WebSecurity How to activate or deactivate a user account I have create an account in mvc4 using the websecurity class as follow : WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { EmailAddress = model.EmailAddress, ContactNo = model.ContactNo, Password = model.Password }); My user have created successfully ... now i want to : activate/deactivate a user whenever i wish. so that user login only if his account is active otherwise he shouldn't be able to login . How can i achieve this? A: You can use UserProfile class for do it. This class located in the AccountModels class which acts as a profile table for each user account. It is here that you'd typically want to include a property named IsActive. [Table("UserProfile")] public class UserProfile { [key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } public string UserName { get; set; } public string LastName { get; set; } public string FirstName { get; set; } public string Email { get; set; } public bool IsActive { get; set; } } You can change IsActive property and check it in login action. See this post for more information.
{ "pile_set_name": "StackExchange" }
Q: Select all except list and it's title I have this chunk of HTML-page <div class="ProductDescriptionContainer"> <p>This handsome Clergy Shirt has a trim low neckband with two reinforced buttonholes, one at the front, one at the back, to align with Ziegler's Collarettes, Collars and Collar buttons. This clerical shirt also includes convertible cuffs which may be buttoned or used with cuff links, and a single breast pocket on a plain button front.&nbsp;All of Ziegler's neckband shirts are designed to be worn with a Parsons Brand Collar or under one of our Cleric-Collar Shirtfronts. Order Now! Neck Sizes Available: 15-20.5" Including Half Sizes Sleeve Lengths Available: Short &nbsp;/&nbsp;Clergy Shirt Colors: &nbsp;Black, White, Grey, Church Purple, Medium Blue, French Blue, Navy</p> <p style="text-align: left;"><strong>Clergy Shirt Details:&nbsp;</strong></p> <ul> <li>Neck Sizes Available: 15-20.5" Including Half Sizes</li> <li>Colors Available: Black, White, Grey, Church Purple, Medium Blue, French Blue, Navy</li> <li>Sleeve Lengths Available: Short</li> <li>Collar: Black Dress Neckband</li> <li>Made in the U.S.A</li> <li>Collars and Buttons sold Separately*</li> <li><a title="CLICK HERE FOR OUR SELECTION OF COLLARS AND COLLARETTES" href="http://www.zieglers.com/church-goods/apparel-and-vestments/collars-and-rabats/">CLICK HERE FOR OUR SELECTION OF COLLARS &amp; COLLARETTES</a></li> </ul> <p style="text-align: center;">*When buying a 2 ply collar or collarette for a neckband shirt it is best to order 1/2 size larger than the actual shirt you purchase for comfort.</p> <p style="text-align: center;"><span style="color: #ff0000;"><strong>*Note- Church Purple, French Blue, Grey, Medium Blue, Navy and White are not standard colors. Availability and ship time will vary on these colors*</strong></span></p> <p>&nbsp;</p> </div> And I need to select in HTML Agility pack all html except list and it's header right above it. I tried to play with following-sibling and preceding-sibling combining with not but it wasn't successful A: You can try LINQ, something like this: var doc = new HtmlAgilityPack.HtmlDocument(); doc.Load(string); var res = doc.DocumentNode.Descendants("p").Where(p => !p.ChildNodes.Any(c => c.Name.Equals("strong")); This will select all p elements that don't have child strong element. I know it's not what you want but this will give you an idea. You can use nextSibling and look for ul as well
{ "pile_set_name": "StackExchange" }
Q: Python: How to understand __new__ as defined in the built-in object class? First of all, this is not a duplication of Why is __init__ not called after __new__ SOMETIMES because this question really is about the implementation of the build-in object class. Here is the full story: I am learning about __new__ vs __init__ in python. Here is the example I've tried: class A(object): def __new__(cls): print("A.__new__ called") return super(A, cls).__new__(cls) def __init__(self): print("A.__init__ called") A() print('finished') The output is A.__new__ called A.__init__ called finished I understand that __new__ does object creation and __init__ does object initialization. __new__ is called automatically when calling the class name. Then __init__ is called every time an instance of the class is returned by __new__, passing the returned instance to __init__ as the self parameter. Knowing this, if we have a bad __new__ function that does not create and return an object instance, then __init__ would not be called: class A(object): def __new__(cls): print("A.__new__ called") #return super(A, cls).__new__(cls) def __init__(self): print("A.__init__ called") A() Note that the __new__ method only prints a string. It does not return anything so __init__ has nothing to pick up. And indeed the output confirms this: A.__new__ called finished "A.__init__ called" is never printed so __init__ is indeed never called. Now if we do not define a __new__ method (this is 99% of the common use case. programmers rarely need to define this method), then the father's __new__ is called by default. e.g. class A(object): def __init__(self): print("A.__init__ called") A() print('finished') output is: A.__init__ called finished In this case the __new__ of built-in object class is called. BUT, as I looked at the how the built-in object class is defined, I see this: class object: """ The most base type """ def __delattr__(self, *args, **kwargs): # real signature unknown """ Implement delattr(self, name). """ pass ... ... ... @staticmethod # known case of __new__ def __new__(cls, *more): # known special case of object.__new__ """ Create and return a new object. See help(type) for accurate signature. """ pass NOTHING is implemented in the __new__! There is just a pass sitting inside !!?? How is this making sense? A: Some of the Cpython implementation is written in C so PyCharm cannot navigate to the source code because it is compiled. However it can and does display stubs that emulate the signature. The source code for object.__new__ for 3.7.3 can be found in their Github repository: https://github.com/python/cpython/blob/v3.7.3/Objects/typeobject.c#L3671-L3732
{ "pile_set_name": "StackExchange" }
Q: UISplitViewController with MonoTouch.Dialog Using a UISplitViewController with MonoTouch.Dialog (DialogViewController) I am having issues when using the "back" button of the navigation controller: http://i.stack.imgur.com/LeykT.png There is a big animation on the detail side vertically from top to bottom. I uploaded a small MonoTouch sample to https://github.com/t9mike/MonoTouch-TabPlusNav1-Sample. [Since updated with fix] I am using the excellent MonoTouch.Dialog library, also on GitHub. The example references this. How I am creating the view controller for the first tab: var spit_view = new MySplitViewController(); spit_view.Delegate = new UISplitViewControllerDelegate(); spit_view.ViewControllers = new UIViewController[] { new MyNavigationController(), new DetailViewController("Tab #1") }; Add(UITabBarSystemItem.Search, spit_view); // custom method Is there a fix for the vertical animation when I pop navigation? Thanks. A: For you first question: Is there a fix for the vertical animation when I pop navigation? Look at: UINavigationController scrolls down on back button click Note that you have a better chance to get answers (and faster ones) if you split your questions :-)
{ "pile_set_name": "StackExchange" }
Q: How to validate SAML assertion signatures How to validate SAML assertion signatures? for (Assertion assertion : samlResponse.getAssertions()) { try { if (assertion.getSignature() != null) { Optional<X509Certificate> x509Certificate = assertion.getSignature().getKeyInfo().getX509Datas() .stream() .findFirst() .map(x509Data -> x509Data.getX509Certificates() .stream() .findFirst() .orElse(null) ); if (x509Certificate.isPresent()) { BasicX509Credential credential = new BasicX509Credential(); credential.setEntityCertificate(KeyInfoHelper.getCertificate(x509Certificate.get())); // what pub key credential to use here? SignatureValidator validator = new SignatureValidator(credential); validator.validate(assertion.getSignature()); } } } catch (ValidationException | CertificateException e) { throw new SAMLException(e.getMessage(), e); } } Basically what to put in new SignatureValidator(credential) As far as I understand, A SAML assertion with KeyInfo supplied and a X809 cert should at least validate (SAML: Why is the certificate within the Signature?) I also have an x509 cert from the idps metadata which I guess should general be used if there is no x509 cert in the assertion or within a trust chain (?) Basically neither the x509 cert in the assertion nor the cert from the idp metadata seems to work. What am I missing here? A: Turned out I did everything correctly. When printing an opensaml object xml you should NOT use the following code: public static String xmlObjectToString(XMLObject xmlObject) { try { Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(xmlObject); StringWriter sw = new StringWriter(); Element authDOM = marshaller.marshall(xmlObject); toString(sw, authDOM); return sw.toString(); } catch (Exception e) { throw new RuntimeException(e); } } private static void toString(StringWriter rspWrt, Element authDOM) throws ParserConfigurationException, TransformerException { DOMSource domSource = new DOMSource(authDOM); StreamResult result = new StreamResult(rspWrt); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); } The above code changes some internal states of the original object Instead go for org.opensaml.xml.util.XMLHelper.prettyPrintXML(message.getDOM())
{ "pile_set_name": "StackExchange" }
Q: how can I put all fetch requests in a Core Data DAL? Totally new to Objective-C and Core Data, coming from a .net background I really want to put all of my fetch requests into some sort of class that I can call, preferably statically to get my objects, something like: ObjectType *myObject = [CoreDataDAL GetObject:ID]; Anyone have a pattern to implement this? I am hacking my way through one right now but it's probably not quite right, will post code when I have it. EIDT: Here is my code as it stands right now - seems to work great - please rip it part if I am going down the wrong road - here is the basic DAL: #import "CoreDataDAL.h" #import "CoreDataAppDelegate.h" @implementation CoreDataDAL @synthesize managedObjectContext; -(id)init { if (self=[super init]) { CoreDataAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; self.managedObjectContext = appDelegate.managedObjectContext; } return self; } -(Client *) GetClient:(NSString *) ClientID{ /* Client Fetch Request */ NSFetchRequest *request = [[NSFetchRequest alloc]init]; NSEntityDescription *entityType = [NSEntityDescription entityForName:@"Client" inManagedObjectContext:managedObjectContext]; [request setEntity:entityType]; NSPredicate *predicate =[NSPredicate predicateWithFormat:@"ClientID==%@",ClientID]; [request setPredicate:predicate]; NSError *error; NSArray *entities = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; return [entities objectAtIndex:0]; } @end And here is how it is used in my view controllers: CoreDataDAL *dal = [[CoreDataDAL alloc]init]; Client *client = [dal GetClient:clientID]; [dal release]; Seems straight forward enough, thoughts? A: Don't do this; what you're doing is porting a pattern from one context to another where it doesn't really make sense. For one thing, you shouldn't be modeling IDs at all in Core Data; the framework does that for you with NSManagedObjectID already. Thus a -clientWithID: method on a CoreDataDAL class is redundant. (Note that I've also changed the name of your hypothetical method to follow proper Cocoa naming conventions.) Instead, you can just use -[NSManagedObjectContext objectWithID:] or -[NSManagedObjectContext existingObjectWithID:error:] to get an object based on its NSManagedObjectID. Similarly, relationship management is handled for you. You don't need to have a method in your DAL that can (say) fetch all of the Address instances that apply for a given Client by evaluating some query. You can just traverse your Client's to-many addresses relationship to get at them, and manipulate the same relationship directly (rather than setting foreign keys etc.). Finally, if you really do want to have methods to perform specialized queries, you can either specify the query via a fetched property on the appropriate entity for its results, or you can add that method directly to the appropriate class. Class methods in Objective-C aren't like static methods in C++, Java or C# - they can be overridden just as instance methods can, and are much more appropriate for this kind of use. For example, say your Client entity has a syncID property representing the ID of the object that it represents in some web service. (Note that this is specifically for relating a local object to a remote object, not the "primary key" of the local object.) You'd probably have class methods on the MyClient class associated with your Client entity like this: @implementation MyClient + (NSString *)entityClassName { return @"Client"; } + (NSEntityDescription *)entityInManagedObjectContext:(NSManagedObjectContext *)context { return [NSEntityDescription entityForName:[self entityClassName] inManagedObjectContext:context]; } + (MyClient *)clientWithSyncID:(NSString *)syncID inManagedObjectContext:(NSManagedObjectContext *)context error:(NSError **)error { MyClient *result = nil; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:[self entityInManagedObjectContext:context]]; [request setPredicate:[NSPredicate predicateWithFormat:@"syncID == %@", syncID]]; [request setFetchLimit:1]; NSArray *results = [context executeFetchRequest:request error:error]; if ([results count] > 0) { result = [results objectAtIndex:0]; } else { if (error != NULL) { *error = [NSError errorWithDomain:MyAppErrorDomain code:MyAppNoClientFoundError userInfo:nil]; } } return result; } @end This is similar to what you wrote in your DAL class, but instead of consolidating all of the fetches in one place, it puts the logic for fetches appropriate to a particular managed object class on that class, which is really where it belongs. Thanks to the fact Objective-C has true class methods, you can actually put methods like +entityInManagedObjectContext: and +entityClassName on a common base class and then override only the latter as appropriate in subclasses (or even have it generate an appropriate entity name from the class name). To sum up: Don't recreate what Core Data already implements for you in terms of things like object IDs, relationship management, and so on. Leverage polymorphism at both the instance and the class level to keep your code clean, rather than use "utility" classes like "data access layers."
{ "pile_set_name": "StackExchange" }
Q: How to Box a trait that has associated types? I'm very new to Rust so I may have terminology confused. I want to use the hashes crates to do some hashing and I want to dynamically pick which algorithm (sha256, sha512, etc.) to use at runtime. I'd like to write something like this: let hasher = match "one of the algorithms" { "sha256" => Box::new(Sha256::new()) as Box<Digest>, "sha512" => Box::new(Sha512::new()) as Box<Digest> // etc... }; I sort of get that that doesn't work because the associated types required by Digest aren't specified. If I attempt to fill them in: "sha256" => Box::new(Sha256::new()) as Box<Digest<<OutputSize = U32, BlockSize = U64>>>, I'm left with an error: the trait 'digest::Digest' cannot be made into an object. I think this approach will fail anyway because match will be returning slightly different types in cases where different algorithms have different associated types. Am I missing something obvious? How can I dynamically create an instance of something that implements a trait and then hold on to that thing and use it through the trait interface? A: The message refers to object safety (longer article). The Digest trait has two incompatibilities: It uses associated types (this can be worked around by explicitly setting all type parameters to values compatible for all Digest objects). It has a method (fn result(self) -> …) taking self by value. You won't be able to call it, which ruins usability of this trait. Once a trait object is created, information about its subtype-specific features such as memory layout or associated types is erased. All calls to the trait object's methods are done via a vtable pointer. This means they all must be compatible, and Rust can't allow you to call any methods that could vary in these aspects. A workaround is to create your custom wrapper trait/adapter that is object-compatible. I'm not sure if that's the best implementation, but it does work: trait Digest { type Assoc; fn result(self); } struct Sha; impl Digest for Sha { type Assoc = u8; fn result(self) {} } /////////////////////////////////////////// trait MyWrapper { fn result(&mut self); // can't be self/Sized } impl<T: Digest> MyWrapper for Option<T> { fn result(&mut self) { // Option::take() gives owned from non-owned self.take().unwrap().result() } } fn main() { let mut digest: Box<MyWrapper> = Box::new(Some(Sha)); digest.result(); }
{ "pile_set_name": "StackExchange" }
Q: Is there a Windows CMD equivalent of Unix shell's exec? Is there any equivalent in Windows to Unix Shell's "exec"? Basically, I need to avoid forking a new process, so that input/output pipes are preserved, as well as process id. Edit: So, here's my problem. I have a process A that starts a script, and this script ends by executing a process B. I need for A to get all of B's output, as well as be able to kill B by killing the process it has spawned (the script). On Unix, executing B with exec does that job. A: AFAIK there isn't. Windows lacks execv() which is how bash exec does it. call works for calling batch files (easy, just interpret the file in the current interpreter, similar to bash's . command) but not for exes. This makes it impossible to write one-liner wrapper scripts for scripts in any language on Windows. You'll always get that "Terminate batch job?" crap on Ctrl+C and killing the batch process (not with Ctrl+C, from task manager say) won't kill the child process. I'm now looking for a C template file to do this wrapping. UPDATE: Windows does have _execv() in its POSIX compatibility layer in MSVCRT, but AFAIK (haven't tested it) it's just a wrapper around CreateProcess so it will always create a new process, it cannot replace the current process.
{ "pile_set_name": "StackExchange" }
Q: Statistical sampling method I'm trying to work on a sample of Telecom customers dataset in order to create a churn prediction model in SAS. What is the best statistical sampling method that allows me only to extract the high value customers? A: Is this really a sampling question? If you already have a column in your data that contains a measure of customer value then a simple where clause may suffice. If, after filtering out low-value customers, you still want to do some sampling, proc surveyselect is usually the way to go for sampling tasks within SAS. It has various sampling methods you can use. Read the documentation and choose one that's right for you. For advice on the choice of statistical technique, I recommend you post a question on https://www.crossvalidated.com
{ "pile_set_name": "StackExchange" }
Q: Python performance: iteration and operations on nested lists Problem Hey folks. I'm looking for some advice on python performance. Some background on my problem: Given: A (x,y) mesh of nodes each with a value (0...255) starting at 0 A list of N input coordinates each at a specified location within the range (0...x, 0...y) A value Z that defines the "neighborhood" in count of nodes Increment the value of the node at the input coordinate and the node's neighbors. Neighbors beyond the mesh edge are ignored. (No wrapping) BASE CASE: A mesh of size 1024x1024 nodes, with 400 input coordinates and a range Z of 75 nodes. Processing should be O(x*y*Z*N). I expect x, y and Z to remain roughly around the values in the base case, but the number of input coordinates N could increase up to 100,000. My goal is to minimize processing time. Current results Between my start and the comments below, we've got several implementations. Running speed on my 2.26 GHz Intel Core 2 Duo with Python 2.6.1: f1: 2.819s f2: 1.567s f3: 1.593s f: 1.579s f3b: 1.526s f4: 0.978s f1 is the initial naive implementation: three nested for loops. f2 is replaces the inner for loop with a list comprehension. f3 is based on Andrei's suggestion in the comments and replaces the outer for with map() f is Chris's suggestion in the answers below f3b is kriss's take on f3 f4 is Alex's contribution. Code is included below for your perusal. Question How can I further reduce the processing time? I'd prefer sub-1.0s for the test parameters. Please, keep the recommendations to native Python. I know I can move to a third-party package such as numpy, but I'm trying to avoid any third party packages. Also, I've generated random input coordinates, and simplified the definition of the node value updates to keep our discussion simple. The specifics have to change slightly and are outside the scope of my question. thanks much! f1 is the initial naive implementation: three nested for loops. def f1(x,y,n,z): rows = [[0]*x for i in xrange(y)] for i in range(n): inputX, inputY = (int(x*random.random()), int(y*random.random())) topleft = (inputX - z, inputY - z) for i in xrange(max(0, topleft[0]), min(topleft[0]+(z*2), x)): for j in xrange(max(0, topleft[1]), min(topleft[1]+(z*2), y)): if rows[i][j] <= 255: rows[i][j] += 1 f2 is replaces the inner for loop with a list comprehension. def f2(x,y,n,z): rows = [[0]*x for i in xrange(y)] for i in range(n): inputX, inputY = (int(x*random.random()), int(y*random.random())) topleft = (inputX - z, inputY - z) for i in xrange(max(0, topleft[0]), min(topleft[0]+(z*2), x)): l = max(0, topleft[1]) r = min(topleft[1]+(z*2), y) rows[i][l:r] = [j+(j<255) for j in rows[i][l:r]] UPDATE: f3 is based on Andrei's suggestion in the comments and replaces the outer for with map(). My first hack at this requires several out-of-local-scope lookups, specifically recommended against by Guido: local variable lookups are much faster than global or built-in variable lookups I hardcoded all but the reference to the main data structure itself to minimize that overhead. rows = [[0]*x for i in xrange(y)] def f3(x,y,n,z): inputs = [(int(x*random.random()), int(y*random.random())) for i in range(n)] rows = map(g, inputs) def g(input): inputX, inputY = input topleft = (inputX - 75, inputY - 75) for i in xrange(max(0, topleft[0]), min(topleft[0]+(75*2), 1024)): l = max(0, topleft[1]) r = min(topleft[1]+(75*2), 1024) rows[i][l:r] = [j+(j<255) for j in rows[i][l:r]] UPDATE3: ChristopeD also pointed out a couple improvements. def f(x,y,n,z): rows = [[0] * y for i in xrange(x)] rn = random.random for i in xrange(n): topleft = (int(x*rn()) - z, int(y*rn()) - z) l = max(0, topleft[1]) r = min(topleft[1]+(z*2), y) for u in xrange(max(0, topleft[0]), min(topleft[0]+(z*2), x)): rows[u][l:r] = [j+(j<255) for j in rows[u][l:r]] UPDATE4: kriss added a few improvements to f3, replacing min/max with the new ternary operator syntax. def f3b(x,y,n,z): rn = random.random rows = [g1(x, y, z) for x, y in [(int(x*rn()), int(y*rn())) for i in xrange(n)]] def g1(x, y, z): l = y - z if y - z > 0 else 0 r = y + z if y + z < 1024 else 1024 for i in xrange(x - z if x - z > 0 else 0, x + z if x + z < 1024 else 1024 ): rows[i][l:r] = [j+(j<255) for j in rows[i][l:r]] UPDATE5: Alex weighed in with his substantive revision, adding a separate map() operation to cap the values at 255 and removing all non-local-scope lookups. The perf differences are non-trivial. def f4(x,y,n,z): rows = [[0]*y for i in range(x)] rr = random.randrange inc = (1).__add__ sat = (0xff).__and__ for i in range(n): inputX, inputY = rr(x), rr(y) b = max(0, inputX - z) t = min(inputX + z, x) l = max(0, inputY - z) r = min(inputY + z, y) for i in range(b, t): rows[i][l:r] = map(inc, rows[i][l:r]) for i in range(x): rows[i] = map(sat, rows[i]) Also, since we all seem to be hacking around with variations, here's my test harness to compare speeds: (improved by ChristopheD) def timing(f,x,y,z,n): fn = "%s(%d,%d,%d,%d)" % (f.__name__, x, y, z, n) ctx = "from __main__ import %s" % f.__name__ results = timeit.Timer(fn, ctx).timeit(10) return "%4.4s: %.3f" % (f.__name__, results / 10.0) if __name__ == "__main__": print timing(f, 1024, 1024, 400, 75) #add more here. A: On my (slow-ish;-) first-day Macbook Air, 1.6GHz Core 2 Duo, system Python 2.5 on MacOSX 10.5, after saving your code in op.py I see the following timings: $ python -mtimeit -s'import op' 'op.f1()' 10 loops, best of 3: 5.58 sec per loop $ python -mtimeit -s'import op' 'op.f2()' 10 loops, best of 3: 3.15 sec per loop So, my machine is slower than yours by a factor of a bit more than 1.9. The fastest code I have for this task is: def f3(x=x,y=y,n=n,z=z): rows = [[0]*y for i in range(x)] rr = random.randrange inc = (1).__add__ sat = (0xff).__and__ for i in range(n): inputX, inputY = rr(x), rr(y) b = max(0, inputX - z) t = min(inputX + z, x) l = max(0, inputY - z) r = min(inputY + z, y) for i in range(b, t): rows[i][l:r] = map(inc, rows[i][l:r]) for i in range(x): rows[i] = map(sat, rows[i]) which times as: $ python -mtimeit -s'import op' 'op.f3()' 10 loops, best of 3: 3 sec per loop so, a very modest speedup, projecting to more than 1.5 seconds on your machine - well above the 1.0 you're aiming for:-(. With a simple C-coded extensions, exte.c...: #include "Python.h" static PyObject* dopoint(PyObject* self, PyObject* args) { int x, y, z, px, py; int b, t, l, r; int i, j; PyObject* rows; if(!PyArg_ParseTuple(args, "iiiiiO", &x, &y, &z, &px, &py, &rows )) return 0; b = px - z; if (b < 0) b = 0; t = px + z; if (t > x) t = x; l = py - z; if (l < 0) l = 0; r = py + z; if (r > y) r = y; for(i = b; i < t; ++i) { PyObject* row = PyList_GetItem(rows, i); for(j = l; j < r; ++j) { PyObject* pyitem = PyList_GetItem(row, j); long item = PyInt_AsLong(pyitem); if (item < 255) { PyObject* newitem = PyInt_FromLong(item + 1); PyList_SetItem(row, j, newitem); } } } Py_RETURN_NONE; } static PyMethodDef exteMethods[] = { {"dopoint", dopoint, METH_VARARGS, "process a point"}, {0} }; void initexte() { Py_InitModule("exte", exteMethods); } (note: I haven't checked it carefully -- I think it doesn't leak memory due to the correct interplay of reference stealing and borrowing, but it should be code inspected very carefully before being put in production;-), we could do import exte def f4(x=x,y=y,n=n,z=z): rows = [[0]*y for i in range(x)] rr = random.randrange for i in range(n): inputX, inputY = rr(x), rr(y) exte.dopoint(x, y, z, inputX, inputY, rows) and the timing $ python -mtimeit -s'import op' 'op.f4()' 10 loops, best of 3: 345 msec per loop shows an acceleration of 8-9 times, which should put you in the ballpark you desire. I've seen a comment saying you don't want any third-party extension, but, well, this tiny extension you could make entirely your own;-). ((Not sure what licensing conditions apply to code on Stack Overflow, but I'll be glad to re-release this under the Apache 2 license or the like, if you need that;-)).
{ "pile_set_name": "StackExchange" }
Q: Why do I get "error: too few arguments to function ‘sock->ops->accept’" I am writing kernel module with sockets. When I try write code for accept connection I get: "error: too few arguments to function ‘sock->ops->accept’ ret = sock->ops->accept(sock, client_sock, 0);" I looked into implementation of socket accept and there are only three arguments so I don't know what's going on. struct socket *sock = NULL, *client_sock = NULL; //some code here, create socket, bind, listen ret = sock->ops->accept(sock, client_sock, 0); I expect that it should works but it doesn't. Why do I get "too few arguments" error if in implementation are only three? How can I fix that? A: The prototype of the ->accept() handler was changed between kernel versions 4.10 and 4.11 by this commit: "net: Work around lockdep limitation in sockets that use sockets". As mentioned in user MofX's answer, the ->accept() handler has a fourth parameter bool kern in current kernel versions (since 4.11). According to the commit description, this is analogous to the kern parameter passed in to ->create(), and distinguishes whether kernel_accept() or sys_accept4() was the caller. See the commit description for details. If you want your code to work for kernels both before and since 4.11, you will need to use conditional compilation: #include <linux/version.h> #if LINUX_VERSION_CODE >= KERNEL_VERSION(4,11,0) #define KV_ACCEPT_HAS_BOOL_KERN #endif #ifdef KV_ACCEPT_HAS_BOOL_KERN // your code needs to determine whether 'kern' should be false or true here... ret = sock->ops->accept(sock, client_sock, 0, kern); #else ret = sock->ops->accept(sock, client_sock, 0); #endif A: There are four arguments in proto_ops::accept struct proto_ops { ... int (*accept) (struct socket *sock, struct socket *newsock, int flags, bool kern); }; See: https://elixir.bootlin.com/linux/latest/source/include/linux/net.h#L147
{ "pile_set_name": "StackExchange" }
Q: ColdFusion 2016 Installation I can't run ColdFusion 2016 after installed. I open terminal window and type in this command: /Applications/Coldfusion2016/cfusion/bin/coldfusion start After that, it prompted me to type the command: sudo ./coldfusion start You must be the root user to configure the ColdFusion connector. Start ColdFusion as "sudo ./coldfusion start" to configure the connector. Once connector has been configured, start ColdFusion as "./coldfusion start" to run ColdFusion as non-root user". I did all the steps however it failed to run. Can anyone help me with this problem? I greatly appreciate your answer. A: You literally need to add the sudo command to the beginning of your start command. MacOS is requiring admin access to start the server. sudo /Applications/Coldfusion2016/cfusion/bin/coldfusion start When this runs, you'll be prompted for your admin password before it starts.
{ "pile_set_name": "StackExchange" }
Q: How to concatenate values into distinct comma separated values in excel Name Class1 Class2 Class3 Class4 XYZ LLC INC1 INC2 INC1 ABC Inc INC4 INC1 INC2 INC1 ZZZ InC INC Result Name Combine XYZ LLC INC1,INC2 ABC Inc INC4,INC1,INC2 ZZZ Inc INC A: Use a simple TEXTJOIN: =TEXTJOIN(",",TRUE,B2:E2)
{ "pile_set_name": "StackExchange" }
Q: How to manually create text summaries in TensorFlow? First of all, I already know how to manually add float or image summaries. I can construct a tf.Summary protobuf manually. But what about text summaries? I look at the definition for summary protobuf here, but I don't find a "string" value option there. A: TensorBoard's text plugin offers a pb method that lets you create text summaries outside of a TensorFlow environment. https://github.com/tensorflow/tensorboard/blob/master/tensorboard/plugins/text/summary.py#L74 Example usage: import tensorboard as tb text_summary_proto = tb.summary.pb('fooTag', 'text data')
{ "pile_set_name": "StackExchange" }
Q: Inbuilt search and relationship field Does the inbuilt search search through the relationship fields? I am using simple_form A: No, the Search module will not look in any related entries when determining if your search terms match a particular entry.
{ "pile_set_name": "StackExchange" }
Q: Problemas con Deploy NodeJS a Heroku Tengo esta situación, tengo un proyecto montado en Heroku y lo actualizo vía git, pero de un tiempo para acá no me deja hacerle git push heroku master me tira este error, he tratado de hacer varias cosas, pero el error persiste , ¿alguien sabe a qué se deba? npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! [email protected] install: `node-pre-gyp install --fallback-to-build` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the [email protected] install script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /tmp/npmcache.ZJa3F/_logs/2019-11-16T01_27_11_336Z-debug.log -----> Build failed We're sorry this build is failing! You can troubleshoot common issues here: https://devcenter.heroku.com/articles/troubleshooting-node-deploys If you're stuck, please submit a ticket so we can help: https://help.heroku.com/ Love, Heroku ! Push rejected, failed to compile Node.js app. ! Push failed Configuración del puerto en la aplicación: app.set('port', process.env.PORT || 4000); //puerto y asì app.listen(app.get('port'), () => { console.log('App listening on port ${app.get('port')}'); //console.log(hostname) }); A: Quiero empezar indicando que esta respuesta no intenta responder el porque del error, sino que apunta a señalar porque no es recomendable utilizar SQLite en Heroku. A continuación cito un fragmento traducido del artículo SQLite on Heroku: [...] SQLite se ejecuta en la memoria y realiza una copia de seguridad de su almacén de datos en archivos en el disco. Si bien esta estrategia funciona bien para el desarrollo, la pila Cedar de Heroku tiene un sistema de archivos efímero. Puede escribirle y leerlo, pero el contenido se borrará periódicamente. Si usara SQLite en Heroku, perdería toda su base de datos al menos una vez cada 24 horas. Incluso si los discos de Heroku fueran persistentes ejecutando SQLite, no encajaría bien. Como SQLite no se ejecuta como un servicio, cada banco de pruebas ejecutaría una copia de ejecución separada. Cada una de estas copias necesita su propia tienda con respaldo de disco. Esto significaría que cada dyno que alimenta su aplicación tendría un conjunto diferente de datos ya que los discos no están sincronizados.[...] En otras palabras, salvo algún caso de uso muy especial, no es una buena idea utilizar SQLite en Heroku. A: Ya ha pasado mucho y habia olvidado contestar esta pregunta, pero en resumen, el problema aqui es que estaba tratando de subir en mi commit la carpeta node_modules, asi que la respuesta fue muy simple. git rm -r --cached node_modules Y listo. Todo bien con mi deploy.
{ "pile_set_name": "StackExchange" }
Q: ReactJS: setState on parent inside child component What is the recommended pattern for doing a setState on a parent from a child component. var Todos = React.createClass({ getInitialState: function() { return { todos: [ "I am done", "I am not done" ] } }, render: function() { var todos = this.state.todos.map(function(todo) { return <div>{todo}</div>; }); return <div> <h3>Todo(s)</h3> {todos} <TodoForm /> </div>; } }); var TodoForm = React.createClass({ getInitialState: function() { return { todoInput: "" } }, handleOnChange: function(e) { e.preventDefault(); this.setState({todoInput: e.target.value}); }, handleClick: function(e) { e.preventDefault(); //add the new todo item }, render: function() { return <div> <br /> <input type="text" value={this.state.todoInput} onChange={this.handleOnChange} /> <button onClick={this.handleClick}>Add Todo</button> </div>; } }); React.render(<Todos />, document.body) I have an array of todo items which is maintained in the parent's state. I want to access the parent's state and add a new todo item, from the TodoForm's handleClick component. My idea is to do a setState on the parent, which will render the newly added todo item. A: In your parent, you can create a function like addTodoItem which will do the required setState and then pass that function as props to the child component. var Todos = React.createClass({ ... addTodoItem: function(todoItem) { this.setState(({ todos }) => ({ todos: { ...todos, todoItem } })); }, render: function() { ... return <div> <h3>Todo(s)</h3> {todos} <TodoForm addTodoItem={this.addTodoItem} /> </div> } }); var TodoForm = React.createClass({ handleClick: function(e) { e.preventDefault(); this.props.addTodoItem(this.state.todoInput); this.setState({todoInput: ""}); }, ... }); You can invoke addTodoItem in TodoForm's handleClick. This will do a setState on the parent which will render the newly added todo item. Hope you get the idea. Fiddle here. A: These are all essentially correct, I just thought I would point to the new(ish) official react documentation which basically recommends:- There should be a single “source of truth” for any data that changes in a React application. Usually, the state is first added to the component that needs it for rendering. Then, if other components also need it, you can lift it up to their closest common ancestor. Instead of trying to sync the state between different components, you should rely on the top-down data flow. See https://reactjs.org/docs/lifting-state-up.html. The page also works through an example. A: You could create an addTodo function in the parent component, bind it to that context, pass it to the child component and call it from there. // in Todos addTodo: function(newTodo) { // add todo } Then, in Todos.render, you would do <TodoForm addToDo={this.addTodo.bind(this)} /> Call this in TodoForm with this.props.addToDo(newTodo);
{ "pile_set_name": "StackExchange" }
Q: What Is difference between .net core 2.2, 3.0, and 3.1? can someone please tell me what are the breaking changes in dotnet core 3.1? A: Forgive me for sounding annoyed, but Googling for ".net core changelist" returns these results immediately: https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0 https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-2-2 https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-2-1 Each of these pages says exactly what's changed and added. Now, finding differences between .NET Core 3.0 and 3.1 is harder - I admit - as it's still in Preview so the postings only detail the changes between Preview releases, however the Preview 1 release notes( https://github.com/dotnet/core/blob/master/release-notes/3.1/preview/3.1.0-preview1.md ) do list the Notable changes indirectly via links to tagged GitHub issues at the bottom. .NET Core 3.1 CLR non-bugfix changes: https://github.com/dotnet/coreclr/issues?q=is%3Aissue+milestone%3A3.1+label%3Aenhancement .NET Core 3.1 BCL non-bugfix changes: https://github.com/dotnet/corefx/issues?q=is%3Aissue+milestone%3A3.1+label%3Aenhancement .NET Core 3.1 ASP.NET Core non-bugfix changes: https://github.com/aspnet/AspNetCore/issues?q=is%3Aissue+milestone%3A3.1.0-preview1+label%3ADone+label%3Aenhancement
{ "pile_set_name": "StackExchange" }
Q: obtener textbox de ventana modal en otra nueva alguien sabe como obtener el valor de una caja de texto de una ventana modal en otra nueva ventana modal? tengo una ventana modal que tiene dos botones, tambien tengo un valor clave en un textbox que necesito recuperar en otra ventana modal para procesar ese valor, trataba de pasar el valor en el evento clic de un boton con el siguiente codigo $("#btnno").click(function () { $('#modalPregunta').modal('hide'); $('#modalNo').modal('show',$("#valor").val()); }); y lo recuperaba asi $('#modal').on('show.bs.modal', function (evnt) { var btn = $(evnt.relatedTarget); console.log( btn); }); pero al debuguearlo no me obtiene ningun valor A: Efectivamente puedes obtener el valor de la primer ventana modal utilizando JQuery o JavaScript. Con JQuery se usa $('#elementoID').val(); esto obtiene el valor del elemento con el ID "elementoID", dado que las ventanas modales no pierden sus valores al cerrase el valor seguirá presente en el elemento aunque esté oculta, otra alternativa puede ser almacenar el valor que requieres de la primer ventana modal en una variable global en caso de ser requerida y más adelante en tu código solamente usas el valor de esa variable.
{ "pile_set_name": "StackExchange" }
Q: "Error: Token Mismatch" After adding a 2nd server to phpMyAdmin I've been searching and trying to solve this problem for about 3 weeks. I'm stumped. Please help! I added a second server to phpMyAdmin by adding the following lines to the end of my "config.inc.php" file in the installation directory. $i++; $cfg['Servers'][$i]['verbose'] = '<SERVER 2 NAME REDACTED>'; $cfg['Servers'][$i]['host'] = '<SERVER 2 ADDRESS REDACTED>.rds.amazonaws.com'; $cfg['Servers'][$i]['connect_type'] = 'tcp'; $cfg['Servers'][$i]['compress'] = false; $cfg['Servers'][$i]['auth_type'] = 'cookie'; $cfg['Servers'][$i]['AllowNoPassword'] = false; $cfg['Servers'][$i]['ssl'] = false; After I added this server, we started getting the "Error: Token Mismatch" popup randomly when running some SQL queries or performing certain actions while logged in to server #2. We never got it on the first server we had set up for several years, and I matched all the server configuration settings to those of the first server. The issue is not 100% reproducible with SQL queries, but it does seem to be 100% reproducible when I try to add users to the database via phpMyAdmin's user creation page. Steps: log in (select server #2 in the "Server Choice" drop-down menu) click "users" tab at top of page click "add user" link fill out the required fields and click "go" At this point I always get the "Error: Token Mismatch" popup. Things I've tried so far: clear cache / cookies (I do this every time I change settings) use different browser (tried Chrome, Firefox, and Safari) change ";session.save_path" variable to “/tmp” in php.ini file Do "chmod 1733" on the sessions save directory Made sure there is free space available (19GB free) After all this, we still get the error. Software: PHP: 5.3.29 Apache: 2.2.23 (Amazon) SQL type: 10.1.23-MariaDB Database client version: libmysql - 5.5.24 PHP extension: mysqli phpMyAdmin: 4.2.2 Hardware: phpMyadmin server hardware: Amazon EC2 m3.large SQL database server hardware: db.m4.2xlarge Any suggestions for places to look or things to try are greatly appreciated. A: One thing that caught my eye is that you mention the ;session.save_path variable; the semicolon in front of it is a comment so for the directive to be recognized you'll have to remove the semicolon. Check the output of phpinfo.php to verify that the change was successful. Other than that, it's tough to guess. You're using an old PHP and old phpMyAdmin version, so I'm not saying an upgrade will or won't fix the problem, but you really should upgrade. One workaround would be to have two phpMyAdmin installations; you can have phpMyAdmin in two different folders, with each one pointing to a different MySQL server. It sounds like it was working fine with one server so if you do it this way, each instance will only have one server and hopefully you won't have the problem.
{ "pile_set_name": "StackExchange" }
Q: Why does Recycle Bin say 16 but I only have 15 items? From the Site Contents page the Recycle Bin has 16 next to it. However, when I go into the Recycle Bin there are only 15 items. Does anyone know why? Thanks A: This is because you dont have permission to see others document. If you are site collection admin then you can everything in both 1st and 2nd stage recyclebin.
{ "pile_set_name": "StackExchange" }
Q: How to authenticate to Google Cloud API without Application Default Credentials or Cloud SDK? I'm trying to access the Google Cloud API from an AWS Lambda function but I don't know how to authenticate. The auth guide in the Google Cloud documentation (https://cloud.google.com/docs/authentication) wants me to download a credentials JSON file and use Application Default Credentials, but as anyone who has used hosted functions already knows, the point is that you don't need to manage a server or runtime environment, so Lambda doesn't give me the ability to store arbitrary files in the environment of the running code. I can use the Cloud SDK locally to get an access token but it expires so I can't use it in my function as a permanent solution. Is there not a way I can get an access token that I can use indefinitely in my code to call the Google Cloud API? Is there any other solution? A: I found how to hard-code the credentials without the need to save them in a JSON file. It was in this documentation here: https://googlecloudplatform.github.io/google-cloud-node/#/docs/language/0.7.0/guides/authentication Below is an example that calls the Language API. var language = require('@google-cloud/language')({ projectId: '', credentials: { client_email: '', private_key: '', } }); language.detectEntities('Axel Foley is from Detroit').then(function(data) { var entities = data[0]; var apiResponse = data[1]; });
{ "pile_set_name": "StackExchange" }
Q: Ошибка с string Здравствуйте. Недавно начал копать С++ и просто решив поэкспериментировать написал следующий код: #include <iostream> int main() { std::string text; std::cout << "Enter text: "; std::cin >> text; std::cout << "Text : " << text; } После чего среда написала возле каждого << и >>, где находилась переменная text, следующее: Error: отсутствует оператор "<<", соответствующий этим операндам Я не придал этому значение и откомпилировал. После чего компилятор выдал мне страшную ошибку. Вот одна только первая её строчка (всю писать я не стал ибо очень большая): [путь]code\code.cpp(10): error C2678: бинарный ">>": не найден оператор, принимающий левый операнд типа "std::istream" (или приемлемое преобразование отсутствует) [путь]\include\istream(1053): может быть "std::basic_istream<_Elem,_Traits> &std::operator >>>(std::basic_istream<_Elem,_Traits> &&,signed char *) [путь]code\code.cpp(10): error C2678: бинарный ">>": не найден оператор, принимающий левый операнд типа "std::istream" (или приемлемое преобразование отсутствует) [путь]include\istream(1053): может быть "std::basic_istream<_Elem,_Traits> &std::operator >>>(std::basic_istream<_Elem,_Traits> &&,signed char *)"` [путь] — путь к корневой папке студии или проекта. Вопрос: Где у меня ошибка и что я сделал неправильно? И конечно же как это исправить? A: #include <string>
{ "pile_set_name": "StackExchange" }
Q: Passing data from ng-Dialog html to controller have some trouble with ng-Dialog. When i note ngDialog controller option, it works. I can get $scope.descriptionText value from <p>Description:</p> <textarea ng-model="descriptionText"></textarea> now i call dialog witout parametr controller ngDialog.open({ template: 'views/pages/timesheet/template/newEventTemplate.html', //controller:'newEventDialogCtrl', scope: $scope, ... and this value $scope.descriptionText is undefined. Please help me return values of html element to my controler, or to controller scope. Dialog call code: $scope.createNewEventModalWindow = function(args) { $scope.setNewEventField('start', args.start.value); $scope.setNewEventField('end', args.end.value); ngDialog.open({ template: 'views/pages/timesheet/template/newEventTemplate.html', //controller:'newEventDialogCtrl', scope: $scope, className: 'ngdialog-theme-default', plain: false, showClose: true, closeByDocument: true, closeByEscape: true, appendTo: false, disableAnimation: false, overlay: false }).closePromise.then(function(value) { console.log('Test msg'); console.log(value); var newEvent = { start: $scope.getNewEventField('start'), end: $scope.getNewEventField('end'), text: $scope.descriptionText, userID: getCurrentUserID(), projectID: $scope.selectedProject, taskID: $scope.selectedTask }; console.log('Event data to server'); console.log(newEvent); /* TimesheetFactory.createEvent(newEvent) .success(function(data) { $scope.events = data; $scope.message('Event created'); console.log($scope.events); }) .error(function(data) { console.log('Error: ' + data); }); */ }); } Html template for dialog: <div class="ngdialog-message"> <h3>Create Event</h3> <p>Project</p> <select id='selectProject' ng-model= "selectedProject"> <option ng-repeat="project in projects" value="{{project.id}}">{{project.name}}</option> </select> <p>Task</p> <select id='selectTask' ng-model="selectedTask"> <option ng-repeat="task in tasks" value="{{task.id}}">{{task.name}}</option> </select> <p>Time</p> <input type="time" id="eventTime" name="input" ng-model="timeLentgh"/> <p>Description:</p> <textarea ng-model="descriptionText"></textarea> </div> <div class="ngdialog-buttons"> <button type="button" class="ngdialog-button ngdialog-button-secondary" ng-click="closeThisDialog()" >Cancel</button> <button type="button" class="ngdialog-button ngdialog-button-primary" ng-click="btnCreateEventClicked()" >Create</button> </div> A: You can access dialog's scope this way: value.$dialog.scope() Where value - argument you get from closePromise. In this cope you'll have descriptionText for example. Plunker to check and play: http://plnkr.co/edit/nTNwAxyL1KGuvKGAeTmy?p=preview
{ "pile_set_name": "StackExchange" }
Q: Why do we have to use the as operator to call the GetScreenshot method In the C# code below, where we're taking a screenshot using the Firefox webdriver, why do we have to use the as operator to call the GetScreenshot method? IWebDriver driver = new FirefoxDriver(); driver.Url = "http://www.google.com"; ITakesScreenshot screenshotDriver = driver as ITakesScreenshot; Screenshot screenShot = screenshotDriver.GetScreenshot(); screenShot.SaveAsFile( screenshotFileName, System.Drawing.Imaging.ImageFormat.Png); FirefoxDriver inherits the RemoteWebDriver class and implements the ITakesScreenshot interface. The interface methods implemented by RemoteWebDriver can be called directly without having to use the as operator on FirefoxDriver objects. The GetScreenshot method is implemented in FirefoxDriver.cs as shown: public class FirefoxDriver : RemoteWebDriver, ITakesScreenshot { //... public Screenshot GetScreenshot() { // Get the screenshot as base64. Response screenshotResponse = Execute(DriverCommand.Screenshot, null); string base64 = screenshotResponse.Value.ToString(); // ... and convert it. return new Screenshot(base64); } } Shouldn't we be able to simply call this method like driver.GetScreenshot()? C# Language Specification document states that explicit interface members can only be accessed via the interface type but I don't see how that applies to the GetScreenshot method here. In the previous EditBox class, the Paint method from the IControl interface and the Bind method from the IDataBound interface are implemented using public members. C# also supports explicit interface member implementations, using which the class or struct can avoid making the members public. An explicit interface member implementation is written using the fully qualified interface member name. For example, the EditBox class could implement the IControl.Paint and IDataBound.Bind methods using explicit interface member implementations as follows. public class EditBox : IControl, IDataBound { void IControl.Paint() {...} void IDataBound.Bind(Binder b) {...} } Explicit interface members can only be accessed via the interface type. For example, the implementation of IControl.Paint provided by the previous EditBox class can only be invoked by first converting the EditBox reference to the IControl interface type. EditBox editBox = new EditBox(); editBox.Paint(); // Error, no such method IControl control = editBox; control.Paint(); Why the as operator is necessary in order for us to call the GetScreenshot method? A: Because it is implemented in FirefoxDriver and enforced by the ITakeScreenshot interface. You've declared it as IWebDriver. Since your variable is of type IWebDriver you cannot call a FirefoxDriver method on it. Therefore, they cast it to ITakeScreenshot. To do what you want.. you could do this: FirefoxDriver driver = new FirefoxDriver(); // make it a FirefoxDriver driver.Url = "http://www.google.com"; ITakesScreenshot screenshotDriver = driver; // no cast. Not needed. Screenshot screenShot = screenshotDriver.GetScreenshot(); You can simply use driver.GetScreenshot() as long as your variable is declared as FirefoxDriver.. not IWebDriver as it is currently.
{ "pile_set_name": "StackExchange" }
Q: html form hidden variable not showing in php I have a HTML form that submits to PHP. There is an onChange event on a drop down box that calls a JavaScript function which writes a hidden variable into the form. This additional hidden variable doesnt show up in PHP though, why is this? So; <script language="JavaScript"> function change() { document.getElementById("myDiv").innerHTML="<input type=\"hidden\" name=\"blah\" value=\"1\"/>"; return; } </script> <form method="post" action="test.php" /> <select name="cid" id="cid" onChange="change();"> <option value="lala">lala</option> </select> <div id="myDiv"></div> </form> PHP doesn't see $_POST['blah']? A: A more logical solution anyway would be to just add the hidden field to your form, and set the value to 1 in the onChange function.
{ "pile_set_name": "StackExchange" }
Q: Calculated Formula to mirror status I have created a custom list with a dropdown field called Project Status with the following options Unassigned Work in Progress Hold Dropped Completed I have also created another hidden field which is called current status with the following calculation =IF([Project Status]="Dropped","Dropped", IF([Project Status]="Work in Progress","Work in Progress", IF([Project Status]="Hold","Hold", IF([Project Status]="Completed","Completed")))) but the calculation is not working as the Current Status field isn't been populated when I update the Project Status field This is part of larger workflow A: You need not to do all this. you just need write below formula for your field Current Status. =[Project Status] Since you just need replica, you can use the column value as is.
{ "pile_set_name": "StackExchange" }
Q: Camel File Poller of a Mounted CIFS We're experiencing a strange problem. We have a file component monitoring a folder. This works perfectly if the path is either a) myrelativepath - which is relative to the Karaf installation where the camel route is run; or b) /tst/mypath - which reads from a folder from the root If I set log level to DEBUG I see the logs of it polling based on my interval. However, if I set the path to be: /mnt/windowsshare - which is a mounted windows share. I get nothing in the logs, I don't see the poll, and it doesn't pick up any files. apparently the route is started though. Interestingly, I have another camel route which writes a file to that location (a subfolder called inbound) and it writes file with no problem. Any ideas? I can get perhaps more logs tomorrow, but this is only happening in this environment where we have a windows share. And the share seems to be fine. For testing we have run Camel as root and as root on the commandline we have tested reading the files (via vi) and all is ok. Any suggestions for things to look at? A: Basically make sure you don't have too many files in the antexlcude...polling is logarithmic and a fraction more makes polling very slow. Needs more code analysis and VM introspection to understand why.
{ "pile_set_name": "StackExchange" }
Q: Building a table with the values of children whose parents only have siblings with particular attribute values I apologize for all of the code, but I couldn't eliminate any more without muddling the clarity of the question. Suppose I have this XML: <Dataset> <Rec RN="FOO"> <Fld FN="ID">ID_1</Fld> <Fld FN="OPT">0</Fld> <Fld FN="DESCRIPTION">DESCRIPTION_1</Fld> </Rec> <Rec RN="BAR" RC="3"> <Fld FN="ID">ID_2</Fld> <Fld FN="TYPE">TYPE_1</Fld> </Rec> <Rec RN="BAR"> <Fld FN="ID">ID_3</Fld> <Fld FN="TYPE">TYPE_2</Fld> </Rec> <Rec RN="FOO"> <Fld FN="ID">ID_4</Fld> <Fld FN="OPT">1</Fld> <Fld FN="DESCRIPTION">DESCRIPTION_2</Fld> </Rec> <Rec RN="BAR" RC="3"> <Fld FN="ID">ID_5</Fld> <Fld FN="TYPE">TYPE_4</Fld> </Rec> <Rec RN="BAR"> <Fld FN="ID">ID_6</Fld> <Fld FN="TYPE">TYPE_5</Fld> </Rec> <Rec RN="SPAM"> <Fld FN="CLASS">CLASS_1</Fld> </Rec> </Dataset> And the following XSLT: <?xml version="1.0" ?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="Dataset"> <html> <head> <link rel="stylesheet" type="text/css" href="On-line Styles.css"/> </head> <body> <p class="subheading"> Commands </p> <p> <xsl:choose> <xsl:when test="Rec[@RN='FOO']"> <xsl:apply-templates select="Rec[@RN='FOO']"/> </xsl:when> <xsl:otherwise> None </xsl:otherwise> </xsl:choose> </p> </body> </html> </xsl:template> <xsl:template match="Rec[@RN='FOO']"> <xsl:for-each select="."> <xsl:value-of select="Fld[@FN='ID']"/> <xsl:if test="Fld[@FN='OPT'] = 1"> (Optional) </xsl:if> - <xsl:value-of select="Fld[@FN='DESCRIPTION']"/> <p> <xsl:choose> <xsl:when test="../Rec[@RN='FOO']"> <table style="border-collapse: separate;" cellspacing="4" border="2" bordercolorlight="#c0c0c0" bordercolordark="#c0c0c0"> <tr bgcolor="#C0C0C0"> <td style="width: 35%; padding: 6px;" valign="top"> <p class="Tableheader" style="margin-bottom: 0;"> <span style="font-weight: bold;">ID</span> </p> </td> <td style="width: 45%; padding: 6px;" valign="top"> <p class="Tableheader" style="margin-bottom: 0;"> <span style="font-weight: bold;">TYPE</span> </p> </td> </tr> <xsl:for-each select="../Rec[@RN='BAR']"> <xsl:if test="preceding-sibling::Rec/@RN='FOO'"> <tr> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;"> <xsl:choose> <xsl:when test="Fld[@FN='ID']"> <xsl:value-of select="Fld[@FN='ID']"/> </xsl:when> <xsl:otherwise> <td>&#xA0;</td> </xsl:otherwise> </xsl:choose> </p> </td> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;"> <xsl:choose> <xsl:when test="Fld[@FN='TYPE']"> <xsl:value-of select="Fld[@FN='TYPE']"/> </xsl:when> <xsl:otherwise> <td>&#xA0;</td> </xsl:otherwise> </xsl:choose> </p> </td> </tr> </xsl:if> </xsl:for-each> </table> </xsl:when> </xsl:choose> </p> </xsl:for-each> </xsl:template> </xsl:stylesheet> I get the following output for the tables: Table 1 <table style="border-collapse: separate;" cellspacing="4" border="2" bordercolorlight="#c0c0c0" bordercolordark="#c0c0c0"> <tr bgcolor="#C0C0C0"> <td style="width: 35%; padding: 6px;" valign="top"> <p class="Tableheader" style="margin-bottom: 0;"> <span style="font-weight: bold;">ID</span> </p> </td> <td style="width: 45%; padding: 6px;" valign="top"> <p class="Tableheader" style="margin-bottom: 0;"> <span style="font-weight: bold;">TYPE</span> </p> </td> </tr> <tr> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">ID_2</p> </td> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">TYPE_1</p> </td> </tr> <tr> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">ID_3</p> </td> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">TYPE_2</p> </td> </tr> <tr> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">ID_5</p> </td> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">TYPE_4</p> </td> </tr> <tr> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">ID_6</p> </td> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">TYPE_5</p> </td> </tr> </table> Table 2 <table style="border-collapse: separate;" cellspacing="4" border="2" bordercolorlight="#c0c0c0" bordercolordark="#c0c0c0"> <tr bgcolor="#C0C0C0"> <td style="width: 35%; padding: 6px;" valign="top"> <p class="Tableheader" style="margin-bottom: 0;"> <span style="font-weight: bold;">ID</span> </p> </td> <td style="width: 45%; padding: 6px;" valign="top"> <p class="Tableheader" style="margin-bottom: 0;"> <span style="font-weight: bold;">TYPE</span> </p> </td> </tr> <tr> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">ID_2</p> </td> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">TYPE_1</p> </td> </tr> <tr> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">ID_3</p> </td> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">TYPE_2</p> </td> </tr> <tr> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">ID_5</p> </td> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">TYPE_4</p> </td> </tr> <tr> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">ID_6</p> </td> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">TYPE_5</p> </td> </tr> </table> What I need is for each table to only display the ID and TYPE text values for only the <Rec RN="BAR">s following the <Rec RN="FOO"> and before the next <Rec RN="FOO"> or <Rec> with another @RN value. There can be 1 to n number of <Rec RN="BAR"> following a <Rec RN="FOO">. The following example shows the output I need: Table 1 <table style="border-collapse: separate;" cellspacing="4" border="2" bordercolorlight="#c0c0c0" bordercolordark="#c0c0c0"> <tr bgcolor="#C0C0C0"> <td style="width: 35%; padding: 6px;" valign="top"> <p class="Tableheader" style="margin-bottom: 0;"> <span style="font-weight: bold;">ID</span> </p> </td> <td style="width: 45%; padding: 6px;" valign="top"> <p class="Tableheader" style="margin-bottom: 0;"> <span style="font-weight: bold;">TYPE</span> </p> </td> </tr> <tr> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">ID_2</p> </td> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">TYPE_1</p> </td> </tr> <tr> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">ID_3</p> </td> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">TYPE_2</p> </td> </tr> </table> Table 2 <table style="border-collapse: separate;" cellspacing="4" border="2" bordercolorlight="#c0c0c0" bordercolordark="#c0c0c0"> <tr bgcolor="#C0C0C0"> <td style="width: 35%; padding: 6px;" valign="top"> <p class="Tableheader" style="margin-bottom: 0;"> <span style="font-weight: bold;">ID</span> </p> </td> <td style="width: 45%; padding: 6px;" valign="top"> <p class="Tableheader" style="margin-bottom: 0;"> <span style="font-weight: bold;">TYPE</span> </p> </td> </tr> <tr> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">ID_5</p> </td> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">TYPE_4</p> </td> </tr> <tr> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">ID_6</p> </td> <td style="padding: 6px;" valign="top"> <p style="margin-bottom: 0;">TYPE_5</p> </td> </tr> </table> A: If I understand this correctly (which is not at all certain), you want to do something like this: XSLT 1.0 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:key name="rows" match="Rec[@RN='BAR']" use="generate-id(preceding-sibling::Rec[@RN='FOO'][1])" /> <xsl:template match="/Dataset"> <html> <body> <xsl:apply-templates select="Rec[@RN='FOO']"/> </body> </html> </xsl:template> <xsl:template match="Rec[@RN='FOO']"> <table border="1"> <tr> <th>ID</th> <th>TYPE</th> </tr> <xsl:apply-templates select="key('rows', generate-id())"/> </table> <p/> </xsl:template> <xsl:template match="Rec[@RN='BAR']"> <tr> <td> <xsl:value-of select="Fld[@FN='ID']"/> </td> <td> <xsl:value-of select="Fld[@FN='TYPE']"/> </td> </tr> </xsl:template> </xsl:stylesheet> Applied to your example input, the result will be: <html> <body> <table border="1"> <tr> <th>ID</th> <th>TYPE</th> </tr> <tr> <td>ID_2</td> <td>TYPE_1</td> </tr> <tr> <td>ID_3</td> <td>TYPE_2</td> </tr> </table> <p></p> <table border="1"> <tr> <th>ID</th> <th>TYPE</th> </tr> <tr> <td>ID_5</td> <td>TYPE_4</td> </tr> <tr> <td>ID_6</td> <td>TYPE_5</td> </tr> </table> <p></p> </body> </html> rendered as:
{ "pile_set_name": "StackExchange" }
Q: Parse new User save does not return new ID When saving anew user in Parse, although the user saves correctly, the new user is not returned after the save, so the code errors at console.log("userResult id " + userResult.id);. If the user already exists, the save function returns the id correctly. Is this a bug with Parse or am I missing something? return userQuery .first(function (userResult) { if (!helpers.isDefined(userResult)) { userResult = new Parse.User(); userResult.set("username", helpers.phoneToUsername(phoneNumber)); userResult.set("password", helpers.generatePassword(phoneNumber)); userResult.set("displayName", displayName); } userResult.set("location", location); userResult.set("smsVerified", false); return userResult.save() }) .then(function (userResult) { console.log("userResult id " + userResult.id); <-- ERROR HERE user = userResult; return Verification.createSmsVerification(userResult); })... The error: Result: TypeError: Cannot read property 'id' of undefined var userQuery = new Parse.Query(Parse.User); userQuery.equalTo("username", helpers.phoneToUsername(phoneNumber)); Its as if the user is being saved after then then() callback, but this should not be the case. A: After some time fiddling around in the dark on this, I've found that the problem is the initial code is within the first() callback rather than the thenable. Changing the top lines of code from first(function()... to first().then(function() has solved the problem. return userQuery.first() .then(function (userResult) { if (!helpers.isDefined(userResult)) { userResult = new Parse.User(); userResult.set("username", helpers.phoneToUsername(phoneNumber)); userResult.set("password", helpers.generatePassword(phoneNumber)); userResult.set("displayName", displayName); } userResult.set("location", location); userResult.set("smsVerified", false); return userResult.save() }) .then(function (userResult) { console.log("userResult id " + userResult.id); <-- ERROR HERE user = userResult; return Verification.createSmsVerification(userResult); })...
{ "pile_set_name": "StackExchange" }
Q: Mysql insert not working and not giving errors i do not know why the following code will not work for inserting data into mysql. if (!$link = mysql_connect('server', 'user', 'password')) { echo '700'; exit; } if (!mysql_select_db('vendors', $link)) { echo '701'; exit; } $sql2 = "INSERT INTO transactions (TransID, payment_status, last_name, first_name, payer_email, address_name, address_state, address_zip, address_country, verify_sign, payment_gross, ipn_track_id, business, reciver_email) VALUES ('kris', 'kris', 'kris', 'kris', 'kris','kris', 'kris', 'kris', 'kris', 'kris', 'kris', 'kris', 'kris', 'kris')"; $result2 = mysql_query($sql2, $link); What is wrong with the code? php is giving no errors. A: Please try not to use mysql_connect instead use mysqli_connect or PDO_MySQL read this Also use die to find if there is any errors in your code $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); if (!$link) { die('Could not connect: ' . mysql_error()); } Otherwise(recommended way)- Procedural style $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO Persons (firstname, lastname, email) VALUES ('Happy', 'John', '[email protected]')"; if (mysqli_query($conn, $sql)) { echo "New Person created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); MySQLi Object-oriented style $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "INSERT INTO Persons (firstname, lastname, email) VALUES ('Happy', 'John', '[email protected]')"; if ($conn->query($sql) === TRUE) { echo "New Person created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close();
{ "pile_set_name": "StackExchange" }
Q: Does a Site Owner have Full Control for other Sites I have a Parent Site (Top Level Site) lets call Farm Logistics There are several sub-sites:Pigs, Cattle, Chickens, and HR There are 5 Site Admins for the Parent Site (Top Level Site) and sub sites. I want to ensure that the Site Admins only have control for their respective sites. When I created the sub-site and input the Site Owner (Site Admin) my understanding is this Site Owner/Site Admin has Full Control for the site, but what is not clear is if the Site Owner also has Full Control for all sites found within the Site Collection ? My Site Owners will have limited SP experience and I essentially only want them to have the ability to add new members to their respective SP Permission Group that has been created for each team. A: Site Collection Administrator have full control over site collection. Site Owners (Full Control) have full control over the site on which access is provided. If you have site owner at parent site and you don't want to share subsite with parent site owner: --> You can break the permission at subsite and then remove Parent Site Owner group and you can add Sub Site Owner group. To have ability to add new members to their respective SP Permission group. --> You can manage SP Permission group by adding respective as Owner of SP Permission group. Site Action --> Site Setting --> People and Groups under Users and Permissions --> Groups ( will be available in left panel). You can selected group and edit and input owner field. Then Owner will be able to add members to that group. Hope this helps !!
{ "pile_set_name": "StackExchange" }
Q: How to save a file using nano I am trying to install Java via the terminal using the guide How to Install Oracle Java JRE on Ubuntu Linux. Everything went perfectly fine until "Step 11: Save the /etc/profile file and exit": I spent maybe 30 minutes figuring out what ^ means (apparently Ctrl), but I cannot understand how that guy called the save command where you can choose yes and no. I did try ^O, but I didn't get the same result as he did. How can I fix this problem? A: Ctrl + X will quit the editor and you will be asked if you want to save your changes. If you do, press Y for Yes. Ctrl + O should also work, since that means to save the file, but you won't be asked "Save modifier buffer ? " because you already told nano to save. A: He save the changes made through Ctrl+O which actually means Write Out while editing a file through nano. Where ^ means Ctrl. Note : You'll also have to press Enter to overwrite the existing file if it exists. A: With the image shown right now you can save just pressing "Y" for yes. To know what key combinations you need to do just check the White square besides the action, which are as follow: Y: yes N: no Ctrl + C: Cancel
{ "pile_set_name": "StackExchange" }
Q: Can I use STDistance in a function? I'm trying to calculate the distance between two coordinates, so I want to use STDistance. Can I use STDistance in a function using two variables as coordinates? I'm trying to call the function in php so that's why I want it to be an SQL function. CREATE FUNCTION measureDistance(@coordsFrom INT, @coordsTo INT) RETURNS INT AS BEGIN DECLARE @g geography; DECLARE @h geography; SET @g = geography::STGeomFromText('LINESTRING(@coordsFrom)', 4326); SET @h = geography::STGeomFromText('LINESTRING(@coordsTo)', 4326); RETURN @g.STDistance(@h); END; GO A: You can not use PHP functions in SQL functions. But you can get the coordinates from the DB, set them to some variables in your PHP and to the calculation there.
{ "pile_set_name": "StackExchange" }
Q: Is is possible to operate D-Star from a software-defined radio? What is preventing a software-defined radio from transmitting the D-Star protocol? A: Nothing is preventing an SDR from transmitting the D-STAR protocol, other than the need to implement it as such. It is open, and currently I know that Digital Signal Decoder (DSD) can actually decode some data and textual frames. What prohibits transmission of D-STAR Digital Voice is the codec used to encode the voice - it's AMBE2000, which is patented and proprietary. A license for one of these is in the ballpark of $100,000, allowing only large businesses to use it. Icom, having already developed P25 hardware using the AMBE codec, is the only one to do so thus far, aside from the DVDongle (though I don't know how they can afford to use it). The reason why AMBE was chosen was because it was the only low-bitrate RF speech codec available at the time. Now, if codec2 can be implemented over D-STAR (or its own protocol, like FreeDV), it would be completely open. This is certainly a future development. A: Nothing. In fact, the UDR56k is an SDR and transmits D-STAR. If you want D-STAR digital voice, you do need to purchase an add-on card which contains an ASIC from DVSI implementing the propritary AMBE codec, or pay a substantial (but undisclosed publicly) licensing fee. One can safely assume that any licensing agreement would forbid any free proliferation of the implementation. The DVDongle contains the same ASIC, visible here as the large IC on the right, with "AMBE-2000" printed on it: The middle IC is at Atmel microcontroller, and the IC on the left looks like an FTDI USB interface. There's not much else to it.
{ "pile_set_name": "StackExchange" }
Q: How to get rowSums for selected columns in R I am a newbie to R and seek help to calculate sums of selected column for each row. My simple data frame is as below. data = data.frame(location = c("a","b","c","d"), v1 = c(3,4,3,3), v2 = c(4,56,3,88), v3 =c(7,6,2,9), v4=c(7,6,1,9), v5 =c(4,4,7,9), v6 = c(2,8,4,6)) I want sum of columns V1 to V3 and V4 to V6 for my each row in a new data frame. x1 x2 a 14 13 b 66 18 c d I did something like below. rowSums(data[,2:4][,5:7]) But something should be wrong in my codes. Thanks in advance for any help. A: My sense would be to use dply: require(dply) data %>% mutate(v2v4 = rowSums(.[2:4])) %>% mutate(v4v6 = rowSums(.[5:7])) %>% select(-(location:v6)) result: > newDf <- data %>% mutate(v2v4 = rowSums(.[2:4])) %>% mutate(v4v6 = rowSums(.[5:7])) %>% select(-(location:v6)) > newDf v2v4 v4v6 1 14 13 2 66 18 3 8 12 4 100 24 A: rowSums(cbind(mydata$variable1, mydata$variable2, mydata$variable3), na.rm = T ) A: Here is a quite simple solution using apply. output <- data.frame( x1 = apply(data[2:4], 1, sum) , x2 = apply(data[5:7], 1, sum) ) result: output > x1 x2 > 1 14 13 > 2 66 18 > 3 8 12 > 4 100 24
{ "pile_set_name": "StackExchange" }
Q: How do I change cursor on keypress (Ctrl) in JQuery? Using jQuery, I would like to change the cursor on page when any key is pressed (for example Ctrl). Simple task, however I can not get make it work... This was my first idea, obviously - does not work: $(document).on('keydown',function(){ $(document).css('cursor','wait'); }); Any idea what is wrong? A: Think what you want is something like this: $('body').css('cursor','wait'); You can't apply CSS to the document. Also if you wanted to only apply this css to the CTRL key press you could do: $(document).on('keydown', function (event) { if (event.ctrlKey) { $('body').css('cursor', 'wait'); } });
{ "pile_set_name": "StackExchange" }
Q: using prinf function for repeated patterns I have codes which append the patterns into text file w.r.t. the user's input as follows; echo -n "WHICH STATIONS?" read station awk -v input="$station" ' BEGIN { n = split(tolower(input), user) pattern= "force %-4s npos 0. .0001\n" } {print} /<< write after this line >>/ { for (i=1; i<=n; i++) printf pattern, user[i] exit } ' ./data > data_2 let assume user's input abcd ab12 then commands append below lines; force abcd npos 0. .0001 force ab12 npos 0. .0001 I need to add epos and upos strings for each input for separate lines as follows (for same inputs as above example); force abcd npos 0. .0001 force abcd epos 0. .0001 force abcd upos 0. .0001 force ab12 npos 0. .0001 force ab12 epos 0. .0001 force ab12 upos 0. .0001 How can I modify the pattern option to append these lines into the data file? A: This is what I understood from the information given by you: awk -v input="$station" ' BEGIN { n = split(tolower(input), user) pattern= "force %-4s npos 0. .0001\n" } {print} { for (i=1; i<=n; i++){ print "force " user[i] " epos 0. .0001" print "force " user[i] " upos 0. .0001" } } ' data In for loop for each user epos and upos strings are getting printed as per your requirement.
{ "pile_set_name": "StackExchange" }
Q: Sql DataBase does not update changes I get the error message below Dynamic sql generation for the update command is not supported against a select command that does not return any key column information when I try to update my database via a button click after I made changes in GridView. Below is the code: private void updateDB_Click(object sender, EventArgs e) { SqlDataAdapter sqlAdapter = new SqlAdapter(@"SELECT [Customer],[Employee],[Product],[State] FROM [Table1]", connection); sqlCmdBuilder = new SqlCommandBuilder(sqlAdapter); DataTable datTable = dataGridView1.DataSource as DataTable; sqlAdapter.Update(datTable); } I have searched a lot to find a solution but I can't find something useful. I know that this is because a PrimaryKey is missing in my database but it is supposed that there is none. So how can I update my database after changes were made without having a PrimaryKey defined? Is it possible to use another way where I can only use my column names and the tablename (I have only found a solution where each element has to be written manually and that's too much)? A: With this code you will update the DataTable, not your database. You can read this Article SqlDataAdapter sqlAdapter = new SqlAdapter(@"SELECT [Customer],[Employee],[Product],[State] FROM [Table1]", connection); sqlCmdBuilder = new SqlCommandBuilder(sqlAdapter); DataTable datTable = dataGridView1.DataSource as DataTable; sqlAdapter.Update(datTable); sqlAdapter.Dispose();// SqlDataAdapter must be Disposed ! From your question when I try to update my database via a button If you want to update your database you need an update query and to call ExecuteNonQuery() of the SqlCommand. You should Insert/Update into your database with adding/updating any of the records in the grid.
{ "pile_set_name": "StackExchange" }
Q: How can a running web deployment process be cancelled? I'm attempting to deploy my web app to a local test server using VS2010 One Click Publish and it seems I've put incorrect settings in to the web deployment dialogue. I didn't realise this until I'd pressed the publish button. After thinking the deployment was taking an unusually long time, I looked at the Output window and say the following error: C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets(3847,5): Warning : Retrying the sync because a socket error (10054) occurred. Retrying operation 'Serialization' on object sitemanifest (sourcePath). Attempt 1 of 10. Now I think I know what I've done wrong, this question isn't about that. Each attempt is taking about three or four minutes. How can I stop the web deployment process when it is doing something like this? A: You can press CTRL-BREAK during publishing to cancel the process.
{ "pile_set_name": "StackExchange" }
Q: Additional requirement for checksum over CAN bus? Im working on a safety system project and sending messages over CAN bus among systems. Since the CAN protocol already includes a hardware CRC for messages sent over the bus,I was wondering if additional checksum for the data bytes is required or is the hardware CRC sufficient. For ex: For 8 data bytes sent in CAN, should 1 byte out of 8 bytes be allocated for checksum of the 7 bytes being sent ,or, can I send 8 data bytes and rely on the hardware CRC to ensure the integrity of message? A: It's a probability game and a tradeoff of costs. What's the cost of getting bad data? What's the cost of decreasing the chance of getting bad data? You can't ever absolutely guarantee that data is received correctly. All you can do is decrease the chance of that happening by throwing ever more resources as it. At some point it becomes not worth it to spend more resources to decrease the chance of bad data a little more. Only you can answer what that point is. That said, the 15 bit CRC checksum CAN uses on every message is good enough for the vast majority of applications. CRCs can be arranged to always detect a single bit error, but it is possible to change multiple bits so that the result looks correct. The 15 bit CRC in a CAN message has 32768 possible values. If you throw random message content at it, there is one chance in 32768 of it resulting in any particular CRC. At first glance, you can therefore say the probability of a bad message looking correct is the probability of getting two or more bit errors within a message, divided by 32768. It's actually less than that because some random errors will make the whole CAN message structurally incorrect, but the above is a good start. You compute the probability of getting bad bits in the first place from the bit error rate. The typical CAN bus is implemented as a symmetric differential signal, and is quite robust even with lots of external noise. Consider that CAN was originally designed for automobiles, which are electrically very noisy environments. The point of this is that the bit error rate will be quite small. For example, 1 in 106 would be a huge and unlikely bit error rate. Unless you are doing something very unusual and critical, just using the CAN checksum without any additional integrity checking at the application level will be good enough. If you're in such a critical application where it's not good enough, then you should be looking at multiple independent and redundant busses and other higher level schemes anyway.
{ "pile_set_name": "StackExchange" }
Q: gdb: (no debugging symbols found) I have a file called test. Even after compiling it with -g, when I run it in gdb, it says no debugging symbols found. I have also tried using -ggdb but it too was off no use. Please help. Output for : gdb test This GDB was configured as "x86_64-linux-gnu". For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>... Reading symbols from /usr/bin/test...(no debugging symbols found)...done. A: The issue is that you are attempting to debug the wrong program. Your program is called test and yet you are debugging /usr/bin/test (a system program that will almost certainly be shipped without symbols; even if it did contain symbols, they wouldn't relate to your source code). gdb will search $PATH to find the executable. From here: exec-file [ filename ] Specify that the program to be run (but not the symbol table) is found in filename. gdb searches the environment variable PATH if necessary to locate your program. Omitting filename means to discard information on the executable file. Try using the command: $ gdb ./test
{ "pile_set_name": "StackExchange" }
Q: Jackson @RestController Spring force return duplicate nested object I have a List of objects with also nested objects, which I return as response in a Spring @RestController, example: [{ "id" : "10", "name" : "test", "createdBy" : { "id" : "10", "user" : { "id" : "55", "name" : "me" } } }, { "id" : "13", "name" : "test 2", "createdBy" : 55 }] As you can see the first nested object is returned correctly, but the second time of the same object is returned only the id. Now I'm wondering if there is a way to force Jackson to always resolve the nested object instead of returning only the id. A: If I remember correctly this is not the default behavior. It only happens when there is a configured @JsonIdentityInfo. Removing it will result in always serializing as full POJOs. Beware of Jackson infinite loops when not using @JsonIdentityInfo.
{ "pile_set_name": "StackExchange" }
Q: Primary decomposition of modules - uniqueness proof Let $M$ be $A$-module, $A$ commutative ring, and $N$ submodule and let $$N=Q_1\cap\dots\cap Q_r=Q'_1\cap \dots \cap Q'_s$$ be reduced primary decompositions of $N$. Then $r=s$. The set of primes belonging to $Q_1,\dots,Q_r$ and $Q'_1,\dots,Q'_r$ is the same. It is part of theorem 3.2 in Chapter X of Lang's Algebra, and he said that proof follows from this theorem (3.5): Let $A$ and $M$ be Noetherian. The associated primes of $M$ are precisely the primes belonging to the primary modules in a reduced primary decomposition of $0$ in $M$. I don't see how it follow from this proof since we need both module and ring to be Noetherian in second theorem? Is there some direct proof for first statement (I tried to prove it myself but without success). Just some definitions for clarity: Submodule $Q$ of $M$ is primary if for every $a\in A$ function $a_{M/Q}:M\rightarrow M$, $a_{M/Q}(x)=ax$ is either injective or nilpotent. And set of all $a\in A$ for which that function is nilpotent is prime ideal which belongs to $Q$. Primary decomposition is reduced if primes that belong to different submodules in decompositions are distinct. A: If $N=Q_1\cap\cdots\cap Q_n$ is a reduced primary decomposition, and $P_i=\sqrt{Q_i}$, then $\operatorname{Ass}(M/N)=\{P_1,\dots,P_n\}$. We have an exact sequence $0\to M/N\to\bigoplus_{i=1}^n M/Q_i$. Then $\operatorname{Ass}(M/N)\subseteq\operatorname{Ass}(\bigoplus_{i=1}^n M/Q_i)$. But $\operatorname{Ass}(\bigoplus_{i=1}^n M/Q_i)=\bigcup_{i=1}^n\operatorname{Ass}(M/Q_i)=\{P_1,\dots,P_n\}$. For the converse, pick up an $x_i\in\bigcap_{j\ne i}Q_j\setminus Q_i$. Now notice that the submodule $Ax_i$ of $M/N$ is isomorphic to the submodule $Ax_i$ of $M/Q_i$ and hence they have the same associated prime ideals. But on one hand $\operatorname{Ass}(Ax_i)\subseteq\operatorname{Ass}(M/N)$, and on the other hand $\operatorname{Ass}(Ax_i)\subseteq\operatorname{Ass}(M/Q_i)=\{P_i\}$. In order to conclude now that $P_i\in\operatorname{Ass}(M/N)$ we have to be sure that $\operatorname{Ass}(Ax_i)\neq\emptyset$, and this requires the assumption $A$ noetherian (no assumption on $M$ is needed!).
{ "pile_set_name": "StackExchange" }
Q: Babel loader not loading form config.json file I am a beginner in using Reactjs and I get the following error when I run the webpack: ERROR in ./src/client/app/index.jsx Module parse failed: Unexpected token (6:11) You may need an appropriate loader to handle this file type. Code: class App extends React.Component { render () { return <p> Hello React!</p>; } } I did this by following the instructions given as in the following site: http://blog.tamizhvendan.in/blog/2015/11/23/a-beginner-guide-to-setup-react-dot-js-environment-using-babel-6-and-webpack/ below lines here will tell you the version details "author": "", "license": "ISC", "babel-preset-react": "^6.24.1", "react": "^16.2.0", "react-dom": "^16.2.0" "babel-core": "^6.26.0", "babel-loader": "^7.1.3", "babel-preset-es2015": "^6.24.1", "webpack": "^4.0.1", "webpack-cli": "^2.0.10" A: The guide you're following is pretty old, and the config object described in webpack.config.js is different now. Replace: module : { loaders : [ { test : /\.jsx?/, include : APP_DIR, loader : 'babel' } ] } ... with: module : { rules: [{ test : /\.jsx?/, include : APP_DIR, use: 'babel-loader' }] } Then, find a newer guide :) Or install an older version of webpack.
{ "pile_set_name": "StackExchange" }
Q: Resize an image with javascript for use inside a canvas createPattern I've seen a few tricks on how you resize an image you want to use inside an IMG-tag but I want to have an image variable inside a Javascript, resize it and then use the image inside a context.createPattern(image, "repeat"). I have not found any hint on how to do that. You can find a functional demo at http://karllarsson.batcave.net/moon.html with images on what I want to do. The solution from Loktar looks good. I haven't had the time yet to fix the correct aspect but now I know how to do it. Thank you once again. Here is an working demo http://karllarsson.batcave.net/moon2.html This is the two lines I don't get to work as I want them too. image.width = side * 2; image.height = side * 2; function drawShape() { try { var canvas = document.getElementById('tutorial'); var image = new Image(); image.src = "http://xxx.yyy.zzz/jjj.jpg"; image.width = side * 2; image.height = side * 2; if (canvas.getContext){ var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = ctx.createPattern(image, "repeat"); ctx.beginPath(); var centerX = canvas.width / 2 - side / 2; var centerY = canvas.height / 2 - side / 2; ctx.rect(centerX, centerY, side, side); ctx.fill(); } else { alert('You need Safari or Firefox 1.5+ to see this demo.'); } } catch (err) { console.log(err); } } A: What you can do is make a temporary canvas, and copy the image to it with the dimensions you require, and then use that temporary canvas as the pattern rather than the image itself. Live Demo First create the canvas var tempCanvas = document.createElement("canvas"), tCtx = tempCanvas.getContext("2d"); tempCanvas.width = side*2; tempCanvas.height = side*2; Now draw the image to it, making the the scaled size you require tCtx.drawImage(image,0,0,image.width,image.height,0,0,side*2,side*2); And now use the canvas you just created as the pattern ctx.fillStyle = ctx.createPattern(tempCanvas, "repeat"); Full code edit created a more generic reusable example function drawPattern(img, size) { var canvas = document.getElementById('canvas'); canvas.height = 500; canvas.width = 500; var tempCanvas = document.createElement("canvas"), tCtx = tempCanvas.getContext("2d"); tempCanvas.width = size; tempCanvas.height = size; tCtx.drawImage(img, 0, 0, img.width, img.height, 0, 0, size, size); // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = ctx.createPattern(tempCanvas, 'repeat'); ctx.beginPath(); ctx.rect(0,0,canvas.width,canvas.height); ctx.fill(); } var img = new Image(); img.src = "http://static6.depositphotos.com/1070439/567/v/450/dep_5679549-Moon-Surface-seamless.jpg"; img.onload = function(){ drawPattern(this, 100); }
{ "pile_set_name": "StackExchange" }
Q: Undefined offset: 2 in codeigniter Here is my controller function as far as i can see there is no error but it still showing me this message .what does it mean . <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class User extends CI_Controller { public function __construct() { parent::__construct(); // Your own constructor code //$this->load->model('user_model'); } public function index() { $this->load->view('user/signup'); } public function registration() { if($this->input->post()) { $fullname=$this->input->post('fullname'); $fullnameSplit= explode(" ", $fullname); $reg_data = array( 'membershipid'=>"Ls-".rand(), 'role'=>1, 'firstname'=>$fullnameSplit[0], 'middlename'=>$fullnameSplit[1], 'lastname'=>$fullnameSplit[2], 'Company_name'=>$this->input->post('companyname'), 'email'=>$this->input->post('email'), 'password'=>sha1($this->input->post('password')), ); print_r($reg_data); //$this->user_model->register_user($reg_data); //redirect('user/login'); //echo '<pre>'; print_r($reg_data); die; }else { //$data['current_page'] = 'Register'; //$this->load->view('registration',$data); } } } This error is showing . A PHP Error was encountered Severity: Notice Message: Undefined offset: 2 Filename: controllers/User.php Line Number: 35 Backtrace: File: /var/www/overtribe.com/public_html/listspread/application/controllers/User.php Line: 35 Function: _error_handler File: /var/www/overtribe.com/public_html/listspread/index.php Line: 293 Function: require_once A: use this line 'lastname'=>$fullnameSplit[2], as 'lastname'=>isset($fullnameSplit[2]) ? $fullnameSplit[2] : '', The error undefined offet:2 means the array $fullnameSplit with key [2] does not exists or is not set. So you need to check condition isset() to avoid that message
{ "pile_set_name": "StackExchange" }
Q: how to push all values from the txt file to local storage using angular js I have a sample application which can store values into local storage when user clicks to local button but i want to all values from the txt file to be in local storage "note2": [] . Plunker Demo A: And yes i found a way to do so ., you can use ng-init='Function name' here i use a function when a user click the to local button to push a value to local $scope.cloneItem = function (todo) { $scope.$storage.notes.push({ "price": todo.price, "id": todo.id, "quan": todo.quan }); } but i want to store all the values from the txt file to local so i use ng-init='your js function name' this function to call push function so that for every ng-repeat the value would push to local Example : <tr ng-repeat="todo in todos" ng-init='cloneItem(todo)'>
{ "pile_set_name": "StackExchange" }
Q: Create Table Query for Redshift for the given datatypes for below data set can anyone provide me the redshift query please 0 object 1 object 2 float64 3 float64 4 object 5 object dtype: object the query that i have tried is CREATE TABLE `promos_zivame` (SKU varchar(max), Category_id varchar(max) NOT NULL, price int(max), specialPrice int(max), sizes varchar(MAX), offer varchar(MAX), Date_Time TIMESTAMP(max)) The error im getting this error Error encountered: Load into table 'promos_zivame' failed. Check 'stl_load_errors' system table for details. The data present in those objects are enter image description here A: Try this. CREATE TABLE `promos_zivame` ( SKU varchar(max), Category_id varchar(max) NOT NULL, price INTEGER, specialPrice INTEGER, sizes varchar(MAX), offer varchar(MAX), Date_Time TIMESTAMP) INT and TIMESTAMP doesn't take MAX arguments.
{ "pile_set_name": "StackExchange" }
Q: Nouveau unknown chipset at install I'm trying to install Ubuntu version 14.10 on my new computer. It's a fresh build with nothing installed yet. You can see a list of the hardware here. At first I had difficulty with the UEFI boot, but I went into the BIOS and set everything that I could to "legacy". Now, when I try to boot, I get the following error: [ 2.817690 nouveau E[ DEVICE][0000:01:00.0] unknown chipset, 0x124020a1 [ 2.817724 nouveau E[ DRM] failed to create 0x80000080, -22 I tried booting in nomodeset, which I thought did something to fix that, but it didn't work. I suspect it has something to do with not having any drivers yet, but I didn't get an optical drive. I was planning on just downloading them. What can I do? A: Do a Ctrl+Alt+F1 login and do sudo apt-get update sudo apt-get upgrade sudo ubuntu-drivers devices see what is recommended sudo apt-get install nvidia-xxx (xxx is your recommended driver) reboot.
{ "pile_set_name": "StackExchange" }
Q: Simulating Orville's Cracked Pepper and Salt Popcorn Has anyone made something that tastes similar to the (discontinued) microwave product? As a bonus question, does anyone know why they discontinued the product? I doubt that it was lack of demand. I think it was only ever available in limited parts of the US. I make popcorn in a Stircrazy quite often so I don't have a problem with the basic technique. I add the salt to the kernels and drop it all in when the 2-3 test kernels pop. However, I love (or used to love) the Orville Redenbacher (natural, buttery salt and ) cracked pepper microwave popcorn. When the product was discontinued I tried several techniques to reproduce the flavor and nothing has worked. Here is what I tried and the results: 1) Adding cracked black pepper to the salt and kernels before popping. While the salt sticks the black pepper mostly stays in the popper. 2) Adding oil and black pepper to the kernels and salt. I mixed it well to coat the kernels and more stuck than with method #1 but much less so than the microwave product and also the flavor wasn't as "special" as the microwave product. 3) Adding cracked pepper after it is all popped. I only added this in case someone was planning to suggest it. The pepper mostly falls off. One thing I haven't tried is grinding the pepper to dust, like popcorn salt. But then it isn't cracked pepper. A: I doubt the cracked pepper flavor in the popcorn actually comes from cracked pepper. Food technologists tend to use extracts for flavors, and then enhance the visuals. The popcorn you like is likely flavored by some sort of pepper extract (probably oil suspended) with some cracked pepper flakes thrown in for visual effect. You may very well be able to re-create this if you take the same approach: get the flavors working and then worry about how it looks. This makes things easier in a way, you can use whatever works to get the right flavor rather than trying to get it from one ingredient. Pepper and chili flavors are both oil-based, and you'll have the best luck trying to get the flavor into an oil and then coating the popcorn in the oil than trying to add the flavor directly to the popcorn. Try adding your pepper dust to oil or butter and gently heating it for 20 minutes or so. You can then try using this oil to pop your corn, this may or may not work properly as pepper tends to burn and get bitter, however if you've extracted the flavor into the oil it may work. If it does turn bitter then the oil would need to be added after the popping. Adding some cracked pepper flakes to the oil at the end ought to give you the visual effect you want as the oil will help it stick to the corn. You could add the salt to the oil or simply sprinkle it on.
{ "pile_set_name": "StackExchange" }
Q: Using saved Dropbox authentication details on Android In the Getting started article on Dropbox website they have a tutorial how to use Core API with Android to get started. When the application launches for the first time, the user is asked to authenticate the software to use the users Dropbox account. After the authentication is successfully finished, you'll receive a pair of authentication strings, the key and a secret. After the user has authenticated the application to use his or her Dropbox account I save the key and the secred using Android's SharedPreferences. How do I use these saved values? I don't mean how I retrieve them using SharedPreferences but how I use these to prevent the need of reauthenticating the application again? On the Dropbox site they don't provide a way to use these. All they say is The finishAuthentication() method will bind the user's access tokens to the session. You'll now be able to retrieve them via mDBApi.getSession().getAccessTokenPair(). You'll need these tokens again after your app closes, so it's important to save them for future access (though it's not shown here). If you don't, the user will have to re-authenticate every time they use your app. A common way to implement storing keys is through Android's SharedPreferences API. A: I had the same problem, The documentation is not great so I saw several related questions about it. The key to solve this problem is in the method isLinked() in the AndroidAuthSession class. I share my code so It might solve your doubts. public class DropBoxInteractorImpl implements DropBoxInteractor { private DropboxAPI<AndroidAuthSession> mDropBoxApi; public DropBoxInteractorImpl(DropboxAPI<AndroidAuthSession> mDropBoxApi) { this.mDropBoxApi = mDropBoxApi; } @Override public void login(final Context context, final CloudServiceCallback cloudServiceCallback) { String accessToken = PrefUtils.getFromPrefs(context, KeysPref.DROPBOX_ACCESS_TOKEN, null); if (accessToken == null) { mDropBoxApi.getSession().startOAuth2Authentication(context); } else { mDropBoxApi.getSession().setOAuth2AccessToken(accessToken); } } @Override public void confirmLogin(Context context, final CloudServiceCallback cloudServiceCallback) { AndroidAuthSession session = mDropBoxApi.getSession(); if (session.authenticationSuccessful()) { // Required to complete auth, sets the access token on the session session.finishAuthentication(); String accessToken = mDropBoxApi.getSession().getOAuth2AccessToken(); PrefUtils.saveToPrefs(context, KeysPref.DROPBOX_ACCESS_TOKEN, accessToken); } if (session.isLinked()) { cloudServiceCallback.loginSuccessful(); } else { cloudServiceCallback.loginError(); Timber.e("There was a problem login in!!"); } } } I will explain it step by step. First of all, I am using Dagger as dependency injection, that's why I get my mDropBoxApi in the constructor, but If you are not, just create the session always the same way as I am doing in this method. @Provides @Singleton public DropboxAPI<AndroidAuthSession> providesDropBoxService() { AppKeyPair appKeyPair = new AppKeyPair(Keys.DROPBOX_APP, Keys.DROPBOX_APP_SECRET); AndroidAuthSession session = new AndroidAuthSession(appKeyPair); return new DropboxAPI<AndroidAuthSession>(session); } Now that you have your DropboxAPI object, you need to either startOAuth2Authentication' orsetOAuth2AccessToken` in case you have it already (saved form the last session). You can do that in onCreate (if it is an activity) or in onActivityCreated if it is a Fragment. @Override public void login(final Context context) { String accessToken = PrefUtils.getFromPrefs(context, KeysPref.DROPBOX_ACCESS_TOKEN, null); if (accessToken == null) { mDropBoxApi.getSession().startOAuth2Authentication(context); } else { mDropBoxApi.getSession().setOAuth2AccessToken(accessToken); } } After that, in your onResume method (and here is where we are going to solve our problem) you check if the login was successful calling the function session.authenticationSuccessful(). This will return true ONLY in case you did the authentication process. If it is not null, either the login was not successful or your account is already LINKED. That's it, LINKED. How do you check that? Well as I said before, It is the key to solved this problem. What you need to check is if the session is already Linked calling session.isLinked() and voilà. It will tell you if you are successfully linked with the dropbox api or , in case it is false, there was a problem in the process. @Override public void confirmLogin(Context context, final CloudServiceCallback callback) { AndroidAuthSession session = mDropBoxApi.getSession(); if (session.authenticationSuccessful()) { // Required to complete auth, sets the access token on the session session.finishAuthentication(); String accessToken = mDropBoxApi.getSession().getOAuth2AccessToken(); PrefUtils.saveToPrefs(context, KeysPref.DROPBOX_ACCESS_TOKEN, accessToken); } if (session.isLinked()) { callback.loginSuccessful(); } else { callback.loginError(); Timber.e("There was a problem login in!!"); } } I hope this solve you doubts about it, and If you have any question, please, don't hesitate to ask. A: The dropbox android JavaDoc seems to expand on what you need to do a little more, showing an alternative AndroidAuthSession constructor: When a user returns to your app and you have tokens stored, just create a new session with them: AndroidAuthSession session = new AndroidAuthSession( myAppKeys, myAccessType, new AccessTokenPair(storedAccessKey, storedAccessSecret)); I guess then you just have to instantiate a DropboxAPI object and you're good to go without the startAuthentication()... endAuthentication() etc. DropboxAPI<AndroidAuthSession> mDBApi = new DropboxAPI<AndroidAuthSession>(session); I haven't tried this out, but it's essentially the same thing that Greg was saying.
{ "pile_set_name": "StackExchange" }
Q: Should adding Maven dependencies be a separate git commit? I implemented some CSV reading functionality to my Java program, for which I required adding a Maven dependency. Should changes to pom.xml be part of the commit for the CSV reading functionality, or should it be a separate commit? I'm leaning towards the dependency being part of a logical unit of code, and thus should be in the same commit. I am however new to using Maven, so I'm not aware if there are any unwritten rules regarding changes to pom.xml. A: You should add the Maven dependency when you add the code, otherwise the project won't compile because you would refer to a CSV reading class in your .java file that doesn't exist on the classpath. Maven is there to handle your dependencies, and make sure that the classes you use are on the classpath so they can be loaded when your project requires them. I would consider the code, and any additional resources required by the code, as a single unit of work. That includes modifications to the pom.xml as well any extra files (sound files, images, SSL certificates, etc).
{ "pile_set_name": "StackExchange" }
Q: How to implement ViewPager with fragments in AndroidX since Google introduced androidX I'm having a problem with viewpager. I want to make a tab layout where I can swipe between fragments. getSupportFragmentManager() is deprecated now and shows an error ViewPagerAdapter(FragmentManager, int) in ViewPagerAdapter cannot be applied to (FragmentManager) Here is my adapter: public class ViewPagerAdapter extends FragmentPagerAdapter { public ViewPagerAdapter(@NonNull FragmentManager fm, int behavior) { super(fm, behavior); } @NonNull @Override public Fragment getItem(int position) { switch (position) { case 0: return new RecentFragment(); case 1: return new TracksFragment(); case 2: return new AlbumFragment(); case 3: return new GenresFragment(); } return null; } @Override public int getCount() { return 4; } } and in my activity I need to call it ViewPager viewPager = findViewById(R.id.view_pager); viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()); I found the solution, in the constructor I have second paremeters and in the viewpager I added page position and is working fine. public static int PAGE_POSITION = 4; ViewPager viewPager = findViewById(R.id.view_pager); viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), PAGE_POSITION)); TabLayout tab = findViewById(R.id.tab_layout); tab.setupWithViewPager(viewPager); A: Your ViewPagerAdapter class has a constructor that takes 2 parameters. When you try to create a new ViewPagerAdapter, you only use 1 parameter. Which is exactly what the error message is telling you. Look at the documentation for the FragmentPagerAdapter class and see what the 2nd parameter should be.
{ "pile_set_name": "StackExchange" }
Q: Change links in wordpress template without creating a table in database I have a wordpress template which have some static content. in fact the index page has a page template and its all static and have no control from wordpress.but using header and footer. I want to change static links in this page using admin panel. How to change this static links from wordpress panel without using a database to store this links? thank you A: You need to edit theme's files. Use Wordpress editor for this. UPDATE Install the plugin for managing options. For example, WP Options Editor In your template replace the code that should be customizable with the get_option('your_option_name');
{ "pile_set_name": "StackExchange" }
Q: ArrayStoreException when concatenating two arrays Stream I was following this Question and was trying to get a new way of concatenating two arrays. int[] c = {1, 34}; int[] d = {3, 1, 5}; I came up with this: Integer [] res= Stream.of(c, d) .flatMap(Stream::of) .toArray(Integer[]::new); Above compiles fine but i get this exception: Exception in thread "main" java.lang.ArrayStoreException at java.lang.System.arraycopy(Native Method) at java.util.stream.SpinedBuffer.copyInto(SpinedBuffer.java:194) at java.util.stream.Nodes$SpinedNodeBuilder.copyInto(Nodes.java:1290) at java.util.stream.SpinedBuffer.asArray(SpinedBuffer.java:215) at java.util.stream.Nodes$SpinedNodeBuilder.asArray(Nodes.java:1296) at java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:439) What is my mistake, and please give a explanation so that i can understand the concept. PS: I have seen Dealing with an ArrayStoreException and believe that my question consists of stream which are incompitable types that is why they are not getting stored, so two questions are different. A: Stream.of treats the input array as a single element. Use Arrays.stream() instead. int[] c = {1, 34}; int[] d = {3, 1, 5}; int[] res= Stream.of(c, d) .flatMapToInt(Arrays::stream) .toArray(); for (int re : res) { System.out.println(re); } Result: 1 34 3 1 5 If you want to have it boxed, go for: Integer[] res= Stream.of(c, d) .flatMapToInt(Arrays::stream).boxed() .toArray(Integer[]::new); A: Stream.of(c, d) is a Stream<int[]>. You can't store int[] elements in an Integer[]. Use IntStream.concat instead: IntStream.concat(IntStream.of(c), IntStream.of(d)).boxed() .toArray(Integer[]::new); A: .flatMap(Stream::of) on a Stream<int[]> returns a Stream<int[]> (Since Stream.of(int[]) will execute Stream<T> of(T t) and not Stream<T> of(T... values)). Therefore these elements cannot be stored in an Integer[] array. You can work with IntStreams instead: int [] res= Stream.of(c, d) .flatMapToInt (IntStream::of) .toArray();
{ "pile_set_name": "StackExchange" }
Q: PHP GMagick: how to get pixel color? Is it possible to get color of any picture pixel with PHP Gmagick extension? In IMagick I can get this info from getImagePixelColor method: $color = $img->getImagePixelColor($x, $y)->getColor(); How to get this result via GMagick? A: There isn't currently a native method to do this with Gmagick. This will get the job done though: $img_clone = clone $img; // No need to modify the original object. $img_clone->cropImage(1, 1, $x, $y); $color = $img_clone->getImageHistogram()[0]->getColor(); Returns (string) rgb(0,0,0)
{ "pile_set_name": "StackExchange" }
Q: How to use sequential relations In my application, I have 3 tables: state, city, district, Each state has many cities in it, and each city contains many districts. I already defined those relations in state and city models. Now I need to retrieve a list of all state, city, and district in to a multidimensional array that reflexes those relations. An example will look like this: [ 'A state' => [ ['AA city' => ['AA1 district', 'AA2 district']], ['AB city'] => ['AB1 district'] ] ] Is it possible to use Model that leverages relations that I define to get the job done effectively? A: Yes, you can. You can fetch the data with the relations like this: $states = State::model()->with('cities.districts')->findAll(); Where State should be you state model name. cities is the name of the relation as defined in the relations array in State. And districts is the name of the relation as defined in the relations array in City. You can loop through the states and access the de cities and districts with a simple -> foreach($states as $state) { var_dump($state->cities); // will probably be an array of cities foreach($state->cities as $city) { var_dump($city->districts); // will probably be an array of districts } }
{ "pile_set_name": "StackExchange" }
Q: arm neon BSL instruction for floating point Is there an inline asm instruction equivalent for neon intrinsic vbslq_f32? In intrinsic manual there is written BSL Vd.16B,Vn.16B,Vm.16B as asm equivalent for vbslq_f32. But in asm manual there is not implementation for 4S, there is only "8B or 16B (though an assembler should accept any valid format)" and it doesn't work with floats. A: You don't need any data type for bitwise operations. Only the vector length matters, either 64bit or 128bit which you specify by 8b or 16b.
{ "pile_set_name": "StackExchange" }
Q: How to apply 3 conditions in formula field? I am trying apply 3 conditions in formula field. but I'm to complete the requirement. My formula will be like this IF( AND( CreatedById = 'xxxxxx', ISPICKVAL(Scenario__c ,'Budget') ), year(EndDate__c) + 1, IF( AND( CreatedById = 'xxxxxx', NOT(ISPICKVAL(Scenario__c ,'Budget')) ), year(EndDate__c), Fore_Year__c ) ) Required result :(1) If created by id and scenerio = 'Budget' then Result will be Enddate+1, (2)If scenerio not equal to Budget then enddate or else (3)foreyear. Could anybody can help me for this. Thanks A: Try to revise the logic: 1) If CreatedById != 'xxx', then Fore_Year__c (it is your external if condition). 2) If CreatedById = 'xxx', then check Scenario__c. IF ( CreatedById = 'xxxxxx', IF ( ISPICKVAL(Scenario__c ,'Budget'), year(EndDate__c) + 1, year(EndDate__c) ), Fore_Year__c )
{ "pile_set_name": "StackExchange" }
Q: Retrieving data with firebase for Web I am trying to retrieve data from a firebase database : firebase.database().ref("/appointments").orderByChild("doctor").equalTo(doctorId).on("value", function(snapshot) { var appointmentsData = snapshot.val(); for(var appointment in appointmentsData) { if (!appointmentsData.hasOwnProperty(appointment)) continue; var obj = appointmentsData.appointment; } }); If I console.log appointment or console.log appointmentsData, I get the correct value, but if I console.log appointmentsData.appointment, I get undefined. Any idea how I can retrieve the properties and values from the object that firebase returns ? A: You want to use Firebase's built in forEach function. It allows you to iterate through a snapshot and easily get the key and value of each property inside that object. It could be another object or a flat value. firebase.database().ref("/appointments").orderByChild("doctor").equalTo(doctorId).on("value", function(snapshot) { snapshot.forEach(function(childSnapshot) { // key var key = childSnapshot.key; // value, could be object var childData = childSnapshot.val(); // Do what you want with these key/values here ... }); }); Reference: forEach, Firebase 3.0
{ "pile_set_name": "StackExchange" }
Q: Достать значение из docker inspect в файл .env Начал изучать Docker. Создал образ который содержит 4 контейнера: 1. php:7.2-apache 2. mariadb 3. composer 4. phpmyadmin В проекте есть файл .env в котором вписаны настройки подключения к бд: хост, юзер и тд. После запуска образа docker-compose up -d и выполнении команды docker inspect mydb Есть табличка с данными об этом контейнере. "NetworkSettings": { "Ports": { "3306/tcp": null }, "Networks": { "sunrise_default": { "IPAMConfig": null, "Links": null, "Aliases": [ "db", "dd6ec2e0badb" ], "IPAddress": "172.19.0.2", Проблема в том, что при перезапуске образа, IPAddress этого контейнера изменяется, и естественно подключение к бд не работает потому что меняется ip. Можно ли как нибудь достать это значение из dockera при запуска контейнера для того чтобы вставить в файл .env?? Либо есть какой нибудь другой способ для решения этой проблемы? A: Вам чаще всего не надо ориентироваться на что-то столь нестабильное как IP адрес контейнера. Это неправильно с точки зрения самой идеи Docker. Если я правильно понял Вам необходимо обратится из одного контейнера в другой, docker-compose для этого предоставляет функционал внутреннего DNS, каждый контейнер будет доступен другим по имени сервиса в файле docker-compose В представленном случае это имя "db"
{ "pile_set_name": "StackExchange" }
Q: Is there a more efficient way to create new variables in a for loop? If you have an ArrayList (named al in this case), and you're looking to get the first five elements of the list as variables, you could do this: String x1 = al.get(0); String x2 = al.get(1); String x3 = al.get(2); String x4 = al.get(3); String x5 = al.get(4); However, using a for loop, is there a way you could do something like this instead: for (int i = 1; i < 6; i++){ String namer = "x" + i.toString(); String [value of String 'namer'] = al.get(i-1); } Or is there a completely different method that is much more efficient? A: Dynamic metaprogramming is not possible in java. Depending on what you are trying to achieve, there would be various options. If you are trying to work in batches of 5 items, the cleanest solution is the one you are using now. If code duplication bothers you as much as it bothers me, then you are looking into Views in Java Collections Framework, specifically the "View of a portion of a collection" section: List<String> nextFive = list.subList(5, 10); A: You can have a String array of size 6 and do the following: String[] str = new String[6]; for(int i=0; i<str.length; i++) a[i] = al.get(i);
{ "pile_set_name": "StackExchange" }
Q: ReactJS App keeps reloading after React Router DOM i'm trying to implement router to my reactjs app and after setting things up, my page wont even load, it just keeps reloading in my browser till it crashs. This is my app.js import React, { Component } from "react"; import { BrowserRouter, Route } from "react-router-dom"; class App extends Component { render() { return ( <div className="App"> <Header /> <Content job={this.state.header_infos[0].job} college={this.state.header_infos[0].college} /> <Skills /> <Portfolio /> <Timeline /> <Footer /> <BrowserRouter> <Route exact path="/" component={App} /> /* if it clicks in my logo, redirect to mainpage */ <Route path="/monitoria" component={Monitoria} /> /* if clicks in Monitoria from Navbar, redirects to Monitoria component. */ </BrowserRouter> </div> ); } } And this is my Header.js with my navbar import React from "react"; import "../sass/Header.scss"; import { NavLink } from "react-router-dom"; const Header = () => { return ( <header className=""> <NavLink exact to="/"> <h1 className="logo">Logo</h1> </NavLink> <input type="checkbox" id="nav-toggle" className="nav-toggle" /> <nav> <ul> <li className="menu-item"> <NavLink to="/monitoria">Monitoria</NavLink> </li> <a className="btn-rounded" href="#"> <li className="menu-item">Fale comigo</li> </a> </ul> </nav> <label htmlFor="nav-toggle" className="nav-toggle-label"> <span /> </label> </header> ); }; export default Header; If i remove React Router DOM from my App.js my page works just fine. What i'm doing wrong? A: As mentioned in comment, in app.js, you are assigning class App into a route that is contained in the App class.
{ "pile_set_name": "StackExchange" }
Q: sudo: effective uid is not 0, is sudo installed setuid root? (on mac os x 10.12) So I'm a bit of a terminal noob so bear with me but I was trying to update brew to install something, so I ran: brew update and got Error: /usr/local must be writable! Wasn't really sure what that was about so I tried running sudo brew update and got sudo: effective uid is not 0, is sudo installed setuid root? Not sure if this helps but running ls -l $(which sudo) gave me: ls: is: No such file or directory ls: is: No such file or directory ls: is: No such file or directory ls: is: No such file or directory ls: sudo: No such file or directory ls: sudo: No such file or directory ls: sudo: No such file or directory ls: sudo: No such file or directory -r-s--x--x 1 root wheel 369136 Sep 13 20:56 /usr/bin/sudo -r-s--x--x 1 my_profile admin 168448 Jan 13 2016 /usr/local/bin/sudo -r-s--x--x 1 my_profile admin 168448 Jan 13 2016 /usr/local/bin/sudo -r-s--x--x 1 my_profile admin 168448 Jan 13 2016 /usr/local/bin/sudo I tried the suggestion here (using Disk Utility and running First Aid) but it didn't seem to have any effect.... Can anyone tell me what's going on and what I need to do? A: If you run ls -la /usr, the result most likely will be something like below: total 0 drwxr-xr-x@ 11 root wheel 374 Oct 14 14:35 . drwxr-xr-x 32 root wheel 1156 Oct 26 09:49 .. drwxr-xr-x 19 root wheel 646 Oct 10 18:51 local ... (some other files and directories) Now it's obvious from the above that unless you are logged in as a root or your user is in the wheel group (which is most likely not), any command you issue with your user which needs write permission (such as brew update) will fail. One of the possible solutions (and I am not claiming is the best one) would be to change permissions of /usr/local. Like so: sudo chown -R $(whoami) /usr/local Interestingly enough, if you then run brew update all goes well and you get the following message: => Migrating HOMEBREW_REPOSITORY (please wait)... ==> Migrated HOMEBREW_REPOSITORY to /usr/local/Homebrew! Homebrew no longer needs to have ownership of /usr/local. If you wish you can return /usr/local to its default ownership with: sudo chown root:wheel /usr/local Which I guess explains what happened in the first place. Hope that helps.
{ "pile_set_name": "StackExchange" }
Q: How deploy intranet WCF-service for Windows 8 store application We are developing a desktop Windows 8 application, that work with WCF-service. We want enable work with Azure WCF-service and with WCF-service in local network(choosingly). Application will be publish in Windows Store. What the best practise deploy WCF-service on local server of company? A: I understand what you want. Let's pretend the Azure part is not an option. How can a Windows Store App use a local service (WCF or not)? That's the fundamental question. Here's the answer(s): First, a Windows Store App cannot access intranet services unless it has private network access declared in its manifest. It looks like this: Second, in order to use private networks in your manifest and get accepted into the Windows Store, you must be a company publisher and not an individual. More on this is discussed in this SO question: Which features are allowed for company store accounts and not individual? Third, a local service cannot be mistakenly thought of as localhost. To this end, localhost is not available to Windows Store Apps, unless they are side-loaded (which means they are manually installed and not delivered through the Windows Store at all). To access localhost, you can enable loopback, but, as I stated, this disqualifies you from the Windows Store. There's more on this here: How does Windows 8 Loop Back work? Forth, because you are talking about a service, you might want to authenticate the user. This is accomplished using enterprise authentication (just like in number 1) only a few checkboxes higher. And it has the same restrictions as private networks. Fifth, you are not asking this, but to be clear, local access does not mean you can speak to a local SQL server. The reason for this is because the SQL namespace is not part of WinRT or .Net for WinRT. Windows Store Apps are intended to be service-based apps. And, that's about it. I think you are good if you follow that. It doesn't sound like you are talking about a pure enterprise-play, but it might be interesting to you to read through some of the strategies for enterprise developers: http://blog.jerrynixon.com/2012/08/windows-8-apps-whats-enterprise-to-do.html As for deploying WCF, there's nothing special just because a Windows Store App is accessing it. So for deployment, just use vanilla techniques you are already using. :) That's it. Best of luck!
{ "pile_set_name": "StackExchange" }
Q: Case-insensitive order_by on GAE using django non-rel Using google app engine and Django non-rel, I'm querying a list of movies and want to order them alphabetically. movies = Movie.objects.all().order_by("title") The problem is for any titles that do not start with an uppercase character is not following the same sort pattern. So if queried these movies and returned them sorted then "iRobot" would not be between Batman and Zoolander: Armageddon Batman Zoolander iRobot How do I get them to do a case-insensitive order_by? Thanks A: You need to denormalize: store a separate property that contains a lower-case version of the title, and sort on that.
{ "pile_set_name": "StackExchange" }
Q: Difficult family conflict about inheritance My mother died 2 years ago and left a house to me and my two younger brothers. She wasn't very good with money and got herself in financial difficulty about 10 years ago and had to be helped with a loan from my uncle to stop her house from being repossessed. There was a contract between them so legally there is no dispute, the contract was for 3% simple interest per year on the loan amount. Also my mother offered to repay the money owed 18 months before her death, the offer was refused due to my uncles legal/business problems at the time. The problem is this, My uncle says that he took out a mortgage of his own to lend the money to my mother (this only came to light after my mother died and the mortgage documents he has to prove this are dated one month after the contract he had with my mother). He wants to be repaid the loan amount, all of the repayments he has made towards the mortgage he took out and 3% interest on the repayments he has made. In addition to this he has difficulty showing the specific repayment amounts because at some point he rolled the mortgage up into another mortgage for a larger amount. My uncle won't be happy if he doesn't get what he has asked for and might cause difficulty for me and my brothers in our extended family. Me and my two brothers each hold different opinions on this issue and we cannot find a way to reconcile them. My eldest brother only wants to pay what is in the contract, I want to pay an amount that wouldn't see my uncle out of pocket for helping my mother and my youngest brother wants to pay him whatever he has asked for. I do not know how to move forward with this. I have already sought legal council and legally any challenge to the contract is extremely unlikely to succeed, this question is only about the family conflict and how to deal with it. A: Money burns bridges Ask your uncle the amount he wants. You stated this on your question, so you should've known by now.. Pay back your uncle whatever the amount your mother owed him, according to the contract. After that1, calculate the difference between the amount he wants and the amount already repaid. Talk with your brothers how much amount (all of) you can and willing to spare for your uncle. Explain to your uncle that the contract has been honored, and this is an appreciation for what he has done. Don't mention any of his mortgage. If he brings it up, thank him for going so far to help your mother, and politely remind him that his mortgage is not in contract and is his responsibility. Avoid further arguments. Give2 the money to him. 1You must finish the contract first before going to the next step. This is to ensure that your responsibility is done, and your uncle can't bring it up in argument. One scenario is your uncle might refuse the payment. Simply transfer the amount to his bank account, and it is a proof that you have paid him. Whatever he will do to that money afterward does not disprove that you have made a payment, including transferring back the money. 2Not pay. You don't owe him anything after you honor your contract. You are not responsible to your uncle bad choices. This is basically a step-by-step to solve this and avoid complication on your morality. Stop feeling guilty. After this drama, you can offer help to your uncle to get through his debt. Personally, I prefer gifts (as money), as you will be prepared not to see your money back, but you can also offer loan, with contract. Remember that "money burns bridges". Everything will never be the same. Whatever your other relatives might think of you, don't feel guilty. You've completed the contract, and you already offering help to your uncle. A: Honor the contract your mother made with him. If she had paid it back (it was not paid back in full at your uncle's request), this would not be an issue. Asking you to take on a burden he made a decision to take does not obligate you to take it on as well. His claims are murky at best and suspicious at worst. ...all of the repayments he has made towards the mortgage he took out and 3% interest on the repayments he has made. He's basically asking you to pay for his bad business decisions (if he could not afford to lend your mother money without endangering himself, he shouldn't have done so.) Repaying his mortgage payments in addition to the loan is basically giving him a big chunk of money for free. If you're afraid there's a real chance he can make life miserable for you, offer him a token, say, increase the interest on your mother's loan to the percent he is paying on his own mortgage loan(s). So if he's paying 5%, give him the amount she owed plus 5% interest (compound or whatever the contract stipulates.) If you have real feelings/care about this uncle, you can be more generous and, say, double his interest on your mother's loan. Or, conversely, you can offer him a loan at your mother's rate of interest to cover the (murky) difference between his loan repayments (only up to your mother's death), but know that you will not get this money back. If you're afraid of what other relatives say, it depends on how important their opinion of you is. Money makes for tricky situations. Edited to reflect comments. A: Quite frankly, your uncle's actions don't speak to good faith on his part. If I'm understanding correctly, your mother offered to pay the loan in full, and your uncle refused. Yet now that your mother is gone, he suddenly is claiming that he has additional out-of-pocket expenses because he over-extended himself on the loan he made to your mother. The first question that springs to mind is: did he discuss this mortgage, and his payments on it, with your mother? If he did, ask him what she said. If he didn't... then you need to ask yourself why he would keep that a secret from your mother, but suddenly become very open about it, and ask for extra compensation for it, with you and your brothers. I'd be very hesitant to give him anything beyond what the contract states. It really sounds like he has decided that he deserves more than was left to him, and sees you and your brothers taking over her estate as an opportunity to get it.
{ "pile_set_name": "StackExchange" }
Q: /etc/shadow in old format, where is salt stored? In /etc/shadow I have entries such as admin:YtChlvAGYzva2:16318:0:99999:7:::. I know the original password and would like to generate the same hash somehow. However, running openssl passwd -crypt password gives me different results every time I run it. I assume salt is involved, so where can I find the salt used to create the original hash? Edit: I got the original hash using the following command: openssl passwd -crypt -salt Yu password A: The salt and the encrypted password are both mashed into the string YtChlvAGYzva2. From the Shadow Password Howto: When a user picks or is assigned a password, it is encoded with a randomly generated value called the salt. This means that any particular password could be stored in 4096 different ways. The salt value is then stored with the encoded password. When a user logs in and supplies a password, the salt is first retrieved from the stored encoded password. The longer password strings you see with modern systems separate the hash using $. But for the older systems, it was just mashed in (Wikipedia): Earlier versions of Unix used a password file (/etc/passwd) to store the hashes of salted passwords (passwords prefixed with two-character random salts). In these older versions of Unix, the salt was also stored in the passwd file (as cleartext) together with the hash of the salted password. In your example, I believe that the salt is "Yt" and the encrypted password is "ChlvAGYzva2". It's literally the first two characters of the string.
{ "pile_set_name": "StackExchange" }
Q: Create Document Library using Client Object Model Just a quick question, is it possible to create a Document Library using the Client Object Model in SharePoint 2010? I know you can create lists etc. Am I right in saying that a Document Library is just a 'special' type of List? How can I specify that the List I create will be a Document Library? Any help will be appreciated Thanks A: Yes. You can specify the TemplateType for your List. List of TemplateTypes using (ClientContext clientCTX = new ClientContext(url)) { ListCreationInformation lci = new ListCreationInformation(); lci.Description = "My own DocLib"; lci.Title = "Library"; lci.TemplateType = 101; List newLib = clientCTX.Web.Lists.Add(lci); clientCTX.Load(newLib); clientCTX.ExecuteQuery(); } A: You can also set the templatetype with the following code, which I think makes things clearer to new programmers: lci.TemplateType = (int) ListTemplateType.DocumentLibrary;
{ "pile_set_name": "StackExchange" }
Q: Adding an individual array list item to individual tile I am currently trying to place individual items within an array list into individual tiles within a inventory GUI. All the tiles are set up and I can display each array list item individually within the console line. This is the simple GUI: This is my attempt so far. HBox itemTile[] = new HBox[31]; for (int i = 0; i < 30; i++) { Button deleteButton = new Button("Delete Item"); deleteButton.setOnAction((ActionEvent event) -> { displayItems2(); //temp info to console - delete item code to be added JOptionPane.showMessageDialog(null, "Item has been deleted", null, 1); }); itemTile[i] = new HBox(new Label("Item: " + i + " ")); itemTile[i].setStyle("-fx-border-color: black;"); itemTile[i].setPadding(new Insets(5)); itemTile[i].getChildren().add(deleteButton); itemTile[i].setAlignment(Pos.CENTER_LEFT); itemTile[i].setStyle("-fx-background-color: #e5efff; -fx-border-color: black;"); this.getChildren().add(itemTile[i]); } } private void displayItems2(){ this.getChildren().removeAll(this.getChildren()); displayInvStructure(); ArrayList<String> descs = InventoryManager.getInstance().getItemDescriptions(); for (int i = 0; i < descs.size(); i++) { String retString = descs.get(i); System.out.println("Array item is = " + " " + i + " " + retString); } //If i = itemTile[i] //Add retString to itemTile[i] } How do I place each individual retString into each tile using the itemTile[i]? I'm relatively new to coding and Java, so I have a sneaking suspicion I am over complicating things. A: If you want to assign values to the itemTile array inside a method like displayItems2, there are two possibilities: 1) pass a reference to itemTile into displayItems2 or 2) make itemTile a class member. Example 1 (pass a reference): private void displayItems2(HBox itemTile) { // [...] itemTile[i] = descs.get(i); } Example 2 (class member): class MyClass { // [...] HBox itemTile; // [...] private void displayItems2() { // [...] itemTile[i] = descs.get(i); } }
{ "pile_set_name": "StackExchange" }
Q: How can I get all the plain text from a website with Scrapy? I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework. With xpath('//body//text()') I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? A: The easiest option would be to extract //body//text() and join everything found: ''.join(sel.select("//body//text()").extract()).strip() where sel is a Selector instance. Another option is to use nltk's clean_html(): >>> import nltk >>> html = """ ... <div class="post-text" itemprop="description"> ... ... <p>I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework. ... With <code>xpath('//body//text()')</code> I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks !</p> ... ... </div>""" >>> nltk.clean_html(html) "I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework.\nWith xpath('//body//text()') I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks !" Another option is to use BeautifulSoup's get_text(): get_text() If you only want the text part of a document or tag, you can use the get_text() method. It returns all the text in a document or beneath a tag, as a single Unicode string. >>> from bs4 import BeautifulSoup >>> soup = BeautifulSoup(html) >>> print soup.get_text().strip() I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework. With xpath('//body//text()') I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks ! Another option is to use lxml.html's text_content(): .text_content() Returns the text content of the element, including the text content of its children, with no markup. >>> import lxml.html >>> tree = lxml.html.fromstring(html) >>> print tree.text_content().strip() I would like to have all the text visible from a website, after the HTML is rendered. I'm working in Python with Scrapy framework. With xpath('//body//text()') I'm able to get it, but with the HTML tags, and I only want the text. Any solution for this? Thanks !
{ "pile_set_name": "StackExchange" }
Q: jQuery function works on localhost but not on the web Really scratching my head on this one and couldn't find a related post anywhere. So I have a function on my website that when a user clicks their avatar two divs tog visibility using jQuery. The end result should look like this: On my localhost everything works fine and I can see the animation but when I bring everything to the web it seems to break down and stop working right. I get this: I tried to mess with the z-index, clearing my cache, and toggling visibility using dev tools but nothing worked. I had a friend go to the site and try it out and the animation works fine for him and he gets the desired animation. You can view the site here: http://infalliblegaming.com/ And btw when I click the avatar the animation goes all the way to the end but then seems to "pop up" into the navbar and is not visible by me on chrome. (if I inspect element on it though I can see the code) username: aelo and password : aeloraelor jQuery: $("#avatar").click(function(){ $("#avatarstats").stop().animate({ width:'toggle', visibility:'toggle' }); $("#avatardropdown").stop().animate({ width:'toggle', visibility:'toggle' }); }); A: In your main.css, try to change your blogspot class to position: block, or just remove the position attribute. main.css, line 159 .blogpost { position: relative; (remove) background:white; border:1px solid #333; margin-top:5px; margin-bottom:5px; box-shadow:1px 1px 5px #333; max-height:500px; overflow:hidden; } Observing the two screenshots, it seems that the first one was taken from a bigger screen. Look this: Screen
{ "pile_set_name": "StackExchange" }
Q: Confused with mysql statement, three tables So i have this problem of printing out table data from 3 different tables as a matrix. And after searching internet, i fanally found a solution to my problem. But i have no idea, how does that mysql statement work. This is a example that i want to do and i think i found a solution so if some one could help explaining me of how it works? SELECT names.codename, s1.score AS "Score1", s1.comment AS "Comments1", s2.score AS "Score2", s2.comment AS "Comments2", SUM(st.score) AS "Total" FROM students names LEFT JOIN scores s1 ON s1.act_id=1 AND names.id=s1.student_id LEFT JOIN scores s2 ON s2.act_id=2 AND names.id=s2.student_id LEFT JOIN scores st ON names.id=st.student_id WHERE names.codename <> '' GROUP BY names.codename ORDER BY names.codename; students table: +----+---------------+ | id | codename | +----+---------------+ | 1 | Budy | +----+---------------+ assignments table: +--------+------------+ | act_id | name | +--------+------------+ | 1 | Activity 1 | | 2 | Activity 2 | +--------+------------+ scores table: +------------+--------+-------+ | student_id | act_id | score | +------------+--------+-------+ | 1 | 1 | 10 | | 1 | 2 | 10 | +------------+--------+-------+ Now the problem was, I wanted to have the assignments listed across the top, and the scores next to the names. Something like this: +---------------+------------+------------+-------+ | codename | Activity 1 | Activity 2 | Total | +---------------+------------+------------+-------+ | budy | 10 | 10 | 20 | +---------------+------------+------------+-------+ A: Try this SELECT s.codename, SUM(IF(act.act_id=1, act.score, 0)) AS 'Activity 1', SUM(IF(act.act_id=2, act.score, 0)) AS 'Activity 2', total.score AS 'total' FROM students s INNER JOIN (SELECT student_id, act_id, SUM(score) AS score FROM scores GROUP BY 1, 2) act ON s.id=act.student_id INNER JOIN (SELECT student_id, SUM(score) AS score FROM scores GROUP BY 1) total ON s.id=total.student_id GROUP BY 1 This will return results for only the students having records in the scores table. If you want to list all students, you'll have to change INNER JOIN to LEFT OUTER JOIN UPDATE I've updated the query and removed the first sub-query SELECT student_id, act_id, SUM(score) AS score FROM scores GROUP BY 1, 2 this is not needed if student_id and act_id are a composite key so we can use the scores table directly. This way the query becomes SELECT s.codename, SUM(IF(act.act_id=1, act.score, 0)) AS 'Activity 1', SUM(IF(act.act_id=2, act.score, 0)) AS 'Activity 2', total.score AS 'total' FROM students s INNER JOIN scores as 'act' ON s.id=act.student_id INNER JOIN (SELECT student_id, SUM(score) AS score FROM scores GROUP BY 1) total ON s.id=total.student_id GROUP BY 1 Explanation The JOIN between student and scores fetches all scores for all students (I added another student with id 2 and name Pal), e.g. +----+----------+------------+--------+-------+ | id | codename | student_id | act_id | score | +----+----------+------------+--------+-------+ | 1 | Buddy | 1 | 1 | 10 | | 1 | Buddy | 1 | 2 | 10 | | 2 | Pal | 2 | 1 | 15 | | 2 | Pal | 2 | 2 | 10 | +----+----------+------------+--------+-------+ The sub-query SELECT student_id, SUM(score) AS score FROM scores GROUP BY 1 fetches sum of scores for each student like this +------------+-------+ | student_id | score | +------------+-------+ | 1 | 20 | | 2 | 25 | +------------+-------+ And we put the results together in the main SELECT part using SELECT s.codename, SUM(IF(act.act_id=1, act.score, 0)) AS 'Activity 1', SUM(IF(act.act_id=2, act.score, 0)) AS 'Activity 2', total.score AS 'total'... we add scores if act_id=1 in column 'Activity 1', similarly we add scores in column 'Activity 2' if act_id=2 and lastly we use the sum from sub-query as 'total' I hope this clarifies your questions
{ "pile_set_name": "StackExchange" }
Q: env not reading variables in ./profile on new session I might be doing something very wrong here, but when I edit my .profile file and I set a new PATH variable I am not able to see it set when I start a new session. So after saving the .profile file I open a new terminal window, type env and the variables are not there. What is it that I am missing? Thanks A: I think ".profile" is only read when invoked as a login shell. You could try putting these variables in your ".bashrc" file.
{ "pile_set_name": "StackExchange" }
Q: How to change str object to datetime.time in python3? First adding the code: import csv from datetime import datetime, date, time with open('T2.csv') as readcsvfile: readcsv=csv.reader(readcsvfile) header=next(readcsv) data=[] for row in readcsv: # if-else construct to read both empty & time string if row[0]==str(): date=str() else:date=datetime.strptime(row[0],'%y%m%d') # stripping the 170101 part with str(ing)p(arse)time and # changing the style/format into '%Y/%m/%d' format with strftime. ID=str(row[5]) if row[6]==str(): O_all=str() else:O_all=datetime.strptime(row[6],'%H:%M').strftime('%H:%M') Combined_datetime=datetime.combine(date,O_all) data.append([Combined_datetime,ID]) print(data) Yields the error: Combined_datetime=datetime.combine(date,O_all) TypeError: combine() argument 2 must be datetime.time, not str But if I check the types, both "date" & "O_all" are 'datetime.datetime' objects. I guess I'm missing something or understood something wrongly. What could be the remedy to get a timetuple named as 'Combined_datetime'? A: The problem was elsewhere. While reading my csv, I could read all the row with simple if-else construct (empty time was considered as empty string). But while combining the date & time with datetime.combine(d,t), it could not handle the empty strings. @amarnath Your suggestion for adding .time() helped though. I removed the rows with empty time this time. Actually it overrides the TypeError: combine() argument 2 must be datetime.time, not str error in this way. Here is the complete working code: #Reading T2 & writing new csv import csv from datetime import datetime, date, time with open('T2.csv') as readcsvfile: readcsv=csv.reader(readcsvfile) header=next(readcsv) data=[] for row in readcsv: #if-else construct to read both empty & time string if row[6]!=str(): d=datetime.strptime(row[0],'%y%m%d') t=datetime.strptime(row[6],'%H:%M').time() print(type(d)) ##stripping the 170101 part with str(ing)p(arse)time and ##changing t from datetime.datetime to datetime.time with `.time()` print(type(t)) ID=str(row[5]) Combined_datetime = datetime.combine(d, t) data.append([Combined_datetime,ID]) print(data) with open('T2_w3.csv','w',newline='') as writecsvfile: writecsv=csv.writer(writecsvfile) writecsv.writerow(['Combined_datetime','ID']) for i in range(len(data)): ROW=data[i] CDT=ROW[0] ID=ROW[1] Final_list=[CDT,ID] writecsv.writerow(Final_list)
{ "pile_set_name": "StackExchange" }
Q: How to resume contact with a former manager who I haven't talked to for 3 years? My manager left the company 3 years ago. I have been on good terms with him. I kept in touch with him for a few months after he left. Then other things became a priority, and I unintentionally neglected to remain in contact with him. Now, I am looking for a job change, and one of the options I am looking for is an opportunity to work with him again. I am fairly certain he would be happy to have me in his team (or at least, he "wouldn't mind"). If I just call him and say, "I am looking for a job change. Would you consider me in your team?", it would sound rather selfish, and I am not comfortable doing this. How do I resume contact with him with this goal in mind, with minimum awkwardness? A: There's nothing wrong with getting back in touch because you're looking for work. In fact, I'd recommend against random "hey how are you it's been a while" contact that slowly morphs to "oh yeah btw I'm looking for a job." It's dishonest and it doesn't fool anyone. However, straight up "can I come work for you?" is very direct and may leave the old manager feeling pressured or unable to decline, resulting in potential embarrassments to you both like an interview you could never succeed in. Instead, be clear that you are looking for work and asking for help, but don't ask your manager to hire you. If the manager happens to be hiring, or to be in a position to open up a space for you, you don't need to suggest such a thing - a good manager can think of that themselves. I would probably email something like this: Hi [name], hope this finds you well. A lot has been going on for me these past few years, and I'm looking for a job change, so I'm reaching out to people I've enjoyed working with in the past. If you know of something available that would suit me, I'd really appreciate any introductions or information you can provide. Since we last worked together I've [learned C++, shipped 3 commercial products, been promoted to senior DBA, taken on more project management, whatever] and I'm looking for a role where I can [continue to learn and grown, lead a team, get into Internet of Things work, speak at conferences several times a year] and [some other thing you want.] Are you aware of anything? Key points about this email are that it lets your manager know how you've grown since your last communication, and describes the position you want. Don't make your manager do all the work of figuring out what would be good for you. In addition to avoiding the pressure of directly asking for a role with the manager, this approach also means that the manager can tell you about "a great opportunity with a friend of mine" without it being some sort of consolation prize to make up for not having a job to offer you. Depending on the response you get you could elaborate that "I really enjoyed working for you and it would be really cool if there was an opening at your firm" but I wouldn't include that in the first email. A: How do I resume contact with him with this goal in mind, with minimum awkwardness? I think the best thing you can do is send him an email asking how he is doing. If you're close enough maybe even a phone call, this would be a stronger approach versus an email. Once you are comfortable that the relationship is intact, then you could ask them to be a reference for you. By asking if they will be a reference, if they are still comfortable with you, they may offer up any opening they have influence over on their own, and you may not have to ask. If you have successfully reconnected, and they don't offer, then ask them about potential opportunities within their organization. By doing this in a general indirect manner, you're allowing your contact to decide whether or not they want to work with you again. Basically, you are attempting to elicit either "Hey I have an opening" or "I know someone who does" type of response. Good luck! A: I think the best way to raise this with your old boss is to send him an email or call to check in, mention you're looking for a new job, and suggest meeting up for coffee or lunch to catch up if he has any openings. If he takes you up on it, then you go, catch up, and have a nice time (also, definitely offer to treat your boss, since you're asking for a favor). A politely worded email would work too, but face-to-face contact makes it easier to re-establish a rapport, especially if it's been a while. Honestly, if you got along well before, I think it's just a matter of re-establishing communication. Most people I know would be happy to help out an old colleague that they got along well with.
{ "pile_set_name": "StackExchange" }
Q: Using an array in a Where clause So what I need to do is find in my tables where id = id and name = name. I have tried this with no success. $sql="SELECT * FROM $mysqltable WHERE id='$id' && name='$name'" EDIT I found that I was missing a } bracket below this and the above code does work :/ Thank you everyone. A: This is how i would have done it: Also try entering the table name instead of a variable. $sql = "SELECT * From $mysqltable WHERE id='$id' AND name='$name'"; $result = mysql_query($sql) or die(mysql_error());
{ "pile_set_name": "StackExchange" }
Q: C# TableLayoutPanel replace control? I was wondering if it was possible to replace one control in a TableLayoutPanel with another at runtime. I have a combo box and a button which are dynamically added to the TableLayoutPanel at runtime, and when the user selects an item in the combo box and hits the button, I'd like to replace the combobox with a label containing the text of the selected combo box item. Basically, if I could simply remove the control and insert another at it's index, that would work for me. However I don't see an option like "splice" or "insert" on the Controls collection of the TableLayoutPanel, and I was wondering if there was a simple way to insert a control at a specific index. Thanks in advance. A: Fixed this by populating a panel with the two controls I wanted to swap and putting that into the TableLayoutPanel. Then I set their visibility according to which I wanted to see at what time.
{ "pile_set_name": "StackExchange" }
Q: Ext js message box - not opening in IE7 I am using Ext js MessageBox to display some warning messages in my application. The code looks as below: Ext.MessageBox.show({ title: 'Confirm', msg: "Some warning message", icon: Ext.MessageBox.WARNING, buttons: Ext.MessageBox.OKCANCEL, fn: function(btn) { if (btn === 'ok') { //Some functionality if (condition) { **showTaxIdWarningMessage();** } else { //some code } } else { // some code } } }); The showTaxIdWarningMessage(); function is as below: function showTaxIdWarningMessage() { Ext.MessageBox.show({ title: 'Confirm', msg: 'Second warning message', icon: Ext.MessageBox.WARNING, buttons: Ext.MessageBox.OK, fn: function(btn) { if (btn === 'ok') { //some functionality } } }); } This code works perfectly on Chrome and IE11. Meaning, I am able to display both the warning messages without any issues. The real problem arises when I have to display these warning messages on IE7 (The application is viewed in compatibility mode on higher environments). On IE7, I'm left with the error message below: SCRIPT5007: Unable to get property 'addCls' of undefined or null reference ext-all-dev.js (133868,21) The Ext js version 4 is used in the application. I am trying to debug to find the issue but so far, I am not able to find anything. Any help is much appreciated. A: I think I made a naive mistake here. Modifying the code as below worked for me: Ext.onReady(function() { ....... functionWithMessageBoxCode(); ....... }); The above change made my code work properly on IE7 and Chrome as well. Posting it here, thinking it might help other rookie developers working Ext js.
{ "pile_set_name": "StackExchange" }
Q: Generate data seeding script using PowerShell and SSMS Here I found a solution for the manual creation of the data seeding script. The manual solution allows me to select for which tables I want to generate the inserts I would like to know if there is an option to run the same process via PowerShell? So far I have managed how to create a SQL script which creates the Database schema seeder: [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null $s = new-object ('Microsoft.SqlServer.Management.Smo.Server') "(localdb)\mssqlLocalDb" $dbs=$s.Databases #$dbs["HdaRoot"].Script() $dbs["HdaRoot"].Script() | Out-File C:\sql-seeding\HdaRoot.sql #Generate script for all tables foreach ($tables in $dbs["HdaRoot"].Tables) { $tables.Script() + "`r GO `r " | out-File C:\sql-seeding\HdaRoot.sql -Append } however is there any similar way to generate the data seeding script? Any ideas? Cheers A: You can use the SMO scripter class. This will allow you to script the table creates as well as INSERT statements for the data within the tables. In my example I'm directly targeting TempDB and defining an array of table names I want to script out rather than scripting out every table. Scripter has a lot of options available, so I've only done a handful in this example - the important one for this task is Options.ScriptData. Without it you'll just get the schema scripts that you're already getting. The EnumScript method at the end does the actual work of generating the scripts, outputting, and appending the script to the file designated in the options. [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null ## target file $outfile = 'f:\scriptOutput.sql' ## target server $s = new-object ('Microsoft.SqlServer.Management.Smo.Server') "localhost" ## target database $db = $s.databases['tempdb'] ## array of tables that we want to check $tables = @('Client','mytable','tablesHolding') ## new Scripter object $tableScripter = new-object ('Microsoft.SqlServer.Management.Smo.Scripter')($s) ##define options for the scripter $tableScripter.Options.AppendToFile = $True $tableScripter.Options.AllowSystemObjects = $False $tableScripter.Options.ClusteredIndexes = $True $tableScripter.Options.Indexes = $True $tableScripter.Options.ScriptData = $True $tableScripter.Options.ToFileOnly = $True $tableScripter.Options.filename = $outfile ## build out the script for each table we defined earlier foreach ($table in $tables) { $tableScripter.enumscript(@($db.tables[$table])) #enumscript expects an array. this is ugly, but it gives it what it wants. }
{ "pile_set_name": "StackExchange" }