qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
241,822
I'm preparing a class on Visual Basic 2005 targeting Visual Basic 6 programmers migrating to the .NET platform. My primary concern is to teach my students the best practices for developing in .NET, and I am wondering about whether to consider the use of the VB runtime functions VB.NET legitimate or not. I have read that many of the VB functions in VB.NET actually invoke methods on the .NET Framework, so it appears they exist primarily to ease the transition from earlier versions of Visual Basic to VB.NET. However, [the VB.NET team](http://blogs.msdn.com/vbteam/) seems to recommend to use them whenvever possible since they claim they put some optimizations in there on top of the .NET framework APIs. What's your take on this?
2008/10/28
[ "https://Stackoverflow.com/questions/241822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26396/" ]
There's already a lot for VB6 programmers to learn in moving to VB.NET. Why not let them use the VB functions at first, but do teach them the .NET framework versions. Later they could switch to the .NET framework functions, particularly if they are likely to need to use C# too. EDIT (much later): two renowned VB gurus take opposing views! * Francesco Balena (in his popular book [Programming Microsoft Visual Basic 2005: The Language](https://rads.stackoverflow.com/amzn/click/com/0735621837)) recommends ex-VB6 developers learn the .NET syntax as soon as they feel comfortable with the new language and avoid using methods and classes in Microsoft.VisualBasic namespace if possible [p. 100]. His point is that in general native .NET methods offer better flexibility and learning them is an investment in case you later need to use C# or another .NET language. * Dan Appleman (in *his* popular book [Moving to VB.NET: Strategies, Concepts, and Code](https://rads.stackoverflow.com/amzn/click/com/1893115976)) recommends you feel free to stick with the native Microsoft.VisualBasic namespace avoiding only those in the Microsoft.VisualBasic.Compatibility.VB6 namespace [p. 265]. His point is that Microsoft.VisualBasic is a core part of the .NET framework.
If you're teaching VB, those functions are part of VB. If you're teaching the .Net Framework, those functions aren't part of the Framework. If you're trying to get your work done and you have tools available, use your tools.
261,825
How would I prevent OS X even *looking* for a swap file? I killed the swap file on my MBP. This is dead easy: just change the default swap file location so the system can't find it (goto /System/Library/LaunchDaemons/com.apple.dynamic\_pager.plist, change the last `<string>` in the `ProgramArguments` section.) This achieves what I wanted it to achieve. My swap file is always 0mb and hence I can leave my mac on for weeks without the crippling swap-induced slowdown I came to loathe. The question is, **how can I stop the system looking for the swap file**? The swap is never created because the path specified in the .plist file doesn't exist. But the system still looks for it, meaning a background process every 10 seconds, which looks like this: ``` dynamic_pager: cannot open swap directory /your/fake/directory/here (com.apple.dynamic_pager[123]) Exited with exit code: 1 (com.apple.dynamic_pager) Throttling respawn: Will restart in 10 seconds ``` I want to stop this from happening, so my machine isn't constantly seeking something that isn't there, and to placate my innate OCD nature (as far as I can tell, this isn't using any real footprint). Does anyone know how?!
2011/03/24
[ "https://superuser.com/questions/261825", "https://superuser.com", "https://superuser.com/users/73239/" ]
Use nmap. example: `nmap -sn 10.10.10.0/24` The arp cache will only tell you those that you have tried to contact recently.
If your network is `192.168.0.0/24`, make an executable file with the following code; Change the `192.168.0` to your actual network. ``` #!/bin/bash for ip in 192.168.0.{1..254}; do ping -c 1 -W 1 $ip | grep "64 bytes" & done ```
23,105,709
I have have some trouble in understanding what is needed to fetch a JSON file with mantle.h from a URL. Can someone give me an example of how it works? For example: -I have a URL www.example.com with a JSONFile as follows: ``` { "name": "michael" } ``` How could I fetch it?
2014/04/16
[ "https://Stackoverflow.com/questions/23105709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2906041/" ]
I use this process for fetching JSON: ``` NSURL *s = url;//Put your desird url here NSURLRequest *requestURL = [NSURLRequest requestWithURL:s cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.00]; NSHTTPURLResponse *response; NSError *error = [[NSError alloc]init]; NSData *apiData = [NSURLConnection sendSynchronousRequest:requestURL returningResponse:&response error:&error]; dictionaryData = [NSJSONSerialization JSONObjectWithData:apiData options:kNilOptions error:&error]; ``` Now the `dictionaryData` contains your JSON. You can fetch it by: ``` NSString *name = [dictionaryData valueForKey:@"name"]; ``` And make sure you are making async request. For this put the code within this block: ``` dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ //Put the code here }); ``` Hope this helps.. :)
Call it with following method ``` [super getRequestDataWithURL:urlString andRequestName:sometext]; ``` You will get response in the following method if successful ``` - (void)successWithRequest:(AFHTTPRequestOperation *)operation withRespose:(id)responseObject withRequestName:(NSString *)requestName { NSString *response = operation.responseString; id jsonObject = [response objectFromJSONString]; if(![super checkforServerRequestFailureErrorMessage:jsonObject]) { [self.leaderboardProxyDelegate leaderboardListSuccessful:jsonObject]; } } ``` You will get dictionary in jsonObject
3,831,510
If $a$ is a constant, what is the name of a curve of the form $a\*(x+y) = x\*y$? And how is this equation related to more this curve's more general equations/characteristics? Plotting this curve, I would risk calling it a hyperbola, but I'm not sure it is, or why it would be one. This equation is similiar to the equivalent parallel resistance formula for two resistors in eletronics (if rearranged: $a = \frac{x\*y}{x+y}$).
2020/09/18
[ "https://math.stackexchange.com/questions/3831510", "https://math.stackexchange.com", "https://math.stackexchange.com/users/826560/" ]
$$xy=a(x+y)$$ $$xy-ax-ay=0$$ $$xy-ax-ay+a^2=a^2$$ $$(x-a)(y-a)=a^2$$ The curve is an hyperbola.
Every 2-degree equation in x and y represents a conic. So, if you see two branches in its graph, it is always going to be a hyperbola.
60,312,824
I want to `console.log` the result of my query using ajax, but it outputs the CI Landing page in the HTML Code. **JS:** ``` function getRouters(data) { $.ajax({ type: 'POST', url: "http://localhost/ldcm/Main_controller/getRouters", data: data, success: function (data) { console.log(data); } }); } $('#generateRes').click(function () { var data = userDetailsObj.data.homesize.id + userDetailsObj.data.floors.id + userDetailsObj.data.internetPlan.id + userDetailsObj.data.devices.id; console.log(data); if(data) { getRouters(data); } else{ } }); ``` **Controller:** ``` public function getRouters(){ $data = $_POST['data']; $this->load->model('Query_Model'); $data = $this->Query_Model->getRouters($data); echo json_encode($data); } ``` **Model:** ``` public function getRouters($data) { $this->db->select('*'); $this->db->where('id', $data); $q = $this->db->get('selection'); $response = $q->result_array(); return $response; } ``` Is it supposed to print that way? Or did i miss a configuration part in config?
2020/02/20
[ "https://Stackoverflow.com/questions/60312824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11188851/" ]
A typical way to handle the order of execution for two different asynchronous operations would be to use promises. ```js var d = $.Deferred(); (function whileLoop(n) { setTimeout(function () { let hashArr = Array.apply(null, Array(n)).map(() => { return '#' }); console.log(hashArr); if (--n) whileLoop(n); else d.resolve(); }, 2000) })(6); d.then(function() { (function whileLoop(n, m) { setTimeout(function () { let hashArr = Array.apply(null, Array(n)).map(() => { return '#' }); console.log(hashArr); if (n < m) { ++n; whileLoop(n, m); } }, 2000) })(1, 6); }); ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> ```
You are almost there. I see that you understand that the recursive call to `setTimeout` emulates a while loop asynchronously. And I see that you understand how to decide when to continue the "loop" and when to stop: ``` if (--n) whileLoop(n); ``` You just need to realize that the loop ends when the `if` condition is false. Thus, to run the second while loop just start it in the `else`: ``` if (--n) { whileLoop(n); } else { whileLoop2(1,6); } ``` There's a few repercussions of this: 1. The second `whileLoop` must be re-written to **NOT** be an IIFE - it must be a regular function called at the end of the first `whileLoop` as above. 2. You cannot reuse the name `whileLoop` for both functions. To differentiate the functions you must rename either the first or second "loop" functions. This preserves your current logic requiring only 4 lines to be changed to get the behavior you want.
34,547,154
How to change the default icon of my Processing `appIconTest.exe` exported application in windows ? **The default one :** [![app icon to change](https://i.stack.imgur.com/u114Y.png)](https://i.stack.imgur.com/u114Y.png)
2015/12/31
[ "https://Stackoverflow.com/questions/34547154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3745908/" ]
After some research, the easiest solution i could find is : 1. Go into `...\processing-3.0.1-windows64\processing-3.0.1\modes\java\application` 2. Save `sketch.ico` somewhere you can find (renaming it will help). 3. Place the icon you want to use in the same folder with the same name `sketch.ico` (which you might create using [GIMP](https://www.gimp.org/)). 4. Now you can export your application from Processing. --- **Important :** Be sure to save the default icon, because every application you export (after changing the icon) using Processing, will have this new icon.
I would recommend Resource Hacker to change the icon of your programs. 1. Install Resource Hacker (latest build). 2. Go to your executable file. 3. Open it with Resource Hacker (right mouseclick, and there should be an option to do that or else you could just click open with). 4. It will open and show some directories, also one called "Icon", open that one, and right click one one of the icon files (stars with some numbers after that), there will be an option: "replace icon ... Ctrl + R", click that one and replace your icon.
27,401
Is there any theoretical or practical limit to the maximum number of passengers - and therefore size - one can build an airplane for?
2016/05/06
[ "https://aviation.stackexchange.com/questions/27401", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/14811/" ]
It is no accident that the biggest birds are flightless. The ability to fly goes down with increasing size, so there is also an upper limit for aircraft. The main reason is that as size increases, masses go up with the cube of the size increase while the load-carrying structures like wing spar cross sections only grow with the square of the size increase. This power law is the simplest of the [scaling laws](http://www.av8n.com/physics/scaling.htm). Since the loads on an aircraft's wing depend not only on its size, but also on many more parameters (angle of attack, speed, aspect ratio …), there is no clear boundary, and advances in materials help to shift the size limit up. If one would try to build the biggest airplane in the world, the wingspan could easily be double of what todays biggest airplanes measure, but the utility of this airplane would be very limited. Using this airplane for passenger travel would add more restrictions like the number of emergency exits and the maximum distance to the nearest exit, but this could be overcome by using several smaller fuselages. A double-hull airplane would also spread out the payload weight, so the wing would experience a reduced root bending moment. Going from this ([source](http://modelismo.wehrmacht-info.com/wp-content/uploads/2013/07/Bundesarchiv_Bild_101I-385-0587-07_Flugzeug_Heinkel_He_111_H-Z.jpg)): [![He-111H in flight](https://i.stack.imgur.com/T6fCp.jpg)](https://i.stack.imgur.com/T6fCp.jpg) to this ([source](http://www.airwar.ru/image/idop/cww2/he111z/he111z-3.jpg)): [![He-111Z in flight](https://i.stack.imgur.com/8vuPY.jpg)](https://i.stack.imgur.com/8vuPY.jpg) would immediately raise the size limit substantially. However, it would require new, wider runways to take off from. And adding more fuselages to the same wing will run into flutter problems soon. The next indication could be [designs which have been studied](https://en.wikipedia.org/wiki/List_of_large_aircraft#Projects) and deemed feasible but were eventually not built for economical reasons. Here the biggest are ground effect vehicles: Flying slowly in dense air pushes the size limit up. The [Boeing Pelican](https://en.wikipedia.org/wiki/Boeing_Pelican) was planned with 152 m wingspan, and [Beriev proposed one](http://www.beriev.com/eng/Be-2500_e/Be-2500_e.html) with 2500 t take-off mass and 125.5 m wing span. I would guess that a wingspan of 200 m is still feasible, and when [spreading the weight](http://www.uh.edu/engines/heliosinflight.jpg) even 500 m should be realistic, but totally unpractical. Taking a lesson from history, this would be a multi-hulled flying boat which flies in ground effect, similar to the (mono-hulled) [biggest aircraft record holders](https://aviation.stackexchange.com/questions/23675/which-came-to-be-first-bigger-airplanes-or-longer-runways/23687#23687) in the 1920s.
Theoretically, unlimited (well bigger than is practically necessary)... TL;DR Airplanes scale fairly well and it would be *physically* possible to build and airplane of just about any size. Granted there are some things that come into play from a structure standpoint but there are surely ways around that. You may have to stray away from the traditional single fuselage, two wing and empennage design but none the less. There are lots of realistic factors that will stand in your way before you even need to design such a plane. 1. You don't have enough money to build such a plane 2. Boeing does not have enough money to build such a plane 3. [Juan Trippe](https://en.wikipedia.org/wiki/Juan_Trippe) has no interest in such a plane so there is probably no reason to build it. 4. There are no runways that could handle such an aircraft. Planes like the A380 and 747 are already route limited by runway length/weight capacity. You would need to modify runways to handle anything significantly bigger. That is of course assuming that it lands in a similar fashion to most airliners (i.e. not VTOL) 5. What route is it going to fly? Planes are not the size they are because we cant build them bigger, they are the size they are because the routes dictate them being such a size. Do you really need to move 1,000 people on a given route at once? How many routes have this much travel density? Let's look at this hypothetically, [Jamiec makes an excellent point](https://aviation.stackexchange.com/questions/27401/is-there-a-maximum-possible-size-for-an-airplane#comment67513_27401) that a plane that has the capacity in excess of 7Bn would be kind of useless so let's take that as a maximum. XKCD what if [covers this in a similar question](https://what-if.xkcd.com/8/) and estimates that shoulder to shoulder all the people on earth take up roughly the size of Rhode Island. For the sake of argument lets say that you would need seats and toilets and what not for this many people so to fit everyone on earth in a plane you would need maybe twice the size of Rhode island or a bit more. Unlike that question we can build up so a 4-8 story (or any amount) of plane would be plausible. The average [FAA person weighs about 180 lb (81.65 kg)](http://www.faa.gov/documentLibrary/media/Advisory_Circular/AC120-27E.pdf) so you would need to lift 1,260,000,000,000 lb Or 630,000,000 tons (572,000,000,000 kg or 572,000,000 metric ton ) To provide a frame of reference the [A380 has a maximum structural payload of 330,300 lb (149,822 kg)](https://en.wikipedia.org/wiki/Airbus_A380). Keep in mind this is only payload, you also need to lift the weight of the airframe, engines, and fuel (if you actually want to go anywhere). So basically you would need a multi level plane close to the size of Rhode Island that had most of the combined thrust available on the planet and enough liquor to keep everyone calm for the flight. The structural issue in some regards boils down to wing loading. One commonly self imposed limit these days is that most planes are typical [low wing cantilever monoplanes](https://en.wikipedia.org/wiki/Wing_configuration) so we view things in relation to that. In other words the fuselage may stress about the wing mounting points and the wings are generally long and low but there is nothing preventing us from using an alternate design with multiple wings or a full lifting body design to accomplish the structure we need. As such the idea of big wings can be overcome and historically this is how the problem was solved in early aviation (tri-planes, etc...) The weight issue (from a practical standpoint) is something we concern ourselves with for efficiency reasons. If we are just building a giant plane we can use jets, rockets and all manners of high thrust devices for the purpose of science. You could fly a cement plane if it was shaped right and you had enough thrust. Remember if Thrust > Drag and Lift > Weight you will fly (I learned this the first day in flight school). Doing so in a controlled and organized manner took significantly more time to learn.... -- Edit -- Since the question has been edited to involve the passenger count there are other issue that crop up. 1. You need to realistically load and unload the plane which takes time. A plane that takes too long to load and unload will not be economical to operate. 2. Weight ([Americans are getting fat](http://articles.orlandosentinel.com/2005-08-11/news/VBIGAIR11_1_airline-passengers-fuel-center-of-gravity)) (see above) 3. You need a reason to move that many people that far all at once. 4. Depending on flight length you need to consider food, water, and restrooms to accommodate everyone (waste tanks are not infinitely large). 5. Are there even enough people in one place? Planes move people (and often stuff) from one place to another but let's take NYC for example which has a population of about [8.5 million people](http://www1.nyc.gov/site/planning/data-maps/nyc-population/current-future-populations.page) the chances that all of them are going to the same place at once is near 0%. So you don't need an 8.5 million passenger plane, but you can start a bit smaller. From an airline standpoint (The people actually buying) planes like the 747 are already big enough and expensive enough. The [747 nearly bankrupt Boeing](https://en.wikipedia.org/wiki/Boeing_747) at the time but has had a fairly successful run since. The A380 is fairly new but it will be interesting to see how it changes the game.
5,806,943
In my Ruby (1.9.2) Rails (3.0.x) I would like to render a web page as PDF using wicked\_pdf, and I would like to control where the page breaks are. My CSS code to control page breaks is as follows: ``` <style> @media print { h1 {page-break-before:always} } </style> ``` However, when I render the page with [wicked\_pdf](https://github.com/mileszs/wicked_pdf), it does not separate the document into two pages. Is there something else that I must do to get page breaks with wicked\_pdf?
2011/04/27
[ "https://Stackoverflow.com/questions/5806943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33890/" ]
Tried Jay's solution but could not get it to work (maybe a conflict with other css) I got it to work with this: ``` <p style='page-break-after:always;'></p> ```
None of these solutions worked for me. I did find a solution that worked for many people in the gem issues here - <https://github.com/wkhtmltopdf/wkhtmltopdf/issues/1524> you want to add CSS on the element that needs the page break. In my case, it was table rows, so I added: ``` tr { page-break-inside: avoid; } ```
1,274,940
So assuming that in our work environment we've decided that the One True Faith forbids this: ``` if (something) doSomething(); ``` And instead we want: ``` if (something) { doSomething(); } ``` Is there a tool that will do that automagically? Awesomest would be to have eclipse just do it, but since we're really just recovering from one ex-employee that thought he was too pretty for coding conventions, a less-friendly tool that would do it right just once would suffice.
2009/08/13
[ "https://Stackoverflow.com/questions/1274940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/409/" ]
I think you can set this in Eclipse's formatting rules and run the built-in formatter.. e.g. the "Use blocks" option: ![Code Style Tab](https://www.ibm.com/developerworks/library/os-eclipse-clean/CodeStyle.jpg) Of course, you need the rest of the formatting options to be set how you want them, since I don't think you can selectively apply only a single rule/option..
I believe that [GreatCode](http://sourceforge.net/projects/gcgreatcode/) can do this for you (along with a ton of other options)
16,706,622
i need to count/group/select product on base of attribute 'country\_of\_manufacture'. like this > > India => 10, Shrilanka => 5, > > > how can achieve it in magento?
2013/05/23
[ "https://Stackoverflow.com/questions/16706622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/767517/" ]
``` $collection = $this->getLoadedProductCollection() ->addAttributeToSelect('*') ->addExpressionAttributeToSelect('total_country_of_manufacture',"COUNT({{entity_id}})",'entity_id') ->groupByAttribute('country_of_manufacture'); ``` for count ``` Mage::getModel('catalog/product')->getCollection()->groupByAttribute('country_of_manufacture') ->addExpressionAttributeToSelect("cnt_product",'COUNT({{entity_id}})', 'entity_id') ->load(); ```
Instead of using ``` count($collection) ``` you can try ``` $collection->getSelect()->count(); ```
186,080
I submitted an assignment in February and I recently received an email accusing me of academic misconduct. I have just finished my second year of university and this is the first time that I have ever been accused of something this serious. The accusation says that I plagiarised the algorithm from someone else. However, I did not look at anyone's code nor did anyone else got to see my code which they could've later copied. Prior the the assignment deadline, me and couple other students (who I do not know closely) attended the in-person office hours of the course's Teaching Assistant (TA). The overwhelmed TA decided to take in all our concerns simultaneously instead of private sessions and perhaps tired of our inefficient (and buggy) code implementations or solution proposals, finally got up and instead *wrote* on the whiteboard what he called "the most efficient and best possible" algorithm for the code. He explained every step line by line which I made sure to understand fully and then later followed his algorithm implementation to write my own code without consulting anyone else, thinking that following the faculty's instruction isn't clearly plagiarism since I've understood everything and am confident in what I'm writing. Much to my dismay, I have now received the Disciplinary Committee's email and have been asked to present a written statement tomorrow followed by a formal hearing later. I have evidence of the TA explaining the algorithm as I did take photos of his algorithm right in front of him. If I am found guilty, I'd either get a grade reduction, a straight F, or a semester-long suspension. This has me worried sick because an accusation this serious can potentially derail all my post-grad plans. Is my evidence sufficient? What other evidence or explanations could I use to strengthen my case? Thanks
2022/06/14
[ "https://academia.stackexchange.com/questions/186080", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/157527/" ]
We can’t read folks minds or predict the future, but if everything you say is true, this seems like a case where your defense would be accepted. This is just my opinion as a faculty member. I have served on academic grievance committees but not our misconduct committee. Note here that I agree with Bryan Krause below- it is typical to use information shared by instructors without attribution when completing assignments for that class.
These are serious accusations, and if one is considering a career in academia a finding of plagiarism may look bad for some time in your career. I am not familiar with the details in a university setting, so this advice is from experience in other workplaces. 1. Get some help from real people not the internet. I am not sure what support you have. In the UK you would be a member of [The National Union of Students](https://www.nus.org.uk/) who would be able to support you. I do not know what the equivalent is where you are, but ensure their responsibility is to you not the university. 2. Say NOTHING until you are certain of what you want to say. Do not respond to vague allegations like "I plagiarised the algorithm from someone else", request in writing specific allegations and the evidence that lead to these allegations. Do not be pressurised to reply by "tomorrow", that is a totally unreasonable time frame to respond to such allegations. It sounds to me like you are assuming a lot of details, you may be right but if you are wrong you may only hurt your case by giving them information without knowing what information they have.
46,552,571
I'm trying to use auto-generated advancedDataGrid - ADGV ([adgv.codeplex.com](https://adgv.codeplex.com)). Current question is similar to the solved question before: [my previous stackoverflow.com question](https://stackoverflow.com/questions/46513792/adgv-c-sharp-datagridview-update-query-bug/46514435#46514435) I have a Form (frmLev) with advancedDataGrid filled with data from SQL. One column of DataGridView is a date field (DD.MM.YYYY) with DateTimePicker placed there. If I get it right...The problem is in that the full row will be saved to SQL only when cell edit is finished manually *after* user picks the date in DatePicker. The cell looks like the edit is finished, but it has to be confirmed again by clicking, pressing enter or tab. Other text cells are with text selected or blinking cursor. I want to save the row to SQL at the end of delDatePick\_textChange(), but calling currentRowSave() will not work at this moment. User has to perform a click first. Data will be saved only when levDGV\_CellLeave() get the event. **QUESTION IS: How to programatically fire CellLeave Event?** ``` MetroFramework.Controls.MetroDateTime delDatePick = new MetroFramework.Controls.MetroDateTime(); Rectangle _Rectangle; private void frmLev_Load(object sender, EventArgs e) { //Add DateTimePicker to Date levDGV.Controls.Add(delDatePick); delDatePick.Visible = false; delDatePick.Format = DateTimePickerFormat.Short; delDatePick.TextChanged += new EventHandler(delDatePick_textChange); delDatePickValueAutomatic = false; } private void levDGV_CellClick(object sender, DataGridViewCellEventArgs e) { switch (levDGV.Columns[e.ColumnIndex].HeaderText) { case "Datum": _Rectangle = levDGV.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); delDatePick.Size = new Size(_Rectangle.Width, _Rectangle.Height); delDatePick.Location = new Point(_Rectangle.X, _Rectangle.Y); delDatePick.Visible = true; if (levDGV.CurrentCell.Value != DBNull.Value) { delDatePick.Value = (DateTime)levDGV.CurrentCell.Value; delDatePickValueAutomatic = true; } break; } } private void delDatePick_textChange(object sender, EventArgs e) { if (delDatePickValueAutomatic != false) // event fired when cell gets focused, so skipping { String pickedDate = delDatePick.Text.ToString(); delDatePick.Visible = false; this.BeginInvoke((MethodInvoker)delegate () {levDGV.CurrentCell.Value = pickedDate;}); levDGV.Refresh(); delDatePick.Visible = false; //I want to update SQL row here, but calling currentRowSave() will not work at this moment because row is in edit mode... } } private void levDGV_CellLeave(object sender, DataGridViewCellEventArgs e) { //skipping first entrance; if (e.ColumnIndex != 0 && e.RowIndex != 0) { delDatePick.Visible = false; currentRowSave(); } } private void currentRowSave() { int rowIdx = levDGV.CurrentCell.RowIndex; DataRowView drv = (DataRowView)levDGV.Rows[rowIdx].DataBoundItem; DataRow dr = drv.Row; BeginInvoke((Action)(() => SaveRowChanges(dr))); } ```
2017/10/03
[ "https://Stackoverflow.com/questions/46552571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5519686/" ]
You can also call cell's EndEdit() method. Something like this: ``` this.BeginInvoke((Action)(() => levDGV.CurrentCell.EndEdit())); ```
Found a workaround... It does not answer my question, but works for me. ``` this.BindingContext[levDGV.DataSource].EndCurrentEdit(); //does not call CellLeave currentRowSave(); ```
1,083,683
I get no keyboard feedback on any java application I run with Java 6 (64-bit) on OSX Leopard 10.5.7. It happens with any swing application, or even with eclipse 3.5 64-bit (which is a SWT-cocoa application). Did't find any reference to this problem on the web...
2009/07/05
[ "https://Stackoverflow.com/questions/1083683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/54623/" ]
This is a stab in the dark, but do you mean that it should read an existing text file to get the lines of text? ``` #include <string> #include <fstream> #include <iostream> int main() { std::ifstream inputFile("c:\\input.txt"); std::ofstream outputFile("c:\\output.txt"); std::string line; while (std::getline(inputFile, line)) outputFile << "1." << line << std::endl; return 0; } ``` Which means, open the input file and the output file, and then for each line read from the input file, write it to the output file with `1.` in front of it.
Just use a prefix variable: ``` #include <fstream> using namespace std; ofstream file; string prefix = "1. "; out_file.open("test.txt"); out_file << prefix << "some text" << endl; out_file << prefix << "some other text" << endl; out_file.close(); ``` Or you could write a little convenience function to do this: ``` void writeLine(ofstream file, string text) { file << "1. " << text << endl; } ``` Certainly, there are more possibilites.
45,375,164
How do I convert a string like ``` string a = "hello"; ``` to it's bit representation which is stored in a int ``` int b = 0110100001100101011011000110110001101111 ``` here `a` and `b` being equivalent.
2017/07/28
[ "https://Stackoverflow.com/questions/45375164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5536095/" ]
Seems like a daft thing to do, bit I think the following (untested) code should work. ``` #include <string> #include <climits> int foo(std::string const & s) { int result = 0; for (int i = 0; i < std::min(sizeof(int), s.size()); ++i) { result = (result << CHAR_BIT) || s[i]; } return result; } ```
``` int output[CHAR_BIT]; char c; int i; for (i = 0; i < CHAR_BIT; ++i) { output[i] = (c >> i) & 1; } ``` More info in this link: [how to convert a char to binary?](https://stackoverflow.com/questions/4892579/how-to-convert-a-char-to-binary)
17,221,254
I'm attempting to calculate 30 days by multiplying milliseconds however the result continually ends up being a negative number for the value of days\_30 and I'm not sure why. Any suggestions are greatly appreciated! CODE SNIPPET: ``` // check to ensure proper time has elapsed SharedPreferences pref = getApplicationContext() .getSharedPreferences("DataCountService", 0); long days_30 = 1000 * 60 * 60 * 24 * 30; long oldTime = pref.getLong("smstimestamp", 0); long newTime = System.currentTimeMillis(); if(newTime - oldTime >= days_30){ ``` days\_30 value results in: -1702967296 P.S. ``` double days_30 = 1000 * 60 * 60 * 24 * 30; double oldTime = pref.getLong("smstimestamp", 0); double newTime = System.currentTimeMillis(); if(newTime - oldTime >= days_30){ ``` Results in a smaller - but still negative number. -1.702967296E9
2013/06/20
[ "https://Stackoverflow.com/questions/17221254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2493722/" ]
You are multiplying `ints` together, and overflow occurs because [the maximum integer is `2^31 - 1`](http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#MAX_VALUE). Only after the multiplications does it get converted to a `long`. Cast the first number as a `long`. ``` long days_30 = (long) 1000 * 60 * 60 * 24 * 30; ``` or use a `long` literal: ``` long days_30 = 1000L * 60 * 60 * 24 * 30; ``` That will force `long` math operations from the start.
Just change your multiplication to `long days_30 = 1000L * 60 * 60 * 24 * 30;`
8,937,714
I created a collection by adding items to a Varien\_Data\_Collection collection object. ``` $collection = new Varien_Data_Collection(); foreach($array_of_products as $productId){ $collection->addItem(Mage::getModel('catalog/product')->load($productId)); } ``` However when this object is passed on to Magento pager block as given below, it breaks the pagination in my custom page. ``` $pager = $this->getLayout()->createBlock('page/html_pager', 'retailerfe.analysis.pager') ->setCollection($collection); ``` P.S I have never had problems with collections fetched from model collections like Mage::getModel('module/modelname')->getCollection(). It is just collections created by adding items to a Varien\_Data\_Collection Object.
2012/01/20
[ "https://Stackoverflow.com/questions/8937714", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1002400/" ]
The pager is calling [`setPageSize`](http://docs.magentocommerce.com/Varien/Varien_Data/Varien_Data_Collection.html#setPageSize) on your collection which - if you trace it - is only used by [`getLastPageNumber`](http://docs.magentocommerce.com/Varien/Varien_Data/Varien_Data_Collection.html#getLastPageNumber). This means the pager can show the number of pages accurately but that's it. It is [`Varien_Data_Collection_Db`](http://docs.magentocommerce.com/Varien/Varien_Data/Varien_Data_Collection_Db.html) that actually does anything with the current page number and size by rendering them as a `LIMIT` clause for SQL. To create a collection that respects the page criteria you will have to create a descendant to the class. For ideas look at [the source of `Varien_Data_Collection_Filesystem`](http://svn.magentocommerce.com/source/branches/1.7-trunk/lib/Varien/Data/Collection/Filesystem.php) and how it implements `loadData`. --- I've just re-read your question and realised you can do this: ``` $collection = Mage::getModel('catalog/product')->getCollection() ->addIdFilter($array_of_products); ``` This collection will page quite happily.
I just doubt on(may be i am wrong): ``` $collection->addItem(Mage::getModel('catalog/product')->load($productId)); ``` which should be like this: ``` $collection->addItem(Mage::getModel('catalog/product')->load($productId)->getData()); ``` Let me know if that works for you. Thanks **EDIT:** Finally i figured it out. Here is how you should do it: ``` <?php $collection = new Varien_Data_Collection(); foreach($array_of_products as $productId){ $product = Mage::getModel('catalog/product')->load($productId); $_rowObject = new Varien_Object(); $_rowObject->setData($product->getData()); $collection->addItem($_rowObject); } ```
81,827
Asking this one for a friend located in the United States. She's currently experiencing significant stress coming directly from her place of employment. All attempts to mediate this with her coworkers and boss have apparently failed and one of the benefits of her employment is a series of free optional visits to a psychiatrist hired by the company. She thinks this has the potential to help and might put her mind at ease until she can work out another place of employment. I'm being told that, if she were to express herself openly and her grievances were to get back to management, she would almost surely be fired (and possible a couple other coworkers might get fired as well if she's taken seriously.) Under normal circumstances I would cite standard doctor-patient confidentiality clauses that should at least guarantee nothing she says leaves the room and certainly doesn't get back to her boss. But I also know from experience, even from questions on this site, that confidentiality breaches happen all the time and don't tend to end well for the employee even if they're in the right. Is it wise to trust psychiatrists employed by a business with business issues? EDIT: I'm noticing there's some drift in the answers, so I'd like to clarify something: it's understood that it is illegal for the psychiatrist to lie about her confidentiality. That's known. What isn't known about this is how smart of a practical option this is. As a trivial example, there are tons of questions about [discovering fraud](https://workplace.stackexchange.com/questions/62686/my-employer-is-forcing-its-employees-to-defraud-its-customers-how-should-i-hand) that would be trivial to answer if you assume that the laws will protect the employee. Based on the answers, that doesn't always work out.
2016/12/21
[ "https://workplace.stackexchange.com/questions/81827", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/53202/" ]
There would be very little incentive for a psychological professional to violate patient confidentiality, risk getting sued for malpractice and lose his/her license to practice. Most of the time, these professionals are contracted to the company through a third party and do not work exclusively for that company. They would have much business to lose from the publicity of a malpractice suit even if it eventually ruled in their favor (and it almost certainly would not be in the case of violating a patient's confidentiality). So I would be fairly confident about this. However, if it is making the person nervous, then choose her own professional and let her health insurance pay for it or pay for it herself.
In such a situation, I would absolutely not trust someone who has ties to the company in question. While the psychiatrist's legal requirement to uphold confidentiality is true, if the psychiatrist violates it, there's no way to prove that. If managers at the company want to fire OP's friend, they can make up any sort of excuse to do so - they don't have to disclose that they received information from the psychiatrist. I'm not trying to say all (or even many) psychiatrists would violate their oath / legal obligations but trusting the psychiatrist in this case is basically a gamble on one particular person's ethics who already has some ties to the company. I'd personally look for a completely independent psychiatrist for help - this would, at least, lower the chance of details leaking back to the company.
61,041,739
I am working with Ag-Grid version 21.1.0 and Angular 8. I am trying row-grouping in ag-grid following the tutorial: <https://www.ag-grid.com/javascript-grid-grouping/> I have a field in my data-model as "Short Name" field and I am trying to group by this field by setting "rowGroup"="true" property of corresponding column-def object. A new column called "Group" is created in the Ag-grid but the values for this newly created column are not displayed by the grid.[![enter image description here](https://i.stack.imgur.com/YmiUI.png)](https://i.stack.imgur.com/YmiUI.png) I am using server side filtering and sorting for the grid and using rowmodeltype="infinite". Kindly help me where I am going wrong. Update: I am creating a list of column Metadata Objects dynamically. For the specific column by which I want to group the data, I am setting the following attributes: ``` columnMetaObj.rowGroup = true; columnMetaObj.enableRowGroup = true; columnMetaObj.hide = true; ``` then finally I am setting grid options as follows: ``` this.gridOptions.columnDefs = this.gridColDataInput.columnDefs; this.gridOptions.rowModelType = 'infinite'; this.gridOptions.cacheBlockSize = 100; this.gridOptions.paginationPageSize = 100; ```
2020/04/05
[ "https://Stackoverflow.com/questions/61041739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4449595/" ]
Probably you're using two different python interpreters on your pycharm and on your terminal. Please, * check the python version on the terminal by `python3 --version` * And then go to pycharm -> file -> settings -> project -> project interpreter and check if both python are the same.
```sh sudo easy_install-3.8 pygame ``` (This will install the dependencies.) ```sh sudo pip3 install pygame ```
21,572
En uno de los [translation-golf](/questions/tagged/translation-golf "show questions tagged 'translation-golf'") recientes, era necesario traducir la típica locución inglesa «*nothing but*», que normalmente se traduce como «nada excepto» o «nada salvo». Sin embargo, [una de las respuestas](https://spanish.stackexchange.com/revisions/21529/1) proponía traducirla como «nada mas», usando **mas** sin tilde en su significado de «pero»; es decir, una traducción literal que, no obstante, suena bastante bien. ¿Sería correcta esta traducción?
2017/07/22
[ "https://spanish.stackexchange.com/questions/21572", "https://spanish.stackexchange.com", "https://spanish.stackexchange.com/users/-1/" ]
Yo interpreto que es un adjetivo. Está afinando el significado de "nosotros" para asegurar que son todos los posibles. "Todo" como adverbio es un caso menos frecuente, como en: "Soy todo oídos" Aquí puedes ver una explicación muy detallada de las diferentes posibilidades. <http://zonaele.com/todo-toda-todos-y-todas/>
A primera vista me parece un pronombre. Del mismo modo que puede haber un doble determinante, como en "todos los participantes", al omitir el sustantivo y usar pronombres ninguno de los dos debería ser "privilegiado" como para ser uno pronombre y otro adjetivo. Lo cierto es que es complicado decidir.
8,662,436
I got confused on `volatile` for reference type . I understand that for primitive type, `volatile` can reflect value changes from another thread immediately. For reference type, it can reflect the address changes immediately. However, what about the content of the object. Are they still cached? (Assuming `List.Add()` is an atomic operation) For example, I have: ``` class A { volatile List<String> list; void AddValue() { list.Add("a value"); } } ``` If one thread calls the function `AddValue`, the address of list does not change, will another thread get updated about the "content" change of the list, or the content may be cached for each thread and it doesn't update for other threads?
2011/12/28
[ "https://Stackoverflow.com/questions/8662436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299230/" ]
> > I understand that for primitive type, volatile can reflect value changes from another thread immediately > > > You understand incorrectly in at least three ways. You should not attempt to use volatile until you deeply understand *everything* about weak memory models, acquire and release semantics, and how they affect your program. First off, be clear that volatile affects **variables**, not **values**. Second, volatile does not affect variables that contain values of value types any differently than it affects variables that contain references. Third, **volatile does not mean that value changes from other threads are visible immediately**. Volatile means that variables have *acquire and release semantics*. Volatile affects *the order in which side effects of memory mutations can be observed to happen from a particular thread*. The idea that there exists a consistent universal order of mutations and that those mutations in that order can be observed instantaneously from all threads is not a guarantee made by the memory model. > > However, what about the content of the object? > > > What about it? The storage location referred to by a volatile variable of reference type need not have any particular threading characteristics. > > If one thread calls the function AddValue, the address of list does not change, will another thread get updated about the "content" change of the list. > > > Nope. Why would it? That other thread might be on a different processor, and that processor cache might have pre-loaded the page that contains the address of the array that is backing the list. Mutating the list might have changed the storage location that contains the address of the array to refer to some completely different location. Of course, the list class is not threadsafe in the first place. If you're not locking access to the list then the list can simply crash and die when you try to do this. You don't need volatile; what you need is to put thread locks around accesses to the list. Since thread locks induce full fences you should not need half fences introduced by volatile.
Look at <http://www.albahari.com/threading/part4.aspx#_The_volatile_keyword> for a good explanation about what volatile actually does and how it impacts fields. The entire part of threading on that site is a must read anyway, it contains huge amounts of useful information that have proved very useful for me when I was designing multi threaded software.
133,571
> > Consider the real function $f$ defined on the real line $\mathbb{R}$ by $f(x)=x^2$. If $b$ is a given positive real number, show that the restriction of $f$ to the closed interval $[0,b]$ is uniformly continuous by starting with an $e\gt 0$ and exhibiting a $d\gt 0$ which satisfies the requirement of the definition > > >
2012/04/18
[ "https://math.stackexchange.com/questions/133571", "https://math.stackexchange.com", "https://math.stackexchange.com/users/29386/" ]
A better way to prove this fact comes in the form of the following theorem. > > **Theorem.** Let $K \subseteq \mathbb{R}^N$ compact, and $f:K \to \mathbb{R}$ continuous. Then $f$ is uniformly continuous. > > > **Proof.** Let $\epsilon > 0$ be given. By continuity of $f$, for every $x\_0 \in K$ choose $\delta(x\_0)$ such that if $x \in K$ with $\Vert x-x\_0 \Vert < \delta(x\_0)$ then $\Vert f(x)- f(x\_0) \Vert < \epsilon/2$. The family of open balls $\{B(x,\frac{1}{2}\delta(x)) : x \in K \}$ forms an open cover of $K$. By compactness of $K$ we may choose finitely many $x\_1,\ldots, x\_n \in K$ such that $\{B(x\_i,\frac{1}{2}\delta(x\_i)) : 1 \leq i \leq n \}$ still covers $K$. Choose $\delta = \frac{1}{2}\min\{\delta(x\_i) : 1 \leq i \leq n \}$. Then for any $x,y \in K$ with $\Vert x - y \Vert< \delta$ there is $i$ with $1\leq i \leq n$ so that $x \in B(x\_0,\frac{1}{2}\delta(x\_0))$ and $\Vert x\_i - y \Vert \leq \Vert x\_i - x \Vert + \Vert x-y \Vert < \frac{1}{2}\delta(x\_i) + \frac{1}{2}\delta(x\_i) \leq \delta(x\_i)$. Thus we have $x,y \in B(x\_i,\delta(x\_i))$ and by the triangle inequality we have $\Vert f(x) -f(y) \Vert \leq \Vert f(x)-f(x\_i) \Vert + \Vert f(x\_i) - f(y) \Vert < \epsilon/2 + \epsilon/2 = \epsilon. ~~\square$ > > > In the case of this problem, we know that $[0,b]$ is compact for all $b>0$ since it is closed and bounded, and that $x \longmapsto x^2$ is continuous on $[0,b]$. Hence by the previous theorem $x \longmapsto x^2$ is uniformly continuous on $[0,b]$. Note: if this is a homework problem, this is probably not the solution your professor is looking for, but it is an extremely useful theorem that you might want to know about anyway.
If a continuous function f satisfies the property $|f(x\_1)-f(x\_2)|\le M|x\_1-x\_2|$ is said to be Lipschitz with constant $M$, and $f$ must be uniformly continuous as in this case you will get $\delta=\frac{\epsilon}{M}$ all the time which will allow your continuous function to be uniformly continuous. For your function we have $|f(x\_1)-f(x\_2)|=|(x\_1^2-x\_2^2)|=|(x\_1-x\_2)(x\_1+x\_2)|\le 2b|x\_1-x\_2|$. I hope you can do now.
27,526,146
I am getting this error: ![enter image description here](https://i.stack.imgur.com/02jMx.jpg) I have installed ADT and SDK using install new software in Eclipse. I am using `Eclipse Java EE IDE for Web Developers. Version: Kepler Service Release 2`. I used this link <https://dl-ssl.google.com/android/eclipse/> I do not know where the SDK is getting installed as it being done through Eclipse. Which path should I provide to remove this error. Actually I cannot even set a path as the OK button in preferences window remains disabled. What can be the issue. I know this has be address earlier but could not get what I am looking for hence added a new thread.
2014/12/17
[ "https://Stackoverflow.com/questions/27526146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1650891/" ]
> > I do not know where the SDK is getting installed as it being done through Eclipse. > > > Not if you installed the ADT plugin separately. You need to [download and install the Android SDK](http://developer.android.com/sdk/index.html#Other) (see "SDK Tools Only"), then teach the ADT plugin where you installed it. Also note that support for the ADT Plugin has been officially discontinued by Google.
I have deleted folder .android in my user folder (c:/users/xyz/.android) and relaunched Eclipse - dialog box "Android SDK installation" (not exact name) has came up - then install of SDK.
6,303,648
I need HTML parser for PHP that can use CSS selectors to select elements, in Java we have jsuop. Is there such a library for PHP?
2011/06/10
[ "https://Stackoverflow.com/questions/6303648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/159793/" ]
Try [phpQuery](http://code.google.com/p/phpquery/); it uses CSS-style selection similar to jQuery, which by the sound of your description is similar to jsoup.
I use this one: <http://simplehtmldom.sourceforge.net/>
43,920,739
I have this problem with image displaying. Image should display on **top** of the card, but it keeps displaying on *bottom*. ``` $(document).ready(function() { $("li:first").click(function () { $(".card").show(); $(".card").append('<img class="card-img-top" src=' + (filmi.Movies[0].Poster) + '/>') ``` Even here in **HTML** can be seen that structure of elements is in right order from top to bottom. When click on the *"movie title"* throws image on the last place in div. ``` <div class="col"> <div class="card" style="width: 20rem;"> <img class="card-img-top" src="" /> <div class="card-block"> <h4 class="card-title"></h4> <p class="card-text"></p> </div> ``` > > Fiddle JS included: <https://jsfiddle.net/x3jem2fb/> > > >
2017/05/11
[ "https://Stackoverflow.com/questions/43920739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7231441/" ]
You just need to update the `src` attribute: ``` $("li:first").click(function () { $($(".card").find('.card-img-top')).attr('src',filmi.Movies[0].Poster) $(".card").show(); }); ``` ### Working fiddle: <https://jsfiddle.net/x3jem2fb/2/> **Final Update, working sample for all the movies:** > > **The Full Movie List:** > > > ``` $.each(filmi.Movies,function(i,item){ $("ul").append('<li class="list-group-item" data-url="'+item.Poster+'">' + (item.Title) + '</li>').attr(item.imdbID) }) ``` > > **The `show card` code, using the `data` attribute:** > > > ``` $("li").click(function () { $($(".card").find('.card-img-top')).attr('src',$(this).data('url')) $(".card").show(); }); ``` ### Final sample: <https://jsfiddle.net/x3jem2fb/4/>
Modify your javascript to use **prepend()** rather than **append()** *Append()* will append the element **after** the previous element whereas *prepend()* does the opposite. ``` $("li:first").click(function () { $(".card").prepend('<img class="card-img-top" src=' + (filmi.Movies[0].Poster) + '/>'); $(".card").show(); }); ``` **HOWEVER** This will continue to add more elements into the DOM for each click you make so you might want to consider how you will handle this. If you just want to update the image source you could do the following: ``` $("li:first").click(function () { $(".card").find('.card-img-top')).attr('src',filmi.Movies[0].Poster); $(".card").show(); }); ``` But you will want a much more dynamic way of selecting the correct image based on the item you selected. See [this](https://stackoverflow.com/questions/21756777/jquery-find-element-by-data-attribute-value) answer for that particular problem:
70,151,308
How to check which number is a power in this array? `arr = [16, 32, 72, 96]` output: `[16, 32]` because `16 = 4^2` and `32 = 2^5` It's not a solution about power of 2, it's about power of n. This is my actual code : ```js let array1 = [16, 32, 72]; function findPowofNum(array1) { // var result = []; if (array1.length == 1) return true; for(let i = 2; i * i <= array1.length; i++) { let value = Math.log(array1/length) / Math.log(i); if((value - Math.floor(value)) < 0.00000001) return true; } return false; } console.log(findPowofNum(array1)); ``` Can you give me a example for this solution by javascript?
2021/11/29
[ "https://Stackoverflow.com/questions/70151308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17016390/" ]
You can use a custom boolean function to iterate through the elements and append to an empty array as you check like this.. ``` function isPowerofTwo(n){ return (Math.ceil((Math.log(n) / Math.log(2)))) == (Math.floor(((Math.log(n) / Math.log(2))))); } let arr= [16, 32, 72, 96]; let values=[] for(let i=0;i<arr.length;i++){ if(isPowerofTwo(arr[i])){ values.push(arr[i]); } } console.log(values); ```
I think it is 2^4 not 4^2 and what I believe is you want to check if the number is and root of 2 or not Solution ``` let arr=[16,32,72,96]; let i=1; for(i=1;i<=10;i++){ // this loop will run up to 2^10 let k=Math.pow(2,i);if(k==arr[i-1]){ //do whatever you want to do with the number } } ```
28,666,080
I'm trying to understand how executables can be run after installing a module using the [JSPM](http://jspm.io/). For instance if I run `jspm install gulp`, then I would expect to be able to run the following command: ``` ./jspm_packages/npm/gulp\@3.8.11/bin/gulp.js ``` Actually it would be better if jspm would handle this so that there is a hidden bin directory containing all retrieved executables (such as gulp) at the following location: ``` ./jspm_packages/.bin ``` That way I could just have a single addition to my PATH environment variable that would allow these executables to run. Currently when I attempt to run a jspm-installed gulp, I get the following error message: ``` [jspm-test]$ ./jspm_packages/npm/gulp\@3.8.11/bin/gulp.js ./jspm_packages/npm/gulp@3.8.11/bin/gulp.js: line 1: /bin: Is a directory ./jspm_packages/npm/gulp@3.8.11/bin/gulp.js: line 2: syntax error near unexpected token `(' ./jspm_packages/npm/gulp@3.8.11/bin/gulp.js: line 2: `(function(process) {' ``` Is there some other way I should be going about this?
2015/02/23
[ "https://Stackoverflow.com/questions/28666080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2316606/" ]
Yes `character_limiter()` function does not work for longer word to prevent word break and/or distort meaning. According to codeigniter documentation, it will not try to break long word to maintain its integrity. As per documentation of [character\_limiter](https://www.codeigniter.com/user_guide/helpers/text_helper.html#character_limiter.) > > Truncates a string to the number of characters specified. It maintains the integrity of words so the character count may be slightly more or less than what you specify. > > > but codeigniter does not stops you from limiting exact character, ahead it mentions in note > > If you need to truncate to an exact number of characters please see the ellipsize() function below. > > > so instead of `character_limiter()` you can use `ellipsize()` function and it will do exact same. Hope it help.
Try this,it will fix your issue. ``` $this->load->helper('text'); $string = "your text here"; $string = character_limiter($string, 10); echo $string; ``` Output:your text…
17,324,057
I have **textbox** and I'm changing the text inside it when `lostFocus` is fired but that also fires up the `textChanged` event, which I'm handling but I don't want it to be fired in this one case, how can I disable it here? UPDATE: ------- The idea with `bool` is good but I have couple of textboxes and I use the same event for all of them, so it's not working exactly as I want the way I want. Now it's working! : ``` private bool setFire = true; private void mytextbox_LostFocus(object sender, RoutedEventArgs e) { if (this.IsLoaded) { System.Windows.Controls.TextBox textbox = sender as System.Windows.Controls.TextBox; if(textbox.Text.ToString().Contains('.')) { textbox.Foreground = new SolidColorBrush(Colors.Gray); textbox.Background = new SolidColorBrush(Colors.White); setFire = false; textbox.Text = "something else"; setFire = true; } } } private void mytextbox_TextChanged(object sender, TextChangedEventArgs e) { if ((this.IsLoaded) && setFire) { System.Windows.Controls.TextBox textbox = sender as System.Windows.Controls.TextBox; if(textbox.Text.ToString().Contains('.')) { textbox.Foreground = new SolidColorBrush(Colors.White); textbox.Background = new SolidColorBrush(Colors.Red); } } setFire = true; } ``` I managed to put the `bool` back on `true` after editing the text and it works so thx guys :]
2013/06/26
[ "https://Stackoverflow.com/questions/17324057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2296407/" ]
I feel.. We can do this in Best way and easy way..! ``` //My textbox value will be set from other methods txtNetPayAmount.Text = "Ravindra.pc"; //I wanted to avoide this to travel in my complex logic in TextChanged private void txtNetPayAmount_TextChanged(object sender, EventArgs e) { _strLoanPayment = Convert.ToString(txtNetPayAmount.Text).Trim(); if (string.IsNullOrEmpty(_strLoanPayment)) return; if(!_isPayAmountEntered) return; //Some logic.. Avoided to run each time on this text change } private bool _isPayAmountEntered = false; private void txtNetPayAmount_Enter(object sender, EventArgs e) { _isPayAmountEntered = true; } private void txtNetPayAmount_Leave(object sender, EventArgs e) { _isPayAmountEntered = false; } private void txtNetPayAmount_KeyPress(object sender, KeyPressEventArgs e) { _isPayAmountEntered = false; } ```
I think you could also simply use the "IsFocused" bool built into the UI. ``` private void mytextbox_TextChanged(object sender, TextChangedEventArgs e) { TextBox textbox = sender as TextBox; if (!textbox.IsLoaded || !textbox.IsFocused) return; if(textbox.Text.ToString().Contains('.')) { textbox.Foreground = new SolidColorBrush(Colors.White); textbox.Background = new SolidColorBrush(Colors.Red); } } ``` This way you don't need a unique bool for each input. HTH
1,135,208
Context ------- I have a personal server that I use for the web. I sometimes need to SSH/SFTP to it. Disclamer: I have very little experience with `nginx` internals. Problem ------- This morning, I figured out that the free wifi in a well-know cafe chain was blocking SSH (actually, they are blocking anything that's not on 80/443). But when I need SSH, I need it, so I looked for ways to share SSH and HTTPS on the same port. What I looked at ---------------- I have looked at a few possible solutions that can run on port 443: * `SSHL`: a SSH/OpenVPN/HTTPS multiplexer; * `OpenVPN`: a VPN solution has a built-in multiplexer for OpenVPN and HTTPS; * [`HAProxy`](https://coolaj86.com/articles/adventures-in-haproxy-tcp-tls-https-ssh-openvpn/): a webserver/load balancer can also multiplex everything. All of these seem pretty straight-forward **but** I don't really like the fact of adding layers and complexity and *possibly* slowing things down just in the unlikely event that I need to SSH on 443. Putting nginx into the mix -------------------------- I know that `nginx` already supports raw TCP streams handling. So I was wondering if I could use that on port 443 too directly in `nginx`. The idea being that `nginx` could choose to use the `http` module if it recognizes HTTP(S) or `stream` for everything else. Questions ========= In that context, I have two questions: * Is `nginx` even capable of doing such a distinction? (I am not even sure I would be able to listen on port 443 in both the `http` and the `stream` block at the same time.) * If so, would there be any blatant performance issue with that setup? (I am thinking about transfer speed with SFTP for instance, not really SSH per se.)
2016/10/08
[ "https://superuser.com/questions/1135208", "https://superuser.com", "https://superuser.com/users/622051/" ]
This question is slightly related to another one I've answered a while ago: <https://stackoverflow.com/questions/34741571/nginx-tcp-forwarding-based-on-hostname/34958192#34958192> Yes, it is technically possible to differentiate between `ssh` and `https` traffic, and route the connection appropriately; however, nginx currently doesn't have such support, to my knowledge. However, what you could do is simply run `sshd` directly on the `https` port in addition to the `ssh` one ([`/usr/sbin/sshd -p 22 -p 443`](http://mdoc.su/f/sshd)), and/or use the firewall and/or port knocking in order to differentiate where connections to port `443` get routed to.
As far as I know, currently nginx doesn't support it. In [SSH-2](https://www.rfc-editor.org/rfc/rfc4253), client will send a hello message to server: > > When the connection has been established, both sides MUST send an identification string. This identification string MUST be > > > > ``` > SSH-protoversion-softwareversion SP comments CR LF > > ``` > > In [TLS 1.2](https://www.rfc-editor.org/rfc/rfc5246), clients need to send first: ``` Client Server ClientHello --------> ServerHello [ChangeCipherSpec] <-------- Finished [ChangeCipherSpec] Finished --------> Application Data <-------> Application Data ``` Clients can use this information for implementation.
24,910,972
I am using serial port communication, there is a `DataReceived` Event of Serial Port, in which if the header & footer of received data matches I am executing 2 complex & lengthy functions, here I have used circular buffer for data receive, Out of the 2 functions first function updates a Graph (Area Chart) of 2058 bytes on Canvas & second functions does some complex calculations on 2058 bytes. I am receiving these 2058 bytes after every 3 seconds. So my requirement is while I am filling data in buffer on the other side I need to execute these 2 functions on the data that is already in the buffer (as it is circular buffer it contains previously filled data). I am little bit confused here, how to achieve this concurrency. I know some ways, 1. use 'Task' 2. use 'Threads' 3. use 'async & await' 4. use 'Task Parallel Library' 5. use 'Background Worker' 6. use 'Dispatcher.Invoke()' Currently I am using `Dispatcher.Invoke()` which takes too much time for UI updates. So here time lag happens. Please suggest me which approach will be more responsive.
2014/07/23
[ "https://Stackoverflow.com/questions/24910972", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3837157/" ]
I have managed it successfully with timers and background worker synchronization. The only important thing I noted is you need a good processor, at least 'core - i3'. The solutions proposed by Mr.SKleanthous is also acceptable. Thanks. And thanks Mr. Andreas Müller, yes I got your point. Thank you so much everybody.
You can use 1-5 for complex work (as those are intended for this scenario). You could use 6 to inject your results into the graph, because the purpose of Dispatcher.Invoke is processing work in the UI-Thread and is required for the majority of controls. I hope that helps.
40,975,934
I want to change background image of a div, depending on what image is currently hovered by mouse. I want to create a gallery, so I have a list of images. I want to display the exact same url dynamically (hovered thumbnail) as hovered as a background of the main div (hero image). ``` <div id="background"> <ul> <li><img src="image/1.jpg" alt="" /></li> <li><img src="image/2.jpg" alt="" /></li> <li><img src="image/3.jpg" alt="" /></li> </ul> </div> ``` At the beginning, the `id="background"` has default background, which should be swaped to hovered image. When the image is unhovered, the image should back to the default one. How can I do that using jquery the easiest way? It has to be the same url as the thumbnail, so it has to be dynamic, without additional url settings in jquery script file.
2016/12/05
[ "https://Stackoverflow.com/questions/40975934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7142790/" ]
My first try ``` $('ul img').on('hover', function(e){ $('#background').css('background-image','url('+ $(this).attr('src')+')'); }); ``` Or if you have problems with selectors ``` $('body').on('hover','ul img', function(e){ $('#background').css('background-image','url('+ $(this).attr('src')+')'); }); ``` Also consider using mouseenter and mouseleave events. Heres working code from your codepen: ``` $('body').on('mouseenter','img', function(e){ $('#hero-image').css('background-image','url('+ $(this).attr('src')+')'); }); ```
Try this ``` $("ul li").on({ mouseenter: function () { $('#background').css('background-image', $(this).attr('src')); //stuff to do on mouse enter }, mouseleave: function () { $('#background').css('background-image', 'default.png'); //stuff to do on mouse leave } }); ``` or ``` $("ul li").hover(function () { $('#background').css('background-image', $(this).attr('src')); //stuff to do on mouse enter }, function () { $('#background').css('background-image', 'default.png'); //stuff to do on mouse leave }); ``` for more details [Is it possible to use jQuery .on and hover?](https://stackoverflow.com/questions/9827095/is-it-possible-to-use-jquery-on-and-hover)
60,378,861
I want to know if there is any possibility to add on an Azure DevOps(TFS) dashboard the start time of the tests. Currently I have a pie chart with all the test runned over night,(passed, fail and not run) and I want to know if there is any possibility to add the time when the test were executed on this dashboard. Thank you.
2020/02/24
[ "https://Stackoverflow.com/questions/60378861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3664679/" ]
Use `return words.some(...)` instead of `forEach`. Returning in a `forEach` doesn't do anything for the result of the function passed to the `filter`. The return in the `forEach` just returns from one iteration of the `forEach` and the `true`/`false` value is thrown away. It does not return a result immediately to the predicate of the `filter`. ``` this.itemsLocation2 = this.option_location.filter(item =>{ item.text = item.text.toLowerCase(); let words = item.text.split(" "); words.forEach((element,index) => { if(element.startsWith(text)){ return true; // returns from one forEach iteration, not from filter. }else{ return false; // returns from one forEach iteration, not from filter. } }); }); ``` Use a technique like this instead: ```js let text = 'My name is James'; let searches = ['nam', 'ja', 'ame']; let words = text.toLowerCase().split(" "); for(let searchTerm of searches) { let found = words.some(w => w.startsWith(searchTerm)); console.log(`${searchTerm} => ${found}`); } ```
The reason is that you used `startswith()` function which checks if the word starts with the given string which obviously `name` does not start with `ame`. Whereas `James` starts with `ja` and `name` starts with `nam` The `includes()` function just checks if the word contains the given string no matter where it is.
52,782,751
I have a Cordova app using Vue.js, and lots of logging using the standard Javascript/browser console.log(). Up until now I've only been targeting iOS, and those console.log messages appear in the xCode log viewer. Now, however, I'm also targeting Android. I've successfully imported the Cordova project into Android Studio and the app is running in debug mode in the Emulator. But, I can't find the console.log output anywhere. I think the log output should appear here, but there is nothing from my app at all. [![enter image description here](https://i.stack.imgur.com/vIf0W.png)](https://i.stack.imgur.com/vIf0W.png) I've also tried Logcat, as @Lukasz describes, which also had no effect: [![enter image description here](https://i.stack.imgur.com/CXk3E.png)](https://i.stack.imgur.com/CXk3E.png)
2018/10/12
[ "https://Stackoverflow.com/questions/52782751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2943799/" ]
I finally resolved this. I had to enable Developer Options in settings and enable USB Debugging.
If you're not seeing console.log in LogCat, ensure your application is debuggable. This will be true for apps run from Android Studio (I think) but if you're debugging a 3rd party APK like I am, it won't. Maybe this will save someone the 3 hours I wasted on it. So ensure `android:debuggable="true"` is there in the `application` tag of of your AndroidManifest.xml file
3,762
I've been fiddling around a bit with CC-mode lately and figured that since I prefer to comment my functions/classes with javadoc-like syntax, I'd like to use the built-in comment highlighting provided by the corresponding `c-doc-comment-style`. This works rather well, it highlights something like this rather easily: ``` /** @brief This is function foo. @param a this is a parameter. @return I return this. */ int foo(unsigned a) {...} ``` However, I noticed that the comment suddenly changed color as well to a default one I don't really like. Any idea how to change that color back to the one defined by the current theme instead?
2014/11/20
[ "https://emacs.stackexchange.com/questions/3762", "https://emacs.stackexchange.com", "https://emacs.stackexchange.com/users/2653/" ]
After fiddling a bit longer with this, I think I figured it out. Adding the following snippet to my CC-mode init-configuration fixed this: ``` (defun my-cc-init-hook () "Initialization hook for CC-mode runs before any other hooks." (setq c-doc-comment-style '((java-mode . javadoc) (pike-mode . autodoc) (c-mode . javadoc) (c++-mode . javadoc))) (set-face-foreground 'font-lock-doc-face (face-foreground font-lock-comment-face))) (add-hook 'c-initialization-hook 'my-cc-init-hook) ``` This basically copies the foreground color of the comment face to the "doc"-face that the javadoc style defines. Any improvements to this is appreciated!
You can just add the mapping to the comment style list: ``` (add-to-list 'c-doc-comment-style '(c++-mode . javadoc)) ``` This is more portable and just extends the list instead of replacing it.
12,074,745
Working with Node.js(monogdb, express and other modules) I'm wondering if there is a mongoose method for database connection, something like if I open a connection `var db = mongoose.connect('mongo://localhost/members');` then I can `db.on('close', function(){ /*do stuffs here*/})`. Basicly, the function below does the job of getting a user list from database and logging when database connection is closed. So I need something in the `if()` to check database connection or whatever just unable to get data while its off and make a logging. I tried `if(docs != null)` it seems just off tho. Any advice would be much appreciated! ``` var logger = require('bunyan'); var log = new logger({ name: "loggings", streams: [ { level: 'error', path: 'test.log', } ], serializers: { err: logger.stdSerializers.err, } }); function(req, res){ memberModel.find(function(err, docs){ if (/*connection is closed*/) { res.render('users.jade', { members: docs }); }else{ try { throw new DatabaseError ("Error!"); } catch (err){ log.warn({err: err}, "Check database connection!"); } res.render('index.jade'); }; }); }; ```
2012/08/22
[ "https://Stackoverflow.com/questions/12074745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1326868/" ]
I am sorry to bear bad news, but look here: [Prevent IIS from changing response when Location header is present](https://stackoverflow.com/questions/10594225/prevent-iis-from-changing-response-when-location-header-is-present) > > Edit: Never did find an answer - I ended up switching to Apache > > > And it seems IIS has had its fingers into headers for a long time: <http://forums.iis.net/t/1158431.aspx> > > This is a bug in IIS FastCGI module. It will be fixed in Windows 7 RTM. We are also looking into possible ways for making this fix available for IIS 7. > > > Hopefully **if** the bugs are related (I expect they are), **if** you now have FastCGI, *then* the fix below could work. Otherwise, switching to PHP non-FastCGI module might also work, and it might be easier than throwing in with Apache. <http://support.microsoft.com/kb/980363>
To circumvent this IIS behavior, you can use an outbound rewrite rule. The following will look for status 201, and if so, eliminate all the content lines up to and including the closing body tag: ``` <outboundRules> <rule name="Remove injected 201 content" preCondition="Status 201"> <match filterByTags="None" pattern="^(?:.*[\r\n]*)*.*&lt;/body>" /> <action type="Rewrite" value="" /> </rule> <preConditions> <preCondition name="Status 201" patternSyntax="Wildcard"> <add input="{RESPONSE_STATUS}" pattern="201" ignoreCase="false" /> </preCondition> </preConditions> </outboundRules> ```
5,675,346
Think this is a quickie for someone. I have this markup (generated by ASP.Net)... ``` <A id=anchorO href="javascript:__doPostBack('anchorO','')">O</A> ``` This anchor is in an update panel, and if I click it manually a partial postback takes place. However.... ``` $('[ID$="anchor'+initial+'"]').click() //JavaScript ``` ..selects the correct anchor, but no postback takes place. Why is this?
2011/04/15
[ "https://Stackoverflow.com/questions/5675346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/395628/" ]
A click and a href are seen as two different things in Javascript, so you can't do `.click()` and call the href, regardless if this is calling `javascript:` or not **Two options:** 1. Just do: > > > ``` > $('#anchor' + initial).click(function() { __doPostBack('anchorO',''); }); > > ``` > > 2. Be evil and use eval: > > > ``` > $('#anchor' + initial).click(function() { eval($(this).attr('href')); }); > > ``` > >
See this question [here](https://stackoverflow.com/questions/1694595/can-i-call-jquery-click-to-follow-an-a-link-if-i-havent-bound-an-event-handl) It appears that you can't follow the href of an a tag using the click event.
36,905,398
I have implemented this code. <http://www.androidbegin.com/tutorial/android-video-streaming-videoview-tutorial/> but it showing progressdialog to whole activity, but my requirement is to show progressDialog only in videoview, like wise showing in youtube when buffering the video.
2016/04/28
[ "https://Stackoverflow.com/questions/36905398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4068788/" ]
Your code seems to be more or less based on an idea [which is presented at gis.stackexchange.com](https://gis.stackexchange.com/questions/25877/how-to-generate-random-locations-nearby-my-location/) and discussed some more there in [this discussion](https://gis.stackexchange.com/questions/69328/generate-random-location-within-specified-distance-of-a-given-point) and in [this discussion](https://gis.stackexchange.com/questions/186135/generating-random-points-near-a-location). If we take a closer look at it based on those discussions then maybe it makes more sense. To easily limit the values to a circle it uses the approach of randomizing a direction and a distance. First we get two random double values between 0.0 ... 1.0: ```java double u = random.nextDouble(); double v = random.nextDouble(); ``` As the radius is given in meters and the calculations require degrees, it's converted: ```java double radiusInDegrees = radiusInMeters / 111000f; ``` The degrees vs. meters ratio of the equator is used here. (Wikipedia suggests 111320 m.) To have a more uniform distribution of the random points the distance is compensated with a square root: ```java w = r * sqrt(u) ``` Otherwise there would be a statistical bias in the amount of points near the center vs. far from the center. The square root of 1 is 1 and 0 of course 0, so multiplying the root of the random double by the intended max. radius always gives a value between 0 and the radius. Then the other random double is multiplied by 2 \* pi because there are 2 \* pi radians in a full circle: ```java t = 2 * Pi * v ``` We now have an angle somewhere between 0 ... 2 \* pi i.e. 0 ... 360 degrees. Then the random x and y coordinate deltas are calculated with basic trigonometry using the random distance and random angle: ```java x = w * cos(t) y = w * sin(t) ``` The `[x,y]` then points some random distance `w` away from the original coordinates towards the direction `t`. Then the varying distance between longitude lines is compensated with trigonometry (`y0` being the center's y coordinate): ```java x' = x / cos(y0) ``` Above `y0` needs to be converted to radians if the `cos()` expects the angle as radians. In Java it does. It's then suggested that these delta values are added to the original coordinates. The `cos` and `sin` are negative for half of the full circle's angles so just adding is fine. Some of the random points will be to the west from Greenwich and and south from the equator. There's no need to randomize should an addition or subtraction be done. So the random point would be at `(x'+x0, y+y0)`. I don't know why your code has: ```java double new_y = y / Math.cos(x0); ``` And like said we can ignore `shouldAddOrSubtractLat` and `shouldAddOrSubtractLon`. In my mind `x` refers to something going from left to right or from west to east. That's how the longitude values grow even though the longitude lines go from south to north. So let's use `x` as longitude and `y` as latitude. So what's left then? Something like: ```java protected static Location getLocationInLatLngRad(double radiusInMeters, Location currentLocation) { double x0 = currentLocation.getLongitude(); double y0 = currentLocation.getLatitude(); Random random = new Random(); // Convert radius from meters to degrees. double radiusInDegrees = radiusInMeters / 111320f; // Get a random distance and a random angle. double u = random.nextDouble(); double v = random.nextDouble(); double w = radiusInDegrees * Math.sqrt(u); double t = 2 * Math.PI * v; // Get the x and y delta values. double x = w * Math.cos(t); double y = w * Math.sin(t); // Compensate the x value. double new_x = x / Math.cos(Math.toRadians(y0)); double foundLatitude; double foundLongitude; foundLatitude = y0 + y; foundLongitude = x0 + new_x; Location copy = new Location(currentLocation); copy.setLatitude(foundLatitude); copy.setLongitude(foundLongitude); return copy; } ```
Longitude and Latitude uses ellipsoidal coordinates so for big radius (hundred meters) the error using this method would become sinificant. A possible trick is to convert to Cartesian coordinates, do the radius randomization and then transform back again to ellipsoidal coordinates for the long-lat. I have tested this up to a couple of kilometers with great success using [this java library](http://www.ibm.com/developerworks/library/j-coordconvert/) from ibm. Longer than that might work, but eventually the radius would fall off as the earth shows its spherical nature.
46,487,261
One nice feature of DataFrames is that it can store columns with different types and it can "auto-recognise" them, e.g.: ``` using DataFrames, DataStructures df1 = wsv""" parName region forType value vol AL broadL_highF 3.3055628012 vol AL con_highF 2.1360975151 vol AQ broadL_highF 5.81984502 vol AQ con_highF 8.1462998309 """ typeof(df1[:parName]) DataArrays.DataArray{String,1} typeof(df1[:value]) DataArrays.DataArray{Float64,1} ``` When I do try however to reach the same result starting from a Matrix (imported from spreadsheet) I "loose" that auto-conversion: ``` dataMatrix = [ "parName" "region" "forType" "value"; "vol" "AL" "broadL_highF" 3.3055628012; "vol" "AL" "con_highF" 2.1360975151; "vol" "AQ" "broadL_highF" 5.81984502; "vol" "AQ" "con_highF" 8.1462998309; ] h = [Symbol(c) for c in dataMatrix[1,:]] vals = dataMatrix[2:end, :] df2 = convert(DataFrame,OrderedDict(zip(h,[vals[:,i] for i in 1:size(vals,2)]))) typeof(df2[:parName]) DataArrays.DataArray{Any,1} typeof(df2[:value]) DataArrays.DataArray{Any,1} ``` There are several questions on S.O. on how to convert a Matrix to Dataframe (e.g. [DataFrame from Array with Header](https://stackoverflow.com/questions/25894634/dataframe-from-array-with-header), [Convert Julia array to dataframe](https://stackoverflow.com/questions/26769162/convert-julia-array-to-dataframe)), but none of the answer there deal with the conversion of a mixed-type matrix. How could I create a DataFrame from a matrix auto-recognising the type of the columns ? EDIT: I [did benchmark the three solutions](https://pastebin.com/fSTTrnfa): (1) convert the df (using the dictionary or matrix constructor.. first one is faster) and then apply try-catch for type conversion (my original answer); (2) convert to string and then use df.inlinetable (Dan Getz answer); (3) check the type of each element and their column-wise consistency (Alexander Morley answer). These are the results: ``` # second time for compilation.. further times ~ results @time toDf1(m) # 0.000946 seconds (336 allocations: 19.811 KiB) @time toDf2(m) # 0.000194 seconds (306 allocations: 17.406 KiB) @time toDf3(m) # 0.001820 seconds (445 allocations: 35.297 KiB) ``` So, crazy it is, the most efficient solution seems to "pour out the water" and reduce the problem to an already solved one ;-) Thank you for all the answers.
2017/09/29
[ "https://Stackoverflow.com/questions/46487261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1586860/" ]
``` mat2df(mat) = DataFrame([[mat[2:end,i]...] for i in 1:size(mat,2)], Symbol.(mat[1,:])) ``` Seems to work and is faster than @dan-getz's answer (at least for this data matrix) :) ``` using DataFrames, BenchmarkTools dataMatrix = [ "parName" "region" "forType" "value"; "vol" "AL" "broadL_highF" 3.3055628012; "vol" "AL" "con_highF" 2.1360975151; "vol" "AQ" "broadL_highF" 5.81984502; "vol" "AQ" "con_highF" 8.1462998309; ] mat2df(mat) = DataFrame([[mat[2:end,i]...] for i in 1:size(mat,2)], Symbol.(mat[1,:])) function mat2dfDan(mat) s = join([join([dataMatrix[i,j] for j in indices(dataMatrix, 2)], '\t') for i in indices(dataMatrix, 1)],'\n') DataFrames.inlinetable(s; separator='\t', header=true) end ``` - ``` julia> @benchmark mat2df(dataMatrix) BenchmarkTools.Trial: memory estimate: 5.05 KiB allocs estimate: 75 -------------- minimum time: 18.601 μs (0.00% GC) median time: 21.318 μs (0.00% GC) mean time: 31.773 μs (2.50% GC) maximum time: 4.287 ms (95.32% GC) -------------- samples: 10000 evals/sample: 1 julia> @benchmark mat2dfDan(dataMatrix) BenchmarkTools.Trial: memory estimate: 17.55 KiB allocs estimate: 318 -------------- minimum time: 69.183 μs (0.00% GC) median time: 81.326 μs (0.00% GC) mean time: 90.284 μs (2.97% GC) maximum time: 5.565 ms (93.72% GC) -------------- samples: 10000 evals/sample: 1 ```
While I didn't find a complete solution, a partial one is to try to convert the individual columns ex-post: ``` """ convertDf!(df) Try to convert each column of the converted df from Any to In64, Float64 or String (in that order). """ function convertDf!(df) for c in names(df) try df[c] = convert(DataArrays.DataArray{Int64,1},df[c]) catch try df[c] = convert(DataArrays.DataArray{Float64,1},df[c]) catch try df[c] = convert(DataArrays.DataArray{String,1},df[c]) catch end end end end end ``` While surely incomplete, it is enough for my needs.
6,650
My next task is creating a robotic voice that gives information to the main character. One idea I had was to create an effect much like when a cell phone is breaking up and the voice gets all choppy and digitally distorted. It's kind of hard to explain, but it is what happens when a cell phone is about to disconnect or is out of range and it's almost mono-tone. Does anyone know of a plug-in that can achieve this effect? Any advice would be much appreciated. Even general tips on how to make a good robotic voice would be great.
2011/03/18
[ "https://sound.stackexchange.com/questions/6650", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/18160/" ]
If you have Waves, try the "reflective room" preset on MetaFlanger - my go to when I don't want TOO much effect to distort the actual words (I'm using it on a Kid's show where the dialog needs to be clear). You can also try the Morphoder for the classic "Cylon" effect (The "Robbie" preset is a good start). Finally, if you're in ProTools, try the Sci-Fi plug-in, and D-Verb with the "Ambience" setting -good metallic sounds.
Not exactly along the telephone idea, but definitely a robot-voice go-to, [Sonic Charge's BitSpeek](http://www.soniccharge.com/bitspeek) is an awesome tool and very affordable!
23,042
The Gospel of John describes a scene where John the Baptist saw Jesus coming toward him and he made the following statement: > > “Look, the Lamb of God, who takes away the sin of the world! This is > the one I meant when I said, ‘A man who comes after me has surpassed > me because he was before me.’ I myself did not know him, but the > reason I came baptizing with water was that he might be revealed to > Israel.” **Then John gave this testimony:** “I saw the Spirit come down > from heaven as a dove and remain on him. And I myself did not know > him, but the one who sent me to baptize with water told me, ‘The man > on whom you see the Spirit come down and remain is the one.” (John > 1:29-34) > > > At first sight, it seems the writer was describing the actual baptism itself, as per Matthew’s account. However, the next few days finds Jesus choosing his disciples – not going into the wilderness as the Synoptics relate it. So, is this scene a ‘revisit’ so to speak? Is it Jesus coming out of the wilderness, walking past John, at about Passover season, some months following his actual baptism? If so, then the Gospel of John is not recording the baptism event **directly**, but is recording John B’s **testimony of that event.** In other words, John B. sees Jesus returning, and calls out, *"This is the man I baptised several months ago! This is the man the dove descended upon!"* So, is the Gospel of John recording the actual baptism event, or is he recording an occasion when Jesus revisited the same place on his way back from the wilderness? The latter explanation may reconcile some of the perceived differences between John and the Synoptic Gospels.
2016/06/23
[ "https://hermeneutics.stackexchange.com/questions/23042", "https://hermeneutics.stackexchange.com", "https://hermeneutics.stackexchange.com/users/8352/" ]
According to the [*Diatessaron* of Tatian](https://www.ccel.org/ccel/schaff/anf09.iv.iii.i.html) - probably the earliest harmony of the Gospels, dating to the late 2nd century - and the [Eusebian Canon](http://earlyenglishbibles.com/specialbibles/UseCanon.html) (early 4th century) the sequence in the Gospels is as follows: **John's Initial Witness** - Matt 3:1-12; Mark 1:1-8; Luke 3:1-18; John 1:15-31 **Baptism of Christ** - Matt 3:13-17; Mark 1:9-11; Luke 3:21-22; John 1:32-34 **Temptation in the Wilderness** - Matt 4:1-11; Mark 1:12-13; Luke 4:1-13 **First Disciples Called** - John 1:35-51 John 1:32-34 is, in fact, a recollection. This is clear in the text: *And John bare record* (ἐμαρτύρησεν) in verse 32. John is stating this recollection in the midst of Christ's calling the first disciples.
From John passage on this in his First Epistle, I would say you are right. This was at a later date. **6) This is He that came by water and blood, even Jesus Christ; not by water only, but water and blood. And it is the Spirit that beareth witness, because the Spirit is Truth. 7) For there are Three that bear record in heaven, the Father, the Word, and the Holy Ghost; and these Three are One. 8) And there are three that bear witness in earth the Spirit, and the water, and the blood: and these three agree in one. 9) If we receive the witness of men, the witness of God is greater, for this is the witness of God which He hath testified of His Son. 10) He that believeth on the Son of God hath the witness in himself: he that believeth not God hath made Him a liar; because he believeth not the record that God gave of Himself. I John 5:6-10** As you have noted the Apostle John gives no eyewitness account of the Baptism of Jesus in his Gospel. Yet he refers to John the Baptist in John 1:29-34 as giving record to Jesus as the Son of God, but John the Baptist stated he bare record that God bare record that Jesus was His Son, remember John stated:**33) And I knew Him not: but He that sent me to baptize with water, the Same said unto me, Upon Whom thou shalt see the Spirit descending, and remaining on Him, the Same is He which baptizeth with the Holy Ghost. 34) And I saw, and bare record that this is the Son of God. John 1:33-34 strong text** The Baptist mention water so that we might know that Jesus water baptism, was God record to the World that our LORD Jesus Christ and the Holy Spirit along with the Father are Three separate Person, yea United as One Godhead/Trinity. Yes I say God's record because all Three Members of the Godhead; the Father, and the Word (Who of course is the Son), and the Holy Spirit gave a heavenly witness because the Son was sent from heaven, the Holy Ghost descended from heaven as a Dove, and the Father's voice, came down from heaven. While we continue to read I John 5 after verse 7, which many modern scholars question; we see the Apostle John state if we receive men's witness the witness of God is greater. Yet even Jesus tells us that many will not receive His witness--John 3:11; 32. So that we see that the record of the Trinity came at Jesus Water Baptism, hence Jesus came by water. We know that Cyprian in 250 AD, quoted the TR complete verse of I John 5:7 with the only difference being instead of the Word, he called Jesus the Son. But what was the witness of men. We see in I John 5:6 that Jesus came by water but also water and blood. In John 19:30-37 we see the Apostle John bearing the witness of men. For in at the end of verse 30 John states that Jesus gave up the Ghost (Spirit). But we also see at our Savior physical death, that instead of breaking any bones in His body, they pierced Him with a spear and what came out, blood and water, John 19:32-34. So that the Apostle states that he bear record in verse 35, So that at Jesus death we see that the Spirit departed, which is a sign of death, and blood and water coming out of the side agree with this sign. So I see John in his Gospel, in passing mentioning Jesus baptism, after it happen, but later in his first epistle, mentioning it again in I John 5:7 as the Heavenly Witness; for all Three Members of the Trinity were presence and this according to John the Baptist was the Father record. While at Jesus death we see John baring witness, to the Spirit departing and the blood and water coming out of His side.
2,574
The various cultures of the Ancient Near East spoke a wide array of languages and we know that there was plenty of communication between cultures. We even have a language like Akkadian that served as a lingua franca between many different cultures. Diplomats, and others, must have received training in foreign languages. Do we have any written grammars from the Ancient Near East used for such teaching? Dictionaries? Explanations of points of grammar? Even exercises used by students?
2012/07/12
[ "https://history.stackexchange.com/questions/2574", "https://history.stackexchange.com", "https://history.stackexchange.com/users/1092/" ]
The [Barbary Pirates](http://en.wikipedia.org/wiki/Barbary_corsairs) raided as far north as Iceland and Scotland to capture slaves. While still Caucasian, North Africans typically have darker skin than northern Europeans.
Fair skinned people are oppressed and lower classes in most fair skinned societies and nations. I'm born Australian and was born in the late 60s. Before multiculuralism took off in the 80s and 90s nearly all of the manual, dirty, dangerous and unpleasant jobs in our society were performed by white people. Most of the wealth went to a relative few white people. The upper classes looked down on the lower classes despite being the same ethnicities. Now the wealth goes to lots of different ethnicities, but there are still a lot of white members of the "under class". And yes tanning creams are (or were before the 90s or so) used by light skinned people as an attempt to convey higher social class. Having a tan in winter in the UK indicated you had the wealth to travel to somewhere that had sun light. Tanning cream may now be relatively common fashion accessory, but way back when a real tan meant exactly what you said - you had money to travel be able to afford to travel and to take the time to do so, which is why fake tans were originally so popular.
11,120,395
I usually use a boolean 'firstTime' like this: in C++: ``` bool firsTime = true; for (int i = 0; i < v.size(); i++) { if (firstTime) { //do something just once firstTime = false; } else { //do the usual thing } } ``` in java it would be the same using a boolean instead a bool so I don't put the code. The questin is, is there anyway in java or c/c++ to use a bool/boolean in an if clause and automatically assign to that bool/boolean the value false? I know it seems a nonsense but it would save my code A LOT of lines because I've a lot of base cases and in big fors or whiles that is critical. I do want to know if there is anyway to put a value to false after using it in an if clause. I know that in a for or while we can just use: ``` if (i == 0) ``` But I was also thinking in calls to functions that needs to know things and that usually is referenced by bools.
2012/06/20
[ "https://Stackoverflow.com/questions/11120395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1468942/" ]
If you don't have a count already, you can use one instead of a boolean ``` long counter = 0; for(String arg: args) { if(counter++ == 0) { // first } } ``` An alternative which uses a boolean is ``` boolean first = true; for(String arg: args) { if(first && !(first = false)) { // first } } ``` --- For sets there is a similar pattern ``` Set<String> seen = ... for(String arg: args) { if(seen.add(arg)) { // first time for this value of arg as its only added once. } } ```
``` for (int i = 0, firstTime = 1; i < v.size(); i++, firstTime = 0) { ```
2,159,516
This is a similar problem to [this question](https://stackoverflow.com/questions/688819/deploy-a-linq-to-sql-library-using-different-sql-users) When I deployed my dev app to the prod server I was getting an error: System.Data.SqlClient.SqlException: Invalid object name 'dbo.Login'. The table attribute on the linq mapping looks like [Table(Name="**dbo**.Login")] When I loaded the prod db schema into the vs2008 server explorer and refreshed my dbml entirely with that one, the application on prod works, but now the application on dev does not work. The table attribute on the linq mapping now looks like [Table(Name="**prodDbUsername**.Login")] On the dev server I now get System.Data.SqlClient.SqlException: Invalid object name 'prodDbUsername.Login'. What is the best way to manage these different user prefixes between dev and prod?
2010/01/29
[ "https://Stackoverflow.com/questions/2159516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55693/" ]
It sounds like you have have identical tables named differently in your different environments. The simplest way to fix your problem is to use identical schema for all environments (the data can be different, but you are asking for all kinds of problems if the schema is not the same). EDIT: With your further clarification, the tables are being created either with a different owner or a within a different schema. See <http://www.sqlteam.com/article/understanding-the-difference-between-owners-and-schemas-in-sql-server> for further clarification on the difference. I would recommend that you try creating your tables with the following syntax: ``` CREATE TABLE [dbo].[MY_TABLE_NAME]... ```
If you're using a single schema (i.e. not multiple schemas in a single db), you can just remove the schema prefix on your tables. E.g. change: ``` <Table Name="dbo.person" Member="Persons"> ``` To: ``` <Table Name="person" Member="Persons"> ```
15,664,505
I have Jackrabbit 2.4.0 (deployed as rar into a JBoss AS 7.1.0) on a Red Hat 6 64-bit machine. The JBoss JVM has the max heap size set to 8 GB. The machine has 24GB of RAM. The curious thing is when the JBoss is started it has almost 20 GB of virtual size (statistic taken from top). The Linux page cache (swap cache) is around 10 GB so the system will actually have free memory somewhere around 5 GB. I'm not sure why the page cache is so big and I'm trying to make a link with the size of the jackrabbit's data directory where the Lucene indexes are kept. The size of the directory is around 10 GB. My question is: does Lucene use memory mapping for indexes files? Thanks in advance.
2013/03/27
[ "https://Stackoverflow.com/questions/15664505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1517754/" ]
> > My question is: does Lucene use memory mapping for indexes files? > > > Lucene uses memory mapping only [if you ask](http://lucene.apache.org/core/4_2_0/core/org/apache/lucene/store/MMapDirectory.html) for it. You might also want to read [this](http://blog.thetaphi.de/2012/07/use-lucenes-mmapdirectory-on-64bit.html).
JBOSS total resident memory is comprised of several factors, not all of which are heap: 1. Heap 2. Perm gen 3. JARs and JVM 4. Mapped byte arrays 5. Thread stacks (~1MB per thread) There's your application and the app server itself. So certainly you should profile using something like Visual VM to see the details of what's going on, but it'll only help with heap and perm gen. You'll need tools like nmap on Linux to ferret out the rest.
39,659,777
How can I delete rows of table with eloquent and where ? My code is wrong? the code doesn't work! ``` Mode::where('expired','<=',Carbon::now()->toDateString())->delete(); ```
2016/09/23
[ "https://Stackoverflow.com/questions/39659777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4363830/" ]
Check if `Carbon::now()->toDateString()` format matches with the format of 'expired' column
If your expired timestamp is in format of `Y-m-d H:i:s` then you can use `toDateTimeString()` in place of `toDateString()` You can use ``` Mode::where('expired','<=',Carbon::now()->toDateTimeString())->delete(); ```
5,019,743
Is there a way to insert a horizontal line after a certain number of rows, which may be variable depending upon a property in data provider of a datagrid? Thanks.
2011/02/16
[ "https://Stackoverflow.com/questions/5019743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/503510/" ]
In fact, in Java the term **constant** has no defined meaning. It occurs in the JLS only in the larger term **compile time constant expression**, which is an expression which can (and must) be calculated by the compiler instead of at runtime. (And the keyword `const` is reserved to allow compilers to give better error messages.) In Java, we instead use the term *final* to refer to variables (whether class, object or local ones) who can't be changed, and *immutable* when we refer to objects who can't change. Both can be used when speaking about a variable `x` - the first then means the variable itself (meaning it can't be switched to another object), the second means the object behind the variable. Thus here the two meanings are orthogonal, and are often combined to create a *"true constant"*.
Immutability of the object means it can't transform it's state... i.e. can't mutate... For examle ``` final class Person { private int age = 0; public Person(int age) { this.age = age; } } ``` The object to this type are immutable objects since you can't change it's state.... (forget Reflection for a moment) Constant at the other hand in Programming means inline... Even the compiler does that they inline the values of the constant variables for primative types... for object types it means the ref variable can't be reassigned.
59,592,356
I have a list of lists and I want to remove all the duplicates so that the similar lists will not appear at all in the new list. ``` k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]] output == [[5,6,2], [3]] ``` So for example, `[1,2]` have a duplicate so it should not appear in the final list at all. This is different from what others have asked as they wanted to keep one copy of the duplicate in the final list.
2020/01/04
[ "https://Stackoverflow.com/questions/59592356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5433663/" ]
As mentioned in the [firestore issue ticket](https://github.com/flutter/flutter/issues/35670#issuecomment-593422250), fixing the version of the firebase core to 0.4.4 instead of using 0.4.4+2 fixed the issue: ``` dependency_overrides: firebase_core: 0.4.4 ``` Add this along with your existing `firebase_auth` dependency.
I found the solution just comment or import and put this code below it should look like this ``` #import "FLTFirebaseCorePlugin.h" // #import "UserAgent.h" // Generated file, do not edit #define LIBRARY_VERSION @"0.4.4-2" #define LIBRARY_NAME @"flutter-fire-core" ```
28,636
I was analyzing the following position for one of the correspondence games that I am playing. In the position, white is up 2 pawns and with my limited understanding, I can't see any real compensation for black. I checked with Stockfish 10 at depth 29 and it evaluated the position as +0.63. I also checked with Komodo 13.2 which gives the position as +0.50 at depth 25. My question is basically on what is the compensation that black has for the 2 extra pawns or is there, in reality, no compensation and I didn't let the computer go into a higher depth. Here is the position(Black to move): ``` [fen "r1br2k1/pp3pbp/6p1/4P3/5P1P/2N1P3/PP4P1/R1B1KR2 w - - 0 1"] ```
2020/02/24
[ "https://chess.stackexchange.com/questions/28636", "https://chess.stackexchange.com", "https://chess.stackexchange.com/users/21014/" ]
First of all, white's pieces don't have much mobility. The B has one legal move, the queen's rook also only has one move, the king's rook only has four moves and none of them are particularly good. The king is kind of in the way. White is going to have to spend some time coordinating his pieces. Second, black has the two Bishops. Third, white's pawns are doubled and there is no clear way to advance them in the short term. There isn't not enough compensation for two pawns but certainly black's more active position is worth at least a pawn, maybe a little more and that's what the engines are saying.
When you get those results from an engine that shows the game is essentially even while you see a two pawn difference then that means you do not fully understand the value of positions. Black has the two bishops. With Bg4 he will control the file his rook is on and finish his mobilization. White will have problems getting his pieces onto useful squares. The white bishop is bad as whites pawns block the bishop Black will double rooks on the queen file threatening a pawn and the bishop if white moves it to d2. p-f6 will be double edged freeing the black bishop but giving white a potential passed pawn in the late endgame. White could advance the behind 3 pawn to reblock the bishop. black should wait on that move until rooks and other bishop are deployed. Overall it is a tough position with a lot of play and white has a minimal edge that might matter between computers but not so much between people who actually do the moves. If you are black I suggest you offer a draw. Especially since you have been getting outside help by posting the question about an ongoing ICCF game online. If you are white I suggest you offer a draw and hope black takes it.
21,507,967
I understand the meaning of this error. I found many similar questions here at stackoverflow.com and I have tried to implement the answers those were suggested but still I am getting this error. What I am trying to do is using php web service I am extracting the data from mysql database server and trying to display it in listview using AsyncTask as follows: ``` class LoadAllProducts extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> { ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); protected ArrayList<HashMap<String, String>> doInBackground(String... args) { List<NameValuePair> params = new ArrayList<NameValuePair>(); JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params); Log.d("All Products: ", json.toString()); try { JSONArray files = json.getJSONArray(TAG_FILES); for(int i=0;i<files.length();i++) { HashMap<String, String> map = new HashMap<String, String>(); JSONObject e = files.getJSONObject(i); String file_name = e.getString(TAG_FILE_NAME); String sender = e.getString(TAG_SENDER); String subject = e.getString(TAG_SUBJECT); map.put(TAG_SENDER, sender); map.put(TAG_SUBJECT, subject); mylist.add(map); } } catch (JSONException e) { e.printStackTrace(); Log.e("log_tag", "Error parsing data "+e.toString()); } return mylist; } ``` This was suggested in many answers that all the processing should be done in doInBackground function. Now below is the code to display this arraylist in ListView ``` protected void onPostExecute(String file_url) { pDialog.dismiss(); runOnUiThread(new Runnable() { public void run() { String[] from = { TAG_SENDER, TAG_SUBJECT }; int[] to = { android.R.id.text1, android.R.id.text2 }; ListAdapter adapter = new SimpleAdapter(AllProductsActivity.this, mylist, android.R.layout.simple_list_item_2, from , to); setListAdapter(adapter); } }); } ``` Please Help cause first of all I am a beginner of android and I dont have any clue how to solve this problem . Please check my code and let me know the problem.
2014/02/02
[ "https://Stackoverflow.com/questions/21507967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2773586/" ]
This type of error will come if your main thread doing so much work. Basically skip frames will happen maximum time when we test our app in emulator, because its already slow and unable to handle huge operation like a device. I saw a simple problem in your code. We know onPostExecute() runs on MainThread, But still you use `runOnUiThread(new Runnable()` in onPostExecute() . You doinbackground method returns an ArrayList , but your onpostexecute hold a string.. Change it as my onPostExecute' parameter that is the ArrayList(mylist)you use in your adapter. **EDIT** ``` class LoadAllProducts extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> { ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>(); protected ArrayList<HashMap<String, String>> doInBackground(String... args){ HttpClient client = new DefaultHttpClient(); HttpGet getData = new HttpGet("your_url"); HttpResponse response = client.execute(getData); BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); String data = ""; while((data = br.readLine()) != null){ JsonArray arr = new JsonArray(data); for(int i=0;i<arr.length();i++) { HashMap<String, String> map = new HashMap<String, String>(); JSONObject e = arr.getJSONObject(i); String file_name = e.getString(TAG_FILE_NAME); String sender = e.getString(TAG_SENDER); String subject = e.getString(TAG_SUBJECT); map.put(TAG_SENDER, sender); map.put(TAG_SUBJECT, subject); mylist.add(map); } return mylist; } protected void onPostExecute(ArrayList<HashMap<String, String>> mylist) { String[] from = { TAG_SENDER, TAG_SUBJECT }; int[] to = { android.R.id.text1, android.R.id.text2 }; ListAdapter adapter = new SimpleAdapter(AllProductsActivity.this, mylist, android.R.layout.simple_list_item_2, from , to); setListAdapter(adapter); pDialog.dismiss(); } ```
I'm sorry this is not a super informed answer, but I have 2 suggestions. First, eliminate the `runOnUiThread` call, because `onPostExecute` already runs on the ui thread (that is the point of the method). That will not help with any frame skipping, but at least you can get rid of some unneeded code. Second, create the `ListAdapter` in `doInBackground`. I doubt it will make much difference, but you might as well get as much off the UI thread as possible. So, instead of `AsyncTask<String, String, ArrayList<HashMap<String, String>>>` you will use `AsyncTask<String, String, ListAdapter>`. That leaves only 2 method calls in `onPostExecute`, `pDialog.dismiss` and `setListAdapter`. You can't get any more efficient than that. If it still skips frames, I would blame the debugger and move on.
1,608,102
Let's say I generate $6$ numbers: $X\_1, \ldots, X\_6$ where $X\_i$ can be any integer between $1$ and $59$ with equal probability (inclusive). For example, the following could have been randomly generated: $$1, 2, 3, 4, 5, 59$$ $$1, 1, 2, 3, 4, 59$$ $$\text{etc}\ldots$$ What is the chance that $1,2,3$ is a subset of the $6$ numbers generated? What is the chance that $1,1,3$ is a subset of the $6$ numbers generated? And in general, What is the chance that $x,y,z$ is a subset of the $6$ numbers generated? **Edit:** As per the definition of "subset", order does not matter. So $1,2,3$ is a subset of $1,2,3,4,5,6$ as well as $1,6,3,5,2,4$
2016/01/11
[ "https://math.stackexchange.com/questions/1608102", "https://math.stackexchange.com", "https://math.stackexchange.com/users/303622/" ]
It should be the latter. By Apollonius Theorem we have, $c^2+b^2=2(BD^2+AD^2)$ Given $a^2=4BD^2<2(AD^2+BD^2)$ So, $c^2+b^2-a^2>0$ So, $\cos A=\frac{c^2+b^2-a^2}{2bc}>0$ So, $ \angle A$ is acute
[![enter image description here](https://i.stack.imgur.com/d4hPQ.jpg)](https://i.stack.imgur.com/d4hPQ.jpg) We are given $BD=CD<AD$. Let angle measures $\alpha, \alpha', \beta, \beta'$ be as indicated. By the exterior angle theorem, $m\angle BDA = \alpha + \alpha'$ and $m\angle CDA = \beta + \beta'$. Since $BD < AD$, then $\beta' < \beta$. Since $CD < AD$, then $\alpha' < \alpha$. Then $2(\alpha' + \beta') < \alpha' + \beta' + \alpha + \beta = 180^\circ$. Hence $m\angle BAC = \alpha' + \beta' < 90^\circ$
17,751,570
Consider two tables: ``` house_market_changes date | house_id | market_status --------------------------------- 2013-04-03 | 1 | "on" 2013-04-06 | 1 | "under offer" 2013-04-11 | 1 | "off" 2013-04-02 | 2 | "on" ... ``` `house_market_changes` tells us what the house changed to and when. ``` agent_visit date | house_id | agent_id --------------------------------- 2013-04-05 | 1 | 1 2013-04-06 | 1 | 1 2013-04-08 | 1 | 1 2013-04-09 | 1 | 1 2013-04-10 | 1 | 1 2013-04-12 | 1 | 1 ... ``` `agent_visit` tells us when an agent went to visit a house. I want a query with these results: ``` agent_visit_info date | house_id | agent_id | house_market_status ----------------------------------------------- 2013-04-05 | 1 | 1 | "on" 2013-04-06 | 1 | 1 | "under offer" 2013-04-08 | 1 | 1 | "under offer" 2013-04-09 | 1 | 1 | "under offer" 2013-04-10 | 1 | 1 | "under offer" 2013-04-12 | 1 | 1 | "off" ... ``` The `house_market_status` column tells us what the status of the house was on that date. So `house_market_status` is the latest value of `market_status` before or on the date of the visit. Anyone know how to do this?
2013/07/19
[ "https://Stackoverflow.com/questions/17751570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/339681/" ]
No. This conclusion comes from [the task and backstack documentation](http://developer.android.com/guide/components/tasks-and-back-stack.html) as well as the [activity documentation](http://developer.android.com/reference/android/app/Activity.html#finish%28%29) and a general understanding of how a [stack data structure](http://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29) works. A stack data strucure only has 2 possible operations push/put, which adds something to the collection, and pop, which removes it. Stacks folow a last in first out model, or LIFO, where by last thing added - in your case an activity - is the first thing removed when pop is called. Within the android lifecycle activities are generally popped from the stack when the back button is pressed. At that point `onDestroy()` is called and the activity is removed (you can verify this by overriding the `onDestroy()` method and logging the results if you want to check). Alternativly you can force `onDestroy()` to be called by calling `finish()` as you are. Finishing an activity effectivly does the same thing as pressing back. The activity is destroyed and must be recreated before it can be added to the stack. For what you're trying to do the stack would have to incorporate some intermediate state in which an activity does not exist but rather something akin to a reference is held that, when moved to the top, would indicate that the corresponding activity should be recreated. Since this is not how the sack works - it only holds activities - that state cannont exist and so the result you are talking about is not possible.
No, i don't think that is possible. Once you finish the Activity it's gone. You could, however, implement and handle your own stack. On back pressed, you would just start the closed Activity again.
236,782
I am not able to write this in latex with the subscript p|n (maybe more than one line) under the product and above the product sign also I need something to be written( say k). Moreover it would be helpful if someone tells me how to display this formula in a neat manner. Thanks in Advance. ![enter image description here](https://i.stack.imgur.com/Cghgz.png)
2015/04/04
[ "https://tex.stackexchange.com/questions/236782", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/75585/" ]
The original picture can be reproduced by ``` \documentclass{article} \usepackage{amsmath} \begin{document} \[ \frac{(-1)^{\varphi(n)/2}n^{\varphi(n)}} {\prod_{p\mid n} p^{\varphi(n)/(p-1)}} \] \end{document} ``` ![enter image description here](https://i.stack.imgur.com/r5unE.png) whereas using `\Pi` instead of `\prod` would give ![enter image description here](https://i.stack.imgur.com/MewPP.png) which is sensibly different. If the condition is desired to be under the product sign, the correct answer is ``` \documentclass{article} \usepackage{amsmath} \begin{document} \[ \frac{(-1)^{\varphi(n)/2}\,n^{\varphi(n)}} {\prod\limits_{p\mid n} p^{\varphi(n)/(p-1)}} \] \end{document} ``` (note the thin space in the numerator and in the exponent at the denominator). ![enter image description here](https://i.stack.imgur.com/RRtRD.png) Using `\displaystyle` would give a much worse output, with a too big product sign ``` \documentclass{article} \usepackage{amsmath} \begin{document} \[ \frac{(-1)^{\varphi(n)/2}\,n^{\varphi(n)}} {\displaystyle\prod_{p\mid n} p^{\varphi(n)/(p-1)}} \] \end{document} ``` ![enter image description here](https://i.stack.imgur.com/82X4T.png)
Exchange \Pi for \prod\limits or \displaystyle\prod Also, you might want to use \begin{equation} or \begin{equation\*} instead of [
81,354
What am I? `03/04/19 13:36 UTC` *This is very abundant* *The most that you'll see* *And its group and number* *Is what you will need* *Now somewhat repetetive* *For you who are us* *You may now start the task* *From now, not before* *You use this to move* *Or choose where to go* *How much am I spotty?* *You need to know* *Some think this will curse you* *But they've got it wrong* *Not quite a domino* *How many of me?* *If your friend in Jakarta* *Wants you to get on the horn* *Then to be direct* *Just remember me* *Take dozen of the best* *Not more, not less* *Now look to the last* *And there this will rest* Hint #1: `03/04/19 18:48 UTC` > > *Though once I was rejected* > > *I am now well known* > > *For I am a part of* > > *All that are equal and right* > > > Hint #2: `04/04/19 13:30 UTC` > > *Work out what each is* > > *For it's a joint effort* > > *Then take them conjointly* > > *And then you will know what I am* > > > Hint #3: `04/04/19 22:33 UTC` > > *If you value your pieces* > > *Then put them together* > > *You will soon find* > > *You're close to the answer* > > > Hint #4: `06/04/19 18:57 UTC` > > *Though I'm very well known* > > *No one can tell you what I am* > > *I'm quite small, but I never end* > > *And you can work on me forever* > > > Hint #5: `08/04/19 15:20 UTC` > > *When solving the first* > > *Look in the Earth's crust* > > *That's part of the answer* > > *Now find the rest* > > > Do you like it? This is my first riddle, so sorry if it's not too good. Not sure what tags I should include to avoid giving extra hints. Note: the timestamps are just that, timestamps. All you need is in the stanzas.
2019/04/03
[ "https://puzzling.stackexchange.com/questions/81354", "https://puzzling.stackexchange.com", "https://puzzling.stackexchange.com/users/48489/" ]
are you > > international phone number such as the one for Indonesia ( Jakarta) +62 21 xxx xxxx > > > This is very abundant The most that you'll see And its group and number Is what you will need > > It is abundant as almost everyone has a phone number. A phone number has "section" / "groups" of numbers. It is necessary it today's world > > > Now somewhat repetitive For you who are us You may now start the task From now, not before > > us as in United States. You have to enter coutnry code while calling internationally. The reference to starting the task can be attributed to the following: > > When calling international numbers there is a wait between entering the country code and then entering area code followed by the number. Sometimes this is guided by a voice over "please enter your xx now" > > > You use this to move Or choose where to go How much am I spotty? You need to know > > you can transfer phone numbers (i.e. move ) , you can also choose your own phone number . Spotty as in spotty phone signal. Need to know the coverage. > > > Some think this will curse you But they've got it wrong Not quite a domino How many of me? > > There was/is a trend of [cell phone signal causing cancer](https://en.wikipedia.org/wiki/Mobile_phone_radiation_and_health) ( i.e. curse you) But there is no evidence to this. > > > If your friend in Jakarta Wants you to get on the horn Then to be direct Just remember me > > Jakarta is the capital of Indonesia. "to get on the horn" means to speak to someone on the phone. There is international direct dialing. > > > Take dozen of the best Not more, not less Now look to the last And there this will rest > > Indonesian phone numbers, when called internationally, are dialed using 12 characters. example: +62 21 xxx xxxx > > >
> > This is very abundant > > The most that you'll see > > And its group and > > number Is what you will need > > > Are you > > hydrogen? oxygen? or H20- group and number derived from periodic table of elements? > > >
51,781,093
I would like to know is it possible to return all value for duplicate column with same ID value for oracle sql My table design would below Table A ``` Name ID Order Year ------ ------ ------- ------ JOHN 1 ORD123 2017 JAKE 2 ORD122 2018 JES 2 ORD111 2017 JOHN 3 ORD323 2012 NICK 4 ORD133 2011 AMY 4 ORD222 2010 MUS 4 ORD132 2010 ``` I want the result of the query to be as below ``` Name ID Order Year ------ ------ ------- ------ JAKE 2 ORD122 2018 JES 2 ORD111 2017 NICK 4 ORD133 2011 AMY 4 ORD222 2010 MUS 4 ORD132 2010 ```
2018/08/10
[ "https://Stackoverflow.com/questions/51781093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10206985/" ]
You can use an analytic function to do it in a single table scan: [SQL Fiddle](http://sqlfiddle.com/#!4/1b978/3) **Oracle 11g R2 Schema Setup**: ``` CREATE TABLE TableA ( Name, ID, "Order", Year ) AS SELECT 'JOHN', 1, 'ORD123', 2017 FROM DUAL UNION ALL SELECT 'JAKE', 2, 'ORD122', 2018 FROM DUAL UNION ALL SELECT 'JES', 2, 'ORD111', 2017 FROM DUAL UNION ALL SELECT 'JOHN', 3, 'ORD323', 2012 FROM DUAL UNION ALL SELECT 'NICK', 4, 'ORD133', 2011 FROM DUAL UNION ALL SELECT 'AMY', 4, 'ORD222', 2010 FROM DUAL UNION ALL SELECT 'MUS', 4, 'ORD132', 2010 FROM DUAL; ``` **Query 1**: ``` SELECT Name, ID, "Order", Year FROM ( SELECT t.*, COUNT(*) OVER ( PARTITION BY id ) AS num_duplicates FROM tableA t ) WHERE num_duplicates > 1 ``` **[Results](http://sqlfiddle.com/#!4/1b978/3/0)**: ``` | NAME | ID | Order | YEAR | |------|----|--------|------| | JAKE | 2 | ORD122 | 2018 | | JES | 2 | ORD111 | 2017 | | NICK | 4 | ORD133 | 2011 | | AMY | 4 | ORD222 | 2010 | | MUS | 4 | ORD132 | 2010 | ``` Using `IN ( SELECT ... GROUP BY id HAVING COUNT(*) > 1 )` or an aggregation in a self-join will require two table/index scans. --- **Update** > > if i have two condition, is it posisble also, maybe id and year? > > > **Query 2**: Just add the additional columns to the `PARTITION BY` clause: ``` SELECT Name, ID, "Order", Year FROM ( SELECT t.*, COUNT(*) OVER ( PARTITION BY id, year ) AS num_duplicates FROM tableA t ) WHERE num_duplicates > 1 ``` **[Results](http://sqlfiddle.com/#!4/1b978/4/1)**: ``` | NAME | ID | Order | YEAR | |------|----|--------|------| | AMY | 4 | ORD222 | 2010 | | MUS | 4 | ORD132 | 2010 | ```
Have a sub-query to return id's that exists more than once. ``` select * from tableA where id in (select id from tableA group by id having count(*) > 1) ```
3,072
Why is "to get" sometimes used where "to be" could be used? Is this usage grammatical? Examples: > > * The video got uploaded to the web site. > * The video was uploaded to the web site. > * He got thrown in the pool. > * He was thrown in the pool. > * We got caught! > * We were caught! > > >
2010/09/15
[ "https://english.stackexchange.com/questions/3072", "https://english.stackexchange.com", "https://english.stackexchange.com/users/212/" ]
This usage is *correct*, but *informal*. It is freely used (and extremely common) in less formal kinds of writing and speaking, but is avoided in the most formal forms of writing. As for "why", I don't think there is any explanation other than the fact that get + <past participle> is slowly displacing be + <past participle> for the passive construction.
**Both forms (i.e. *be* and *get* forms followed by past participle) are grammatically correct.** > > The video got uploaded to the website > [by a user]. > > > is passive voice. > > In a sentence using active voice, the > subject of the sentence performs the > action expressed in the verb. > [(source)](http://owl.english.purdue.edu/owl/resource/539/01/) > > > So, in this case, the subject of the sentence, "the video", wasn't the thing performing the action. The unnamed user (or whomever performed the action) did.
7,088,905
When I commit something to SVN, should I update first my local copy, or the merging is automatically done ? In other words, *should I always update before committing*, or can I just commit ?
2011/08/17
[ "https://Stackoverflow.com/questions/7088905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/257022/" ]
**Yes you should.** While its not always necessary, it's a good idea to do so. Imagine someone else changes something that wouldn't result in a conflict but has a reaction on your changes. Then, you would check in and the version on the server is not that what you tested. So, before committing, always do an `svn update` to ensure that your changes still behave like you thought they do: test the version that is in your WC, if your commit is still reasonable, do it. In case of errors, fix them before committing to the repo.
The merging is done to your working copy. Therefore, you should update first, in order to avoid conflicts. No harm is done, however, if you try to commit. If there are remote conflicting modifications, the commit will remain undone anyway.
17,641,957
I have a PDF File. When I want to encrypt it using codes below the `Length of the data to encrypt is invalid.` error occurred: ``` string inputFile = @"C:\sample.pdf"; string outputFile = @"C:\sample_enc.pdf"; try { using (RijndaelManaged aes = new RijndaelManaged()) { byte[] key = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; byte[] iv = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; aes.Key = key; aes.IV = iv; aes.Mode = CipherMode.CFB; aes.Padding = PaddingMode.None; aes.KeySize = 128; aes.BlockSize = 128; using (FileStream fsCrypt = new FileStream(outputFile, FileMode.Create)) { using (ICryptoTransform encryptor = aes.CreateEncryptor(key,iv)) { using (CryptoStream cs = new CryptoStream(fsCrypt, encryptor, CryptoStreamMode.Write)) { using (FileStream fsIn = new FileStream(inputFile, FileMode.Open)) { int data; while ((data = fsIn.ReadByte()) != -1) { cs.WriteByte((byte)data); } } } } } } } catch (Exception ex) { // Length of the data to encrypt is invalid. Console.WriteLine(ex.Message); } ``` With `CipherMode.CBC` and `PaddingMode.PKCS7`, I don't have any errors. But because of my client, I have to encrypt the file using **AES/CFB** with **No Padding**. Any ideas what's happening here?
2013/07/14
[ "https://Stackoverflow.com/questions/17641957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/822718/" ]
When you use PaddingMode.None you can wrap the ICrytoTransform and handle final block yourself: ``` new CryptoStream(fsCrypt, new NoPaddingTransformWrapper(encryptor), CryptoStreamMode.Write) ``` The following is a wrapper class itself: ``` public class NoPaddingTransformWrapper : ICryptoTransform { private ICryptoTransform m_Transform; public NoPaddingTransformWrapper(ICryptoTransform symmetricAlgoTransform) { if (symmetricAlgoTransform == null) throw new ArgumentNullException("symmetricAlgoTransform"); m_Transform = symmetricAlgoTransform; } #region simple wrap public bool CanReuseTransform { get { return m_Transform.CanReuseTransform; } } public bool CanTransformMultipleBlocks { get { return m_Transform.CanTransformMultipleBlocks; } } public int InputBlockSize { get { return m_Transform.InputBlockSize; } } public int OutputBlockSize { get { return m_Transform.OutputBlockSize; } } public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { return m_Transform.TransformBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); } #endregion public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { if (inputCount % m_Transform.InputBlockSize == 0) return m_Transform.TransformFinalBlock(inputBuffer, inputOffset, inputCount); else { byte[] lastBlocks = new byte[inputCount / m_Transform.InputBlockSize + m_Transform.InputBlockSize]; Buffer.BlockCopy(inputBuffer,inputOffset, lastBlocks, 0, inputCount); byte[] result = m_Transform.TransformFinalBlock(lastBlocks, 0, lastBlocks.Length); Debug.Assert(inputCount < result.Length); Array.Resize(ref result, inputCount); return result; } } public void Dispose() { m_Transform.Dispose(); } } ``` OR you can wrap a SymmetricAlgorithm so that it will do appropriate wrapping in CreateEncryptor/CreateDecryptor depending on padding mode: ``` public class NoPadProblemSymmetricAlgorithm : SymmetricAlgorithm { private SymmetricAlgorithm m_Algo; public NoPadProblemSymmetricAlgorithm(SymmetricAlgorithm algo) { if (algo == null) throw new ArgumentNullException(); m_Algo = algo; } public override ICryptoTransform CreateDecryptor(byte[] rgbKey, byte[] rgbIV) { if (m_Algo.Padding == PaddingMode.None) return new NoPaddingTransformWrapper(m_Algo.CreateDecryptor(rgbKey, rgbIV)); else return m_Algo.CreateDecryptor(rgbKey, rgbIV); } public override ICryptoTransform CreateEncryptor(byte[] rgbKey, byte[] rgbIV) { if (m_Algo.Padding == PaddingMode.None) return new NoPaddingTransformWrapper(m_Algo.CreateEncryptor(rgbKey, rgbIV)); else return m_Algo.CreateEncryptor(rgbKey, rgbIV); } #region simple wrap public override void GenerateIV() { m_Algo.GenerateIV(); } public override void GenerateKey() { m_Algo.GenerateIV(); } public override int BlockSize { get { return m_Algo.BlockSize; } set { m_Algo.BlockSize = value; } } public override int FeedbackSize { get { return m_Algo.FeedbackSize; } set { m_Algo.FeedbackSize = value; } } public override byte[] IV { get { return m_Algo.IV; } set { m_Algo.IV = value; } } public override byte[] Key { get { return m_Algo.Key; } set { m_Algo.Key = value; } } public override int KeySize { get { return m_Algo.KeySize; } set { m_Algo.KeySize = value; } } public override KeySizes[] LegalBlockSizes { get { return m_Algo.LegalBlockSizes; } } public override KeySizes[] LegalKeySizes { get { return m_Algo.LegalKeySizes; } } public override CipherMode Mode { get { return m_Algo.Mode; } set { m_Algo.Mode = value; } } public override PaddingMode Padding { get { return m_Algo.Padding; } set { m_Algo.Padding = m_Algo.Padding; } } protected override void Dispose(bool disposing) { if (disposing) m_Algo.Dispose(); base.Dispose(disposing); } #endregion } ```
A (not ideal) solution I have used in this situation is to place the raw length of the plaintext into the first x bytes of data to be encrypted. The length then is encrypted with the rest of the data. When decrypting using the stream you simply read the first x bytes and convert them using the BitConverter class back to the length. This then tells you how many subsequent decrypted bytes are part of your message. Any data beyond that can be ignored as padding.
3,235,679
Note:I don't mean some theoretical question which don't have any implementation just languages that don't have both!!!!! --- These days there exists a c/c++ interpreter(cint) and a python compiler(to python bytecode). I understand that the simplest definition is that a compiler just converts code from language a to language b, and then you have a machine which runs b it together with input, while an interpreter is simply something that takes input plus code in language a and runs it. And that using these definitions if something has an interpreter or compiler its fairly simple to get the other by immediately running the output of the compiler or embedding the compiler w/ the source code to get an interpreter. So ignoring those which languages don't have both a compiler (which compile source code in A to B preferably an intermediate language) and an interpreter that run large chunks of code without compiling them?
2010/07/13
[ "https://Stackoverflow.com/questions/3235679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/259130/" ]
The **ladder language** for programmable logic controllers (PLC) has no compiler or interpreter. The ladders are converted into boolean conditions to manage inputs, outputs and memory states. Ladders are evaluated thousands times a second to actually run the code on the hardware. Good luck! Reference: [Programmable logic controller on Wikipedia](http://en.wikipedia.org/wiki/Programmable_logic_controller)
One of my classmates can write a complete mic-in to speaker program on an `APPLE ][` by punching all the hex codes after a `CALL -151`. So the answer can probably be: machine code.
44,752
I have a drive that I cannot boot, but it has an installation of Windows XP on it. I need to know what type of XP it has, and MS's solution (<http://support.microsoft.com/kb/310104>) presupposes I can load the OS. Is there a folder or file I can look at that might give me a clue as to the flavor of XP (Home, Pro, MCE, etc) I need to use for a recovery installation? Thanks.
2009/09/21
[ "https://superuser.com/questions/44752", "https://superuser.com", "https://superuser.com/users/-1/" ]
If you are able to boot to the command prompt you can type in: ``` type c:\windows\system32\prodspec.ini ``` and it should show you what version of XP you have installed. Similar to something like this: ``` ; ;Note to user: DO NOT ALTER OR DELETE THIS FILE. ; [SMS Inventory Identification] Version=1.0 [Product Specification] Product=Windows XP Professional Version=5.0 Localization=English ServicePackNumber=0 BitVersion=40 [Version] DriverVer=07/01/2001,5.1.2600.0 ```
Start -> Control Panel -> System Under the General tab. The computer I'm on now says: ``` Microsoft Windows XP Professional Version 2002 Service Pack 3 ```
26,796,707
I'm writing a program in C++ that has to use dynamically allocated arrays from various structures (in separate files). A lot of times, I need to initiate these arrays inside of a function. Usually after initiating them, I write data to the array of a structure, or even an array inside of an array of structures, and then use the data later on. Therefore I don't use delete inside of the function. For example, here is one of the structures that I use, a student structure: ``` struct Student { int id; // student ID char gradeOption; // either G or P double totalScore; std::string studentName; int* rawScores = NULL; // array that holds raw scores for a student // if no scores are entered for a specific ID, we check for NULL // we can then set the scores to 0 std::string* finalGrade; // final grade given in course }; ``` And here is the function to input raw scores. ``` // input raw scores for each id void inputRawScores(int gradedArtifacts, int id, Student* student) { student[id].rawScores = new int[gradedArtifacts]; for(int i = 0; i < gradedArtifacts; i++) { std::cin >> student[id].rawScores[i]; } } ``` In my driver file, students also gets initialized with a value. Shown here: ``` Student* students = new Student[numOfStudents]; // array of students ``` The problem is is that I use these raw scores, and the array of students for calculations in a separate file, and use them for output in other files, and in other methods. How would I go about deleting any of these? Also I realize that using `delete` will delete the structure and the pointers inside of the structure, but not the objects that the pointers point to. So I'm assuming this ties back into the first question and I can't just issue a `delete` at the end of my program. Edit: I'm sorry, as many others have pointed out I should have stated the restraints that I have on the project. I'm not allowed to uses: classes, vectors, functions inside of structs (like constructors, destructors).
2014/11/07
[ "https://Stackoverflow.com/questions/26796707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3427023/" ]
Given your newly posted constraints, I think you could just implement a deletion-function to traverse through the `Student` array and do manual cleanup. First, we create a function that deletes the dynamic objects of **one** single student. Note that we could have used `Student&`as the parameter type, but given the information in your question I am not sure if you have learned references yet, or if you are allowed to use them. So we stick with the pointer: ``` void cleanupStudent(Student* student) { delete[] student->rawScores; delete student->finalGrade; // EDIT: Setting pointers back to NULL after deletion provides // some improved safety and is good practice. student->rawScores = NULL; student->finalGrade = NULL; } ``` After that we create a function that allows you to delete the complete `Student` array by looping through all the items in the array and calling the cleanup function: ``` void deleteStudents(Student* students, int studentCount) { for(int i = 0; i < studentCount; i++) { cleanupStudent(&students[i]); } delete[] students; } ``` Here, please note the ampersand-symbol (`&students[i]`) which we require to get a pointer to the object (which is required as a parameter to the cleanup function). After that, the student array itself is deleted. You can call these functions like this: ``` int numOfStudents = 16; Student* students = new Student[numOfStudents]; deleteStudents(students, numOfStudents); ``` Or with a single student: ``` Student* student = new Student; cleanupStudent(student); delete student; ``` As you might have noticed we sometimes use `delete` and sometimes `delete[]`. The first one just deallocates memory that has been allocated with `new`. The latter does the same thing to memory that has been allocated with `new[]`. This is very important to get right, otherwise you will get runtime errors. Also, make always sure that **EVERY** pointer in your struct is initialized wih `NULL` (C) or `nullptr` (C++). Since it seems that you are just learning C/C++ it is crucial to mention that the above code is very unsafe, and you could get into real problems if e.g. the `studentCount` is not matching the actual number of items in the array. But for now I guess you wouldn't know (or aren't allowed) to do better. EDIT: I noticed that your `finalGrade` member is of type `std::string*`. Is there a reason for this to be a pointer? Because if you just want to store a string, you can just do a `std::string`, no reason there to be a pointer. Please don't confuse a C-String of type `char*` with a STL string `std::string`.
**This answer is obsolete since the owner of this questions specified some constraints that do not allow constructors/destructors.** As far as I unterstand your question, you do not know how to delete the actual dynamically allocated `rawScores` and `finalGrad` objects in your `Student` object, right? If so, the answer is quite simple, you just use a Destructor: ``` struct Student { int id; // student ID char gradeOption; // either G or P double totalScore; std::string studentName; int* rawScores = nullptr; std::string* finalGrade = nullptr; // Disable copy and move assignment Student& operator=(const Student& rhs) = delete; Student& operator=(Student&& rhs) = delete; // Disable copy and move construction Student(const Student& rhs) = delete; Student(Student&& rhs) = delete; Student() { // Initialize members. } // Destructor ~Student() { delete[] rawScores; delete finalGrade; } }; ``` As soon as you deallocate a `Student` object using the `delete` operator: ``` Student* students = new Student[numOfStudents]; delete[] students; // <-- deallocation ``` The destructor is called for each object, which in turn will delete the dynamically allocated objects inside. You don't have to bother if the pointers are `NULL` or not, calling `delete` on a pointer that is `NULL` is valid. Also, please initialize ALL pointers initially with `nullptr` when constructing the object (as shown above). As long as you are not mixing runtimes accross different EXE/DLL boundaries you can `delete` the `Student` array from anywhere in your program, not matter in which file you allocate/deallocate it. I hope this answers your question. If not, please be more specific about the problem you have. EDIT: As pointed out in the comments, you should disable copy/move semantics if you are doing it this way (or implement them). But disabling them would practically pin you to dynamic allocation of the `Student` struct and give you less flexibility with most of the STL containers. Otherwise you could also use an `std::vector` instead of dynamically allocated arrays as pointed out in the other anwers.
463,811
I'm trying to clone/pull a repository in another PC using Ubuntu Quantal. I have done this on Windows before but I don't know what is the problem on ubuntu. I tried these: ``` git clone file:////pc-name/repo/repository.git git clone file:////192.168.100.18/repo/repository.git git clone file:////user:pass@pc-name/repo/repository.git git clone smb://c-pc/repo/repository.git git clone //192.168.100.18/repo/repository.git ``` Always I got: ``` Cloning into 'intranet'... fatal: '//c-pc/repo/repository.git' does not appear to be a git repository fatal: The remote end hung up unexpectedly ``` or ``` fatal: repository '//192.168.100.18/repo/repository.git' does not exist ``` More: * The other PC has username and password * Is not networking issue, I can access and ping it. * I just installed git doing `apt-get install git` (dependencies installed) * I'm running git from the terminal (I'm not using git-shell) What is causing this and how to fix this? Any help would be great! ### UPDATE I have cloned the repo on Windows using `git clone //192.168.100.18/repo/intranet.git` without problems. So, the repo is accessible and exist! Maybe the problem is due user credentials?
2013/01/07
[ "https://serverfault.com/questions/463811", "https://serverfault.com", "https://serverfault.com/users/144709/" ]
It depends on how you have your server configured to serve content. If over ssh: ``` git clone user@192.168.100.18:repo/repository.git ``` or if a webserver is providing the content (http or https) ``` https://user@192.168.100.18/repo/repository.git ``` or if available via a file path: ``` git clone file://path/to/repo ``` or if the server is running the git daemon: ``` git clone git://192.168.100.18/repo ```
This issue seems similar to <https://stackoverflow.com/questions/5200181/how-to-git-clone-a-repo-in-windows-from-other-pc-within-the-lan>. Perhaps the administrative share helps alleviate the problem (e.g. //pc-name/c$/path/to/repo)
1,783,494
I need a random number generation algorithm that generates a random number for a specific input. But it will generate the same number every time it gets the same input. If this kind of algorithm available in the internet or i have to build one. If exists and any one knows that please let me know. (c, c++ , java, c# or any pseudo code will help much) Thanks in advance.
2009/11/23
[ "https://Stackoverflow.com/questions/1783494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/181272/" ]
Usually the standard implementation of random number generator depends on seed value. You can use standard random with seed value set to some hash function of your input. C# example: ``` string input = "Foo"; Random rnd = new Random(input.GetHashCode()); int random = rnd.Next(); ```
How about.. ``` public int getRandonNumber() { // decided by a roll of a dice. Can't get fairer than that! return 4; } ``` Or did you want a random number each time? :-)
4,464,271
I'm trying to programatically download a file in C# via FTP, here is the relevant code (obviously with fake credntials and URI): ``` try { var request = FtpWebRequest.Create("ftp://ftp.mydomain.com/folder/file.zip"); request.Credentials = new NetworkCredential("username", "password"); using (var response = request.GetResponse()) { ... } } catch (WebException we) { ... } ``` The exception is thrown at `request.GetResponse()`, and the error code is 550. The issue is not with the credentials or the URI, as they work just fine in IE and the file downloads successfully there. What am I missing? Is there some other kind of credential object I should be using? Is there a property on the `request` object I'm not setting? Any help would be appreciated.
2010/12/16
[ "https://Stackoverflow.com/questions/4464271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/545187/" ]
Turns out the FTP root isn't necessarily the same as the URL root. Perhaps I'm mixing up terminology, so let me explain: in my case, connecting to ftp.mydomain.com already starts at /folder, so my URL needed to just be <ftp://ftp.mydomain.com/file.zip>. IE8 knows how to eliminate the redundant /folder part in the original path while the FtpRequest class does not, which is why it worked in IE8 but not in the C# code.
I recently had this problem and after much testing discovered that some module between here and there did not like a mixed case URI and so my resolution was to use .ToLower() on the URI
457,018
I am including a special font for greek, but when I use it, the `\textbf{}` command does not result in bold letters. I have added a `[FakeBold=3]`, but it has no effect. What's the problem? ``` \documentclass[openany]{book} \usepackage{fontspec} \setmainfont[BoldFont={* Semibold},ItalicFont={* Italic},BoldItalicFont={* Semibold Italic}]{Times New Roman} \newfontfamily\bgkfamily[FakeBold=3]{SBL Greek} %%% \newfontfamily\bgkfamily[BoldFeatures={FakeBold=2.5}]{SBL Greek} \DeclareTextFontCommand{\bgreek}{\bgkfamily\upshape} \begin{document} Here is a sentence. This is \bgreek{και \textbf{και } και} \end{document} ``` In case it matters, I am using Texpad.
2018/10/27
[ "https://tex.stackexchange.com/questions/457018", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/123001/" ]
The solution is simple: you have to declare the bold font. In the code I choose the font by file name as I'm not going to add SBL Greek to my system fonts. ``` \documentclass[openany]{book} \usepackage{fontspec} \newfontfamily\bgkfamily{SBL_grk}[ Path=./, Extension=.ttf, BoldFont=*, BoldFeatures={FakeBold=4}, ] \DeclareTextFontCommand{\bgreek}{\bgkfamily\upshape} \begin{document} Here is a sentence. This is \bgreek{και \textbf{και} και} \end{document} ``` If you have the font installed among the system fonts, you can use ``` \newfontfamily\bgkfamily{SBL Greek}[ BoldFont=*, BoldFeatures={FakeBold=4}, ] ``` I used 4 to make the boldfacing more evident. [![enter image description here](https://i.stack.imgur.com/UZeMx.png)](https://i.stack.imgur.com/UZeMx.png)
``` \documentclass[a4paper, 12pt]{article} \usepackage{amsfonts, amssymb, amsmath, amsthm} \usepackage[no-math]{fontspec} \setmainfont{ModernMTStd-Extended.otf}[ FakeBold=2, Ligatures=TeX, ] \setsansfont[% FakeBold=2, ItalicFont=NewCMSans10-Oblique.otf,% BoldFont=NewCMSans10-Bold.otf,% BoldItalicFont=NewCMSans10-BoldOblique.otf,% SmallCapsFeatures={Numbers=OldStyle}]{NewCMSans10-Regular.otf} \setmonofont[% FakeBold=2, ItalicFont=NewCMMono10-Italic.otf,% BoldFont=NewCMMono10-Bold.otf,% BoldItalicFont=NewCMMono10-BoldOblique.otf,% SmallCapsFeatures={Numbers=OldStyle}]{NewCMMono10-Regular.otf} \let\mathbbalt\mathbb \usepackage{unicode-math} \setmathfont{NewCMMath-Regular.otf}[FakeBold=2] \let\mathbb\mathbbalt \begin{document} This is how you fakebold \texttt{custom} \textsf{fonts}. You need to have the fonts specified in the \texttt{setmainfont} arguments installed on your machine or in the directory you are working on. \begin{align*} v\in\mathbb{V}\\ f\in\mathbb{F} \end{align*} \end{document} ``` [![Output](https://i.stack.imgur.com/hmUJG.png)](https://i.stack.imgur.com/hmUJG.png)
8,616,606
I have the current table data: ``` <table> <tr class="Violão"> <td>Violão</td> <td class="td2 8">8</td> </tr> <tr class="Violão"> <td>Violão</td> <td class="td2 23">23</td> </tr> <tr class="Guitarra"> <td>Guitarra</td> <td class="td2 16">16</td> </tr> </table> ``` What I want to do is groupby the TDs which are the same, and sum the values on the second td to get the total. With that in mind I´ve put the name of the product to be a class on the TR (don't know if it is needed) and I've coded the current javascript: ``` $(".groupWrapper").each(function() { var total = 0; $(this).find(".td2").each(function() { total += parseInt($(this).text()); }); $(this).append($("<td></td>").text('Total: ' + total)); }); ``` by the way the current java scripr doesn't groupby. Now i'm lost, I don't know what else I can do, or if there is a pluging that does what I want.
2011/12/23
[ "https://Stackoverflow.com/questions/8616606", "https://Stackoverflow.com", "https://Stackoverflow.com/users/542798/" ]
``` // declare an array to hold unique class names var dictionary = []; // Cycle through the table rows $("table tr").each(function() { var thisName = $(this).attr("class"); // Add them to the array if they aren't in it. if ($.inArray(thisName, dictionary) == -1) { dictionary.push(thisName); } }); // Cycle through the array for(var obj in dictionary) { var className = dictionary[obj]; var total = 0; // Cycle through all tr's with the current class, get the amount from each, add them to the total $("table tr." + className).each(function() { total += parseInt($(this).children(".td2").text()); }); // Append a td with the total. $("table tr." + className).append("<td>Total: " + total + "</td>"); } ``` Fiddler (on the roof): <http://jsfiddle.net/ABRsj/>
First stick and ID on the table and select that first with jQuery as matching an ID is always the most efficient. Then all you need to do is match the class, parse the string to a number and add them up. I've created a simple example for you below <http://jsfiddle.net/Phunky/Vng7F/> But what you didn't make clear is how your expecting to get the value of the td class, if this is dynamic and can change you could make it much more versatile but hopefully this will give you a bit of understanding about where to go from here.
22,927,035
I'm trying to send int data via UDP using protobuf. from visual c++ to Java(Android Studio) **proto file**: ``` message rbr { required int32 rpm = 1; required int32 gear = 2; required int32 speed = 3; } ``` **C++ sending:** ``` telemetry.set_rpm(1200); telemetry.set_speed(120); telemetry.set_gear(4); telemetry.SerializeToString(&serializedMessage); memset(message, '\0', BUFLEN); memcpy(message, serializedMessage.c_str(), serializedMessage.size()); //send the message if (sendto(s, message, serializedMessage.size(), 0, (struct sockaddr *) &si_other, slen) == SOCKET_ERROR) { printf("sendto() failed with error code : %d", WSAGetLastError()); exit(EXIT_FAILURE); } ``` Java(Android) receive using square wire protobuff library: ``` socket = new DatagramSocket(8888); Wire wire = new Wire(); while (true) { packet = new DatagramPacket(buf, buf.length); socket.receive(packet); s = new String(packet.getData(), 0, packet.getLength()); byte[] bytes = s.getBytes(); rbr newMsg = wire.parseFrom(bytes, rbr.class); sGear = newMsg.gear.toString(); sRpm = String.valueOf(newMsg.rpm); sSpeed = newMsg.speed.toString(); tvRpm.post(new Runnable() { public void run() { tvRpm.setText(sRpm); tvGear.setText(sGear); tvSpeed.setText(sSpeed); } }); } ``` The data is received correctly if the value is below 127, when I send 128 the result is 3104751. But it works fine when I try to receive it in Visual C++ too. updated code to use SerilizeToArray ``` int size = telemetry.ByteSize(); char* array = new char[size]; telemetry.SerializeToArray(array, size); memset(message, '\0', BUFLEN); memcpy(message, array, size); ``` but how to receive on java? i try this code but not working. ``` packet = new DatagramPacket(buf, buf.length); socket.receive(packet); byte[] bytes = packet.getData(); rbr newMsg = wire.parseFrom(bytes, rbr.class); ```
2014/04/08
[ "https://Stackoverflow.com/questions/22927035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3505409/" ]
I agree with Ted Hopp. try this : ``` public void saveCheckBoxState(boolean isChecked){ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); SharedPreferences.Editor editor = prefs.edit(); editor.putBoolean("key",isChecked); editor.commit(); } ``` Call `saveCheckBoxState(boolean)` in your `onCheckedChanged()` and ``` public boolean getCheckBoxState(){ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); return prefs.getBoolean("key", false); } ``` call `getCheckBoxState()` in `onResume()` of your activity.
You should persist the checkbox state. For example, you can use [SharedPreferences](http://developer.android.com/guide/topics/data/data-storage.html#pref).
5,115,885
Just started to experiment with HTML5 features and really like the localStorage. And now I wonder if it makes sense to create some libraries which make life easier. Something which easily persists objects from the localStorage to the server-DB. Something like a object.findAllByAttribute(Attribute) etc. So my question is: is there already something out there which helps me to write offline html5 applications? If not, would it make sense or am I thinking the wrong way?
2011/02/25
[ "https://Stackoverflow.com/questions/5115885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204769/" ]
just found <http://www.javascriptmvc.com/> . Looks interesting, simpler than backbone.js and closer to Rails or Grails. But have to admit that the focus is not the offline feature. But I guess when you already have a model, offline isn't the big problem anymore.
things advanced and it seems that <http://angularjs.org/> is what I was looking for at the time I asked the question. There is also a great talk about using AngularJs together with Grails for creating SPI Applications: <http://skillsmatter.com/podcast/home/developing-spi-applications-using-grails-and-angularjs>
20,656,521
``` select distinct ani_digit, ani_business_line from cta_tq_matrix_exp limit 5 ``` I want to select top five rows from my resultset. if I used above query, getting syntax error.
2013/12/18
[ "https://Stackoverflow.com/questions/20656521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2654334/" ]
You'll need to use `DISTINCT` *before* you select the "top 5": ``` SELECT * FROM (SELECT DISTINCT ani_digit, ani_business_line FROM cta_tq_matrix_exp) A WHERE rownum <= 5 ```
**LIMIT** clause is not available in Oracle. Seeing your query, you seem to be interested only in a certain number of rows (not ordered based on certain column value) and so you can use **ROWNUM** clause to limit the number of rows being returned. ``` select distinct ani_digit, ani_business_line from cta_tq_matrix_exp WHERE rownum <= 5 ``` If you want to order the resultset and then limit the number of rows, you can modify your query as per the details in the link provided by Colin, in the comments above.
27,382,701
I want to change value of global variable within a function with parameters name,value. All examples that ive read was with no parameter function. Example ``` var one = 100; var change = function(name,value){ // name is the name of the global variable //value is the new value }; change(one,300); ```
2014/12/09
[ "https://Stackoverflow.com/questions/27382701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4237507/" ]
Try this. When you pass it as a parameter, pass as string, not the variable. ``` var one = 100; var change = function(name, value) { window[name] = value; }; change('one', 300); console.log(one); ```
All global variable are set on window object. so you can try the following . ``` window[name] = value; ```
92,331
I left my last employer in the UK end of last year, but he still pays me my monthly salary. (It feels like one of these surreal dreams) In march I told them about it and asked how I should deal with it. But even though I addressed it to my CFO and copied in the CEO, the CFO only replied to some other questions in the same email, but ignored the overpayment issue. Since then I still get monthly payments, but I'm not sure whether I can keep it or if I need to save it until they realise that error? It would be great if someone can help me with this, because I'm not familiar with the UK law system as I'm from another European country. Are there any deadlines for them to notify me? What are the chances for me to keep the money? (only from a legal point of view, not from a moral one)
2017/06/07
[ "https://workplace.stackexchange.com/questions/92331", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/71112/" ]
Verify all of this with an attorney, but I believe it works like this. Take the money and put it in an escrow account. Leave it there until that appropriate statutes run out. Make a sincere effort to return the money, which means keep trying but put a REASONABLE effort into it. Save all of your correspondence as proof that you made a sincere effort. After whatever applicable statutes run out, the money becomes yours.
No, you cannot keep it. At least, not officially. As Nij commented, **do not spend it**. The best you can do in such a situation is to put this money on a 100% safe investment, like savings products without minimum duration. At least you will be able to keep any interests earn when you will have to give the money back. You may also do several actions: 1. Inform in an official way you ex-employer. I do not know if an email is a sufficient proof you warned them in UK. 2. Take a look about how to declare it. UK equivalent of IRS may find suspicious (and/or illegal) that you earn money which is maybe not declared. Do you still get pay sheets?
18,662,669
I have a method like this ``` public static LinkedList<Object> getListObjectWithConditionInXMLFile(String className){ LinkedList<Object> lstObj = new LinkedList<Object>(); if(className.equals("Customer")){ //read Data from XML File Customer customer = ...; lstObj.add(customer); } .... return lstObj; } ``` after that i call this method and want to cast : ``` LinkedList<Customer> lstCustomer = (LinkedList<Customer>()) getListObjectWithConditionInXMLFile("Customer"); ``` But it cannot cast. How can i cast from LinkedList to LinkedList ? Pls help me ! thanks so much !
2013/09/06
[ "https://Stackoverflow.com/questions/18662669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755074/" ]
You can refactor your method to something like this: ``` public static <E> LinkedList<E> getListObjectWithConditionInXMLFile(Class<E> type){ LinkedList<E> lstObj = new LinkedList<E>(); if (type.equals(Customer.class)) { Customer customer = ... lstObj.add((E)customer); } return lstObj; } ``` By making the method generic and passing a `Class` parameter you can return a list of the right type. You can call it this way ``` List<Customer> l = getListObjectWithConditionInXMLFile(Customer.class); ```
You will have to create new List and add casted object to the new linked list of Customer. ``` LinkedList<Customer> custList = new LinkedList<>(); for(Object obj: getListObjectWithConditionInXMLFile("Customer")) { custList.add((Customer)obj)); } ``` Or, it is better to use generics if possible as mentioned by "Boris the Spider" in comment. ``` public static <T> LinkedList<T> getListObjectWithConditionInXMLFile(Class<T> requiredClass) ``` The definition can be as follows as given by "micha". ``` public static <T> LinkedList<T> getListObjectWithConditionInXMLFile(Class<T> requiredClass){ LinkedList<T> listObj = new LinkedList<>(); if (requiredClass.equals(Customer.class)) { Customer customer = /*...*/ listObj.add((T)customer); } return listObj; } ``` Then, You can call as ``` LinkedList<Customer> custList = getListObjectWithConditionInXMLFile(Customer.class); ```
53,050,451
I have an Xcode 10 - iOS12 swift project that links against My own framework (also Xcode 10 + iOS12). The app project is referencing my framework project as a sub-project reference. My Framework project references PromiseKit.framework (a universal framework - fat library), made using the following build script: ``` # Merge Script # 1 # Set bash script to exit immediately if any commands fail. set -e # 2 # Setup some constants for use later on. FRAMEWORK_NAME="PromiseKit" # 3 # If remnants from a previous build exist, delete them. if [ -d "${SRCROOT}/build" ]; then rm -rf "${SRCROOT}/build" fi # 4 # Build the framework for device and for simulator (using # all needed architectures). xcodebuild -target "${FRAMEWORK_NAME}" -configuration Release -arch arm64 only_active_arch=no defines_module=yes -sdk "iphoneos" xcodebuild -target "${FRAMEWORK_NAME}" -configuration Release -arch x86_64 only_active_arch=no defines_module=yes -sdk "iphonesimulator" # 5 # Remove .framework file if exists on Desktop from previous run. if [ -d "${SRCROOT}/${FRAMEWORK_NAME}.framework" ]; then rm -rf "${SRCROOT}/${FRAMEWORK_NAME}.framework" fi # 6 # Copy the device version of framework to Desktop. cp -r "${SRCROOT}/build/Release-iphoneos/${FRAMEWORK_NAME}.framework" "${SRCROOT}/${FRAMEWORK_NAME}.framework" # 7 # Replace the framework executable within the framework with # a new version created by merging the device and simulator # frameworks' executables with lipo. lipo -create -output "${SRCROOT}/${FRAMEWORK_NAME}.framework/${FRAMEWORK_NAME}" "${SRCROOT}/build/Release-iphoneos/${FRAMEWORK_NAME}.framework/${FRAMEWORK_NAME}" "${SRCROOT}/build/Release-iphonesimulator/${FRAMEWORK_NAME}.framework/${FRAMEWORK_NAME}" # 8 # Copy the Swift module mappings for the simulator into the # framework. The device mappings already exist from step 6. cp -r "${SRCROOT}/build/Release-iphonesimulator/${FRAMEWORK_NAME}.framework/Modules/${FRAMEWORK_NAME}.swiftmodule/" "${SRCROOT}/${FRAMEWORK_NAME}.framework/Modules/${FRAMEWORK_NAME}.swiftmodule" # 9 # Delete the most recent build. if [ -d "${SRCROOT}/build" ]; then rm -rf "${SRCROOT}/build" fi ``` When I go to archive my Parent App Project using Xcode 10 (And also 9.4.1) with Bitcode ON (that contains My Framework reference, and PromiseKit Fat library), I get the following error on the Signing stage: (Failed to verify bitcode in PromiseKit.framework/PromiseKit: error Cannot extract bundle from /var/folders..../(x86\_64) - which suggests that it's simulator slice related) [![enter image description here](https://i.stack.imgur.com/SjTgK.png)](https://i.stack.imgur.com/SjTgK.png) If I turn the "Rebuild from Bitcode" option in the Organizer to OFF, then I get a different error: (Code signing "PromiseKit.framework" failed) [![enter image description here](https://i.stack.imgur.com/CpQYI.png)](https://i.stack.imgur.com/CpQYI.png) However, if I use Xcode 9.4.1 With Bitcode OFF, then it exports and signs fine. Why is it trying to individually re-sign sub frameworks, and what can I do to alleviate the issues? I need the archiving to work normally with Xcode 10, along with any future third party dependencies being added to my framework target. (This is the first dynamic framework dependency added to my Framework target. Before I was "baking in" - in-boarding all 3rd parties for ease of development purposes, but PromiseKit is difficult to inboard due to extensive dependencies on Objective-c). The Xcode Archive log is: ``` { code = 330; description = "Failed to resolve linkage dependency PromiseKit x86_64 -> @rpath/libswiftFoundation.dylib: Unknown arch x86_64"; info = { }; level = WARN; }, { code = 330; description = "Failed to resolve linkage dependency PromiseKit x86_64 -> @rpath/libswiftObjectiveC.dylib: Unknown arch x86_64"; info = { }; level = WARN; }, { code = 0; description = "Failed to verify bitcode in PromiseKit.framework/PromiseKit:\nerror: Cannot extract bundle from /var/folders/q5/hm9v_6x53lj0gj02yxqtkmd40000gn/T/IDEDistributionOptionThinning.RJD/Payload/MyAppName.app/Frameworks/PromiseKit.framework/PromiseKit (x86_64)\n\n"; info = { }; level = ERROR; type = "malformed-payload"; } ); ``` Some other solutions I tried was using a Project Reference to PromiseKit, instead of a Framework reference, however this doesn't work - in that I still need a framework reference from my main project, because I will get "library not loaded" error at runtime, if running without a FW reference. Same issue occurs when archiving while using a project reference.
2018/10/29
[ "https://Stackoverflow.com/questions/53050451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1315512/" ]
Same issue here. The only workaround I've found is to use static library instead of framework. In case you are not able to use static library, you'd better file a bug report to Apple.
This is what worked for me, I have application and 2 in-house built frameworks, say **A $ B.** Application needs A, but A needs B and since Apple doesn't recommend nesting frameworks, so both A and B had to be included in the app. This is what my Xcode project looks like. [![structure of the application in Xcode](https://i.stack.imgur.com/Bsh2Q.png)](https://i.stack.imgur.com/Bsh2Q.png) **SOLUTION** In the application, under **Frameworks, Libraries and Embedded Content**, select **Embed & Sign** for all necessary frameworks. (as shown below) [![application frameworks](https://i.stack.imgur.com/7hczi.png)](https://i.stack.imgur.com/7hczi.png) But for all the custom framework projects, under **Frameworks and Libraries** section, select **Do Not Embed**. (as shown below) This fixed the issue for me [![custom frameworks](https://i.stack.imgur.com/1D8ha.png)](https://i.stack.imgur.com/1D8ha.png)
1,329
So, when doing LaTeX, it is absolutely necessary for ones sanity to using a preview program which updates automatically every time you compile. Of course, any previewer designed for DVIs will do this, but as far I can tell, Adobe Acrobat not only does not automatically update, but will not let you change the PDF with it open. On a Mac one can get around this by using Skim, and on \*nix by using xpdf, but what should one do on Windows?
2009/10/20
[ "https://mathoverflow.net/questions/1329", "https://mathoverflow.net", "https://mathoverflow.net/users/66/" ]
As noted, SumatraPDF is probably the best solution. Alternatively, look for pdfopen and pdfclose which can be set to automatically close the pdf file before you compile the TeX file and then reopen it. They are built into many TeX frontends. Finally, some versions of Reader (e.g., 6) running on some versions of Windows allow you to reopen your pdf file at the position you closed it by hitting Alt-left arrow.
Or use a latex editor with a preview window on the right. LEd has this feature. Every time you compile, the preview window updates. Moreover, you can see your code and output in the same screen, which is nice.
62,030
To what extent does the study of history use hypothesis testing? By Hypothesis testing I mean the usage of p-values and significance levels to dictate how an actual event differs from the event by chance; An example where it could be used in history: To evaluate the change in attitudes of female politicians since laws in country A was changed. The sample would be all politicians of country A for a single year and evaluate the p value with assumed distribution X~B(sample size, 0.5). This can then be graphed to show that the distribution is becoming less/more/as true. The math would probably take more into account but the basic idea is the same
2020/11/29
[ "https://history.stackexchange.com/questions/62030", "https://history.stackexchange.com", "https://history.stackexchange.com/users/32011/" ]
It seems to me, you mixed two control methods. One, the practical-level method, is statistics. Yes, it is used, alas, very often, without the understanding of the tool. Historians are seldom good at maths, and the Theory of Probability is one of its most demanding areas. It is known, that even people with good math background, but without deeper knowledge of the ToP, can be easily caught by its numerous paradoxes. (The most simple and famous one: "A family has 2 children, one of them is a boy. What is the probability that another one is a boy, too?" Answer - 1/3.) And understanding statistics without the understanding of ToP is impossible. Second, is a much more deep and important method - predict-and-check. This is the method that divides science from non-science. It is not connected directly to statistics and, naturally, can be used and is used in history, not predicting the future, but predicting the results of excavations. They cannot be known beforehand but can be predicted by the theory you want to check. Freshly translated or newly found documents can serve the same way. That method needn't statistics, but demands an even deeper understanding of probabilities - conditional probabilities and probabilities of conditions. Less mechanical counting, but much more thinking and understanding. (I advise [HPMOR](http://www.hpmor.com/) as a very good popular source and a starting point) Thank God, the method can be often used on an intuitive level, which is practiced by 90% of scientists. Alas, that can sometimes lead to serious errors. If you want to cross these methods and to predict the results of statistics, yes, it is possible, but you will be in the area of sociology, economics, and politology (as your example), but not of history. And seriously, you don't want it. You really must know ToP and statistics at a very good level for it. Say, 2-3 years of lections and a thousand solved practical problems. On the base of combinatorics, the theory of sets, and logic, of course.
Yes, of course. Suppose archaeologists are excavating a region. On average,they find n pottery shards per hectare. At one dig they count 5n pottery shards. They ask themselves "What are the likelihood of finding 5n pottery shards at a random dig?" Since they have estimated the parameters of the pottery shards distribution for the region they can calculate this. So they calculate it and the answer is that it is incredibly unlikely. "Aha!" they say, "here there must have been a settlement!" This is an example of hypothesis testing. Another example is trying to reconstruct partially destroyed manuscripts. To fill in the blanks you need statistical methods to model the language the manuscript is written in.
170,664
Am hesitant to ask yet one more embarrassing question, but I can't seem to see the problem with the `\foreach` in the MWE. It should produce several horizontal lines but only produces the one with the `yValue` as specified in the `\newcommand{\yValue}{0.3}`: ![enter image description here](https://i.stack.imgur.com/yyqUt.png) Code: ----- ``` \documentclass{article} \usepackage{pgfplots} \newcommand{\yValue}{0.3} \begin{document} \begin{tikzpicture} \begin{axis} [ ymin=0, ymax=1, xmin=0, xmax=1, ] \foreach \yValue in {0.00,0.1,...,1.00} { \draw [red] (axis cs:0,\yValue) -- (axis cs:1,\yValue); } \end{axis} \end{tikzpicture} \end{document} ```
2014/04/10
[ "https://tex.stackexchange.com/questions/170664", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/4301/" ]
According to pages 470-471 of the [`pgfplots` documentation](http://texdoc.net/texmf-dist/doc/latex/pgfplots/pgfplots.pdf): (*Note:* in `pgfplots` documentation v1.17, the page range has changed to 544-545.) > > Keep in mind that inside of an axis environment, all loop constructions (including custom loops, `\foreach` and `\pgfplotsforeachungrouped`) need to be handled with care: loop arguments can only be used in places where they are immediately evaluated; but `pgfplots` postpones the evaluation of many macros. For example, to loop over something and to generate axis descriptions of the form `\node at (axis cs:\i,0.5)....`, the loop macro `\i` will be evaluated in `\end{axis}` – but at that time, the loop is over and its value is lost. The correct way to handle such an application is to *expand* the loop variable *explicitly*. > > > Thus, you need to do: ``` \documentclass{article} \usepackage{pgfplots} \begin{document} \begin{tikzpicture} \begin{axis} [ ymin=0, ymax=1, xmin=0, xmax=1, ] \foreach \yValue in {0.00,0.1,...,1.00} { \edef\temp{\noexpand\draw [red] (axis cs:0,\yValue) -- (axis cs:1,\yValue);} \temp } \end{axis} \end{tikzpicture} \end{document} ``` ![enter image description here](https://i.stack.imgur.com/7aYQi.png) --- Edit ---- As [@percusee points out in the comments](https://tex.stackexchange.com/questions/170664/foreach-not-behaving-in-axis-environment/170670#comment393042_170670), you can also use `\pgfplotsinvokeforeach`. This is different from `\foreach` because, according to page 471 of the [documentation](http://texdoc.net/texmf-dist/doc/latex/pgfplots/pgfplots.pdf): > > the `\x` would not be expanded whereas `#1` is. > > > That is to say, it does exactly what is needed to handle the fact that `pgfplots` doesn't evaluate loop macros until `\end{axis}`. Thus, you can also do: ``` \pgfplotsinvokeforeach{0.00,0.1,...,1.00}{ \draw [red] (axis cs:0,#1) -- (axis cs:1,#1); } ``` Note that the syntax is slightly different. `\pgfplotsinvokeforeach` uses `#1`, just like a `\newcommand` would, instead of allowing you to name your own variable.
I ran into a similar problem and the answers above didn't work for me. However, I realized that you often want to use `foreach` *inside* an `axis` environment because you want to have access to the `axis cs` coordinate system. I came up with the following workaround which I show here for the original MWE: ``` \documentclass{article} \usepackage{pgfplots} \usetikzlibrary{calc} \begin{document} \begin{tikzpicture} \begin{axis}[ymin=0, ymax=1, xmin=0, xmax=1] \coordinate (O) at (axis cs:0,0); \coordinate (X) at (axis cs:1,0); \coordinate (Y) at (axis cs:0,1); \end{axis} \begin{scope}[x={($(X)-(O)$)}, y={($(Y)-(O)$)}, shift={(O)}] \foreach \y in {0, 0.1, ..., 1} { \draw[red] (0,\y) -- (1,\y); } \end{scope} \end{tikzpicture} \end{document} ``` The idea obviously is that you "recreate" the coordinate system in the `scope` after leaving the `axis` environment. This also works with 3D coordinates. (Note that in newer versions of `pgfplots` you don't need the `axis cs:` prefix anymore.)
17,458,261
I have an `Activity` with multiple `Fragment`s. I want to show a `DialogFragment` or open another `Fragment` from one of the `Fragment`s. I know that an `Activity` should be the one tasked with opening `Fragment`s so instead I have tried a couple things. **FIRST** I tried to use `getActivity()` and cast it so I can call a method in the `Activity` to show a `Fragment` however this creates a dependency in the `Fragment` with the `Activity` and I would like to avoid adding a dependency if possible. **SECOND** Next I tried a listener to notify the `Activity` that it should show a `Fragment`. So I created a class in the `Activity` to implement the listener interface. But I had problems because I had to use `New MyActivity().new Listener();` and it would throw an `Exception` when I tried to use `getSupportFragmentManager()` since this instance of the `Activity` is not initialized. **THIRD** I then tried to have the `Activity` implement the listener directly which works because then I am only creating a dependency with the listener and not the Activity. However now I am getting to the point where my `Activity` will be implementing 2 - 4 different interfaces which is making me hesitant because it will severely reduce cohesion. So any way I have tried I seem to be running into a brick wall and creating dependancies I'm not sure I need to be creating. Am I screwed and have to go with one of these options? If so which option would be best? Any help or suggestions are are greatly appreciated.
2013/07/03
[ "https://Stackoverflow.com/questions/17458261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215222/" ]
Personally I would say that fragments should be thought as reusable and modular components. So in order to provide this re-usability, fragments shouldn't know much about their parent activities. But in return activities must know about fragments they are holding. So, the first option should never be considered in my opinion for the dependency reason you mentioned causing a very highly coupled code. About the second option, fragments may delegate any application flow or UI related decisions (showing a new fragment, deciding what to do when a fragment specific event is triggered etc..) to their parent activities. So your listeners/callbacks should be fragment specific and thus they should be declared in fragments. And the activities holding these fragments should implement these interfaces and decide what to do. So for me the third option makes more sense. I believe that activities are more readable in terms of what they are holding and doing on specific callbacks. But yes you are right your activity might become a god object. Maybe you can check Square's [Otto](http://square.github.io/otto/) project if you don't want to implement several interfaces. It's basically an event bus.
Have you tried something like this (from the Fragment): ``` FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction(); Fragment prev = getActivity().getSupportFragmentManager().findFragmentByTag("some_name"); if (prev != null) { ft.remove(prev); } ft.addToBackStack(null); DialogFragment dialogFragment = DialogFragmentClass.newInstance(); dialogFragment.show(ft, "some_name"); ``` Let me know, cheers.
6,510,649
I have an image that I upload with a HTTP Post method to my webserver written in PHP. My code compresses a bitmap to a jpeg coded byte array and sends that Base64 encoded to the server which decodes, writes it to a file and opens it as a jpg image. Index.php: ``` <?php $base=$_REQUEST['image']; echo $base; // base64 encoded utf-8 string $binary=base64_decode($base); // binary, utf-8 bytes header('Content-Type: bitmap; charset=utf-8'); // print($binary); //$theFile = base64_decode($image_data); $file = fopen('test.jpg', 'wb'); fwrite($file, $binary); fclose($file); echo '<img src=test.jpg>'; ?> ``` and I have an empty 0kb test.jpg in the same directory. Sometimes I can see the image when I quickly press F5(refresh), but then when I refresh again, the image is removed again and it's again 0KB. (working on Google Chrome) 1) How can I make that the picture keeps displaying the data written to test.jpg and doesn't change back to 0kb? So when I view it, the picture is still there. (note that my PHP knowledge is not so good, so instructions would be really much appreciated.) Upload method in JAVA, Android: ``` public void uploadFrame(byte[] Frame, String WebClient) { String ba1=Base64.encodeBytes(mCurrentFrame); ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("image",ba1)); try{ HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(WebClient); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); }catch(Exception e){ Log.e("log_tag", "Error in http connection "+e.toString()); } } ``` 2) Another question is, if this method is actually safe because people could send any POST Method data to it and display any picture. So how would this work in PHP to first check if a parameter in JAVA is equal to a parameter in your PHP code, so only people with the same parameter could upload this code to his webserver. This could be a quite intresting topic for some people. EDIT: ``` <?php if (isset($_REQUEST['image'])) { $base=$_REQUEST['image']; echo $base; // base64 encoded utf-8 string $binary=base64_decode($base); // binary, utf-8 bytes header('Content-Type: bitmap; charset=utf-8'); // print($binary); //$theFile = base64_decode($image_data); $file = fopen('test.jpg', 'wb'); fwrite($file, $binary); fclose($file); echo '<img src=test.jpg>'; } header('Content-type: image/jpeg'); readfile('test.jpg'); ?> ```
2011/06/28
[ "https://Stackoverflow.com/questions/6510649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/798314/" ]
Every time you refresh the page, it's going to write data to that `test.jpg` file. If you don't submit a base64 image, it'll just write out a blank/null string, which means a 0-byte file. Instead, try this: ``` <?php if (isset($_REQUEST['image'])) { ... your decoding/fopen/fwrite stuff here ... } header('Content-type: image/jpeg') readfile('test.jpg'); ``` This will directly output the image as a jpg, rather than outputting HTML and forcing the browser to open yet another HTTP connection to load the .jpg file.
Answering question 2: No, it is not safe. You should really probably sign it or outright encrypt it in transit to ensure you can trust the data you get -- it's either yours, or garbage. Check out [`mcrypt()`](http://us2.php.net/manual/en/book.mcrypt.php) for more info on that.
4,854,264
I am getting the following error when trying to send an email message where I give the 'To' parameter a tuple of email addresses. ``` > TypeError: sequence item 0: expected > string, tuple found ``` I have looked at the Django documentation for the [EmailMessage class](http://docs.djangoproject.com/en/dev/topics/email/#emailmessage-objects) and it indicates this should be fine. Anyone have any suggestions about what could be going wrong? I construct the EmailMessage object like so: ``` spam = EmailMessage("Some title - %s \"%s\"" % (subject, task.name), message, "%s <%s>" % (user.get_full_name(), user.email), settings.MAIL_LIST) spam.content_subtype = "html" spam.send() ``` and ``` settings.MAIL_LIST = ["foo@bar.com", "foo2@bar.com", "foo3@bar.com"] ``` Partial Stack trace: ``` > File "/myClass/Mail.py", line 217, in > contact_owner > spam.send() > > File > "/port/python-environments/port_web/lib/python2.6/site-packages/django/core/mail.py", > line 281, in send > return self.get_connection(fail_silently).send_messages([self]) > > File > "/port/python-environments/port_web/lib/python2.6/site-packages/django/core/mail.py", > line 185, in send_messages > sent = self._send(message) > > File > "/port/python-environments/port_web/lib/python2.6/site-packages/django/core/mail.py", > line 199, in _send > email_message.message().as_string()) > > File > "/port/python-environments/port_web/lib/python2.6/site-packages/django/core/mail.py", > line 253, in message > msg['To'] = ', '.join(self.to) > > TypeError: sequence item 0: expected > string, tuple found ```
2011/01/31
[ "https://Stackoverflow.com/questions/4854264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/330013/" ]
To generate unique ids for objects you could use the aptly named **ObjectIDGenerator** that we conveniently provide for you: <http://msdn.microsoft.com/en-us/library/system.runtime.serialization.objectidgenerator.aspx> Note that, as the comment points out, the object id generator keeps a reference to the object alive, so it is only suitable for objects that you know are going to survive the life of the application anyway. If you intend to use this thing on more ephemeral objects then it is not a good solution. You could build your own object ID generator that kept weak references if you wanted; it wouldn't be that difficult.
Do you need the identifier to be unique across all objects or just within a specific type? You have a couple of options: 1. If you aren't overriding `Object.GetHashCode()`, this will give you a *pretty* (but not 100%) reliable identifier. Note, though, that (per the docs), this is not *guaranteed* to be unique. Your chances of hitting a duplicate, though, are pretty low. 2. If you are (or need 100%), the simplest solution would be to use a `private static long lastObjectId` in your class. Within the base constructor, use [`Interlocked.Increment(ref lasObjectId)`](http://msdn.microsoft.com/en-us/library/zs86dyzy.aspx) as the value for the current object. 3. If you need the identifier to be unique across objects, you can do something similar to 2., but you'll have to use a central class to manage these ID's.
19,966,126
Let me explain. I am not looking for a particular attribute of a particular DOM element. I started thinking that if I checked the `background-color` of the **body** element, I would find the background color of a page. But for example for this site: [performance bikes](http://www.performancebike.com/bikes/Product_10052_10551_1135340_-1_1830021__1830021) the background color of body is **black**, and it's "obvious" that the main background color of the site is **white**. So, I am parsing the site with **PhantomJS**. What do you think would be a good strategy to be able to find the most "visible" background-color. I don't know how to say that, but for a human it is kind of obvious which color is the background. How to find it programatically? EDIT: the bikes site is just an example. I am thinking on how I would do this for "any" page.
2013/11/13
[ "https://Stackoverflow.com/questions/19966126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196150/" ]
What about something like this? Not perfect, but should return you the element with the biggest area and make sure that it is visible. Won't account for it being below other elements, but it's a start... ``` var element={ width:0, height:0, color:'', jQEl:{} } $('*:visible').each(function(){ var $this = $(this); var area = element.width*element.height; var thisArea = $this.width()*$this.height(); if(thisArea>area){ element.width = $this.width(); element.height= $this.height(); element.color=$this.css('background-color'); element.jQEl=$this; } }); console.log(element) ```
Another nice solution is to use browser plug-ins. I use Eye Dropper for chrome. <https://chrome.google.com/webstore/detail/eye-dropper/hmdcmlfkchdmnmnmheododdhjedfccka?hl=en> Or you can use colorPicker for Firefox. To get it, in your firefox browser, goto: Tools -> Add-ons -> top right search bar look for "colorPicker" It's 10 times faster to find the color of a background on a site this way than searching through the CSS code.
6,370,318
``` $(document).ready(function () { //Store the sub types StoreSubTypes(); //Set up company Type on Change $("#option").change(CompanyTypeOnChange); $(".status").change(InsuranceTypeChange); CompanyTypeOnChange(); } ); ```
2011/06/16
[ "https://Stackoverflow.com/questions/6370318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/798992/" ]
Have a look at libpd (Pure Data for embedded applications) <http://download.puredata.info/libpd> (the library has been released very recently, but the code is very mature indeed) <http://createdigitalmusic.com/2010/10/libpd-put-pure-data-in-your-app-on-an-iphone-or-android-and-everywhere-free/>
Audio is often problematic and it is pretty much always a good idea to write your own high-level API that does exactly what you want to do (and nothing else) and to assume you will then be writing a thin layer between it and whatever audio library you are using underneath. If you're lucky and there's a library available that does things the way you would do them then it's trivial. If not, at least it's still possible. In either case, your app code is not tied to an external sound API. I have used FMOD on multiple different commercial projects over the years for PC, Mac and iPhone, and have always liked it - but it's not free. OpenAL has always seemed sorta, I dunno: clunky? But you only have to deal with it when writing your API layer, and your app code never has to see it. It's easy for me to say "write your own API" since I've been writing commercial games for 20 years and so know what I think an audio API should look like. If you don't have your own idea how you think it should be, then I suggest you look at a 3rd party library that makes sense to you and take the functions from it that you will be using and write your own API to do be a set of functions that do nothing but call those. Since you have both OpenAL and FMOD available to you free for development you can then make your API work with both, and chances are it's then going to work with anything else you might come across.
83,200
I'm having issues with a site that has recently moved to a new host. The hosting company say it's not their issue but I'm a bit stuck for ideas. i'm not quite sure how to post a full set of logs here but any help is appreciated! ``` Invalid method Mage_Catalog_Block_Product_View::_isSecure(Array ( ) ) Trace: #0 /var/www/vhosts/<DOMAIN>/httpdocs/app/design/frontend/base/default/template/catalog/product/view.phtml(42): Varien_Object->__call('_isSecure', Array) ```
2015/09/15
[ "https://magento.stackexchange.com/questions/83200", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/31166/" ]
The `_isSecure` call was introduced in Magento CE 1.9.2.0. * [view.phtml](https://github.com/bragento/magento-core/blob/1.9.2.0/app/design/frontend/base/default/template/catalog/product/view.phtml#L42) * [Mage\_Core\_Block\_Abstract](https://github.com/bragento/magento-core/blob/1.9.2.0/app/code/core/Mage/Core/Block/Abstract.php#L1480) As per your comment you updated the base theme but not the core files. This leads to a version mismatch (template files access block methods). Revert the theme or upgrade the Magento installation to align both.
I assume you understand the error? ``` Invalid method Mage_Catalog_Block_Product_View::_isSecure() ``` The class `Mage_Catalog_Block_Product_View` doesn't have a method `_isSecure`. Therefore it seems like magento creates the wrong object somewhere and calls a method which doesn't exist. Did you change the base template? I can't find any `_isSecure` call in a 1.9.1
36,169,123
My assignment is to convert binary to decimal in a JLabel array without using pre-written methods (there's no user input). I have the right idea but for some reason the output is always a little bit off. I've gone through it countless times but I can't find anything wrong with my algorithm and I'm very confused as to why it doesn't produce the correct answer. I'd be very grateful if someone could help me out. Thanks! Side note: I've read similar discussion threads regarding binary to decimal conversions but I don't understand how to do it with arrays. Here is a snippet of my code: ``` private void convert() { int[] digit = new int[8]; //temporary storage array int count = 0; for(int x = 0; x < digit.length; x++) { digit[x] = Integer.parseInt(bits[x].getText()); //bits is the original array count= count + digit[digit.length - 1 - x] * (int)(Math.pow(2, x)); } label.setText("" + count); } ```
2016/03/23
[ "https://Stackoverflow.com/questions/36169123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6102002/" ]
You are following the binary number from left to right but are grabbing the wrong digit. You want the same digit but to multiply by the right power of two - first index being +n\*128 and not +n\*1 ``` int count = 0; for(int i = 0; i < bits.length; i++) { count += Integer.parseInt(bits[i].getText()) * Math.pow(2, bits.length - i - 1); } ```
Obviously there is a bug in your snippet. You set the digit[x], but not set the digit[length - 1 - x]. for example, x = 0, you set the digit[0], but not set digit[7]. So there will be an error when you want use the digit[length - 1 -x] here : ``` count= count + digit[digit.length - 1 - x] * (int)(Math.pow(2, x)); ``` This the correct code here: ``` private void convert() { int count = 0, length = 8; for(int i = 0; i < length; count += Integer.parseInt(bits[i].getText()) * (1 << (length - 1 - i)), i++); label.setText("" + count); } ``` Have not test the code. But I think it will work.
139,434
I am working as a TA for a seminar course and class presentations are considered a significant part of the total mark for the course. Some of the students in the class — who mostly happen to be international students — do not perform the best presentation in terms of the communications of ideas with the audience. It is mostly because of their thick accent and other flaws in their English, making the presentation hard to understand for the audiences. What is the best marking strategies in these situations? I am skeptical about commenting on this issue and discussing the problem with the students or reducing a part of the mark for the lack of communication quality, as I am afraid it would come across as racist. The university is in North America and about 80% of the students are native speakers of English.
2019/11/02
[ "https://academia.stackexchange.com/questions/139434", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/-1/" ]
There are two ways to interpret the issue that is being raised. One is that the people simply have accents and not completely correct grammar in spoken English... but not to the point that it seriously impedes intelligibility. The other is that their English is so poor that it does greatly impede intelligibility. The former is of little consequence, of course. The latter is a serious problem, in fact. It's not about bias for/against languages/nationalities, but about the context in which one operates. If one cannot communicate effectively, that's a minus. Even if/when people are "understanding", it's still not a plus, but a minus. Overcoming such an impediment should have a pretty high priority... as opposed to simply believing that such an issue solves itself in time. In particular, this will not happen for people whose English is sufficiently compromised that they spend nearly all waking hours with their fellow speakers, and thereby never practice the local language (as Dir. of Grad. Studies in Math. at my university on two different occasions, and participating in such issues for 35+ years, I've seen many cases). In particular, outside of super-special cases, it serves no grad student well to have English be an obstacle. It will significantly obstruct their hiring on teaching-communication grounds, if nothing else. And, unavoidably, it reduces the impact of their portrayal of their research work.
Some decades ago, my professor summarized it roughly like this: * The professional vocabulary **must** be right. * The grammar **should** be right, but errors are acceptable if they don't affect meaning. * The pronunciation is **optional**. The goal was to train students to write acceptable papers, and to understand (or be understood by) other students who are benevolent and largely have the same accent. I haven't been in academia for some years, so standards might have shifted at least in some places. Being able to present your results is part of scientific process.
22,992,149
With all the chatter going on about the heartbleed bug, it's hard to find information on what exactly the exploited heartbeat extension for OpenSSL is used for. Also, is it possible to disable it for Apache w/ mod\_ssl without recompling with the `-DOPENSSL_NO_HEARTBEATS` flag as suggested @ <http://heartbleed.com/>?
2014/04/10
[ "https://Stackoverflow.com/questions/22992149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2891365/" ]
Heartbeat is an echo functionality where either side (client or server) requests that a number of bytes of data that it sends to the other side be echoed back. The idea appears to be that this can be used as a keep-alive feature, with the echo functionality presumably meant to allow verifying that both ends continue to correctly handle encryption and decryption. The problem, of course, is that until the recent patch, OpenSSL did not guard against sending back more data than was provided in the first place. I'm not really aware of where the heartbeat extension is actually used in an application since most communication that requires it (e.g. websockets) rely on their own keep-alive features implemented on a higher level. I can't answer your second question---but it would surprise me if the answer was yes.
Try this for info on heart beats: <http://www.troyhunt.com/2014/04/everything-you-need-to-know-about.html> I'm not really an apache guy, I gather that the flag works but that there may be a performance hit. The advice is to recompile. Also talk to your devs about sending emails, you may want to consider asking your users to change their passwords - just to be on the safe side. I've had a couple of services email like that already
72,247
Due to misplaced keys, we are going to either rekey or replace an old lock on our front door. The manufacturer was Barrows, which seems to be somewhat rare since our local hardware doesn't carry blanks for new keys. We would replace it only if it is feasible replace only the approx 1" diameter cylinder on the deadbolt with common brand such as Schlage or Baldwin or ... What security factors come into play? For example, does the rarity of Barrows locksets make them more secure, or is Barrows know for poor or good security?
2015/08/22
[ "https://diy.stackexchange.com/questions/72247", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/41735/" ]
Lockpicking is tremendously sensitive to the accuracy of manufacture. A good-quality cylinder really is more secure than a cheap equivalent. (There are good-quality second-source cylinders, but don't expect to find them in a $3 lock set.) Degree and kind of protection from brute-force attacks varies; that's a lot of what the lock grading system is about. Grade 2 locks are physically more durable than the cheap grade 3 versions. (Grade 1, commercial, is more so but is mostly needed where you're also concerned about how well the lock will stand up to the wear and tear of being used frequently.) High-security cylinders do make a difference. So do higher-security strikes, anchored to the framing rather than the trim. Master keying should be used only when necessary and should always start with a more-secure-than-usual cylinder. (Some locksmiths describe master keying as "the controlled destruction of security" -- I'd say reduction but they aren't far off.) And so on. Seriously, the number of ways to get security wrong or right approaches the number of lock designs on the market, and there are real limits on what can be discussed in a public forum .... or should be, anyway.
Number of pins and turns of the tumbler. Some tumblers can turn twice. I'm not sure how they work exactly but I'm assured that they are more difficult to pick. In any case, most burglars who find the front door locked will enter in via a window as they are often easier to open.
6,109,833
I have a 2D space with objects, each object has coordinate vector and an array of vertexes relative to his coordinate, now I need an efficiency way of storing the objects, this store should be able to add and remove objects, also the most important part is the collision detection: I want to get a list of objects which have a **chance** to collide (close neighbor etc.), should be fast and simple in about `O([number of objects with collision chance] * log([number of all objects]))` so that way when there is no close objects it should do it in `O(1)` and not the brute force way of just going over all of the objects in `O(n)`. Ask if something not clear. Maybe you know some link on the subject or any good ideas. Thanks.
2011/05/24
[ "https://Stackoverflow.com/questions/6109833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/620029/" ]
you could use a [quadtree](http://en.wikipedia.org/wiki/Quadtree) for this to check all the nearby objects.
You want to use a spatial index or a quadtree. A quadtree can be simple a space-filling-curve (sfc) or a hilbert curve. A sfc reduce the 2d complexity to a 1d complexity and is used in many maps applications or heat maps. A sfc can be used to store a zipcode search, too. You want to search for Nick's hilbert curve quadtree spatial index blog.
36,324
**NOTE:** The *Question has been updated*. View *Edit Revisions* to view original question. The scenario. An animal charity that at the moment, track their establishment's costs via a spreadsheet like so: [*broken image link removed*] **1NF:** The above table is already in 1NF because it abides to the definition of 1NF. > > *First Normal Form: A relation in which the intersection of each row and column contains one and only one value.* > > > After reading [Catcall's answer](https://dba.stackexchange.com/a/36326/20381) I can see that it is in determining my dependencies that I messed up. All I did originally was exactly like Catcall said ! added a primary key column, and said to myself "there, that fixes that!" So obviously that was wrong. I have now read more carefully into functional dependencies and in this book I have, it defines them as: > > *Functional Dependency: Describes the relationship between attributes in a relation. For example if A and B are attributes of relation R, and B is functionally dependent on A (denoted by A --> B), if each value of A is associated with **exactly** one value of B. There exists a functional dependency.* > > > Keeping the above definition in mind, and examining my now expanded (more data) sample table, I can see that PetHouse Ltd is not always going to be associated with Dog food, and this breaks the part of definition about A being associated with EXACTLY one value of B. So I guess in reality I am stuck here in identifying my functional dependencies. Here I am a little bit in the dark as I've never worked with a composite key that was made up of three different columns, but I'll go ahead anyway and see where I get to. Catcall suggested using 3 columns [*Name, BoughtFrom, TimeBought*] as identifiers of data (i.e. a composite key for the table that is made up of 3 columns) and that makes sense as that would uniquely identify each row of data in the table. So the notation for the relation becomes: IncuredCosts (**Name**, **BoughtFrom**, **TimeBought**, Cost) The book in my possession also has this interesting part about the functional dependencies we need for normalization. It states that the functional dependencies we are after must have the following characteristics: * There is a *one-to-one* relationship between the attribute(s) on the left-hand side (determinant) and those on the right-hand side of a functional dependency. (Note that the relationship in the opposite direction can be a one-to-one or one-to-many relationship.) * They hold for *all* time. * The determinant has the *minimal* number of attributes necessary to maintain the dependency with the attribute(s) on the right-hand side. In other words, there must be a full functional dependency between the attribute(s) on the left-hand and right-hand sides of the dependency. I believe all the above characteristics hold true for this functional dependency: > > (Name, BoughtFrom, TimeBought) --> Cost > > > Now then, Transitive Dependencies, which in the book (could be wrong like Catcall said) is defined as: > > *Transitive Dependency: A condition where A, B and C are attributes of a relation such that if A --> B and B --> C, then C is said to be transitively dependent on A via B (provided that A is not functionally dependent on B or C).* > > > Am I right in thinking that my relationship as defined earlier does not have any transitive dependencies? But then again, if that the case, it would *imply that I have reached 3NF*! cause apparently the major step to 3NF is the removal of Transitive Dependencies into their own relation. Have I really reached 3NF? Thank you by the way. I learnt a lot through this post.
2013/03/10
[ "https://dba.stackexchange.com/questions/36324", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/20381/" ]
Yes, it's in 1NF. You can't side-step the often hard work of determining *all* the candidate keys by hanging a number off the end of the table and saying, "There. I've got a primary key." One natural candidate key for this table is {Name, Bought from, Date bought}. Consider using "Time bought" instead of "Date bought". Your definition of 2NF is wrong. Instead of > > Second Normal Form: A relation that is in First Normal Form and every > non-primary-key attribute is fully functionally dependent on the > primary key. > > > you need something more like this. *Second Normal Form: a relation that is in First Normal Form, and every non-prime attribute is fully functionally dependent on every candidate key.* The term *non-prime* attribute doesn't mean quite what *non-primary-key* attribute means. Your definition of 3NF is wrong, and it's wrong for the same reasons as your definition for 2NF was wrong. Instead of this > > Third Normal Form: A relation that is in First and Second Normal Form > and in which no non-primary-key attribute is transitively dependent on > the primary key. > > > you need something closer to this. *Third Normal Form: A relation that is in Second Normal Form and in which every non-prime attribute is nontransitively dependent on every candidate key. (There isn't a really good way to express all those negative in one sentence.)*
First, it looks to me like you are building an accounting database. Let me just advise you to reconsider or look at existing open source dbs out there (I maintain LedgerSMB for example). Secondly regarding normalization, you need extra tables. You should break off what you bought and who you bought it from into other tables, and then have a table which records, more or less, the information you have here but with keys to the other tables, as a minimalist solution. So something like (sorry for the PostgreSQL-isms here): ``` CREATE TABLE vendor ( id serial not null unique, company_name text primary key, vat_number text unique, ... ); CREATE TABLE things_to_purchase ( id serial not null unique, label text primary key, .... ); CREATE TABLE invoice ( vendor_id int not null references vendor(id), what_purchased int not null references things_to_purchase(id), when_purchased date not null, expense numeric not null ); ```
63,697,495
I am on Windows 10 and I have WSL2 enabled. When I do `docker pull ubuntu` followed by `docker run ubuntu`, a new ubuntu container with a randomly generated name shows up in my dashboard and it starts for half a second, but then immediately stops. If I press the start button the same behaviour is observed. I tried running these commands from Command Prompt, PowerShell, and my downloaded Ubuntu 18.04 distro (which is also my default WSL2 distro) all with the same result. How do I fix this? Also, `docker logs <container_name>` doesn't result in anything and double-clicking the container name in the dashboard doesn't show any logs.
2020/09/02
[ "https://Stackoverflow.com/questions/63697495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4900292/" ]
You can easily reuse a `String` in a loop by creating it outside the loop and `clear`ing it after using the contents: ``` // Use Kevin's suggestion not to make a new `SmallRng` each time: let mut rng_iter = rand::rngs::SmallRng::from_entropy().sample_iter(rand::distributions::Alphanumeric); let mut s = String::with_capacity(line_size + 1); // allocate the buffer for _ in 0..line_count { s.extend(rng_iter.by_ref().take(line_size)); // fill the buffer s.push('\n'); file.write(s.as_bytes())?; // use the contents s.clear(); // clear the buffer } ``` `String::clear` erases the contents of the `String` (dropping if necessary), but does not free its backing buffer, so it can be reused without needing to reallocate. See also -------- * [Weird behaviour when using read\_line in a loop](https://stackoverflow.com/q/45232943/3650362) * [Why does Iterator::take\_while take ownership of the iterator?](https://stackoverflow.com/q/31374051/3650362) explains why `by_ref` is needed
I (MakotoE) benchmarked Kevin Reid's answer, and it seems their method is faster though memory allocation seems to be the same. Benchmarking time-wise: ``` #[cfg(test)] mod tests { extern crate test; use test::Bencher; use super::*; #[bench] fn bench_write_random_lines0(b: &mut Bencher) { let mut data: Vec<u8> = Vec::new(); data.reserve(100 * 1000000); b.iter(|| { write_random_lines0(&mut data, 100, 1000000).unwrap(); data.clear(); }); } #[bench] fn bench_write_random_lines1(b: &mut Bencher) { let mut data: Vec<u8> = Vec::new(); data.reserve(100 * 1000000); b.iter(|| { // This is Kevin's implementation write_random_lines1(&mut data, 100, 1000000).unwrap(); data.clear(); }); } } ``` ``` test tests::bench_write_random_lines0 ... bench: 764,953,658 ns/iter (+/- 7,597,989) test tests::bench_write_random_lines1 ... bench: 360,662,595 ns/iter (+/- 886,456) ``` Benchmarking memory usage using valgrind's Massif shows that both are about the same. Mine used 3.072 Gi total, 101.0 MB at peak level. Kevin's used 4.166 Gi total, 128.0 MB peak.
31,176,675
I have a string like this: ``` [{\"ID\":2,\"Text\":\"Capital Good\"},{\"ID\":3,\"Text\":\"General Office Items\"},{\"ID\":1,\"Text\":\"Raw Material Purchase\"}]&@[{\"ID\":2,\"Text\":\"Capital Good\"},{\"ID\":3,\"Text\":\"General Office Items\"},{\"ID\":1,\"Text\":\"Raw Material Purchase\"},{\"ID\":0,\"Text\":\"Approved\"},{\"ID\":1,\"Text\":\"Freezed\"},{\"ID\":2,\"Text\":\"Cancelled\"},{\"ID\":3,\"Text\":\"Completed\"},{\"ID\":4,\"Text\":\"Foreclosed\"},{\"ID\":5,\"Text\":\"UnApproved\"}] ``` I want to split my string into two based on &@ character combination like this: ``` String [] separated=line.split("&@"); ``` but when I checked the values separated[0] contains perfect first half of the string but when I checked separated[1] it contains full string without "&@" characters. I wanto separated[1] contain characters after "&@". Any help would be appreciated.
2015/07/02
[ "https://Stackoverflow.com/questions/31176675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4985048/" ]
``` [{\"ID\":2,\"Text\":\"Capital Good\"},{\"ID\":3,\"Text\":\"General Office Items\"},{\"ID\":1,\"Text\":\"Raw Material Purchase\"}] //&@ [{\"ID\":2,\"Text\":\"Capital Good\"},{\"ID\":3,\"Text\":\"General Office Items\"},{\"ID\":1,\"Text\":\"Raw Material Purchase\"},{\"ID\":0,\"Text\":\"Approved\"},{\"ID\":1,\"Text\":\"Freezed\"},{\"ID\":2,\"Text\":\"Cancelled\"},{\"ID\":3,\"Text\":\"Completed\"},{\"ID\":4,\"Text\":\"Foreclosed\"},{\"ID\":5,\"Text\":\"UnApproved\"}] ``` that's your original String with line break around &@ to make it clear where it splits. As you can see the 2nd String starts with a repeated 1st String (without the closing `]`). Your split works fine.
You need regex something like `String mySpitedStr[] = myStr.split("&|@");`
7,093,028
I'm having some problems with exercise 35 in "Learn python the hard way". ``` def bear_room(): print "There is a bear here." print "The bear has a bunch of honey." print "The fat bear is in front of another door." print "How are you going to move the bear?" bear_moved = False while True: next = raw_input("> ") if next == "take honey": dead("The bear looks at you then slaps your face off.") elif next == "taunt bear" and not bear_moved: print "The bear has moved from the door. You can go through it now." bear_moved = True elif next == "taunt bear" and bear_moved: dead("The bear gets pissed off and chews your leg off.") elif next == "open door" and bear_moved: gold_room() else: print "I got no idea what that means." ``` a) I don't understand why the While activates. In line 6 we write that the bear\_moved condition is False. So if it's False, and While activates when it's True, it shouldn't activate! b) I also have problems with the AND operator in the IF and ELIF lines. Why are we asking if bear\_moved changes in value?? No other instruction in the block affects bear\_moved other than line 33 (but that line exits the while). I'm not sure I've explaned myself, please do tell me if I haven't. And thank you for your answers, i'm a complete newbie. <http://learnpythonthehardway.org/book/ex35.html>
2011/08/17
[ "https://Stackoverflow.com/questions/7093028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/898631/" ]
`while` loop executes its body while the boolean condition is true. `TRUE` is always true so it is an infinite loop.
> > a) I don't understand why the While activates. In line 6 we write that the bear\_moved condition is False. So if it's False, and While activates when it's True, it shouldn't activate! > > > while True just means loop indefinitely until a break. Each time the while loop starts, it checks if True is True (and it very obviously is) so it loops forever (again, or until a break). bear\_moved is a variable that has nothing to do with the execution of the while loop.
14,482,170
I have a listview with custom adapter which displays names from the contacts . currently its displaying them as > > Rohit > > Rahul > > .... > > > I want it to be like > > 1. Rohit > 2. Rahul > .... > > > i.e, number should be appended automatically . I tried doing that using a count variable in both bindview() & newview() method but it gets messed up when i scroll down and come back the way I am setting text is ``` name = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); contactName.setText(count + ". " + name); ```
2013/01/23
[ "https://Stackoverflow.com/questions/14482170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1662342/" ]
try ``` name = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME)); contactName.setText(cursor.getPosition() + ". " + name); ```
Maybe try :`long count = cursor.getPosition();`
50,713,291
I am having a little issue with my positioning of my buttons in my android app. Bascially if you look at the image below I have three buttons. I want the buttons positioned as they are except with the 'Players 2' button displayed smack bang middle of the screen. I tried setting layout\_parentcenter but this had no affect and I don't want to do it by margins because when I tried this the buttons were not in the correct position when I rotated the phone to horizontal. Below is the image of the current buttons layout: [![enter image description here](https://i.stack.imgur.com/qYJkb.png)](https://i.stack.imgur.com/qYJkb.png) Below is the code: ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" android:background="@drawable/brick_wall"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Title " android:layout_centerHorizontal="true" android:layout_marginTop="20dp" app:fontFamily="@font/balloon_extra_bold" android:textSize="50sp" android:textColor="@color/colorPrimaryLight" /> <Button android:id="@+id/button_players1" android:layout_width="143dp" android:layout_height="30dp" android:layout_centerHorizontal="true" android:background="@drawable/app_buttons" android:fontFamily="@font/balloon_extra_bold" android:gravity="center" android:text="1 Player" android:textColor="@color/black" android:textSize="20sp" android:layout_below="@id/title"/> <Button android:id="@+id/button_players2" android:layout_width="145dp" android:layout_height="30dp" android:layout_below="@id/button_players1" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="@drawable/app_buttons" android:fontFamily="@font/balloon_extra_bold" android:gravity="center" android:text="2 Players" android:textColor="@color/black" android:textSize="20sp" android:layout_marginTop="15dp"/> <Button android:id="@+id/button_how_to_play" android:layout_width="148dp" android:layout_height="30dp" android:layout_below="@id/button_players2" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="@drawable/app_buttons" android:fontFamily="@font/balloon_extra_bold" android:gravity="center" android:text="How to Play" android:textColor="@color/black" android:textSize="20sp" android:layout_marginTop="15dp"/> <ImageView android:id="@+id/footer_logo" android:layout_width="wrap_content" android:layout_height="50dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="20dp" android:src="@drawable/logo" /> </RelativeLayout> ```
2018/06/06
[ "https://Stackoverflow.com/questions/50713291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7740272/" ]
Make your button\_players2 in center of the vertical and put button\_players1 above button\_players2. button\_players1,button\_players2 and button\_how\_to\_play will be in center of the screen. Try to paste below code. ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/brick_wall" android:orientation="vertical"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:text="Title " android:textColor="@color/colorPrimaryLight" android:textSize="50sp" app:fontFamily="@font/balloon_extra_bold" /> <Button android:id="@+id/button_players1" android:layout_width="143dp" android:layout_height="30dp" android:layout_centerHorizontal="true" android:layout_above="@id/button_players2" android:background="@drawable/app_buttons" android:fontFamily="@font/balloon_extra_bold" android:gravity="center" android:text="1 Player" android:textColor="@color/black" android:textSize="20sp" /> <Button android:id="@+id/button_players2" android:layout_width="145dp" android:layout_height="30dp" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_marginTop="15dp" android:background="@drawable/app_buttons" android:fontFamily="@font/balloon_extra_bold" android:gravity="center" android:text="2 Players" android:textColor="@color/black" android:textSize="20sp" /> <Button android:id="@+id/button_how_to_play" android:layout_width="148dp" android:layout_height="30dp" android:layout_below="@id/button_players2" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_marginTop="15dp" android:background="@drawable/app_buttons" android:fontFamily="@font/balloon_extra_bold" android:gravity="center" android:text="How to Play" android:textColor="@color/black" android:textSize="20sp" /> <ImageView android:id="@+id/footer_logo" android:layout_width="wrap_content" android:layout_height="50dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="20dp" android:src="@mipmap/logo" /> </RelativeLayout> ```
You can take group of buttons and wrap it in relativelayout and make that relative layout parent center or vertical and horizontal center ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:background="@drawable/brick_wall"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Title " android:layout_centerHorizontal="true" android:layout_marginTop="20dp" app:fontFamily="@font/balloon_extra_bold" android:textSize="50sp" android:textColor="@color/colorPrimaryLight" /> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/title" android:layout_centerParent="true"> <Button android:id="@+id/button_players1" android:layout_width="143dp" android:layout_height="30dp" android:layout_centerHorizontal="true" android:background="@drawable/app_buttons" android:fontFamily="@font/balloon_extra_bold" android:gravity="center" android:text="1 Player" android:textColor="@color/black" android:textSize="20sp" /> <Button android:id="@+id/button_players2" android:layout_width="145dp" android:layout_height="30dp" android:layout_below="@id/button_players1" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="@drawable/app_buttons" android:fontFamily="@font/balloon_extra_bold" android:gravity="center" android:text="2 Players" android:textColor="@color/black" android:textSize="20sp" android:layout_marginTop="15dp"/> <Button android:id="@+id/button_how_to_play" android:layout_width="148dp" android:layout_height="30dp" android:layout_below="@id/button_players2" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:background="@drawable/app_buttons" android:fontFamily="@font/balloon_extra_bold" android:gravity="center" android:text="How to Play" android:textColor="@color/black" android:textSize="20sp" android:layout_marginTop="15dp"/> </RelativeLayout> <ImageView android:id="@+id/footer_logo" android:layout_width="wrap_content" android:layout_height="50dp" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="20dp" android:src="@drawable/logo" /> </RelativeLayout> ```
22,653,320
Below code gives me outupt as name xxxxx. while as per documentation session\_write\_close closes the session. Kindly help me understanding this. ``` session_start(); $_SESSION['name'] = "xxxxx"; session_write_close(); print_r($_SESSION); ```
2014/03/26
[ "https://Stackoverflow.com/questions/22653320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2715041/" ]
``` session_write_close != session-destroy ``` *Definition*: > > End the current session and store session data. Session data is usually stored after your script terminated without the need to call session\_write\_close(), but as session data is locked to prevent concurrent writes only one script may operate on a session at any time. When using framesets together with sessions you will experience the frames loading one by one due to this locking. You can reduce the time needed to load all the frames by ending the session as soon as all changes to session variables are done. > > >
Other answers mentioned you by [**session\_destroy()**](http://www.php.net/manual/en/function.session-destroy.php) to destroy the session, but note it does not **unset any of the global variables associated with the session**, or unset the session cookie. You have to use the below: ``` // Unset all of the session variables. $_SESSION = array(); ```
42,250,222
I'm using the Windows 10 Home operating system. I have installed Docker toolbox. I have created a docker image of my .net core application by using following command. ``` $ docker build -t helloWorld:core . ``` Now I want to ship this image, to another machine. But I am not getting the image file. Can someone please tell me, where my image will get saved? Or is there any way, to specify docker an image path in docker build command.
2017/02/15
[ "https://Stackoverflow.com/questions/42250222", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3990660/" ]
1. By using the `docker info` command. 2. In the result - check for **Docker Root Dir** This folder will conatins images, containers, ... [![enter image description here](https://i.stack.imgur.com/oh00c.png)](https://i.stack.imgur.com/oh00c.png)
you can use below command to export your image and can copy same to linux / another machine docker export [OPTIONS] CONTAINER example: ``` docker export --output="latest.tar" red_panda ```
388,435
According to the accepted answer on "*[Rationale to prefer local variables over instance variables?](https://softwareengineering.stackexchange.com/questions/388052/rationale-to-prefer-local-variables-over-instance-variables)*", variables should live in the smallest scope possible. Simplify the problem into my interpretation, it means we should refactor this kind of code: ```java public class Main { private A a; private B b; public ABResult getResult() { getA(); getB(); return ABFactory.mix(a, b); } private getA() { a = SomeFactory.getA(); } private getB() { b = SomeFactory.getB(); } } ``` into something like this: ```java public class Main { public ABResult getResult() { A a = getA(); B b = getB(); return ABFactory.mix(a, b); } private getA() { return SomeFactory.getA(); } private getB() { return SomeFactory.getB(); } } ``` but according to the "spirit" of "variables should live in the smallest scope as possible", isn't "never have variables" have smaller scope than "have variables"? So I think the version above should be refactored: ```java public class Main { public ABResult getResult() { return ABFactory.mix(getA(), getB()); } private getA() { return SomeFactory.getA(); } private getB() { return SomeFactory.getB(); } } ``` so that `getResult()` doesn't have any local variables at all. Is that true?
2019/03/12
[ "https://softwareengineering.stackexchange.com/questions/388435", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/248528/" ]
I would say no, because you should read "smallest scope possible" as "among existing scopes or ones that are reasonable to add". Otherwise it would imply that you should create artificial scopes (e.g. gratuitous `{}` blocks in C-like languages) just to ensure that a variable's scope does not extend beyond the last intended use, and that would generally be frowned upon as obfuscation/clutter unless there's already a good reason for the scope to exist independently.
Referring to just your title: absolutely, if a variable is unnecessary it should be deleted. But “unnecessary” doesn’t mean that an equivalent program can be written without using the variable, otherwise we’d be told that we should write everything in binary. The most common kind of unnecessary variable is an unused variable, the smaller the scope of the variable the easier it is to determine that it is unnecessary. Whether an intermediate variable is unnecessary is harder to determine, because it’s not a binary situation, it’s contextual. In fact identical source code in two different methods could produce a different answer by the same user depending upon past experience fixing problems in the surrounding code. If your example code was exactly as represented, I would suggest getting rid of the two private methods, but would have little to no concern about whether you saved the result of the factory calls to a local variable or just used them as arguments to the mix method. Code readability trumps everything except working correctly (correctly includes acceptable performance criteria, which is seldom “as fast as possible”).
1,816,573
If mysql record with condition exists-update it,else create new record
2009/11/29
[ "https://Stackoverflow.com/questions/1816573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/182671/" ]
Is this what you're looking for? ``` INSERT INTO table (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1; ``` <http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html>
You can use the `REPLACE INTO` for that with the syntax of `INSERT INTO`. This way MySQL will invoke an `UPDATE` whenever there's a fictive constraint violation. Be aware that this construct is MySQL-specific, so your query ain't going to work whenever you switch from DB.
6,083,465
What's wrong with this SQL statement: ``` ALTER TABLE `tbl_issue` ADD CONSTRAINT `FK_issue_requester` FOREIGN KEY (`requester_id`) REFERENCES `tbl_user` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT; ``` I have tables called tbl\_issue and tbl\_user within a database called trackstar\_dev. phpMyAdmin said: ``` #1005 - Can't create table 'trackstar_dev.#sql-1a4_9d' (errno: 121) (<a href="server_engines.php?engine=InnoDB&amp;page=Status&amp;token=fdfsdghrw222323hndgsf">Details...</a>) ```
2011/05/21
[ "https://Stackoverflow.com/questions/6083465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/600873/" ]
The most common reason for this error is that the foreign key constraint have the same name as in another table. Foreign keys' names must be unique in the database (not just on table level). Do you have `requester_id` in another table in your database?
you will get this message if you're trying to add a `constraint` with a name that's already used somewhere else, c you will get this message if you're trying to add a constraint with a name that's already used somewhere else . change it and it will be ok :)
33,785,305
I am trying to make a conditional statement with two "ifs", and it works when I input the correct thing, but when I input an incorrect pokemon and a correct level it still works. I am pretty sure that one of the conditions in my while statement is always true (the first part). Here is the code (sorry about the formatting, just know that it is all formatted correctly in the Java environment): ``` while ((!(Pokemon.equalsIgnoreCase(Pikachu)) || !(Pokemon.equalsIgnoreCase(Charmander)) || !(Pokemon.equalsIgnoreCase(Squirtle)) || !(Pokemon.equalsIgnoreCase(Bulbasaur))) && !((Level <= 15)&&(Level >= 1 ))) { System.out.println(); System.out.println("Which one would you like? What level should it be?\n1 to 15 would be best, I think."); Pokemon = sc.next(); Level = sc.nextInt(); if ((Level <= 15) && (Level >= 1)) { if ((Pokemon.equalsIgnoreCase(Pikachu)) || (Pokemon.equalsIgnoreCase(Charmander)) || (Pokemon.equalsIgnoreCase(Squirtle)) || (Pokemon.equalsIgnoreCase(Bulbasaur))) { System.out.print("Added level " + Level + " " + Pokemon + " for " + Trainer + "."); } else { System.out.println("Invalid Pokemon!"); } } else { System.out.println("Invalid Level!"); } } ```
2015/11/18
[ "https://Stackoverflow.com/questions/33785305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5568470/" ]
Pokeman will always be either not X or not Y, it's basic logic since if it's X, then not-Y is true. If it's Y, then not-X is true. If it's neither then **both** will be true. Change `||` to `&&` and think through your logic on paper.
Should be: ``` while ((!(Pokemon.equalsIgnoreCase(Pikachu)) && !(Pokemon.equalsIgnoreCase(Charmander)) && !(Pokemon.equalsIgnoreCase(Squirtle)) && !(Pokemon.equalsIgnoreCase(Bulbasaur))) && !((Level <= 15)&&(Level >= 1 ))) ```
95,828
For a given $n \ge 5$ create every $n$-by-$n$ matrix containing exactly four $1$'s strictly below the diagonal and $0$'s elsewhere.
2015/09/30
[ "https://mathematica.stackexchange.com/questions/95828", "https://mathematica.stackexchange.com", "https://mathematica.stackexchange.com/users/34197/" ]
``` indices = Flatten[Table[{i, j}, {i, 2, 5}, {j, 1, i - 1}], 1]; allarrays = SparseArray[# -> 1, 5] & /@ Subsets[indices, {4}]; ``` The code generates 210 such matrices (see `Length@allarrays`). Here is a sample of one of them: ``` allarrays[[3]] // Normal (* Out: {{0, 0, 0, 0, 0}, {1, 0, 0, 0, 0}, {1, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 0, 0}} *) ``` ![Mathematica graphics](https://i.stack.imgur.com/SCQzm.png) --- Here is a **general function** to accomplish the task: ``` generator[n_Integer] := Module[ {indices, allarrays}, indices = Flatten[Table[{i, j}, {i, 2, n}, {j, 1, i - 1}], 1]; allarrays = SparseArray[# -> 1, n] & /@ Subsets[indices, {n - 1}] ] ``` You can check the output against the $n=5$ case shown above: ``` generator[5] == allarrays (* Out: True *) ``` Keep in mind that the number of matrices to be generated blows up really quickly and the results take quite a bit of space in memory as well. For instance: ``` results = generator[8]; // AbsoluteTiming Length[results] ByteCount[results]/1024.^3 (* to convert to GB *) (* Out: {11.9763, Null} 1 184 040 0.996862 *) ```
Eh, what the heck... With `RandomSample` and `ReplacePart`: ``` With[{ss = Subsets[Flatten@ MapIndexed[Range[#1, #2 + #1 - 1] &, Range[6, 21, 5]], {4}]}, Partition[ReplacePart[ConstantArray[0, 25], Thread[# -> 1]], 5] & /@ ss] ``` And... ``` MatrixForm/@% ``` [![enter image description here](https://i.stack.imgur.com/KrqK1.png)](https://i.stack.imgur.com/KrqK1.png)
35,844,830
I would like to put a new empty value in my combo ``` <select name="myCombo" id="myCombo"> <option value="1">option5</option>; <option value="2">option4</option>; <option value="3">option3</option>; <option value="4">Other</option>; </select> ``` jquery: ``` $('[name=myCombo]').val(''); ``` doesnt work, but it does; ``` $('[name=myCobmo] option[value=1]').val(''); ``` I want to change whatever the value selected is. How can I do it?
2016/03/07
[ "https://Stackoverflow.com/questions/35844830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5212118/" ]
I think you are looking for this ``` $('#myCombo option:selected').val(''); ```
If I understand, you want to had an option in your select box with an empty value ? Like this ? ``` <select name="myCombo" id="myCombo"> <option value="">-- no value --</option> <option value="1">option5</option> <option value="2">option4</option> <option value="3">option3</option> <option value="4">Other</option> </select> ``` If yes, why do you try to do it in Javascript ? Just change HTML. If not, change your question coz you are not really clear =) thx Edit : If you cant change HTML, please specify it.
78,689
The Problem ----------- Right now, if a post is edited 10 times by its author, it will be automatically converted to CW ([Source](https://meta.stackexchange.com/questions/11740/what-are-community-wiki-posts/11741#11741)). I think that this is flawed logic, and should be removed. The Argument ------------ I'd argue that having the auto-cw feature is a deterrent to authors maintaining high quality posts. Without the edit limit, authors are have a dis-incentive to updating their posts. So you wind up in a situation where posts go out of date (and can be -1ed) because the original author didn't want to lose ownership (and rep) associated with the post. Examples -------- [This answer](https://stackoverflow.com/posts/1957830/revisions) was auto-converted to CW because the poster expanded the body a few (ok, 9) times with additional examples, references and more information. Does that make it a clear candidate for CW? I'd argue no. [This answer](https://stackoverflow.com/questions/4948322/fundamental-difference-between-hashing-and-encryption-algorithms/4948393#4948393) was not auto-converted yet. But I'm discouraged from editing more unless I really need to since I don't want to have it auto-convert... Conclusion ---------- We already have the mode where if a post is edited by 5 users it automatically becomes CW (which makes sense). Why not just leave it as that. Let the users say if it should be CW by actually contributing to the post, rather than just saying it should be because the author took the time to expand the post.
2011/02/09
[ "https://meta.stackexchange.com/questions/78689", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/147370/" ]
I disagree. The current system encourages authors to write high-quality posts the first time around, instead of slapping anything down and editing 50 times to make one typo fix each time. It is quite rare for a post to get ten really substantial edits. For the purposes of this post, I'm defining a "substantial edit" as the addition of information based on significant further research or testing of answers/comments; in other words, stuff that couldn't have been written earlier. In practice, many edits are made to fix things that wouldn't have needed fixing if the author had only put more time or thought into the post initially.
The only strong rationale I can see for caring about multiple edits on one's own post is that it could be bump abuse. Answers that talk about how many edits are or are not excessive are statements of opinion that really should not be brought to bear on how another person chooses to edit their posts. If I want to edit my post 20 times because I feel like it's making my post better, I should be able to do that without someone else second-guessing it. Unless they're second-guessing that I might be trying to get bumps out it. In my opinion, the 10 edit on own post => automatic conversion to CW is a very broken and needlessly meddlesome idea, but one which may have to stay in place if there is no better way to prevent "bump abuse."