qid
int64
1
74.7M
question
stringlengths
25
64.6k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
0
115k
response_k
stringlengths
3
61.5k
72,099,233
I have a durable function that calls a method that simply adds a row to an efcore object. It doesn't call db save. When I step through the code, and get to the for loop, it will immediately jump to the line after the for loop. If I step into the call to add the efcore object, and back to the for loop, it continues and loops to the next item. If I press F5 to let it go without debugging, it immediately "breaks" the for loop. It jumps out of the for loop where i wrote `//HERE!!!!!!` I'm pulling my hair out on this one. obligatory code: ```cs //foreach (stagingFileMap stagingFileMap in fileMaps) foreach (stagingFileMap stagingFileMap in fileMaps) { if (ActivitySyncHelper.IsSyncCancelled(aso, _configuration)) { break; } if (!string.IsNullOrEmpty(stagingFileMap.URL)) { // Ensure the url is valid try { string x = await GetTotalBytes(stagingFileMap.URL); double.TryParse(x, out double fileByteCount); if (fileByteCount > 0) { // Create or update the video in vimeo if (string.IsNullOrEmpty(stagingFileMap.VimeoId)) { // Azure won't be ready with its backups, so use confex host for video 'get' string title = stagingFileMap.FileName; if (stagingFileMap.FileName.Length > 127) { title = stagingFileMap.FileName.Substring(0, 127); } Video video = vimeoClient.UploadPullLinkAsync(stagingFileMap.URL, title, stagingFileMap.id, meetingIdFolder.Uri).Result; stagingFileMap.VimeoId = video.Id.ToString(); stagingFileMap.VimeoId = video.Id.ToString(); //HERE!!!!!! await syncLog.WriteInfoMsg($"Vimeo create {stagingFileMap.FileName}"); //HERE!!!!!! } else { // Attempt to pull the existing video and update it if (long.TryParse(stagingFileMap.VimeoId, out long videoId)) { Video video = vimeoClient.GetVideoAsync(videoId).Result; if (video.Id.HasValue) { Video res = await vimeoClient.UploadPullReplaceAsync(stagingFileMap.URL, video.Id.Value, fileByteCount); await syncLog.WriteInfoMsg($"Vimeo replace {stagingFileMap.FileName} id {res.Id}"); } } } break; } } catch (Exception ex) { // IDK what to do besides skip it and continue // log something once logging works await syncLog.WriteErrorMsg(aso, ex.Message); await syncLog.Save(); continue; } // We need to save here requently because if there is big error, all the work syncing to vimeo will be desync with the DB dbContext.Update(stagingFileMap); await dbContext.SaveChangesAsync(); await syncLog.Save(); } } await dbContext.DisposeAsync(); ``` ```cs public async Task WriteInfoMsg( string msg) { SyncAttemptDetail sad = new() { SyncAttemptId = _id, Message = msg, MsgLevel = SyncAttemptMessageLevel.Info, AddDate = DateTime.UtcNow, AddUser = "SYSTEM" }; await _dbContext.SyncAttemptDetail.AddAsync(sad); } ```
2022/05/03
[ "https://Stackoverflow.com/questions/72099233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649043/" ]
```css *{ font-family: 'Open Sans'; } body{ margin: 0px; } img{ width: 100%; } section{ position: relative; } section svg { position: absolute; left: 0; top: 0; } section .arc-overlay { position: absolute; width: 100%; left: 0; top: 0; } section .st0 { fill: transparent; } @media screen and (max-width: 768px) { .content > div{ display: block !important; } .content .cnt-1{ max-width: 100% !important; } } ``` ```html <!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400&display=swap" rel="stylesheet"> <script src="https://code.jquery.com/jquery.min.js"></script> <script src="https://demo.zhardsoft.com/arc-pattern/svg-inject.js"></script> <script type="text/javascript"> SVGInject.setOptions({ useCache: false, copyAttributes: false, makeIdsUnique: false, afterInject: function(img, svg) { var svgElm=$(svg); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }, }); $(window).on('resize',function(){ $('section svg').each(function(){ var svgElm=$(this); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }) }) </script> </head> <body> <section style="min-height: 500px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2733014.jpg);background-size: 100% auto;"> <div class="content" style="padding: 40px;padding-bottom: 150px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%"> <div style="padding: 20px"><img src="https://demo.zhardsoft.com/arc-pattern/img1.png" style="width: 250px"></div> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%"> <h1>ECOLOGICAL PRODUCTION</h1> We recycle all organic waste we produce, also, we obtain organic waste from other farms, restaurants, and food markets. The organic waste we collect allows a particular larva from the Hermetia illucens species, known commonly as black soldier fly larva (BSFL), to feeds on it and grow fatter. When the larva has developed to a pupa, it is cleaned, cooked and grided to a paste used as a high-quality protein and lipids perfectly suited as ecological animal feed, reducing the need for wild-sourced feed ingredients such as fishmeal which contributes to the global overfishing.</div> </div> </div> </section> <section style="min-height: 300px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;padding: 0 40px"> <div class="content" style="padding: 20px;padding-bottom: 40px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%;justify-content: flex-end;"> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%;text-align: right;flex-grow: 1"> <h1 style="color: #FDC403">LOCAL COMMUNITY<br>ENGAGEMENT.</h1> It is in our core believe that if you benefit the local community, the people there will add value to your business as well. For every site we establish a manufacturing facility, our project will add value to the community as whole. We will provide jobs for hundreds of local residents with positions available within our production, sales, administration, and management teams. We will also offer hundreds of local farmers opportunities to join our supply network, providing training, coaching, and financial support to help them adapt to a more intensive and efficient farming system. Through our research and development, anything learned or discovered will be shared with our farmers to produce more efficiently and a healthier product. One among many different local benefitting activities, is that we will arrange cleanup days where we offer students an extra income for their effort as well as courses in environment know-how and teach them the importance of keeping the environment healthy. </div> </div> <div class="arc-overlay" style="background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;-webkit-mask: url('https://demo.zhardsoft.com/arc-pattern/arc.svg') top/100% auto no-repeat"></div> <img src="https://demo.zhardsoft.com/arc-pattern/arc.svg" onload="SVGInject(this);"/> </section> </body> </html> ``` **For SVG** Add a path under the arc in your SVG, to cover the bottom of the pattern. This is used to manipulate the background to match the pattern below it. for the above pattern no additional path is needed <https://i.stack.imgur.com/qxsWV.png> the class name (path) in the SVG file must match the css style (.st0) you can change it with the class name you want. <https://i.stack.imgur.com/dhLa1.png>
\*\* I'm Can Solving Your Problem But I want to have the svg so that I know how to make a clip path for it, so I want you to send it to me, and this is the solution. You want it to be dynamic, but first I have to have my svg and thank you ```css section { position: relative; } .arc { width: 100%; position: relative; height: 200px; } .arc::after { content: url(arc1.svg); position: absolute; left: 50%; transform: translateX(-50%) rotate(130deg); bottom: 0; } ``` ```html <div class="container"> <section style="background:black;"> Content goes here... </section> <div class="arc"></div> <section style="background:grey"> Content goes here... </section> <div class="arc"></div> </div> ``` \*\*
72,099,233
I have a durable function that calls a method that simply adds a row to an efcore object. It doesn't call db save. When I step through the code, and get to the for loop, it will immediately jump to the line after the for loop. If I step into the call to add the efcore object, and back to the for loop, it continues and loops to the next item. If I press F5 to let it go without debugging, it immediately "breaks" the for loop. It jumps out of the for loop where i wrote `//HERE!!!!!!` I'm pulling my hair out on this one. obligatory code: ```cs //foreach (stagingFileMap stagingFileMap in fileMaps) foreach (stagingFileMap stagingFileMap in fileMaps) { if (ActivitySyncHelper.IsSyncCancelled(aso, _configuration)) { break; } if (!string.IsNullOrEmpty(stagingFileMap.URL)) { // Ensure the url is valid try { string x = await GetTotalBytes(stagingFileMap.URL); double.TryParse(x, out double fileByteCount); if (fileByteCount > 0) { // Create or update the video in vimeo if (string.IsNullOrEmpty(stagingFileMap.VimeoId)) { // Azure won't be ready with its backups, so use confex host for video 'get' string title = stagingFileMap.FileName; if (stagingFileMap.FileName.Length > 127) { title = stagingFileMap.FileName.Substring(0, 127); } Video video = vimeoClient.UploadPullLinkAsync(stagingFileMap.URL, title, stagingFileMap.id, meetingIdFolder.Uri).Result; stagingFileMap.VimeoId = video.Id.ToString(); stagingFileMap.VimeoId = video.Id.ToString(); //HERE!!!!!! await syncLog.WriteInfoMsg($"Vimeo create {stagingFileMap.FileName}"); //HERE!!!!!! } else { // Attempt to pull the existing video and update it if (long.TryParse(stagingFileMap.VimeoId, out long videoId)) { Video video = vimeoClient.GetVideoAsync(videoId).Result; if (video.Id.HasValue) { Video res = await vimeoClient.UploadPullReplaceAsync(stagingFileMap.URL, video.Id.Value, fileByteCount); await syncLog.WriteInfoMsg($"Vimeo replace {stagingFileMap.FileName} id {res.Id}"); } } } break; } } catch (Exception ex) { // IDK what to do besides skip it and continue // log something once logging works await syncLog.WriteErrorMsg(aso, ex.Message); await syncLog.Save(); continue; } // We need to save here requently because if there is big error, all the work syncing to vimeo will be desync with the DB dbContext.Update(stagingFileMap); await dbContext.SaveChangesAsync(); await syncLog.Save(); } } await dbContext.DisposeAsync(); ``` ```cs public async Task WriteInfoMsg( string msg) { SyncAttemptDetail sad = new() { SyncAttemptId = _id, Message = msg, MsgLevel = SyncAttemptMessageLevel.Info, AddDate = DateTime.UtcNow, AddUser = "SYSTEM" }; await _dbContext.SyncAttemptDetail.AddAsync(sad); } ```
2022/05/03
[ "https://Stackoverflow.com/questions/72099233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649043/" ]
You can use [clip-path](https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path) to clip elements (section) in some shape. I created a **rough example** just to show how it could work: ```css section { position: relative; } section > div { min-height: 600px; } section:not(:last-of-type) > div { clip-path: ellipse(125% 70% at 20% 0%); } section + section { margin-top: -50%; } .red { background-color: red; } .blue { background-color: blue; } section:not(:last-of-type):before { content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' version='1.2' viewBox='0 0 393 86'%3E%3Cpath fill='red' d='M-12 63s61-18.9 85-12c24 6.9 110 18.1 143 8C249 48.9 408-5 408-5v29S240.3 79.7 213 82C84 93-6 72.9-6 72.9z'/%3E%3C/svg%3E"); position: absolute; top: 50%; left: 0; right: 0; z-index: 500; } ``` ```html <section style="z-index: 3"> <div style="background: black;"> Content goes here... </div> </section> <section style="z-index: 2"> <div style="background: gray;"> Content goes here... </div> </section> <section style="z-index: 1"> <div style="background: lightgray;"> Content goes here... </div> </section> ``` You can use online clip-path generators like [Clippy](https://bennettfeely.com/clippy/) to create custom shape.
``` <body> <!-- Main Section Start--> <div class="wrapper"> <section class="header-img"> <img src="images/header-img.png" alt="header-image" title="header-image"> </section> <section class="pattern_1 pattern"> <div class="container"> <div class="row"> <div class="col-sm-12 margin-b"> <h1>We Are Using</h1> <p>High-tech and artificial intelligence (AI) To produce ecological food.</p> </div> <div class="col-sm-6 text-center"> <img src="images/about-img.png" alt="about-img" title="about-img"> </div> <div class="col-sm-6"> <h2>About Us</h2> <p> Pete’s Claws and Fins is a high-tech producer of ecological seafood. We use state-of-the-art, highly computerized equipment to monitor and manage our seafood to ensure it is of the highest possible quality. All equipment we use is developed by ourselves in-house. We are the only company operating such high-tech equipment. The company started its research and development 2016 by Peter Persson, a Swedish inventor who has designed and built automated and computer-controlled machines and robots for over 30 years. Peter has over the years developed an increasing personal interest for natural and unprocessed food, and though he could make difference with help of his high-tech knowhow. </p> </div> </div> </div> <img class="about-divider" src="images/about-bottom-img.png"/> </section> <section class="pattern_2 pattern"> <div class="container"> <div class="row margin-b"> <div class="col-sm-6"> <h2>Ecological Production</h2> <p> Pete’s Claws and Fins is a high-tech producer of ecological seafood. We use state-of-the-art, highly computerized equipment to monitor and manage our seafood to ensure it is of the highest possible quality. All equipment we use is developed by ourselves in-house. We are the only company operating such high-tech equipment. The company started its research and development 2016 by Peter Persson, a Swedish inventor who has designed and built automated and computer-controlled machines and robots for over 30 years. Peter has over the years developed an increasing personal interest for natural and unprocessed food, and though he could make difference with help of his high-tech knowhow. </p> </div> <div class="col-sm-6 text-center pattern-2img"> <img src="images/about-img-02.png" alt="about-img" title="about-img"> </div> </div> <div class="row"> <div class="col-sm-5 text-center"> <img src="images/about-img-03.png" alt="about-img" title="about-img"> </div> <div class="col-sm-7"> <p> Pete’s Claws and Fins is a high-tech producer of ecological seafood. We use state-of-the-art, highly computerized equipment to monitor and manage our seafood to ensure it is of the highest possible quality. All equipment we use is developed by ourselves in-house. We are the only company operating such high-tech equipment. The company started its research and development 2016 by Peter Persson, a Swedish inventor who has designed and built automated and computer-controlled machines and robots for over 30 years. Peter has over the years developed an increasing personal interest for natural and unprocessed food, and though he could make difference with help of his high-tech knowhow. </p> </div> </div> </div> <img class="about-divider" src="images/ecology-bottom-img.png"/> </section> <section class="pattern_3 pattern"> <div class="container"> <div class="row margin-b"> <div class="col-sm-8 pull-right text-r"> <h2>Local Community Engagement.</h2> <p> Pete’s Claws and Fins is a high-tech producer of ecological seafood. We use state-of-the-art, highly computerized equipment to monitor and manage our seafood to ensure it is of the highest possible quality. All equipment we use is developed by ourselves in-house. We are the only company operating such high-tech equipment. The company started its research and development 2016 by Peter Persson, a Swedish inventor who has designed and built automated and computer-controlled machines and robots for over 30 years. Peter has over the years developed an increasing personal interest for natural and unprocessed food, and though he could make difference with help of his high-tech knowhow. </p> </div> </div> </div> </section> <section class="foote-img"> <img class="circle-img" src="images/circle-img.png"/> <img src="images/footer-img.png" alt="footer-img" title="footer-img"> </section> </div> <!--/Main Section End--> </body> ```
72,099,233
I have a durable function that calls a method that simply adds a row to an efcore object. It doesn't call db save. When I step through the code, and get to the for loop, it will immediately jump to the line after the for loop. If I step into the call to add the efcore object, and back to the for loop, it continues and loops to the next item. If I press F5 to let it go without debugging, it immediately "breaks" the for loop. It jumps out of the for loop where i wrote `//HERE!!!!!!` I'm pulling my hair out on this one. obligatory code: ```cs //foreach (stagingFileMap stagingFileMap in fileMaps) foreach (stagingFileMap stagingFileMap in fileMaps) { if (ActivitySyncHelper.IsSyncCancelled(aso, _configuration)) { break; } if (!string.IsNullOrEmpty(stagingFileMap.URL)) { // Ensure the url is valid try { string x = await GetTotalBytes(stagingFileMap.URL); double.TryParse(x, out double fileByteCount); if (fileByteCount > 0) { // Create or update the video in vimeo if (string.IsNullOrEmpty(stagingFileMap.VimeoId)) { // Azure won't be ready with its backups, so use confex host for video 'get' string title = stagingFileMap.FileName; if (stagingFileMap.FileName.Length > 127) { title = stagingFileMap.FileName.Substring(0, 127); } Video video = vimeoClient.UploadPullLinkAsync(stagingFileMap.URL, title, stagingFileMap.id, meetingIdFolder.Uri).Result; stagingFileMap.VimeoId = video.Id.ToString(); stagingFileMap.VimeoId = video.Id.ToString(); //HERE!!!!!! await syncLog.WriteInfoMsg($"Vimeo create {stagingFileMap.FileName}"); //HERE!!!!!! } else { // Attempt to pull the existing video and update it if (long.TryParse(stagingFileMap.VimeoId, out long videoId)) { Video video = vimeoClient.GetVideoAsync(videoId).Result; if (video.Id.HasValue) { Video res = await vimeoClient.UploadPullReplaceAsync(stagingFileMap.URL, video.Id.Value, fileByteCount); await syncLog.WriteInfoMsg($"Vimeo replace {stagingFileMap.FileName} id {res.Id}"); } } } break; } } catch (Exception ex) { // IDK what to do besides skip it and continue // log something once logging works await syncLog.WriteErrorMsg(aso, ex.Message); await syncLog.Save(); continue; } // We need to save here requently because if there is big error, all the work syncing to vimeo will be desync with the DB dbContext.Update(stagingFileMap); await dbContext.SaveChangesAsync(); await syncLog.Save(); } } await dbContext.DisposeAsync(); ``` ```cs public async Task WriteInfoMsg( string msg) { SyncAttemptDetail sad = new() { SyncAttemptId = _id, Message = msg, MsgLevel = SyncAttemptMessageLevel.Info, AddDate = DateTime.UtcNow, AddUser = "SYSTEM" }; await _dbContext.SyncAttemptDetail.AddAsync(sad); } ```
2022/05/03
[ "https://Stackoverflow.com/questions/72099233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649043/" ]
```css *{ font-family: 'Open Sans'; } body{ margin: 0px; } img{ width: 100%; } section{ position: relative; } section svg { position: absolute; left: 0; top: 0; } section .arc-overlay { position: absolute; width: 100%; left: 0; top: 0; } section .st0 { fill: transparent; } @media screen and (max-width: 768px) { .content > div{ display: block !important; } .content .cnt-1{ max-width: 100% !important; } } ``` ```html <!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400&display=swap" rel="stylesheet"> <script src="https://code.jquery.com/jquery.min.js"></script> <script src="https://demo.zhardsoft.com/arc-pattern/svg-inject.js"></script> <script type="text/javascript"> SVGInject.setOptions({ useCache: false, copyAttributes: false, makeIdsUnique: false, afterInject: function(img, svg) { var svgElm=$(svg); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }, }); $(window).on('resize',function(){ $('section svg').each(function(){ var svgElm=$(this); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }) }) </script> </head> <body> <section style="min-height: 500px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2733014.jpg);background-size: 100% auto;"> <div class="content" style="padding: 40px;padding-bottom: 150px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%"> <div style="padding: 20px"><img src="https://demo.zhardsoft.com/arc-pattern/img1.png" style="width: 250px"></div> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%"> <h1>ECOLOGICAL PRODUCTION</h1> We recycle all organic waste we produce, also, we obtain organic waste from other farms, restaurants, and food markets. The organic waste we collect allows a particular larva from the Hermetia illucens species, known commonly as black soldier fly larva (BSFL), to feeds on it and grow fatter. When the larva has developed to a pupa, it is cleaned, cooked and grided to a paste used as a high-quality protein and lipids perfectly suited as ecological animal feed, reducing the need for wild-sourced feed ingredients such as fishmeal which contributes to the global overfishing.</div> </div> </div> </section> <section style="min-height: 300px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;padding: 0 40px"> <div class="content" style="padding: 20px;padding-bottom: 40px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%;justify-content: flex-end;"> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%;text-align: right;flex-grow: 1"> <h1 style="color: #FDC403">LOCAL COMMUNITY<br>ENGAGEMENT.</h1> It is in our core believe that if you benefit the local community, the people there will add value to your business as well. For every site we establish a manufacturing facility, our project will add value to the community as whole. We will provide jobs for hundreds of local residents with positions available within our production, sales, administration, and management teams. We will also offer hundreds of local farmers opportunities to join our supply network, providing training, coaching, and financial support to help them adapt to a more intensive and efficient farming system. Through our research and development, anything learned or discovered will be shared with our farmers to produce more efficiently and a healthier product. One among many different local benefitting activities, is that we will arrange cleanup days where we offer students an extra income for their effort as well as courses in environment know-how and teach them the importance of keeping the environment healthy. </div> </div> <div class="arc-overlay" style="background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;-webkit-mask: url('https://demo.zhardsoft.com/arc-pattern/arc.svg') top/100% auto no-repeat"></div> <img src="https://demo.zhardsoft.com/arc-pattern/arc.svg" onload="SVGInject(this);"/> </section> </body> </html> ``` **For SVG** Add a path under the arc in your SVG, to cover the bottom of the pattern. This is used to manipulate the background to match the pattern below it. for the above pattern no additional path is needed <https://i.stack.imgur.com/qxsWV.png> the class name (path) in the SVG file must match the css style (.st0) you can change it with the class name you want. <https://i.stack.imgur.com/dhLa1.png>
``` body{ background-image: url(bg.png); background-size: contain; background-position: bottom; margin: 0; padding: 0; } .logo{ position: absolute; left: 100px; top: 100px; z-index: 999; } .bg-1, .bg-2, .bg-3{ padding: 100px 0; background-repeat: no-repeat; background-size: cover; background-position: bottom; width: 100%; height: auto; } .bg-1{ background-image: url(bg-111.png); padding-top: 0; z-index: 50; } .bg-1 .title{ color: #ffc602; font-size: 77px; margin-bottom: 50px: } .bg-1 .sub-title{ color: #fff; font-size: 34px; margin-bottom: 70px; } .bg-2 .food{ position: absolute; right: 0; bottom: 0px; z-index: 200; } .bg-3 .food{ position: absolute; left: 0; bottom: -25px; z-index: 200; } .about h2 { color: #ffc602; font-size: 55px; margin-bottom: 50px: } .about p { color: #fff; font-size: 15px; line-height: 1.8; margin-bottom: 50px: } #section_2 .title, #section_3 .title{ font-size: 55px; margin-bottom: 30px; } .article-1{ padding: 100px; z-index: 10; } section{ position: relative; } #section_2{ margin-top: -450px } #section_2 .section-2-outer{ position: relative; width: 100%; height: auto; } .section-2-inner-content{ margin-left: auto; margin-right: 2%; } #arc-2{ position: absolute; bottom: -120px; left: 0; z-index: 100; } #arc_3{ position: absolute; bottom: -110px; left: 0; z-index: 100; } ```
72,099,233
I have a durable function that calls a method that simply adds a row to an efcore object. It doesn't call db save. When I step through the code, and get to the for loop, it will immediately jump to the line after the for loop. If I step into the call to add the efcore object, and back to the for loop, it continues and loops to the next item. If I press F5 to let it go without debugging, it immediately "breaks" the for loop. It jumps out of the for loop where i wrote `//HERE!!!!!!` I'm pulling my hair out on this one. obligatory code: ```cs //foreach (stagingFileMap stagingFileMap in fileMaps) foreach (stagingFileMap stagingFileMap in fileMaps) { if (ActivitySyncHelper.IsSyncCancelled(aso, _configuration)) { break; } if (!string.IsNullOrEmpty(stagingFileMap.URL)) { // Ensure the url is valid try { string x = await GetTotalBytes(stagingFileMap.URL); double.TryParse(x, out double fileByteCount); if (fileByteCount > 0) { // Create or update the video in vimeo if (string.IsNullOrEmpty(stagingFileMap.VimeoId)) { // Azure won't be ready with its backups, so use confex host for video 'get' string title = stagingFileMap.FileName; if (stagingFileMap.FileName.Length > 127) { title = stagingFileMap.FileName.Substring(0, 127); } Video video = vimeoClient.UploadPullLinkAsync(stagingFileMap.URL, title, stagingFileMap.id, meetingIdFolder.Uri).Result; stagingFileMap.VimeoId = video.Id.ToString(); stagingFileMap.VimeoId = video.Id.ToString(); //HERE!!!!!! await syncLog.WriteInfoMsg($"Vimeo create {stagingFileMap.FileName}"); //HERE!!!!!! } else { // Attempt to pull the existing video and update it if (long.TryParse(stagingFileMap.VimeoId, out long videoId)) { Video video = vimeoClient.GetVideoAsync(videoId).Result; if (video.Id.HasValue) { Video res = await vimeoClient.UploadPullReplaceAsync(stagingFileMap.URL, video.Id.Value, fileByteCount); await syncLog.WriteInfoMsg($"Vimeo replace {stagingFileMap.FileName} id {res.Id}"); } } } break; } } catch (Exception ex) { // IDK what to do besides skip it and continue // log something once logging works await syncLog.WriteErrorMsg(aso, ex.Message); await syncLog.Save(); continue; } // We need to save here requently because if there is big error, all the work syncing to vimeo will be desync with the DB dbContext.Update(stagingFileMap); await dbContext.SaveChangesAsync(); await syncLog.Save(); } } await dbContext.DisposeAsync(); ``` ```cs public async Task WriteInfoMsg( string msg) { SyncAttemptDetail sad = new() { SyncAttemptId = _id, Message = msg, MsgLevel = SyncAttemptMessageLevel.Info, AddDate = DateTime.UtcNow, AddUser = "SYSTEM" }; await _dbContext.SyncAttemptDetail.AddAsync(sad); } ```
2022/05/03
[ "https://Stackoverflow.com/questions/72099233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649043/" ]
```css *{ font-family: 'Open Sans'; } body{ margin: 0px; } img{ width: 100%; } section{ position: relative; } section svg { position: absolute; left: 0; top: 0; } section .arc-overlay { position: absolute; width: 100%; left: 0; top: 0; } section .st0 { fill: transparent; } @media screen and (max-width: 768px) { .content > div{ display: block !important; } .content .cnt-1{ max-width: 100% !important; } } ``` ```html <!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400&display=swap" rel="stylesheet"> <script src="https://code.jquery.com/jquery.min.js"></script> <script src="https://demo.zhardsoft.com/arc-pattern/svg-inject.js"></script> <script type="text/javascript"> SVGInject.setOptions({ useCache: false, copyAttributes: false, makeIdsUnique: false, afterInject: function(img, svg) { var svgElm=$(svg); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }, }); $(window).on('resize',function(){ $('section svg').each(function(){ var svgElm=$(this); var svgHeight=svgElm.height(); svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); }) }) </script> </head> <body> <section style="min-height: 500px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2733014.jpg);background-size: 100% auto;"> <div class="content" style="padding: 40px;padding-bottom: 150px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%"> <div style="padding: 20px"><img src="https://demo.zhardsoft.com/arc-pattern/img1.png" style="width: 250px"></div> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%"> <h1>ECOLOGICAL PRODUCTION</h1> We recycle all organic waste we produce, also, we obtain organic waste from other farms, restaurants, and food markets. The organic waste we collect allows a particular larva from the Hermetia illucens species, known commonly as black soldier fly larva (BSFL), to feeds on it and grow fatter. When the larva has developed to a pupa, it is cleaned, cooked and grided to a paste used as a high-quality protein and lipids perfectly suited as ecological animal feed, reducing the need for wild-sourced feed ingredients such as fishmeal which contributes to the global overfishing.</div> </div> </div> </section> <section style="min-height: 300px;background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;padding: 0 40px"> <div class="content" style="padding: 20px;padding-bottom: 40px"> <div style="display: flex;display: -inline-flex;display: -webkit-flex;width: 100%;justify-content: flex-end;"> <div class="cnt-1" style="color: #EBEBEB;max-width: 50%;text-align: right;flex-grow: 1"> <h1 style="color: #FDC403">LOCAL COMMUNITY<br>ENGAGEMENT.</h1> It is in our core believe that if you benefit the local community, the people there will add value to your business as well. For every site we establish a manufacturing facility, our project will add value to the community as whole. We will provide jobs for hundreds of local residents with positions available within our production, sales, administration, and management teams. We will also offer hundreds of local farmers opportunities to join our supply network, providing training, coaching, and financial support to help them adapt to a more intensive and efficient farming system. Through our research and development, anything learned or discovered will be shared with our farmers to produce more efficiently and a healthier product. One among many different local benefitting activities, is that we will arrange cleanup days where we offer students an extra income for their effort as well as courses in environment know-how and teach them the importance of keeping the environment healthy. </div> </div> <div class="arc-overlay" style="background-image: url(https://demo.zhardsoft.com/arc-pattern/wp2732984.jpg);background-size: 100% auto;-webkit-mask: url('https://demo.zhardsoft.com/arc-pattern/arc.svg') top/100% auto no-repeat"></div> <img src="https://demo.zhardsoft.com/arc-pattern/arc.svg" onload="SVGInject(this);"/> </section> </body> </html> ``` **For SVG** Add a path under the arc in your SVG, to cover the bottom of the pattern. This is used to manipulate the background to match the pattern below it. for the above pattern no additional path is needed <https://i.stack.imgur.com/qxsWV.png> the class name (path) in the SVG file must match the css style (.st0) you can change it with the class name you want. <https://i.stack.imgur.com/dhLa1.png>
```css *{ font-family: 'Open Sans'; } body{ margin: 0px; } img{ width: 100%; } section{ position: relative; } section svg { position: absolute; left: 0; top: 0; } section .content{ position: absolute; left: 0; top: 0px; z-index: 1; } section .top-clip { position: absolute; width: 100%; left: 0; top: 0; } section { /*background-size: 100% auto;*/ } section #pattern_top { fill: transparent; } section #pattern_bottom { fill: transparent; } .pattern-prev-clip,.pattern-bottom-clip{ /*background-size: 100% auto;*/ } @media screen and (max-width: 768px) { .content > div{ display: block !important; } .content .cnt-1{ max-width: 100% !important; } } ``` ```html <!doctype html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300;400&display=swap" rel="stylesheet"> <script src="https://code.jquery.com/jquery.min.js"></script> <script src="https://demo.zhardsoft.com/arc-pattern-3/svg-inject.js"></script> <script type="text/javascript"> var svgInjectElements=[]; var tt=0; SVGInject.setOptions({ useCache: false, // no caching copyAttributes: false, // do not copy attributes from `<img>` to `<svg>` makeIdsUnique: false, // do not make ids used within the SVG unique afterInject: function(img, svg) { svgInjectElements[parseInt($(img).attr('img-arc'))]=svg; if(tt > $('.img-arc').length){ svgInjectElements.forEach(function(svg){ loadSVGInject(svg); }) } tt++; }, }); function loadSVGInject(svg){ var svgElm=$(svg); var parentSection=svgElm.parents('.section'); var prevSection=svgElm.parents('.section').prev(); // svgElm.parents('section').find('svg #pattern_bottom').wrap('<defs></defs>').wrap('<clipPath id="my-clip" clipPathUnits="objectBoundingBox"></clipPath>'); var clipID=parentSection.attr('data-clip-id'); var prevClipID=prevSection.attr('data-clip-id'); parentSection.find('svg #pattern_bottom_clip').attr('id','pattern_bottom_clip_'+clipID); parentSection.find('svg #pattern_top_clip').attr('id','pattern_top_clip_'+clipID); var svgHeight=svgElm.height(); parentSection.css({'background-position-y':'-'+svgHeight+'px'}); parentSection.find('svg').css({'top':'-'+(svgHeight-1)+'px',}); if(prevSection.find('.pattern-prev-clip').length<=0){ parentSection.find('svg #pattern_top').attr('transform','scale('+(1/svgElm[0].viewBox.baseVal.width)+','+(1/svgElm[0].viewBox.baseVal.height)+')'); var bgPrev=prevSection.css('background-image'); var patternPrevClip=document.createElement('div'); $(patternPrevClip).addClass('pattern-prev-clip').css({'-webkit-clip-path': 'url(#pattern_top_clip_'+clipID+')','clip-path': 'url(#pattern_top_clip_'+clipID+')'}); // $(patternPrevClip).addClass('pattern-prev-clip').css('background-image', bgPrev); prevSection.append(patternPrevClip); var blockContent=document.createElement('div'); $(blockContent).addClass('block-content'); $(patternPrevClip).before(blockContent); } var baseHeight=svgElm.height()/svgElm[0].viewBox.baseVal.height; // console.log(svgElm.height()+" - "+svgElm[0].viewBox.baseVal.height); var ppcHeightTop=parseInt(parentSection.find('svg #pattern_top')[0].getAttribute('height'))*baseHeight; var ppcHeightBottom=parseInt(parentSection.find('svg #pattern_bottom')[0].getAttribute('height'))*baseHeight; if(prevSection.find('svg').length>0){ var basePrevHeight=prevSection.find('svg').height()/prevSection.find('svg')[0].viewBox.baseVal.height; var ppcPrevHeightBottom=parseInt(prevSection.find('svg #pattern_bottom')[0].getAttribute('height'))*basePrevHeight; } // parentSection.css({'top':(svgElm.height()-ppcHeightTop)+'px'}); prevSection.find('.pattern-prev-clip').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}).attr('height',svgHeight); if(parentSection.find('.pattern-bottom-clip').length<=0){ parentSection.find('svg #pattern_bottom').attr('transform','scale('+(1/svgElm[0].viewBox.baseVal.width)+','+(1/svgElm[0].viewBox.baseVal.height)+')'); var bg=parentSection.css('background-image'); var patternTopClip=document.createElement('div'); $(patternTopClip).addClass('top-clip pattern-bottom-clip').css({'background-image': bg,'-webkit-clip-path': 'url(#pattern_bottom_clip_'+clipID+')','clip-path': 'url(#pattern_bottom_clip_'+clipID+')'}); svgElm.before(patternTopClip); } parentSection.find('.pattern-bottom-clip').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}).attr('height',svgHeight); // console.log("prev section id: "+(ppcPrevHeightBottom ?? 0)); // console.log(((svgElm.height()-ppcHeightTop) + prevSection.find('.pattern-prev-clip').height())); // prevSection.find('.content').css('min-height',prevSection.height() - ((svgElm.height()-ppcHeightTop)) ); // // prevSection.css('min-height', (prevSection.find('.pattern-prev-clip').height() + prevSection.find('.content').outerHeight()) - (ppcPrevHeightBottom ?? 0) ); var prevBlockContentHeight=(prevSection.find('.content').outerHeight() - ppcHeightTop) - (ppcPrevHeightBottom ?? 0); // prevBlockContentHeight=prevBlockContentHeight>200?prevBlockContentHeight:200; prevSection.find('.block-content').css('height', prevBlockContentHeight).attr('height',prevBlockContentHeight); parentSection.find('.content').css('top','-'+ppcHeightBottom+'px'); // parentSection.find('.pattern-bottom-clip').css('background-size','auto '+parentSection.find('.pattern-prev-clip').attr('height')+'px'); // console.log(prevSection.find('.pattern-prev-clip').css('height')); // prevSection.find('.pattern-bottom-clip').css('background-size','auto '+(parseFloat(prevSection.find('.pattern-prev-clip').attr('height')) + parseFloat(prevSection.find('.block-content').attr('height')) )+'px'); var bgPrevHeight=( parseFloat(prevSection.find('.pattern-prev-clip').attr('height')) + parseFloat(prevSection.find('.block-content').attr('height')) + parseFloat( (prevSection.find('.pattern-bottom-clip').attr('height') ?? 0) ) ); prevSection.css({'background-size':'auto '+ bgPrevHeight +'px'}); prevSection.find('.pattern-bottom-clip').css('background-size','auto '+ bgPrevHeight +'px'); if($('.section').last().attr('data-clip-id') == clipID){ if(parentSection.find('.block-content').length<=0){ var blockContent=document.createElement('div'); $(blockContent).addClass('block-content'); parentSection.append(blockContent); } var lastBlockContent=(parentSection.find('.content').outerHeight() - ppcHeightBottom); lastBlockContent=(lastBlockContent > 0 ? lastBlockContent : 100); parentSection.find('.block-content').css('min-height', lastBlockContent ).attr('height',lastBlockContent); var bgHeight=( parseFloat(parentSection.find('.block-content').attr('height')) + parseFloat(parentSection.find('.pattern-bottom-clip').attr('height')) ); parentSection.css({'background-size':'auto '+ bgHeight +'px'}); parentSection.find('.pattern-bottom-clip').css('background-size','auto '+ bgHeight +'px'); } // prevSection.css('min-height',prevSection.height()-(svgElm.height()-ppcHeightTop)); var prevSvgHeight=prevSection.find('svg').height(); if(prevSection.find('.pattern-bottom-clip').nextAll('.pattern-prev-clip').length>0){ $(patternPrevClip).css('background-position-y', '-'+prevSvgHeight+'px'); }else{ $(patternPrevClip).addClass('pattern-prev-clip').css('background-position-y', '-'+prevSection.find('.content').innerHeight()+'px'); } } $(document).ready(function(){ $('.img-arc').each(function(){ SVGInject(this); }) }) $(window).on('resize',function(){ svgInjectElements.forEach(function(svg){ loadSVGInject(svg); }) // $('section svg').each(function(){ // var svgElm=$(this); // var svgHeight=svgElm.height(); // svgElm.parents('section').css({'background-position-y':'-'+svgHeight+'px'}); // svgElm.parents('section').find('.arc-overlay').css({'height':svgHeight+'px','top':'-'+(svgHeight-1)+'px'}); // svgElm.parents('section').find('svg').css({'top':'-'+(svgHeight-1)+'px',}); // }) }) </script> </head> <body> <section class="section" data-clip-id="1" style="background-image: url(https://demo.zhardsoft.com/arc-pattern-3/pattern_bg1.jpg);"> <div class="content"> <div style="padding: 0 40px;padding-top: 50px"> <div class="cnt-1" style="color: #EBEBEB;padding: 0 40px;"> <h1>ECOLOGICAL PRODUCTION</h1> <div style="padding: 20px;float: right"><img src="https://demo.zhardsoft.com/arc-pattern-3/img1.png" style="max-width: 300px"></div> We recycle all organic waste we produce, also, we obtain organic waste from other farms, restaurants, and food markets. The organic waste we collect allows a particular larva from the Hermetia illucens species, known commonly as black soldier fly larva (BSFL), to feeds on it and grow fatter. When the larva has developed to a pupa, it is cleaned, cooked and grided to a paste used as a high-quality protein and lipids perfectly suited as ecological animal feed, reducing the need for wild-sourced feed ingredients such as fishmeal which contributes to the global overfishing.</div> </div> <div style="padding: 0 40px;padding-top: 50px"> <div class="cnt-1" style="color: #EBEBEB;padding: 0 40px;"> <div style="padding: 20px;float: left"><img src="https://demo.zhardsoft.com/arc-pattern-3/img1.png" style="max-width: 500px"></div> We recycle all organic waste we produce, also, we obtain organic waste from other farms, restaurants, and food markets. The organic waste we collect allows a particular larva from the Hermetia illucens species, known commonly as black soldier fly larva (BSFL), to feeds on it and grow fatter. When the larva has developed to a pupa, it is cleaned, cooked and grided to a paste used as a high-quality protein and lipids perfectly suited as ecological animal feed, reducing the need for wild-sourced feed ingredients such as fishmeal which contributes to the global overfishing.</div> </div> </div> </section> <section class="section" data-clip-id="2" style="background-image: url(https://demo.zhardsoft.com/arc-pattern-3/pattern_bg2.jpg);"> <div class="content"> <div style="padding: 0 40px;padding-bottom: 60px"> <div class="cnt-1" style="color: #EBEBEB;text-align: right;flex-grow: 1"> <h1 style="color: #FDC403">LOCAL COMMUNITY<br>ENGAGEMENT.</h1> It is in our core believe that if you benefit the local community, the people there will add value to your business as well. For every site we establish a manufacturing facility, our project will add value to the community as whole. We will provide jobs for hundreds of local residents with positions available within our production, sales, administration, and management teams. We will also offer hundreds of local farmers opportunities to join our supply network, providing training, coaching, and financial support to help them adapt to a more intensive and efficient farming system. Through our research and development, anything learned or discovered will be shared with our farmers to produce more efficiently and a healthier product. One among many different local benefitting activities, is that we will arrange cleanup days where we offer students an extra income for their effort as well as courses in environment know-how and teach them the importance of keeping the environment healthy. </div> </div> </div> <!-- <img src="arc_1.svg" onload="SVGInject(this);"/> --> <img img-arc="1" class="img-arc" src="https://demo.zhardsoft.com/arc-pattern-3/arc_1.svg"/> </section> <section class="section" data-clip-id="3" style="background-image: url(https://demo.zhardsoft.com/arc-pattern-3/pattern_bg3.jpg);"> <div class="content"> <div style="padding: 0 40px;padding-top: 50px"> <div class="cnt-1" style="color: #EBEBEB;text-align: center;flex-grow: 1"> <h1 style="color: #FDC403">LOCAL COMMUNITY<br>ENGAGEMENT. 2</h1> It is in our core believe that if you benefit the local community, the people there will add value to your business as well. For every site we establish a manufacturing facility, our project will add value to the community as whole. We will provide jobs for hundreds of local residents with positions available within our production, sales, administration, and management teams. We will also offer hundreds of local farmers opportunities to join our supply network, providing training, coaching, and financial support to help them adapt to a more intensive and efficient farming system. Through our research and development, anything learned or discovered will be shared with our farmers to produce more efficiently and a healthier product. One among many different local benefitting activities, is that we will arrange cleanup days where we offer students an extra income for their effort as well as courses in environment know-how and teach them the importance of keeping the environment healthy. <img src="https://demo.zhardsoft.com/arc-pattern-3/img1.png" style="max-width: 400px"> </div> </div> </div> <img img-arc="2" class="img-arc" src="https://demo.zhardsoft.com/arc-pattern-3/arc_2.svg"/> </section> <section class="section" data-clip-id="4" style="background-image: url(https://demo.zhardsoft.com/arc-pattern-3/pattern_bg4.jpg);"> <div class="content"> <div style="padding: 0 40px;padding-top: 50px"> <div class="cnt-1" style="color: #EBEBEB;text-align: left;"> <p><h1 style="color: #FDC403">LOCAL COMMUNITY<br/>ENGAGEMENT. 3</h1> <img src="https://demo.zhardsoft.com/arc-pattern-3/img1.png" style="float: right;max-width: 500px;padding: 0 40px"> It is in our core believe that if you benefit the local community, the people there will add value to your business as well. For every site we establish a manufacturing facility, our project will add value to the community as whole. We will provide jobs for hundreds of local residents with positions available within our production, sales, administration, and management teams. We will also offer hundreds of local farmers opportunities to join our supply network, providing training, coaching, and financial support to help them adapt to a more intensive and efficient farming system. Through our research and development, anything learned or discovered will be shared with our farmers to produce more efficiently and a healthier product. One among many different local benefitting activities, is that we will arrange cleanup days where we offer students an extra income for their effort as well as courses in environment know-how and teach them the importance of keeping the environment healthy. </p> </div> </div> </div> <img img-arc="3" class="img-arc" src="https://demo.zhardsoft.com/arc-pattern-3/arc_3.svg"/> </section> </body> </html> ``` This is the code that I have improved from my previous post, please check it
72,660,500
I have a React application with this basic layout: ``` function App() { return ( <div className="app"> <Header /> <Main /> <Footer /> </div> ); } export default App; ``` My issue is that I have separate stylesheets for each of these components, but I can't get my footer to both be at the bottom of the page, and always stay below content. That is, if the page is blank, the footer would still be at the bottom, and if there was content that was larger than the viewport height, the footer would still remain under it. I've seen answers to this issue, but only with regular HTML pages, not with different React components with different stylesheets. I have an `index.css`, `App.css`, and CSS pages for each of my App components. Is there a way I should go about it? Which stylesheet should I add the code to have the footer stay at the bottom and below the content. I currently have code in my `Footer.css`, but the code doesn't keep the footer at the bottom of the page and below content. I think the issue is that usually all the components are on the same HTML page within the `body`, but React is broken up a little differently. Any help would be great.
2022/06/17
[ "https://Stackoverflow.com/questions/72660500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18060222/" ]
You could add the below lines inside `index.css` for example. You can change auto to a fixed value if you want, like 100px. ```css .app { min-height: 100vh; display: grid; grid-template-rows: auto 1fr auto; gap: 3rem; } ``` That would do the job. Additionally you can make sure there isn't some `padding` or `margin` coming from the outside, I mean the div with `root` id, `body` and `html`, to avoid any unnecessary horizontal scroll.
You need to add style to global container: ``` html,body,#root { display: flex; flex-direction: column; min-height: 100%; } ``` then add style to your footer component: ``` .footer { padding-top: auto; } ``` I won't recommend using ``` min-height: 100vh; ``` it will break on mobile, because of how its calculated.
72,660,500
I have a React application with this basic layout: ``` function App() { return ( <div className="app"> <Header /> <Main /> <Footer /> </div> ); } export default App; ``` My issue is that I have separate stylesheets for each of these components, but I can't get my footer to both be at the bottom of the page, and always stay below content. That is, if the page is blank, the footer would still be at the bottom, and if there was content that was larger than the viewport height, the footer would still remain under it. I've seen answers to this issue, but only with regular HTML pages, not with different React components with different stylesheets. I have an `index.css`, `App.css`, and CSS pages for each of my App components. Is there a way I should go about it? Which stylesheet should I add the code to have the footer stay at the bottom and below the content. I currently have code in my `Footer.css`, but the code doesn't keep the footer at the bottom of the page and below content. I think the issue is that usually all the components are on the same HTML page within the `body`, but React is broken up a little differently. Any help would be great.
2022/06/17
[ "https://Stackoverflow.com/questions/72660500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18060222/" ]
You could add the below lines inside `index.css` for example. You can change auto to a fixed value if you want, like 100px. ```css .app { min-height: 100vh; display: grid; grid-template-rows: auto 1fr auto; gap: 3rem; } ``` That would do the job. Additionally you can make sure there isn't some `padding` or `margin` coming from the outside, I mean the div with `root` id, `body` and `html`, to avoid any unnecessary horizontal scroll.
In `index.css` add this: ``` Footer { width: 300px; text-align: center; position: relative; bottom: 0; left: 50%; -webkit-transform: translate(-50%, 0); transform: translate(-50%, 0); } ``` Example: <https://codesandbox.io/embed/quirky-sound-bitt9k?fontsize=14&hidenavigation=1&theme=dark> You can change `position: fixed;` if you want the footer section to show at the bottom of the page relative to the viewport, rather than relative to the page content. Sources for your reference: > > <https://getridbug.com/html/transform-translate-50-50/> > <https://www.w3schools.com/css/css_positioning.asp> > > >
72,660,500
I have a React application with this basic layout: ``` function App() { return ( <div className="app"> <Header /> <Main /> <Footer /> </div> ); } export default App; ``` My issue is that I have separate stylesheets for each of these components, but I can't get my footer to both be at the bottom of the page, and always stay below content. That is, if the page is blank, the footer would still be at the bottom, and if there was content that was larger than the viewport height, the footer would still remain under it. I've seen answers to this issue, but only with regular HTML pages, not with different React components with different stylesheets. I have an `index.css`, `App.css`, and CSS pages for each of my App components. Is there a way I should go about it? Which stylesheet should I add the code to have the footer stay at the bottom and below the content. I currently have code in my `Footer.css`, but the code doesn't keep the footer at the bottom of the page and below content. I think the issue is that usually all the components are on the same HTML page within the `body`, but React is broken up a little differently. Any help would be great.
2022/06/17
[ "https://Stackoverflow.com/questions/72660500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18060222/" ]
I was having an issue using grid and grid-template-rows, but switching to flex did the trick. My understanding is that using a `flex-direction: column;` and `justify-content: space-between;` spaces my three components and forces my `<Footer />` underneath `<Main />` no matter the viewport height. If anyone has a better understanding of why my answer works better than others, I'd love an explanation. index.css file: ``` .app { min-height: 100%; display: flex; flex-direction: column; justify-content: space-between; } ```
You need to add style to global container: ``` html,body,#root { display: flex; flex-direction: column; min-height: 100%; } ``` then add style to your footer component: ``` .footer { padding-top: auto; } ``` I won't recommend using ``` min-height: 100vh; ``` it will break on mobile, because of how its calculated.
72,660,500
I have a React application with this basic layout: ``` function App() { return ( <div className="app"> <Header /> <Main /> <Footer /> </div> ); } export default App; ``` My issue is that I have separate stylesheets for each of these components, but I can't get my footer to both be at the bottom of the page, and always stay below content. That is, if the page is blank, the footer would still be at the bottom, and if there was content that was larger than the viewport height, the footer would still remain under it. I've seen answers to this issue, but only with regular HTML pages, not with different React components with different stylesheets. I have an `index.css`, `App.css`, and CSS pages for each of my App components. Is there a way I should go about it? Which stylesheet should I add the code to have the footer stay at the bottom and below the content. I currently have code in my `Footer.css`, but the code doesn't keep the footer at the bottom of the page and below content. I think the issue is that usually all the components are on the same HTML page within the `body`, but React is broken up a little differently. Any help would be great.
2022/06/17
[ "https://Stackoverflow.com/questions/72660500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18060222/" ]
I was having an issue using grid and grid-template-rows, but switching to flex did the trick. My understanding is that using a `flex-direction: column;` and `justify-content: space-between;` spaces my three components and forces my `<Footer />` underneath `<Main />` no matter the viewport height. If anyone has a better understanding of why my answer works better than others, I'd love an explanation. index.css file: ``` .app { min-height: 100%; display: flex; flex-direction: column; justify-content: space-between; } ```
In `index.css` add this: ``` Footer { width: 300px; text-align: center; position: relative; bottom: 0; left: 50%; -webkit-transform: translate(-50%, 0); transform: translate(-50%, 0); } ``` Example: <https://codesandbox.io/embed/quirky-sound-bitt9k?fontsize=14&hidenavigation=1&theme=dark> You can change `position: fixed;` if you want the footer section to show at the bottom of the page relative to the viewport, rather than relative to the page content. Sources for your reference: > > <https://getridbug.com/html/transform-translate-50-50/> > <https://www.w3schools.com/css/css_positioning.asp> > > >
54,362,004
I need to make a pdf file with user content and send it back. I chose **pdfmake**, because then can make a tables. I use **Koa**.js; ``` router.post('/pdf', koaBody(), async ctx => { const doc = printer.createPdfKitDocument(myFunctionGeneratePDFBody(ctx.request.body)); doc.pipe(ctx.res, { end: false }); doc.end(); ctx.res.writeHead(200, { 'Content-Type': 'application/pdf', "Content-Disposition": "attachment; filename=document.pdf", }); ctx.res.end(); }); ``` And get an error ``` Error [ERR_STREAM_WRITE_AFTER_END]: write after end at write_ (_http_outgoing.js:572:17) at ServerResponse.write (_http_outgoing.js:567:10) at PDFDocument.ondata (_stream_readable.js:666:20) at PDFDocument.emit (events.js:182:13) at PDFDocument.EventEmitter.emit (domain.js:442:20) at PDFDocument.Readable.read (_stream_readable.js:486:10) at flow (_stream_readable.js:922:34) at resume_ (_stream_readable.js:904:3) at process._tickCallback (internal/process/next_tick.js:63:19) ``` But save in intermediate file and send its work ... ``` router.post('/pdf', koaBody(), async ctx => { await new Promise((resolve, reject) => { const doc = printer.createPdfKitDocument(generatePDF(ctx.request.body)); doc.pipe(fs.createWriteStream(__dirname + '/document.pdf')); doc.end(); doc.on('error', reject); doc.on('end', resolve); }) .then(async () => { ctx.res.writeHead(200, { 'Content-Type': 'application/pdf', 'Content-Disposition': 'attachment; filename=document.pdf', }); const stream = fs.createReadStream(__dirname + '/document.pdf'); return new Promise((resolve, reject) => { stream.pipe(ctx.res, { end: false }); stream.on('error', reject); stream.on('end', resolve); }); }); ctx.res.end(); }); ```
2019/01/25
[ "https://Stackoverflow.com/questions/54362004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10606188/" ]
I just ran into the same issue and your question helped me out, and I've figured out the issue: you're ending the response/stream right away, while it isn't completely written yet. The problem is `doc.end()` returns right away, before writing is finished. The trick is to let your doc end the stream when it's finished (so no more `end: false`) and wait for this event, for example using a Promise. The fixed code looks like this: ```js router.post('/pdf', koaBody(), async ctx => { const doc = printer.createPdfKitDocument(myFunctionGeneratePDFBody(ctx.request.body)); doc.pipe(ctx.res); doc.end(); ctx.res.writeHead(200, { 'Content-Type': 'application/pdf', "Content-Disposition": "attachment; filename=document.pdf", }); return new Promise(resolve => ctx.res.on('finish', resolve)); }); ```
Avoid using `writeHead`, see <https://koajs.com/#response>. Do like this: ``` ctx.attachment('file.pdf'); ctx.type = 'application/pdf'; const stream = fs.createReadStream(`${process.cwd()}/uploads/file.pdf`); ctx.ok(stream); // from https://github.com/jeffijoe/koa-respond ```
40,058,120
I am using Botdetect captcha, But i need to remove the link they have given below the image captcha, how to remove it ``` <a href="//captcha.org/captcha.html?codeigniter" title="BotDetect CAPTCHA Library for CodeIgniter" style="display: block !important; height: 10px !important; margin: 0 !important; padding: 0 !important; font-size: 9px !important; line-height: 9px !important; visibility: visible !important; font-family: Verdana, DejaVu Sans, Bitstream Vera Sans, Verdana Ref, sans-serif !important; vertical-align: middle !important; text-align: center !important; text-decoration: none !important; background-color: #f8f8f8 !important; color: #606060 !important;">BotDetect CAPTCHA Library for CodeIgniter</a> ``` Here is the image [![enter image description here](https://i.stack.imgur.com/9vb5Z.png)](https://i.stack.imgur.com/9vb5Z.png)
2016/10/15
[ "https://Stackoverflow.com/questions/40058120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5575047/" ]
I had used botdetect captcha for non commercial use, where I was able to successfully removed the link and title . Path of file to be modified , vendor/captcha-com/examples/captcha/lib/botdetect/CaptchaInculdes.php ``` private static function iqy23{ return ''; } ``` And ``` public static function GetHelpLinkText($_1qfl5bimwvnl8fd7, $_iitpwcsaaap742gstb7q5) { return ''; } ``` Return blank in above two functions. Hope it helps someone looking for non commercial use or who is willing to understand the algorithm , it is always recommendable to purchase the paid version for commercial use. Cheers :)
You can make a div over the legend: ``` <botDetect:captcha id="miCaptcha" userInputID="captchaCode" codeLength="4" imageWidth="150" imageStyle="GRAFFITI2"/> <div id="tapa" style="background-color: #ffffd9;height: 10px;width: 150px;position: relative;top: -10px;"></div> ```
40,058,120
I am using Botdetect captcha, But i need to remove the link they have given below the image captcha, how to remove it ``` <a href="//captcha.org/captcha.html?codeigniter" title="BotDetect CAPTCHA Library for CodeIgniter" style="display: block !important; height: 10px !important; margin: 0 !important; padding: 0 !important; font-size: 9px !important; line-height: 9px !important; visibility: visible !important; font-family: Verdana, DejaVu Sans, Bitstream Vera Sans, Verdana Ref, sans-serif !important; vertical-align: middle !important; text-align: center !important; text-decoration: none !important; background-color: #f8f8f8 !important; color: #606060 !important;">BotDetect CAPTCHA Library for CodeIgniter</a> ``` Here is the image [![enter image description here](https://i.stack.imgur.com/9vb5Z.png)](https://i.stack.imgur.com/9vb5Z.png)
2016/10/15
[ "https://Stackoverflow.com/questions/40058120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5575047/" ]
add code top site ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("a[title ~= 'BotDetect']").removeAttr("style"); $("a[title ~= 'BotDetect']").removeAttr("href"); $("a[title ~= 'BotDetect']").css('visibility', 'hidden'); }); </script> ```
I had used botdetect captcha for non commercial use, where I was able to successfully removed the link and title . Path of file to be modified , vendor/captcha-com/examples/captcha/lib/botdetect/CaptchaInculdes.php ``` private static function iqy23{ return ''; } ``` And ``` public static function GetHelpLinkText($_1qfl5bimwvnl8fd7, $_iitpwcsaaap742gstb7q5) { return ''; } ``` Return blank in above two functions. Hope it helps someone looking for non commercial use or who is willing to understand the algorithm , it is always recommendable to purchase the paid version for commercial use. Cheers :)
40,058,120
I am using Botdetect captcha, But i need to remove the link they have given below the image captcha, how to remove it ``` <a href="//captcha.org/captcha.html?codeigniter" title="BotDetect CAPTCHA Library for CodeIgniter" style="display: block !important; height: 10px !important; margin: 0 !important; padding: 0 !important; font-size: 9px !important; line-height: 9px !important; visibility: visible !important; font-family: Verdana, DejaVu Sans, Bitstream Vera Sans, Verdana Ref, sans-serif !important; vertical-align: middle !important; text-align: center !important; text-decoration: none !important; background-color: #f8f8f8 !important; color: #606060 !important;">BotDetect CAPTCHA Library for CodeIgniter</a> ``` Here is the image [![enter image description here](https://i.stack.imgur.com/9vb5Z.png)](https://i.stack.imgur.com/9vb5Z.png)
2016/10/15
[ "https://Stackoverflow.com/questions/40058120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5575047/" ]
add code top site ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("a[title ~= 'BotDetect']").removeAttr("style"); $("a[title ~= 'BotDetect']").removeAttr("href"); $("a[title ~= 'BotDetect']").css('visibility', 'hidden'); }); </script> ```
You can make a div over the legend: ``` <botDetect:captcha id="miCaptcha" userInputID="captchaCode" codeLength="4" imageWidth="150" imageStyle="GRAFFITI2"/> <div id="tapa" style="background-color: #ffffd9;height: 10px;width: 150px;position: relative;top: -10px;"></div> ```
40,058,120
I am using Botdetect captcha, But i need to remove the link they have given below the image captcha, how to remove it ``` <a href="//captcha.org/captcha.html?codeigniter" title="BotDetect CAPTCHA Library for CodeIgniter" style="display: block !important; height: 10px !important; margin: 0 !important; padding: 0 !important; font-size: 9px !important; line-height: 9px !important; visibility: visible !important; font-family: Verdana, DejaVu Sans, Bitstream Vera Sans, Verdana Ref, sans-serif !important; vertical-align: middle !important; text-align: center !important; text-decoration: none !important; background-color: #f8f8f8 !important; color: #606060 !important;">BotDetect CAPTCHA Library for CodeIgniter</a> ``` Here is the image [![enter image description here](https://i.stack.imgur.com/9vb5Z.png)](https://i.stack.imgur.com/9vb5Z.png)
2016/10/15
[ "https://Stackoverflow.com/questions/40058120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5575047/" ]
Read the below links. I suggest you can convert the help link mode to image instead. It will hide the text from getting displayed and instead captcha will be clickable. <https://captcha.com/doc/java/captcha-options.html#captcha_help_link_mode> <https://captcha.com/license/captcha-free-version-limitations.html#link>
You can make a div over the legend: ``` <botDetect:captcha id="miCaptcha" userInputID="captchaCode" codeLength="4" imageWidth="150" imageStyle="GRAFFITI2"/> <div id="tapa" style="background-color: #ffffd9;height: 10px;width: 150px;position: relative;top: -10px;"></div> ```
40,058,120
I am using Botdetect captcha, But i need to remove the link they have given below the image captcha, how to remove it ``` <a href="//captcha.org/captcha.html?codeigniter" title="BotDetect CAPTCHA Library for CodeIgniter" style="display: block !important; height: 10px !important; margin: 0 !important; padding: 0 !important; font-size: 9px !important; line-height: 9px !important; visibility: visible !important; font-family: Verdana, DejaVu Sans, Bitstream Vera Sans, Verdana Ref, sans-serif !important; vertical-align: middle !important; text-align: center !important; text-decoration: none !important; background-color: #f8f8f8 !important; color: #606060 !important;">BotDetect CAPTCHA Library for CodeIgniter</a> ``` Here is the image [![enter image description here](https://i.stack.imgur.com/9vb5Z.png)](https://i.stack.imgur.com/9vb5Z.png)
2016/10/15
[ "https://Stackoverflow.com/questions/40058120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5575047/" ]
You can add HelpLinkMode property with "Image" value Like this: <BotDetect:WebFormsCaptcha ID="ExampleCaptcha" UserInputID="CaptchaCode" runat="server" HelpLinkMode="Image"/>
You can make a div over the legend: ``` <botDetect:captcha id="miCaptcha" userInputID="captchaCode" codeLength="4" imageWidth="150" imageStyle="GRAFFITI2"/> <div id="tapa" style="background-color: #ffffd9;height: 10px;width: 150px;position: relative;top: -10px;"></div> ```
40,058,120
I am using Botdetect captcha, But i need to remove the link they have given below the image captcha, how to remove it ``` <a href="//captcha.org/captcha.html?codeigniter" title="BotDetect CAPTCHA Library for CodeIgniter" style="display: block !important; height: 10px !important; margin: 0 !important; padding: 0 !important; font-size: 9px !important; line-height: 9px !important; visibility: visible !important; font-family: Verdana, DejaVu Sans, Bitstream Vera Sans, Verdana Ref, sans-serif !important; vertical-align: middle !important; text-align: center !important; text-decoration: none !important; background-color: #f8f8f8 !important; color: #606060 !important;">BotDetect CAPTCHA Library for CodeIgniter</a> ``` Here is the image [![enter image description here](https://i.stack.imgur.com/9vb5Z.png)](https://i.stack.imgur.com/9vb5Z.png)
2016/10/15
[ "https://Stackoverflow.com/questions/40058120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5575047/" ]
add code top site ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("a[title ~= 'BotDetect']").removeAttr("style"); $("a[title ~= 'BotDetect']").removeAttr("href"); $("a[title ~= 'BotDetect']").css('visibility', 'hidden'); }); </script> ```
Read the below links. I suggest you can convert the help link mode to image instead. It will hide the text from getting displayed and instead captcha will be clickable. <https://captcha.com/doc/java/captcha-options.html#captcha_help_link_mode> <https://captcha.com/license/captcha-free-version-limitations.html#link>
40,058,120
I am using Botdetect captcha, But i need to remove the link they have given below the image captcha, how to remove it ``` <a href="//captcha.org/captcha.html?codeigniter" title="BotDetect CAPTCHA Library for CodeIgniter" style="display: block !important; height: 10px !important; margin: 0 !important; padding: 0 !important; font-size: 9px !important; line-height: 9px !important; visibility: visible !important; font-family: Verdana, DejaVu Sans, Bitstream Vera Sans, Verdana Ref, sans-serif !important; vertical-align: middle !important; text-align: center !important; text-decoration: none !important; background-color: #f8f8f8 !important; color: #606060 !important;">BotDetect CAPTCHA Library for CodeIgniter</a> ``` Here is the image [![enter image description here](https://i.stack.imgur.com/9vb5Z.png)](https://i.stack.imgur.com/9vb5Z.png)
2016/10/15
[ "https://Stackoverflow.com/questions/40058120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5575047/" ]
add code top site ``` <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("a[title ~= 'BotDetect']").removeAttr("style"); $("a[title ~= 'BotDetect']").removeAttr("href"); $("a[title ~= 'BotDetect']").css('visibility', 'hidden'); }); </script> ```
You can add HelpLinkMode property with "Image" value Like this: <BotDetect:WebFormsCaptcha ID="ExampleCaptcha" UserInputID="CaptchaCode" runat="server" HelpLinkMode="Image"/>
74,189,685
``` def getAllBooksPagesURLs(): lists_of_url = [] lists_of_url.append(r"http://books.toscrape.com/") for j in range(2,51): lists_of_url.append(r"http://books.toscrape.com/catalogue/page-%d.html"%j) return lists_of_url def getAndParseURL(url): result = requests.get(url) soup = BeautifulSoup(result.text, 'html.parser') return soup def getBooksURLs(url,z): soup = getAndParseURL(url) return([z+ x.a.get('href') for x in soup.findAll( "div", class_="image_container")]) books_url = [] title_list = [] main_page_list = [] list_of_rewiew_num = [] list_of_bookpage = [] list_of_resultitle = [] books_done_page = [] list_of_review_num=[] for y in getAllBooksPagesURLs()[0:1]: main_page=getAndParseURL(y) result_of_title = main_page.findAll("h3") for x in result_of_title: list_of_resultitle.append(x.find("a").get("title")) books_url = getBooksURLs(y,y) for b in books_url: print(b) books_page = getAndParseURL(b) if books_page.find("td") is None: list_of_review_num.append(0) else: review_num =books_page.find("td").contents[0] list_of_review_num.append(review_num) books_url list_of_resultitle list_of_review_num ``` > > above is my code ,the result is > > > ['a897fe39b1053632', '90fa61229261140a', '6957f44c3847a760', 'e00eb4fd7b871a48', '4165285e1663650f', 'f77dbf2323deb740', '2597b5a345f45e1b', 'e72a5dfc7e9267b2', 'e10e1e165dc8be4a', '1dfe412b8ac00530', '0312262ecafa5a40', '30a7f60cd76ca58c', 'ce6396b0f23f6ecc', '3b1c02bac2a429e6', 'a34ba96d4081e6a4', 'deda3e61b9514b83', 'feb7cc7701ecf901', 'e30f54cea9b38190', 'a18a4f574854aced', 'a22124811bfa8350'] > > the garble codes are like 'a22124811bfa8350', is it about dynamic html? I donnot know. > my desire output of list\_of\_review\_num should be > > > ``` [0,1,2,3] ``` how to get the correct output?could you plz help me? thank u in advance
2022/10/25
[ "https://Stackoverflow.com/questions/74189685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16566489/" ]
You are facing a cyclic calculation due to the use of percentage value. The parent is an inline-block element so its width is defined by its content and that same content is using a percentage value so the content need a reference for that percentage which is the width of the parent. You have a cycle. In such case, the browser will first ignore the padding to define the parent width and then calculate the padding BUT we don't get to calculate the parent width again because will have an infinite loop. Check this: ```css .parent { display: inline-block; } .child { border: 2px solid red; } ``` ```html <div class="parent"> <div class="child">CSSisAwesome</div> </div> <br> <br> <div class="parent"> <div class="child" style="padding: 20%;">CSSisAwesome</div> </div> ``` Note how in both cases, the width of the parent is the same and that width is defined by the content. The padding is added later and create an overflow. You can find mode detail in [the Specification](https://www.w3.org/TR/css-sizing-3/#cyclic-percentage-contribution) > > Sometimes the size of a percentage-sized box’s containing block depends on the intrinsic size contribution of the box itself, creating a cyclic dependency. > > > Related questions: [Why does percentage padding break my flex item?](https://stackoverflow.com/q/53536266/8620333) [CSS Grid - unnecessary word break](https://stackoverflow.com/q/53355708/8620333) [How percentage truly works compared to other units in different situations](https://stackoverflow.com/q/67961622/8620333)
As seen in [this CSSTricks article](https://css-tricks.com/oh-hey-padding-percentage-is-based-on-the-parent-elements-width/), padding using percentage units is in relation to the parent container, not the content within the element. The 20% padding you're setting in your code snippet is in relation to the `.parent` div's dimensions, not in relation to the content within the `.child` div.
74,189,685
``` def getAllBooksPagesURLs(): lists_of_url = [] lists_of_url.append(r"http://books.toscrape.com/") for j in range(2,51): lists_of_url.append(r"http://books.toscrape.com/catalogue/page-%d.html"%j) return lists_of_url def getAndParseURL(url): result = requests.get(url) soup = BeautifulSoup(result.text, 'html.parser') return soup def getBooksURLs(url,z): soup = getAndParseURL(url) return([z+ x.a.get('href') for x in soup.findAll( "div", class_="image_container")]) books_url = [] title_list = [] main_page_list = [] list_of_rewiew_num = [] list_of_bookpage = [] list_of_resultitle = [] books_done_page = [] list_of_review_num=[] for y in getAllBooksPagesURLs()[0:1]: main_page=getAndParseURL(y) result_of_title = main_page.findAll("h3") for x in result_of_title: list_of_resultitle.append(x.find("a").get("title")) books_url = getBooksURLs(y,y) for b in books_url: print(b) books_page = getAndParseURL(b) if books_page.find("td") is None: list_of_review_num.append(0) else: review_num =books_page.find("td").contents[0] list_of_review_num.append(review_num) books_url list_of_resultitle list_of_review_num ``` > > above is my code ,the result is > > > ['a897fe39b1053632', '90fa61229261140a', '6957f44c3847a760', 'e00eb4fd7b871a48', '4165285e1663650f', 'f77dbf2323deb740', '2597b5a345f45e1b', 'e72a5dfc7e9267b2', 'e10e1e165dc8be4a', '1dfe412b8ac00530', '0312262ecafa5a40', '30a7f60cd76ca58c', 'ce6396b0f23f6ecc', '3b1c02bac2a429e6', 'a34ba96d4081e6a4', 'deda3e61b9514b83', 'feb7cc7701ecf901', 'e30f54cea9b38190', 'a18a4f574854aced', 'a22124811bfa8350'] > > the garble codes are like 'a22124811bfa8350', is it about dynamic html? I donnot know. > my desire output of list\_of\_review\_num should be > > > ``` [0,1,2,3] ``` how to get the correct output?could you plz help me? thank u in advance
2022/10/25
[ "https://Stackoverflow.com/questions/74189685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16566489/" ]
You are facing a cyclic calculation due to the use of percentage value. The parent is an inline-block element so its width is defined by its content and that same content is using a percentage value so the content need a reference for that percentage which is the width of the parent. You have a cycle. In such case, the browser will first ignore the padding to define the parent width and then calculate the padding BUT we don't get to calculate the parent width again because will have an infinite loop. Check this: ```css .parent { display: inline-block; } .child { border: 2px solid red; } ``` ```html <div class="parent"> <div class="child">CSSisAwesome</div> </div> <br> <br> <div class="parent"> <div class="child" style="padding: 20%;">CSSisAwesome</div> </div> ``` Note how in both cases, the width of the parent is the same and that width is defined by the content. The padding is added later and create an overflow. You can find mode detail in [the Specification](https://www.w3.org/TR/css-sizing-3/#cyclic-percentage-contribution) > > Sometimes the size of a percentage-sized box’s containing block depends on the intrinsic size contribution of the box itself, creating a cyclic dependency. > > > Related questions: [Why does percentage padding break my flex item?](https://stackoverflow.com/q/53536266/8620333) [CSS Grid - unnecessary word break](https://stackoverflow.com/q/53355708/8620333) [How percentage truly works compared to other units in different situations](https://stackoverflow.com/q/67961622/8620333)
If you are using % as a unit, Parent should have fixed width and height
6,009,025
I have setup an image table in my database to store my images as blob type. My problem is that i do not know how to display the images in the db from my web search page. Anytime i enter a searh query, it will display the keyword & the image name but it will not display the image itself. rather it displays long sql codes. Here are my php codes for Imagesearch.php; ``` <style type="text/css"> body { background-color: #FFF; } </style> <?php //get data $button = $_GET['submit']; $search = $_GET['search']; $x = ""; $construct = ""; if (!$button){ echo "You didint submit a keyword."; } else{ if (strlen($search)<=2) { echo "Search term too short."; } else { echo "You searched for <b>$search</b><hr size='1'>"; //connect to database mysql_connect("localhost","root",""); mysql_select_db("searchengine"); //explode our search term $search_exploded = explode(" ",$search); foreach($search_exploded as $search_each) { //constuct query $x++; if ($x==1) { $construct .= "keywords LIKE '%$search_each%'"; } else { $construct .= " OR keywords LIKE '%$search_each%'"; } } //echo out construct $construct = "SELECT * FROM images WHERE $construct"; $run = mysql_query($construct) or die(mysql_error()); $foundnum = mysql_num_rows($run); if ($foundnum==0) { echo "No results found."; } else { echo "$foundnum results found!<p>"; while ($runrows = mysql_fetch_assoc($run)) { //get data $name = $runrows['name']; $image = $runrows['image']; echo " <b>$name</b><br> $image<br> "; } } } ``` }
2011/05/15
[ "https://Stackoverflow.com/questions/6009025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/754539/" ]
I would go with the extending class. That is actually what you are doing, extending the current class with some extra methods. As for the name: you should not name at for the new features, as you might add more later on. It is your extended BitSet class, so `BitSetEx` allready sounds better then the `BitSetWithConversionMethods` you propose. You don't want to write a class with the static methods, this is like procedural programming in an OOP environment, and is considered wrong. You have an object that has certain methods (like the `fromByteArray()` you want to make) so you want those methods to be in that class. Extending is the way to go.
It depends. As nanne pointed out, subclass is an option. But only sometimes. Strings are declared final, so you cannot create a subclass. You have at least 2 other options: 1) Use 'encapsulation', i.e. create a class MyString which has a String on which it operates (as opposed to extending String, which you cannot do). Basically a wrapper around the String that adds your functionality. 2) Create a utility/helper, i.e. a class with only static methods that operate on Strings. So something like ``` class OurStringUtil { .... public static int getMd5Hash(String string) {...} .... } ``` Take a look at the [Apache StringUtils](http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html) stuff, it follows this approach; it's wonderful.
6,009,025
I have setup an image table in my database to store my images as blob type. My problem is that i do not know how to display the images in the db from my web search page. Anytime i enter a searh query, it will display the keyword & the image name but it will not display the image itself. rather it displays long sql codes. Here are my php codes for Imagesearch.php; ``` <style type="text/css"> body { background-color: #FFF; } </style> <?php //get data $button = $_GET['submit']; $search = $_GET['search']; $x = ""; $construct = ""; if (!$button){ echo "You didint submit a keyword."; } else{ if (strlen($search)<=2) { echo "Search term too short."; } else { echo "You searched for <b>$search</b><hr size='1'>"; //connect to database mysql_connect("localhost","root",""); mysql_select_db("searchengine"); //explode our search term $search_exploded = explode(" ",$search); foreach($search_exploded as $search_each) { //constuct query $x++; if ($x==1) { $construct .= "keywords LIKE '%$search_each%'"; } else { $construct .= " OR keywords LIKE '%$search_each%'"; } } //echo out construct $construct = "SELECT * FROM images WHERE $construct"; $run = mysql_query($construct) or die(mysql_error()); $foundnum = mysql_num_rows($run); if ($foundnum==0) { echo "No results found."; } else { echo "$foundnum results found!<p>"; while ($runrows = mysql_fetch_assoc($run)) { //get data $name = $runrows['name']; $image = $runrows['image']; echo " <b>$name</b><br> $image<br> "; } } } ``` }
2011/05/15
[ "https://Stackoverflow.com/questions/6009025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/754539/" ]
I would go with the extending class. That is actually what you are doing, extending the current class with some extra methods. As for the name: you should not name at for the new features, as you might add more later on. It is your extended BitSet class, so `BitSetEx` allready sounds better then the `BitSetWithConversionMethods` you propose. You don't want to write a class with the static methods, this is like procedural programming in an OOP environment, and is considered wrong. You have an object that has certain methods (like the `fromByteArray()` you want to make) so you want those methods to be in that class. Extending is the way to go.
"Best way" is kinda subjective. And keep in mind that String is a final class, so you can't extend it. Two possible approaches are writing wrappers such as `StringWrapper(String)` with your extra methods, or some kind of `StringUtils` class full of static methods (since Java 5, static methods can be imported if you wan't to use the util class directly).
6,009,025
I have setup an image table in my database to store my images as blob type. My problem is that i do not know how to display the images in the db from my web search page. Anytime i enter a searh query, it will display the keyword & the image name but it will not display the image itself. rather it displays long sql codes. Here are my php codes for Imagesearch.php; ``` <style type="text/css"> body { background-color: #FFF; } </style> <?php //get data $button = $_GET['submit']; $search = $_GET['search']; $x = ""; $construct = ""; if (!$button){ echo "You didint submit a keyword."; } else{ if (strlen($search)<=2) { echo "Search term too short."; } else { echo "You searched for <b>$search</b><hr size='1'>"; //connect to database mysql_connect("localhost","root",""); mysql_select_db("searchengine"); //explode our search term $search_exploded = explode(" ",$search); foreach($search_exploded as $search_each) { //constuct query $x++; if ($x==1) { $construct .= "keywords LIKE '%$search_each%'"; } else { $construct .= " OR keywords LIKE '%$search_each%'"; } } //echo out construct $construct = "SELECT * FROM images WHERE $construct"; $run = mysql_query($construct) or die(mysql_error()); $foundnum = mysql_num_rows($run); if ($foundnum==0) { echo "No results found."; } else { echo "$foundnum results found!<p>"; while ($runrows = mysql_fetch_assoc($run)) { //get data $name = $runrows['name']; $image = $runrows['image']; echo " <b>$name</b><br> $image<br> "; } } } ``` }
2011/05/15
[ "https://Stackoverflow.com/questions/6009025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/754539/" ]
There are a few approaches here: Firstly, you could come up with a better name for the `extends BitSet` class. No, `BitsetWithConversionMethods` isn't a good name, but maybe something like `ConvertibleBitSet` is. Does that convey the intent and usage of the class? If so, it's a good name. Likewise you might have a `HashableString` (bearing in mind that you can't extend `String`, as Anthony points out in another answer). This approach of naming child classes with `XableY` (or `XingY`, like `BufferingPort` or `SigningEmailSender`) can sometimes be a useful one to describe the addition of new behaviour. That said, I think there's a fair hint in your problem (not being able to find a name) that maybe this isn't a good design decision, and it's trying to do too much. It is generally a good design principle that a class should "do one thing". Obviously, depending on the level of abstraction, that can be stretched to include anything, but it's worth thinking about: do 'manipulating the set/unset state of a number of bits' and 'convert a bit pattern to another format' count as one thing? I'd argue that (especially with the hint that you're having a hard time coming up with a name) they're probably two different responsibilities. If so, having two classes will end up being cleaner, easier to maintain (another rule is that 'a class should have one reason to change'; one class to both manipulate + convert has at least 2 reasons to change), easier to test in isolation, etc. So without knowing your design, I would suggest maybe two classes; in the `BitSet` example, have both a `BitSet` and (say) a `BitSetConverter` which is responsible for the conversion. If you wanted to get really fancy, perhaps even: ``` interface BitSetConverter<T> { T convert(BitSet in); BitSet parse(T in); } ``` then you might have: ``` BitSetConverter<Integer> intConverter = ...; Integer i = intConverter.convert(myBitSet); BitSet new = intConverter.parse(12345); ``` which really isolates your changes, makes each different converter testable, etc. (Of course, once you do that, you might like to look at [guava](http://code.google.com/p/guava-libraries/) and consider using a [Function](http://guava-libraries.googlecode.com/svn/tags/release09/javadoc/com/google/common/base/Function.html), e.g. a `Function<BitSet, Integer>` for one case, and `Function<Integer, BitSet>` for the other. Then you gain a whole ecosystem of `Function`-supporting code which may be useful)
I would go with the extending class. That is actually what you are doing, extending the current class with some extra methods. As for the name: you should not name at for the new features, as you might add more later on. It is your extended BitSet class, so `BitSetEx` allready sounds better then the `BitSetWithConversionMethods` you propose. You don't want to write a class with the static methods, this is like procedural programming in an OOP environment, and is considered wrong. You have an object that has certain methods (like the `fromByteArray()` you want to make) so you want those methods to be in that class. Extending is the way to go.
6,009,025
I have setup an image table in my database to store my images as blob type. My problem is that i do not know how to display the images in the db from my web search page. Anytime i enter a searh query, it will display the keyword & the image name but it will not display the image itself. rather it displays long sql codes. Here are my php codes for Imagesearch.php; ``` <style type="text/css"> body { background-color: #FFF; } </style> <?php //get data $button = $_GET['submit']; $search = $_GET['search']; $x = ""; $construct = ""; if (!$button){ echo "You didint submit a keyword."; } else{ if (strlen($search)<=2) { echo "Search term too short."; } else { echo "You searched for <b>$search</b><hr size='1'>"; //connect to database mysql_connect("localhost","root",""); mysql_select_db("searchengine"); //explode our search term $search_exploded = explode(" ",$search); foreach($search_exploded as $search_each) { //constuct query $x++; if ($x==1) { $construct .= "keywords LIKE '%$search_each%'"; } else { $construct .= " OR keywords LIKE '%$search_each%'"; } } //echo out construct $construct = "SELECT * FROM images WHERE $construct"; $run = mysql_query($construct) or die(mysql_error()); $foundnum = mysql_num_rows($run); if ($foundnum==0) { echo "No results found."; } else { echo "$foundnum results found!<p>"; while ($runrows = mysql_fetch_assoc($run)) { //get data $name = $runrows['name']; $image = $runrows['image']; echo " <b>$name</b><br> $image<br> "; } } } ``` }
2011/05/15
[ "https://Stackoverflow.com/questions/6009025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/754539/" ]
There are a few approaches here: Firstly, you could come up with a better name for the `extends BitSet` class. No, `BitsetWithConversionMethods` isn't a good name, but maybe something like `ConvertibleBitSet` is. Does that convey the intent and usage of the class? If so, it's a good name. Likewise you might have a `HashableString` (bearing in mind that you can't extend `String`, as Anthony points out in another answer). This approach of naming child classes with `XableY` (or `XingY`, like `BufferingPort` or `SigningEmailSender`) can sometimes be a useful one to describe the addition of new behaviour. That said, I think there's a fair hint in your problem (not being able to find a name) that maybe this isn't a good design decision, and it's trying to do too much. It is generally a good design principle that a class should "do one thing". Obviously, depending on the level of abstraction, that can be stretched to include anything, but it's worth thinking about: do 'manipulating the set/unset state of a number of bits' and 'convert a bit pattern to another format' count as one thing? I'd argue that (especially with the hint that you're having a hard time coming up with a name) they're probably two different responsibilities. If so, having two classes will end up being cleaner, easier to maintain (another rule is that 'a class should have one reason to change'; one class to both manipulate + convert has at least 2 reasons to change), easier to test in isolation, etc. So without knowing your design, I would suggest maybe two classes; in the `BitSet` example, have both a `BitSet` and (say) a `BitSetConverter` which is responsible for the conversion. If you wanted to get really fancy, perhaps even: ``` interface BitSetConverter<T> { T convert(BitSet in); BitSet parse(T in); } ``` then you might have: ``` BitSetConverter<Integer> intConverter = ...; Integer i = intConverter.convert(myBitSet); BitSet new = intConverter.parse(12345); ``` which really isolates your changes, makes each different converter testable, etc. (Of course, once you do that, you might like to look at [guava](http://code.google.com/p/guava-libraries/) and consider using a [Function](http://guava-libraries.googlecode.com/svn/tags/release09/javadoc/com/google/common/base/Function.html), e.g. a `Function<BitSet, Integer>` for one case, and `Function<Integer, BitSet>` for the other. Then you gain a whole ecosystem of `Function`-supporting code which may be useful)
It depends. As nanne pointed out, subclass is an option. But only sometimes. Strings are declared final, so you cannot create a subclass. You have at least 2 other options: 1) Use 'encapsulation', i.e. create a class MyString which has a String on which it operates (as opposed to extending String, which you cannot do). Basically a wrapper around the String that adds your functionality. 2) Create a utility/helper, i.e. a class with only static methods that operate on Strings. So something like ``` class OurStringUtil { .... public static int getMd5Hash(String string) {...} .... } ``` Take a look at the [Apache StringUtils](http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html) stuff, it follows this approach; it's wonderful.
6,009,025
I have setup an image table in my database to store my images as blob type. My problem is that i do not know how to display the images in the db from my web search page. Anytime i enter a searh query, it will display the keyword & the image name but it will not display the image itself. rather it displays long sql codes. Here are my php codes for Imagesearch.php; ``` <style type="text/css"> body { background-color: #FFF; } </style> <?php //get data $button = $_GET['submit']; $search = $_GET['search']; $x = ""; $construct = ""; if (!$button){ echo "You didint submit a keyword."; } else{ if (strlen($search)<=2) { echo "Search term too short."; } else { echo "You searched for <b>$search</b><hr size='1'>"; //connect to database mysql_connect("localhost","root",""); mysql_select_db("searchengine"); //explode our search term $search_exploded = explode(" ",$search); foreach($search_exploded as $search_each) { //constuct query $x++; if ($x==1) { $construct .= "keywords LIKE '%$search_each%'"; } else { $construct .= " OR keywords LIKE '%$search_each%'"; } } //echo out construct $construct = "SELECT * FROM images WHERE $construct"; $run = mysql_query($construct) or die(mysql_error()); $foundnum = mysql_num_rows($run); if ($foundnum==0) { echo "No results found."; } else { echo "$foundnum results found!<p>"; while ($runrows = mysql_fetch_assoc($run)) { //get data $name = $runrows['name']; $image = $runrows['image']; echo " <b>$name</b><br> $image<br> "; } } } ``` }
2011/05/15
[ "https://Stackoverflow.com/questions/6009025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/754539/" ]
There are a few approaches here: Firstly, you could come up with a better name for the `extends BitSet` class. No, `BitsetWithConversionMethods` isn't a good name, but maybe something like `ConvertibleBitSet` is. Does that convey the intent and usage of the class? If so, it's a good name. Likewise you might have a `HashableString` (bearing in mind that you can't extend `String`, as Anthony points out in another answer). This approach of naming child classes with `XableY` (or `XingY`, like `BufferingPort` or `SigningEmailSender`) can sometimes be a useful one to describe the addition of new behaviour. That said, I think there's a fair hint in your problem (not being able to find a name) that maybe this isn't a good design decision, and it's trying to do too much. It is generally a good design principle that a class should "do one thing". Obviously, depending on the level of abstraction, that can be stretched to include anything, but it's worth thinking about: do 'manipulating the set/unset state of a number of bits' and 'convert a bit pattern to another format' count as one thing? I'd argue that (especially with the hint that you're having a hard time coming up with a name) they're probably two different responsibilities. If so, having two classes will end up being cleaner, easier to maintain (another rule is that 'a class should have one reason to change'; one class to both manipulate + convert has at least 2 reasons to change), easier to test in isolation, etc. So without knowing your design, I would suggest maybe two classes; in the `BitSet` example, have both a `BitSet` and (say) a `BitSetConverter` which is responsible for the conversion. If you wanted to get really fancy, perhaps even: ``` interface BitSetConverter<T> { T convert(BitSet in); BitSet parse(T in); } ``` then you might have: ``` BitSetConverter<Integer> intConverter = ...; Integer i = intConverter.convert(myBitSet); BitSet new = intConverter.parse(12345); ``` which really isolates your changes, makes each different converter testable, etc. (Of course, once you do that, you might like to look at [guava](http://code.google.com/p/guava-libraries/) and consider using a [Function](http://guava-libraries.googlecode.com/svn/tags/release09/javadoc/com/google/common/base/Function.html), e.g. a `Function<BitSet, Integer>` for one case, and `Function<Integer, BitSet>` for the other. Then you gain a whole ecosystem of `Function`-supporting code which may be useful)
"Best way" is kinda subjective. And keep in mind that String is a final class, so you can't extend it. Two possible approaches are writing wrappers such as `StringWrapper(String)` with your extra methods, or some kind of `StringUtils` class full of static methods (since Java 5, static methods can be imported if you wan't to use the util class directly).
63,585,295
I am building a small game in pygame and I wanted a function to exit out. However it takes multiple clicks to exit and it is not consistent either. Also the windows exit function is restarting the program, too Here is the part of the code that deals with exiting ``` if isKill: pygame.mixer.music.stop() gameover = myfont.render("Press R to Respawn", False, (255, 255, 255)) rect = gameover.get_rect() rect.center = screen.get_rect().center screen.blit(gameover, rect) if event.type == KEYDOWN: if event.key == K_r: gameloop() ``` and ``` for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False ``` \*gameloop() is the whole script
2020/08/25
[ "https://Stackoverflow.com/questions/63585295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14034090/" ]
Instead of `event.type`, you can use the pygame builtin event `QUIT` Refer the following code ``` running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False #Can use pygame.quit() in place of running=False if the above line doesn't work. ``` This `while` loop is the starting of gameloop. The contents of the gameloop should be inside it. **Don't** call the `gameloop()` function inside the while loop
In your game loop, you should always keep the loop running at one level. In your code, the respawn actually freezes the current level and reruns the game at a lower level. This is why several quit commands are required to exit the game. When the player respawns, reset the game variables, then continue the game loop. Update your code similar to this: ``` if isKill: # game is over pygame.mixer.music.stop() gameover = myfont.render("Press R to Respawn", False, (255, 255, 255)) rect = gameover.get_rect() rect.center = screen.get_rect().center screen.blit(gameover, rect) if event.type == KEYDOWN: if event.key == K_r: #gameloop() # remove this dospawn() # initialize\reset game variables here (can use same function at game start) isKill = False # start new game continue # skip rest of game process ```
63,585,295
I am building a small game in pygame and I wanted a function to exit out. However it takes multiple clicks to exit and it is not consistent either. Also the windows exit function is restarting the program, too Here is the part of the code that deals with exiting ``` if isKill: pygame.mixer.music.stop() gameover = myfont.render("Press R to Respawn", False, (255, 255, 255)) rect = gameover.get_rect() rect.center = screen.get_rect().center screen.blit(gameover, rect) if event.type == KEYDOWN: if event.key == K_r: gameloop() ``` and ``` for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False ``` \*gameloop() is the whole script
2020/08/25
[ "https://Stackoverflow.com/questions/63585295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14034090/" ]
Perhaps use `sys.exit` to stop the program. Try: ``` import sys import pygame while 1: #code for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() ```
In your game loop, you should always keep the loop running at one level. In your code, the respawn actually freezes the current level and reruns the game at a lower level. This is why several quit commands are required to exit the game. When the player respawns, reset the game variables, then continue the game loop. Update your code similar to this: ``` if isKill: # game is over pygame.mixer.music.stop() gameover = myfont.render("Press R to Respawn", False, (255, 255, 255)) rect = gameover.get_rect() rect.center = screen.get_rect().center screen.blit(gameover, rect) if event.type == KEYDOWN: if event.key == K_r: #gameloop() # remove this dospawn() # initialize\reset game variables here (can use same function at game start) isKill = False # start new game continue # skip rest of game process ```
154,721
I need to prove: > > Let $A$ be open in $\mathbb{R}^m$, $g:A \longrightarrow \mathbb{R}^n$ a locally lipschitz function and $C$ a compact subset of $A$. > > > Show that $g$ is lipschitz on $C$. > > > Can anyone help me?
2012/06/06
[ "https://math.stackexchange.com/questions/154721", "https://math.stackexchange.com", "https://math.stackexchange.com/users/33095/" ]
In general I prefer covering arguments (such as the one @WillieWong posted) to "choose a sequence and get a contradiction", but in this particular problem the second approach could be easier to implement (it avoids the technicalities pointed out by Willie). Suppose $g$ is not Lipschitz on $C$: that is, there exists two sequences $x\_n,y\_n\in C$ such that $|g(x\_n)-g(y\_n)|/|x\_n-y\_n|\to \infty$. Since $g$ is bounded on $C$ (why?), we have $|x\_n-y\_n|\to 0$. Choose a convergent subsequence $x\_{n\_k}\to x$. Observe that the local Lipschitz-ness fails at $x$.
Hint: $C$ being compact means for any open cover it has a finite subcover. Let $x\in C$ and let $U\_x$ be the corresponding open set on which $g:U\_x\to\mathbb{R}^n$ is Lipschitz. This means that $C$ can be covered by finitely many of the $U\_x$. Lastly use the fact that the among a finite set of positive numbers you can choose a maximum one.
154,721
I need to prove: > > Let $A$ be open in $\mathbb{R}^m$, $g:A \longrightarrow \mathbb{R}^n$ a locally lipschitz function and $C$ a compact subset of $A$. > > > Show that $g$ is lipschitz on $C$. > > > Can anyone help me?
2012/06/06
[ "https://math.stackexchange.com/questions/154721", "https://math.stackexchange.com", "https://math.stackexchange.com/users/33095/" ]
In general I prefer covering arguments (such as the one @WillieWong posted) to "choose a sequence and get a contradiction", but in this particular problem the second approach could be easier to implement (it avoids the technicalities pointed out by Willie). Suppose $g$ is not Lipschitz on $C$: that is, there exists two sequences $x\_n,y\_n\in C$ such that $|g(x\_n)-g(y\_n)|/|x\_n-y\_n|\to \infty$. Since $g$ is bounded on $C$ (why?), we have $|x\_n-y\_n|\to 0$. Choose a convergent subsequence $x\_{n\_k}\to x$. Observe that the local Lipschitz-ness fails at $x$.
Maximize the continuous function $f(x,y)=\frac{|g(x)-g(y)|}{|x-y|}$ over the compact set $C\times C\cap\{|x-y| \geq \varepsilon\}$ with a sufficiently small $\varepsilon>0$. Locally Lipschitz condition is used to show that $f$ is bounded in $C\times C\cap\{|x-y|<\varepsilon\}$.
55,804,367
Background: I have a list that contains 13,000 records of human names, some of them are duplicates and I want to find out the similar ones to do the manual duplication process. For an array like: ``` ["jeff","Jeff","mandy","king","queen"] ``` What would be an efficient way to get: ``` [["jeff","Jeff"]] ``` **Explanation** `["jeff","Jeff"]` since their Levenshtein distance is 1(which can be variable like 3). ``` /* Working but a slow solution */ function extractSimilarNames(uniqueNames) { let similarNamesGroup = []; for (let i = 0; i < uniqueNames.length; i++) { //compare with the rest of the array const currentName = uniqueNames[i]; let suspiciousNames = []; for (let j = i + 1; j < uniqueNames.length; j++) { const matchingName = uniqueNames[j]; if (isInLevenshteinRange(currentName, matchingName, 1)) { suspiciousNames.push(matchingName); removeElementFromArray(uniqueNames, matchingName); removeElementFromArray(uniqueNames, currentName); i--; j--; } } if (suspiciousNames.length > 0) { suspiciousNames.push(currentName); } } return similarNamesGroup; } ``` I want to find the similarity via Levenshtein distance, not only the lower/uppercase similarity I already find one of the [fastest Levenshtein implementation](https://github.com/yomguithereal/talisman#readme) but it still takes me to 35 mins to get the result of 13000 items list.
2019/04/23
[ "https://Stackoverflow.com/questions/55804367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4291360/" ]
Your problem is not the speed of the Levenshtein distance implementation. Your problem is that you have to compare each word with each other word. This means you make 13000² comparisons (and each time calculate the Levenshtein distance). So my approach would be to try to reduce the number of comparisons. Here are some ideas: * words are only similar if their lengths differ less than 20% (just my estimation) → we can group by length and only compare words with other words of length ±20% * words are only similar if they share a lot of letters → we can create a list of e.g. 3-grams (all lower case) that refer to the words they are part of. → only compare (e.g. with Levenshtein distance) a word with other words that have several 3-grams in common with it.
If we remove one character from "Jeff" at different positions we end up at "eff", "Jff", "Jef" and "Jef". If we do the same with "jeff", we get "eff", "jff", "Jef" and "jef". Now if you look closely, you'll see that both strings produce "eff" as a result, which means that we could create a Map of those combinations to their original version, then for each string generate all combinations and look them up in the Map. Through the lookup, you'll get results that are similar, e.g. "ab*c*" and "*c*ab" but they do not necessarily have a levenshtein distance of 1, so we have to check that afterwards. Now why is that better? Well iterating all names is O(n) (n being the number of words), creating all combinations is O(m) (m being the average number of characters in a word) and looking up in a Map is O(1), therefore this runs in O(n \* m), whereas your algorithm is O(n \* n \* m), which means for 10.000 words, mine is 10.000 times faster (or my calculation is wrong :)) ``` // A "OneToMany" Map class MultiMap extends Map { set(k, v) { if(super.has(k)) { super.get(k).push(v); } else super.set(k, [v]); } get(k) { return super.get(k) || []; } } function* oneShorter(word) { for(let pos = 0; pos < word.length; pos++) yield word.substr(0, pos) + word.substr(pos + 1); } function findDuplicates(names) { const combos = new MultiMap(); const duplicates = []; const check = (name, combo) => { const dupes = combos.get(combo); for(const dupe of dupes) { if((isInLevenshteinRange(name, combo, 1)) duplicates.push([name, dupe]); } combos.set(combo, name); }; for(const name of names) { check(name, name); for(const combo of oneShorter(name)) { check(name, combo); } } return duplicates; } ```
55,804,367
Background: I have a list that contains 13,000 records of human names, some of them are duplicates and I want to find out the similar ones to do the manual duplication process. For an array like: ``` ["jeff","Jeff","mandy","king","queen"] ``` What would be an efficient way to get: ``` [["jeff","Jeff"]] ``` **Explanation** `["jeff","Jeff"]` since their Levenshtein distance is 1(which can be variable like 3). ``` /* Working but a slow solution */ function extractSimilarNames(uniqueNames) { let similarNamesGroup = []; for (let i = 0; i < uniqueNames.length; i++) { //compare with the rest of the array const currentName = uniqueNames[i]; let suspiciousNames = []; for (let j = i + 1; j < uniqueNames.length; j++) { const matchingName = uniqueNames[j]; if (isInLevenshteinRange(currentName, matchingName, 1)) { suspiciousNames.push(matchingName); removeElementFromArray(uniqueNames, matchingName); removeElementFromArray(uniqueNames, currentName); i--; j--; } } if (suspiciousNames.length > 0) { suspiciousNames.push(currentName); } } return similarNamesGroup; } ``` I want to find the similarity via Levenshtein distance, not only the lower/uppercase similarity I already find one of the [fastest Levenshtein implementation](https://github.com/yomguithereal/talisman#readme) but it still takes me to 35 mins to get the result of 13000 items list.
2019/04/23
[ "https://Stackoverflow.com/questions/55804367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4291360/" ]
Approaches to remove similar names: 1. Use phonetical representation of the words. [cmudict](http://www.speech.cs.cmu.edu/cgi-bin/cmudict) It works with python nltk. You can find which names are close to each other phonetically. 2. Try different forms of stemming or simplifications. I would try most aggressive stemmers like Porter stemmer. 3. Levenshtein trie. You can create trie data structure that will help to find word with minimum distance to searched item, this is used for full text search in some search engines. As far as I know it's already implemented in Java. In your case you need to search one item then add it to the structure on every step, you need to make sure that item that you search is not in the structure yet. 4. Manual naive approach. Find all suitable representations of every word/name, put all representations to map and find representations that have more than 1 word. If you have around 15 different representations of one word you will need only 280K iterations to generate this object (much faster than compare each word to another, which requires around 80M comparisons with 13K names). -- Edit -- If there is a choice I would use something like Python or Java instead of JS for this. It's only my opinion based on: I don't know all requirements, it's common to use Java/Python for natural language processing, task looks more like heavy data processing than front end.
If we remove one character from "Jeff" at different positions we end up at "eff", "Jff", "Jef" and "Jef". If we do the same with "jeff", we get "eff", "jff", "Jef" and "jef". Now if you look closely, you'll see that both strings produce "eff" as a result, which means that we could create a Map of those combinations to their original version, then for each string generate all combinations and look them up in the Map. Through the lookup, you'll get results that are similar, e.g. "ab*c*" and "*c*ab" but they do not necessarily have a levenshtein distance of 1, so we have to check that afterwards. Now why is that better? Well iterating all names is O(n) (n being the number of words), creating all combinations is O(m) (m being the average number of characters in a word) and looking up in a Map is O(1), therefore this runs in O(n \* m), whereas your algorithm is O(n \* n \* m), which means for 10.000 words, mine is 10.000 times faster (or my calculation is wrong :)) ``` // A "OneToMany" Map class MultiMap extends Map { set(k, v) { if(super.has(k)) { super.get(k).push(v); } else super.set(k, [v]); } get(k) { return super.get(k) || []; } } function* oneShorter(word) { for(let pos = 0; pos < word.length; pos++) yield word.substr(0, pos) + word.substr(pos + 1); } function findDuplicates(names) { const combos = new MultiMap(); const duplicates = []; const check = (name, combo) => { const dupes = combos.get(combo); for(const dupe of dupes) { if((isInLevenshteinRange(name, combo, 1)) duplicates.push([name, dupe]); } combos.set(combo, name); }; for(const name of names) { check(name, name); for(const combo of oneShorter(name)) { check(name, combo); } } return duplicates; } ```
55,804,367
Background: I have a list that contains 13,000 records of human names, some of them are duplicates and I want to find out the similar ones to do the manual duplication process. For an array like: ``` ["jeff","Jeff","mandy","king","queen"] ``` What would be an efficient way to get: ``` [["jeff","Jeff"]] ``` **Explanation** `["jeff","Jeff"]` since their Levenshtein distance is 1(which can be variable like 3). ``` /* Working but a slow solution */ function extractSimilarNames(uniqueNames) { let similarNamesGroup = []; for (let i = 0; i < uniqueNames.length; i++) { //compare with the rest of the array const currentName = uniqueNames[i]; let suspiciousNames = []; for (let j = i + 1; j < uniqueNames.length; j++) { const matchingName = uniqueNames[j]; if (isInLevenshteinRange(currentName, matchingName, 1)) { suspiciousNames.push(matchingName); removeElementFromArray(uniqueNames, matchingName); removeElementFromArray(uniqueNames, currentName); i--; j--; } } if (suspiciousNames.length > 0) { suspiciousNames.push(currentName); } } return similarNamesGroup; } ``` I want to find the similarity via Levenshtein distance, not only the lower/uppercase similarity I already find one of the [fastest Levenshtein implementation](https://github.com/yomguithereal/talisman#readme) but it still takes me to 35 mins to get the result of 13000 items list.
2019/04/23
[ "https://Stackoverflow.com/questions/55804367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4291360/" ]
As in your working code you use Levenshtein distance 1 only, I will assume no other distances need to be found. I will propose a similar solution as Jonas Wilms posted, with these differences: * No need to call a `isLevenshtein` function * Produces only unique pairs * Each pair is lexically ordered ```js // Sample data with lots of similar names const names = ["Adela","Adelaida","Adelaide","Adele","Adelia","AdeLina","Adeline", "Adell","AdellA","Adelle","Ardelia","Ardell","Ardella","Ardelle", "Ardis","Madeline","Odelia","ODELL","Odessa","Odette"]; const map = {}; const pairs = new Set; for (const name of names) { for (const i in name+"_") { // Additional iteration to NOT delete a character const key = (name.slice(0, i) + name.slice(+i + 1, name.length)).toLowerCase(); // Group words together where the removal from the same index leads to the same key if (!map[key]) map[key] = Array.from({length: key.length+1}, () => new Set); // If NO character was removed, put the word in EACH group for (const set of (+i < name.length ? [map[key][i]] : map[key])) { if (set.has(name)) continue; for (let similar of set) pairs.add(JSON.stringify([similar, name].sort())); set.add(name); } } } const result = [...pairs].sort().map(JSON.parse); // sort is optional console.log(result); ``` I tested this on a set of 13000 names, including at least 4000 *different* names, and it produced 8000 pairs in about 0.3 seconds.
If we remove one character from "Jeff" at different positions we end up at "eff", "Jff", "Jef" and "Jef". If we do the same with "jeff", we get "eff", "jff", "Jef" and "jef". Now if you look closely, you'll see that both strings produce "eff" as a result, which means that we could create a Map of those combinations to their original version, then for each string generate all combinations and look them up in the Map. Through the lookup, you'll get results that are similar, e.g. "ab*c*" and "*c*ab" but they do not necessarily have a levenshtein distance of 1, so we have to check that afterwards. Now why is that better? Well iterating all names is O(n) (n being the number of words), creating all combinations is O(m) (m being the average number of characters in a word) and looking up in a Map is O(1), therefore this runs in O(n \* m), whereas your algorithm is O(n \* n \* m), which means for 10.000 words, mine is 10.000 times faster (or my calculation is wrong :)) ``` // A "OneToMany" Map class MultiMap extends Map { set(k, v) { if(super.has(k)) { super.get(k).push(v); } else super.set(k, [v]); } get(k) { return super.get(k) || []; } } function* oneShorter(word) { for(let pos = 0; pos < word.length; pos++) yield word.substr(0, pos) + word.substr(pos + 1); } function findDuplicates(names) { const combos = new MultiMap(); const duplicates = []; const check = (name, combo) => { const dupes = combos.get(combo); for(const dupe of dupes) { if((isInLevenshteinRange(name, combo, 1)) duplicates.push([name, dupe]); } combos.set(combo, name); }; for(const name of names) { check(name, name); for(const combo of oneShorter(name)) { check(name, combo); } } return duplicates; } ```
55,804,367
Background: I have a list that contains 13,000 records of human names, some of them are duplicates and I want to find out the similar ones to do the manual duplication process. For an array like: ``` ["jeff","Jeff","mandy","king","queen"] ``` What would be an efficient way to get: ``` [["jeff","Jeff"]] ``` **Explanation** `["jeff","Jeff"]` since their Levenshtein distance is 1(which can be variable like 3). ``` /* Working but a slow solution */ function extractSimilarNames(uniqueNames) { let similarNamesGroup = []; for (let i = 0; i < uniqueNames.length; i++) { //compare with the rest of the array const currentName = uniqueNames[i]; let suspiciousNames = []; for (let j = i + 1; j < uniqueNames.length; j++) { const matchingName = uniqueNames[j]; if (isInLevenshteinRange(currentName, matchingName, 1)) { suspiciousNames.push(matchingName); removeElementFromArray(uniqueNames, matchingName); removeElementFromArray(uniqueNames, currentName); i--; j--; } } if (suspiciousNames.length > 0) { suspiciousNames.push(currentName); } } return similarNamesGroup; } ``` I want to find the similarity via Levenshtein distance, not only the lower/uppercase similarity I already find one of the [fastest Levenshtein implementation](https://github.com/yomguithereal/talisman#readme) but it still takes me to 35 mins to get the result of 13000 items list.
2019/04/23
[ "https://Stackoverflow.com/questions/55804367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4291360/" ]
Your problem is not the speed of the Levenshtein distance implementation. Your problem is that you have to compare each word with each other word. This means you make 13000² comparisons (and each time calculate the Levenshtein distance). So my approach would be to try to reduce the number of comparisons. Here are some ideas: * words are only similar if their lengths differ less than 20% (just my estimation) → we can group by length and only compare words with other words of length ±20% * words are only similar if they share a lot of letters → we can create a list of e.g. 3-grams (all lower case) that refer to the words they are part of. → only compare (e.g. with Levenshtein distance) a word with other words that have several 3-grams in common with it.
Approaches to remove similar names: 1. Use phonetical representation of the words. [cmudict](http://www.speech.cs.cmu.edu/cgi-bin/cmudict) It works with python nltk. You can find which names are close to each other phonetically. 2. Try different forms of stemming or simplifications. I would try most aggressive stemmers like Porter stemmer. 3. Levenshtein trie. You can create trie data structure that will help to find word with minimum distance to searched item, this is used for full text search in some search engines. As far as I know it's already implemented in Java. In your case you need to search one item then add it to the structure on every step, you need to make sure that item that you search is not in the structure yet. 4. Manual naive approach. Find all suitable representations of every word/name, put all representations to map and find representations that have more than 1 word. If you have around 15 different representations of one word you will need only 280K iterations to generate this object (much faster than compare each word to another, which requires around 80M comparisons with 13K names). -- Edit -- If there is a choice I would use something like Python or Java instead of JS for this. It's only my opinion based on: I don't know all requirements, it's common to use Java/Python for natural language processing, task looks more like heavy data processing than front end.
55,804,367
Background: I have a list that contains 13,000 records of human names, some of them are duplicates and I want to find out the similar ones to do the manual duplication process. For an array like: ``` ["jeff","Jeff","mandy","king","queen"] ``` What would be an efficient way to get: ``` [["jeff","Jeff"]] ``` **Explanation** `["jeff","Jeff"]` since their Levenshtein distance is 1(which can be variable like 3). ``` /* Working but a slow solution */ function extractSimilarNames(uniqueNames) { let similarNamesGroup = []; for (let i = 0; i < uniqueNames.length; i++) { //compare with the rest of the array const currentName = uniqueNames[i]; let suspiciousNames = []; for (let j = i + 1; j < uniqueNames.length; j++) { const matchingName = uniqueNames[j]; if (isInLevenshteinRange(currentName, matchingName, 1)) { suspiciousNames.push(matchingName); removeElementFromArray(uniqueNames, matchingName); removeElementFromArray(uniqueNames, currentName); i--; j--; } } if (suspiciousNames.length > 0) { suspiciousNames.push(currentName); } } return similarNamesGroup; } ``` I want to find the similarity via Levenshtein distance, not only the lower/uppercase similarity I already find one of the [fastest Levenshtein implementation](https://github.com/yomguithereal/talisman#readme) but it still takes me to 35 mins to get the result of 13000 items list.
2019/04/23
[ "https://Stackoverflow.com/questions/55804367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4291360/" ]
Your problem is not the speed of the Levenshtein distance implementation. Your problem is that you have to compare each word with each other word. This means you make 13000² comparisons (and each time calculate the Levenshtein distance). So my approach would be to try to reduce the number of comparisons. Here are some ideas: * words are only similar if their lengths differ less than 20% (just my estimation) → we can group by length and only compare words with other words of length ±20% * words are only similar if they share a lot of letters → we can create a list of e.g. 3-grams (all lower case) that refer to the words they are part of. → only compare (e.g. with Levenshtein distance) a word with other words that have several 3-grams in common with it.
I have yet a completely different way of approaching this problem, but I believe I am presenting a pretty fast (but debatable as to how correct/incorrect) it is. My approach is to map the strings to numeric values, sort those values once, and then run through that list once, comparing neighboring values to each other. Like this: ```js // Test strings (provided by OP) with some additions var strs = ["Jeff","mandy","jeff","king","queen","joff", "Queen", "jff", "tim", "Timmo", "Tom", "Rob", "Bob"] // Function to convert a string into a numeric representation // to aid with string similarity comparison function atoi(str, maxLen){ var i = 0; for( var j = 0; j < maxLen; j++ ){ if( str[j] != null ){ i += str.toLowerCase().charCodeAt(j)*Math.pow(64,maxLen-j) - 'a'.charCodeAt(0)*Math.pow(64,maxLen-j) } else { // Normalize the string with a pad char // up to the maxLen (update the value, but don't actually // update the string...) i += '-'.charCodeAt(0)*Math.pow(64,maxLen-j) - 'a'.charCodeAt(0)*Math.pow(64,maxLen-j) } } valMap.push({ str, i }) return i; } Number.prototype.inRange = function(min, max){ return(this >= min && this <= max) } var valMap = []; // Array of string-value pairs var maxLen = strs.map((s) => s.length).sort().pop() // maxLen of all strings in the array console.log('maxLen', maxLen) strs.forEach((s) => atoi(s, maxLen)) // Map strings to values var similars = []; var subArr = [] var margin = 0.05; valMap.sort((a,b) => a.i > b.i ? 1 : -1) // Sort the map... valMap.forEach((entry, idx) => { if( idx > 0 ){ var closeness = Math.abs(entry.i / valMap[idx-1].i); if( closeness.inRange( 1 - margin, 1 + margin ) ){ if( subArr.length == 0 ) subArr.push(valMap[idx-1].str) subArr.push(entry.str) if( idx == valMap.length - 1){ similars.push(subArr) } } else { if( subArr.length > 0 ) similars.push(subArr) subArr = [] } } }) console.log('similars', similars) ``` I'm treating each string as if each were a "64-bit number", where each "bit" could take on the alphanumeric values, with 'a' representing 0. Then I sort that *once*. Then, if similar values are encountered to the previous one (i.e., if the ratio of the two is near 1), then I deduce I have similar strings. The other thing I do is check for the max string length, and normalize all the strings to that length in the calculation of the "64-bit value". --- EDIT: even more stress testing --- And yet, here is some additional testing, which pulls a large list of names and performs the processing rather quickly (~ 50ms on 20k+ names, with lots of false positives). Regardless, this snippet should make it easier to troubleshoot: ```js var valMap = []; // Array of string-value pairs /* Extensions */ Number.prototype.inRange = function(min, max){ return(this >= min && this <= max) } /* Methods */ // Function to convert a string into a numeric representation // to aid with string similarity comparison function atoi(str, maxLen){ var i = 0; for( var j = 0; j < maxLen; j++ ){ if( str[j] != null ){ i += str.toLowerCase().charCodeAt(j)*Math.pow(64,maxLen-j) - 'a'.charCodeAt(0)*Math.pow(64,maxLen-j) } else { // Normalize the string with a pad char // up to the maxLen (update the value, but don't actually // update the string...) i += '-'.charCodeAt(0)*Math.pow(64,maxLen-j) - 'a'.charCodeAt(0)*Math.pow(64,maxLen-j) } } valMap.push({ str, i }) return i; } function findSimilars(strs){ var maxLen = strs.map((s) => s.length).sort().pop() // maxLen of all strings in the array console.log('maxLen', maxLen) strs.forEach((s) => atoi(s, maxLen)) // Map strings to values var similars = []; var subArr = [] var margin = 0.05; valMap.sort((a,b) => a.i > b.i ? 1 : -1) // Sort the map... valMap.forEach((entry, idx) => { if( idx > 0 ){ var closeness = Math.abs(entry.i / valMap[idx-1].i); if( closeness.inRange( 1 - margin, 1 + margin ) ){ if( subArr.length == 0 ) subArr.push(valMap[idx-1].str) subArr.push(entry.str) if( idx == valMap.length - 1){ similars.push(subArr) } } else { if( subArr.length > 0 ) similars.push(subArr) subArr = [] } } }) console.log('similars', similars) } // Stress test with 20k+ names $.get('https://raw.githubusercontent.com/dominictarr/random-name/master/names.json') .then((resp) => { var strs = JSON.parse(resp); console.time('processing') findSimilars(strs) console.timeEnd('processing') }) .catch((err) => { console.err('Err retrieving JSON'); }) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> ``` (For some reason, when I run this in [JSFiddle](https://jsfiddle.net/3o5L4svx/1/), I get it to run in ~50ms, but in the Stackoverflow snippet, it's closer to 1000ms.)
55,804,367
Background: I have a list that contains 13,000 records of human names, some of them are duplicates and I want to find out the similar ones to do the manual duplication process. For an array like: ``` ["jeff","Jeff","mandy","king","queen"] ``` What would be an efficient way to get: ``` [["jeff","Jeff"]] ``` **Explanation** `["jeff","Jeff"]` since their Levenshtein distance is 1(which can be variable like 3). ``` /* Working but a slow solution */ function extractSimilarNames(uniqueNames) { let similarNamesGroup = []; for (let i = 0; i < uniqueNames.length; i++) { //compare with the rest of the array const currentName = uniqueNames[i]; let suspiciousNames = []; for (let j = i + 1; j < uniqueNames.length; j++) { const matchingName = uniqueNames[j]; if (isInLevenshteinRange(currentName, matchingName, 1)) { suspiciousNames.push(matchingName); removeElementFromArray(uniqueNames, matchingName); removeElementFromArray(uniqueNames, currentName); i--; j--; } } if (suspiciousNames.length > 0) { suspiciousNames.push(currentName); } } return similarNamesGroup; } ``` I want to find the similarity via Levenshtein distance, not only the lower/uppercase similarity I already find one of the [fastest Levenshtein implementation](https://github.com/yomguithereal/talisman#readme) but it still takes me to 35 mins to get the result of 13000 items list.
2019/04/23
[ "https://Stackoverflow.com/questions/55804367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4291360/" ]
Your problem is not the speed of the Levenshtein distance implementation. Your problem is that you have to compare each word with each other word. This means you make 13000² comparisons (and each time calculate the Levenshtein distance). So my approach would be to try to reduce the number of comparisons. Here are some ideas: * words are only similar if their lengths differ less than 20% (just my estimation) → we can group by length and only compare words with other words of length ±20% * words are only similar if they share a lot of letters → we can create a list of e.g. 3-grams (all lower case) that refer to the words they are part of. → only compare (e.g. with Levenshtein distance) a word with other words that have several 3-grams in common with it.
As in your working code you use Levenshtein distance 1 only, I will assume no other distances need to be found. I will propose a similar solution as Jonas Wilms posted, with these differences: * No need to call a `isLevenshtein` function * Produces only unique pairs * Each pair is lexically ordered ```js // Sample data with lots of similar names const names = ["Adela","Adelaida","Adelaide","Adele","Adelia","AdeLina","Adeline", "Adell","AdellA","Adelle","Ardelia","Ardell","Ardella","Ardelle", "Ardis","Madeline","Odelia","ODELL","Odessa","Odette"]; const map = {}; const pairs = new Set; for (const name of names) { for (const i in name+"_") { // Additional iteration to NOT delete a character const key = (name.slice(0, i) + name.slice(+i + 1, name.length)).toLowerCase(); // Group words together where the removal from the same index leads to the same key if (!map[key]) map[key] = Array.from({length: key.length+1}, () => new Set); // If NO character was removed, put the word in EACH group for (const set of (+i < name.length ? [map[key][i]] : map[key])) { if (set.has(name)) continue; for (let similar of set) pairs.add(JSON.stringify([similar, name].sort())); set.add(name); } } } const result = [...pairs].sort().map(JSON.parse); // sort is optional console.log(result); ``` I tested this on a set of 13000 names, including at least 4000 *different* names, and it produced 8000 pairs in about 0.3 seconds.
55,804,367
Background: I have a list that contains 13,000 records of human names, some of them are duplicates and I want to find out the similar ones to do the manual duplication process. For an array like: ``` ["jeff","Jeff","mandy","king","queen"] ``` What would be an efficient way to get: ``` [["jeff","Jeff"]] ``` **Explanation** `["jeff","Jeff"]` since their Levenshtein distance is 1(which can be variable like 3). ``` /* Working but a slow solution */ function extractSimilarNames(uniqueNames) { let similarNamesGroup = []; for (let i = 0; i < uniqueNames.length; i++) { //compare with the rest of the array const currentName = uniqueNames[i]; let suspiciousNames = []; for (let j = i + 1; j < uniqueNames.length; j++) { const matchingName = uniqueNames[j]; if (isInLevenshteinRange(currentName, matchingName, 1)) { suspiciousNames.push(matchingName); removeElementFromArray(uniqueNames, matchingName); removeElementFromArray(uniqueNames, currentName); i--; j--; } } if (suspiciousNames.length > 0) { suspiciousNames.push(currentName); } } return similarNamesGroup; } ``` I want to find the similarity via Levenshtein distance, not only the lower/uppercase similarity I already find one of the [fastest Levenshtein implementation](https://github.com/yomguithereal/talisman#readme) but it still takes me to 35 mins to get the result of 13000 items list.
2019/04/23
[ "https://Stackoverflow.com/questions/55804367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4291360/" ]
Approaches to remove similar names: 1. Use phonetical representation of the words. [cmudict](http://www.speech.cs.cmu.edu/cgi-bin/cmudict) It works with python nltk. You can find which names are close to each other phonetically. 2. Try different forms of stemming or simplifications. I would try most aggressive stemmers like Porter stemmer. 3. Levenshtein trie. You can create trie data structure that will help to find word with minimum distance to searched item, this is used for full text search in some search engines. As far as I know it's already implemented in Java. In your case you need to search one item then add it to the structure on every step, you need to make sure that item that you search is not in the structure yet. 4. Manual naive approach. Find all suitable representations of every word/name, put all representations to map and find representations that have more than 1 word. If you have around 15 different representations of one word you will need only 280K iterations to generate this object (much faster than compare each word to another, which requires around 80M comparisons with 13K names). -- Edit -- If there is a choice I would use something like Python or Java instead of JS for this. It's only my opinion based on: I don't know all requirements, it's common to use Java/Python for natural language processing, task looks more like heavy data processing than front end.
I have yet a completely different way of approaching this problem, but I believe I am presenting a pretty fast (but debatable as to how correct/incorrect) it is. My approach is to map the strings to numeric values, sort those values once, and then run through that list once, comparing neighboring values to each other. Like this: ```js // Test strings (provided by OP) with some additions var strs = ["Jeff","mandy","jeff","king","queen","joff", "Queen", "jff", "tim", "Timmo", "Tom", "Rob", "Bob"] // Function to convert a string into a numeric representation // to aid with string similarity comparison function atoi(str, maxLen){ var i = 0; for( var j = 0; j < maxLen; j++ ){ if( str[j] != null ){ i += str.toLowerCase().charCodeAt(j)*Math.pow(64,maxLen-j) - 'a'.charCodeAt(0)*Math.pow(64,maxLen-j) } else { // Normalize the string with a pad char // up to the maxLen (update the value, but don't actually // update the string...) i += '-'.charCodeAt(0)*Math.pow(64,maxLen-j) - 'a'.charCodeAt(0)*Math.pow(64,maxLen-j) } } valMap.push({ str, i }) return i; } Number.prototype.inRange = function(min, max){ return(this >= min && this <= max) } var valMap = []; // Array of string-value pairs var maxLen = strs.map((s) => s.length).sort().pop() // maxLen of all strings in the array console.log('maxLen', maxLen) strs.forEach((s) => atoi(s, maxLen)) // Map strings to values var similars = []; var subArr = [] var margin = 0.05; valMap.sort((a,b) => a.i > b.i ? 1 : -1) // Sort the map... valMap.forEach((entry, idx) => { if( idx > 0 ){ var closeness = Math.abs(entry.i / valMap[idx-1].i); if( closeness.inRange( 1 - margin, 1 + margin ) ){ if( subArr.length == 0 ) subArr.push(valMap[idx-1].str) subArr.push(entry.str) if( idx == valMap.length - 1){ similars.push(subArr) } } else { if( subArr.length > 0 ) similars.push(subArr) subArr = [] } } }) console.log('similars', similars) ``` I'm treating each string as if each were a "64-bit number", where each "bit" could take on the alphanumeric values, with 'a' representing 0. Then I sort that *once*. Then, if similar values are encountered to the previous one (i.e., if the ratio of the two is near 1), then I deduce I have similar strings. The other thing I do is check for the max string length, and normalize all the strings to that length in the calculation of the "64-bit value". --- EDIT: even more stress testing --- And yet, here is some additional testing, which pulls a large list of names and performs the processing rather quickly (~ 50ms on 20k+ names, with lots of false positives). Regardless, this snippet should make it easier to troubleshoot: ```js var valMap = []; // Array of string-value pairs /* Extensions */ Number.prototype.inRange = function(min, max){ return(this >= min && this <= max) } /* Methods */ // Function to convert a string into a numeric representation // to aid with string similarity comparison function atoi(str, maxLen){ var i = 0; for( var j = 0; j < maxLen; j++ ){ if( str[j] != null ){ i += str.toLowerCase().charCodeAt(j)*Math.pow(64,maxLen-j) - 'a'.charCodeAt(0)*Math.pow(64,maxLen-j) } else { // Normalize the string with a pad char // up to the maxLen (update the value, but don't actually // update the string...) i += '-'.charCodeAt(0)*Math.pow(64,maxLen-j) - 'a'.charCodeAt(0)*Math.pow(64,maxLen-j) } } valMap.push({ str, i }) return i; } function findSimilars(strs){ var maxLen = strs.map((s) => s.length).sort().pop() // maxLen of all strings in the array console.log('maxLen', maxLen) strs.forEach((s) => atoi(s, maxLen)) // Map strings to values var similars = []; var subArr = [] var margin = 0.05; valMap.sort((a,b) => a.i > b.i ? 1 : -1) // Sort the map... valMap.forEach((entry, idx) => { if( idx > 0 ){ var closeness = Math.abs(entry.i / valMap[idx-1].i); if( closeness.inRange( 1 - margin, 1 + margin ) ){ if( subArr.length == 0 ) subArr.push(valMap[idx-1].str) subArr.push(entry.str) if( idx == valMap.length - 1){ similars.push(subArr) } } else { if( subArr.length > 0 ) similars.push(subArr) subArr = [] } } }) console.log('similars', similars) } // Stress test with 20k+ names $.get('https://raw.githubusercontent.com/dominictarr/random-name/master/names.json') .then((resp) => { var strs = JSON.parse(resp); console.time('processing') findSimilars(strs) console.timeEnd('processing') }) .catch((err) => { console.err('Err retrieving JSON'); }) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> ``` (For some reason, when I run this in [JSFiddle](https://jsfiddle.net/3o5L4svx/1/), I get it to run in ~50ms, but in the Stackoverflow snippet, it's closer to 1000ms.)
55,804,367
Background: I have a list that contains 13,000 records of human names, some of them are duplicates and I want to find out the similar ones to do the manual duplication process. For an array like: ``` ["jeff","Jeff","mandy","king","queen"] ``` What would be an efficient way to get: ``` [["jeff","Jeff"]] ``` **Explanation** `["jeff","Jeff"]` since their Levenshtein distance is 1(which can be variable like 3). ``` /* Working but a slow solution */ function extractSimilarNames(uniqueNames) { let similarNamesGroup = []; for (let i = 0; i < uniqueNames.length; i++) { //compare with the rest of the array const currentName = uniqueNames[i]; let suspiciousNames = []; for (let j = i + 1; j < uniqueNames.length; j++) { const matchingName = uniqueNames[j]; if (isInLevenshteinRange(currentName, matchingName, 1)) { suspiciousNames.push(matchingName); removeElementFromArray(uniqueNames, matchingName); removeElementFromArray(uniqueNames, currentName); i--; j--; } } if (suspiciousNames.length > 0) { suspiciousNames.push(currentName); } } return similarNamesGroup; } ``` I want to find the similarity via Levenshtein distance, not only the lower/uppercase similarity I already find one of the [fastest Levenshtein implementation](https://github.com/yomguithereal/talisman#readme) but it still takes me to 35 mins to get the result of 13000 items list.
2019/04/23
[ "https://Stackoverflow.com/questions/55804367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4291360/" ]
As in your working code you use Levenshtein distance 1 only, I will assume no other distances need to be found. I will propose a similar solution as Jonas Wilms posted, with these differences: * No need to call a `isLevenshtein` function * Produces only unique pairs * Each pair is lexically ordered ```js // Sample data with lots of similar names const names = ["Adela","Adelaida","Adelaide","Adele","Adelia","AdeLina","Adeline", "Adell","AdellA","Adelle","Ardelia","Ardell","Ardella","Ardelle", "Ardis","Madeline","Odelia","ODELL","Odessa","Odette"]; const map = {}; const pairs = new Set; for (const name of names) { for (const i in name+"_") { // Additional iteration to NOT delete a character const key = (name.slice(0, i) + name.slice(+i + 1, name.length)).toLowerCase(); // Group words together where the removal from the same index leads to the same key if (!map[key]) map[key] = Array.from({length: key.length+1}, () => new Set); // If NO character was removed, put the word in EACH group for (const set of (+i < name.length ? [map[key][i]] : map[key])) { if (set.has(name)) continue; for (let similar of set) pairs.add(JSON.stringify([similar, name].sort())); set.add(name); } } } const result = [...pairs].sort().map(JSON.parse); // sort is optional console.log(result); ``` I tested this on a set of 13000 names, including at least 4000 *different* names, and it produced 8000 pairs in about 0.3 seconds.
I have yet a completely different way of approaching this problem, but I believe I am presenting a pretty fast (but debatable as to how correct/incorrect) it is. My approach is to map the strings to numeric values, sort those values once, and then run through that list once, comparing neighboring values to each other. Like this: ```js // Test strings (provided by OP) with some additions var strs = ["Jeff","mandy","jeff","king","queen","joff", "Queen", "jff", "tim", "Timmo", "Tom", "Rob", "Bob"] // Function to convert a string into a numeric representation // to aid with string similarity comparison function atoi(str, maxLen){ var i = 0; for( var j = 0; j < maxLen; j++ ){ if( str[j] != null ){ i += str.toLowerCase().charCodeAt(j)*Math.pow(64,maxLen-j) - 'a'.charCodeAt(0)*Math.pow(64,maxLen-j) } else { // Normalize the string with a pad char // up to the maxLen (update the value, but don't actually // update the string...) i += '-'.charCodeAt(0)*Math.pow(64,maxLen-j) - 'a'.charCodeAt(0)*Math.pow(64,maxLen-j) } } valMap.push({ str, i }) return i; } Number.prototype.inRange = function(min, max){ return(this >= min && this <= max) } var valMap = []; // Array of string-value pairs var maxLen = strs.map((s) => s.length).sort().pop() // maxLen of all strings in the array console.log('maxLen', maxLen) strs.forEach((s) => atoi(s, maxLen)) // Map strings to values var similars = []; var subArr = [] var margin = 0.05; valMap.sort((a,b) => a.i > b.i ? 1 : -1) // Sort the map... valMap.forEach((entry, idx) => { if( idx > 0 ){ var closeness = Math.abs(entry.i / valMap[idx-1].i); if( closeness.inRange( 1 - margin, 1 + margin ) ){ if( subArr.length == 0 ) subArr.push(valMap[idx-1].str) subArr.push(entry.str) if( idx == valMap.length - 1){ similars.push(subArr) } } else { if( subArr.length > 0 ) similars.push(subArr) subArr = [] } } }) console.log('similars', similars) ``` I'm treating each string as if each were a "64-bit number", where each "bit" could take on the alphanumeric values, with 'a' representing 0. Then I sort that *once*. Then, if similar values are encountered to the previous one (i.e., if the ratio of the two is near 1), then I deduce I have similar strings. The other thing I do is check for the max string length, and normalize all the strings to that length in the calculation of the "64-bit value". --- EDIT: even more stress testing --- And yet, here is some additional testing, which pulls a large list of names and performs the processing rather quickly (~ 50ms on 20k+ names, with lots of false positives). Regardless, this snippet should make it easier to troubleshoot: ```js var valMap = []; // Array of string-value pairs /* Extensions */ Number.prototype.inRange = function(min, max){ return(this >= min && this <= max) } /* Methods */ // Function to convert a string into a numeric representation // to aid with string similarity comparison function atoi(str, maxLen){ var i = 0; for( var j = 0; j < maxLen; j++ ){ if( str[j] != null ){ i += str.toLowerCase().charCodeAt(j)*Math.pow(64,maxLen-j) - 'a'.charCodeAt(0)*Math.pow(64,maxLen-j) } else { // Normalize the string with a pad char // up to the maxLen (update the value, but don't actually // update the string...) i += '-'.charCodeAt(0)*Math.pow(64,maxLen-j) - 'a'.charCodeAt(0)*Math.pow(64,maxLen-j) } } valMap.push({ str, i }) return i; } function findSimilars(strs){ var maxLen = strs.map((s) => s.length).sort().pop() // maxLen of all strings in the array console.log('maxLen', maxLen) strs.forEach((s) => atoi(s, maxLen)) // Map strings to values var similars = []; var subArr = [] var margin = 0.05; valMap.sort((a,b) => a.i > b.i ? 1 : -1) // Sort the map... valMap.forEach((entry, idx) => { if( idx > 0 ){ var closeness = Math.abs(entry.i / valMap[idx-1].i); if( closeness.inRange( 1 - margin, 1 + margin ) ){ if( subArr.length == 0 ) subArr.push(valMap[idx-1].str) subArr.push(entry.str) if( idx == valMap.length - 1){ similars.push(subArr) } } else { if( subArr.length > 0 ) similars.push(subArr) subArr = [] } } }) console.log('similars', similars) } // Stress test with 20k+ names $.get('https://raw.githubusercontent.com/dominictarr/random-name/master/names.json') .then((resp) => { var strs = JSON.parse(resp); console.time('processing') findSimilars(strs) console.timeEnd('processing') }) .catch((err) => { console.err('Err retrieving JSON'); }) ``` ```html <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> ``` (For some reason, when I run this in [JSFiddle](https://jsfiddle.net/3o5L4svx/1/), I get it to run in ~50ms, but in the Stackoverflow snippet, it's closer to 1000ms.)
42,841,290
I am really new to using `DWORD` in C++ in place of boolean. Hence, please excuse my question. I have an `enum`: ``` enum foo { foo1 = 0x0; foo2 = 0x1 //.... } DWORD foo; ``` I am using this `enum` to check for multiple conditions: ``` if(somethinghappenstothisvariable) { foo|= foo1; } if(somethinghappenstosecondvariable) { foo|=foo2; } ``` Now in another file I have to check for individual variables condition ``` if(foo &foo1) { //do something; } if(foo & foo2) { //do something; } ``` I figured that `|=` adds up the value to the `DWORD` if both conditions are `true` which leads to `foo & foo2` only to be true while `foo & foo1` will not be as the value of `DWORD` will be `1`. Hence, I was wondering if there is anyway I can check this for individual `DWORD` value.
2017/03/16
[ "https://Stackoverflow.com/questions/42841290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1435077/" ]
The issue: 1 = bit 0, 0 is invalid. To the check each "condition" should represent a separate bit (bit 0 = 1, bit 1 = 2, etc.) So - a simple change: `foo1 = 0x01; foo2 = 0x02;` should fix it. NOTE: any additional checks should represent bit values, NOT ordinal. In other words, `foo3 = 0x04;` (not `0x03;`)
You can make it correct easier by creating these constants with shifts: ``` enum foo { foo1 = 1 << 0; foo2 = 1 << 1; foo3 = 1 << 2; //.... } ``` This way you can be sure that each mask has a single bit set.
544,509
I use both `Moodle` and `latex` to write all my quizzes. but, I use `latex` to generate formula rich questions in `moodle`. The latex package `Moodle` can do this. Then I import it as XML file to `moodle`. This works perfectly. Before import the quiz the latex compile the code and produce a PDF so can make sure everything ok. It works well for the close quiz question as well. But, when I have the all the question in the close quiz the 'multichoice' then when I import it as an xml then I get error message although latex compile it without any error. appreciate any help **Latex code:** ```latex \documentclass[10pt,a4paper]{article} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} \usepackage{amsmath} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{graphicx} \usepackage{moodle} \begin{document} \begin{quiz}{MRTS} \begin{cloze}{MRTS Q1}\\ A production function is given as $ Q=15\sqrt{KL}$. Q=quantity of output, L = the units of labour, K = the units of capital. The marginal product of labour, $MP_L$ of this function is: \begin{multi}[horizontal] \item*$7.5K^{0.5}L^{-0.5}$ \item $7.5K^{-0.5}L^{0.5}$ \item $K^{0.5}L^{-0.5}$ \item $K^{-0.5}L^{0.5}$ \item $15K^{0.5}L^{-0.5}$ \item $15K^{-0.5}L^{0.5}$ \end{multi} A production function is given as $ Q=15\sqrt{KL}$. Q=quantity of output, L = the units of labour, K = the units of capital. The marginal product of labour, $MP_K$ of this function is:? \begin{multi}[horizontal] \item $7.5K^{0.5}L^{-0.5}$ \item *$7.5K^{-0.5}L^{0.5}$ \item $K^{0.5}L^{-0.5}$ \item $K^{-0.5}L^{0.5}$ \item $15K^{0.5}L^{-0.5}$ \item $15K^{-0.5}L^{0.5}$ \end{multi} A production function is given as $ Q=15\sqrt{KL}$. Q=quantity of output, L = the units of labour, K = the units of capital.The marginal rate of technical substitution associated with this production function is?\\ Note: $MRTS=\displaystyle -\frac{\frac{\partial Q}{\partial L}}{\frac{\partial Q}{\partial K}}$ \begin{multi}[horizontal] \item $\frac{K}{L}$ \item*$-\frac{K}{L}$ \item $\sqrt{\frac{K}{L}}$ \item $\sqrt{\frac{L}{K}}$ \item $-\sqrt{\frac{K}{L}}$ \item $-\sqrt{\frac{L}{K}}$ \end{multi} \end{cloze} \end{quiz} \end{document} ``` [![Moodle output](https://i.stack.imgur.com/gBp0U.png)](https://i.stack.imgur.com/gBp0U.png)
2020/05/16
[ "https://tex.stackexchange.com/questions/544509", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/215771/" ]
Unfortunately, I suspect it is a bug/limitation of the Cloze type of questions. This MWE ```latex % \documentclass{article} \usepackage[T1]{fontenc} \usepackage{moodle} \begin{document} \begin{quiz}{Test cloze} \begin{cloze}{Multiple questions} A $x$ is \begin{multi}[vertical] One two three \item* one $u^1$ \item two \item three \end{multi} \end{cloze} \end{quiz} \end{document} ``` works ok, and give the expected result in Moodle: [![enter image description here](https://i.stack.imgur.com/vlNS9.png)](https://i.stack.imgur.com/vlNS9.png) But if you add braces around the exponent: ```latex \begin{document} \begin{quiz}{Test cloze} \begin{cloze}{Multiple questions} A $x$ is \begin{multi}[vertical] One two three \item* one $u^{1}$ \item two \item three \end{multi} \end{cloze} \end{quiz} \end{document} ``` Moodle fails importing it with: [![enter image description here](https://i.stack.imgur.com/9m1c7.png)](https://i.stack.imgur.com/9m1c7.png) Now, the only difference between the two XML files generated is this one: ``` [romano:~/tmp] % diff quiz-hr-moodle\ \(copy\).xml quiz-hr-moodle.xml 15c15 < <text><![CDATA[<p></P><P>A \(x\) is </P><P>One two three {1:MULTICHOICE_V:=one \(u^{1}\)~two~three}</p>]]></text> --- > <text><![CDATA[<p></P><P>A \(x\) is </P><P>One two three {1:MULTICHOICE_V:=one \(u^1\)~two~three}</p>]]></text> ``` and so it seems that the parser of Moodle get confused by the closing brace in the formula. I really do not know how to escape it, and even if the problem is recognized in the Moodle doc, it seems that simply it will not work: [![enter image description here](https://i.stack.imgur.com/N5xpQ.png)](https://i.stack.imgur.com/N5xpQ.png) So basically my takeout is that you can't use formulas in answers in cloze questions. The manual says you can: [![enter image description here](https://i.stack.imgur.com/z6XAZ.png)](https://i.stack.imgur.com/z6XAZ.png) ...but I didn't manage to get it going. Notice that if you go in the XML file and escape the `{` `}` with `\{`and `\}` then the XML file is accepted, but the formula is broken. This does not happen in normal (no `cloze`) `multi` questions, fortunately. So my stopgap solution would be to use Unicode formulas directly typed there, and switch to `lualatex` for the compilation. Another stopgap solution is to use images for your formulas: ``` % \documentclass{article} \usepackage[T1]{fontenc} \usepackage{graphicx} \usepackage{moodle} \begin{document} \begin{quiz}{Test cloze} \begin{cloze}{one cloze} A $x$ is \begin{multi}[vertical] One two three \item* one \includegraphics[height=4ex]{formula1.png} \item two \item three \end{multi} \end{cloze} \end{quiz} \end{document} ``` will render as: [![Output with embedded graph ](https://i.stack.imgur.com/d0mTK.png)](https://i.stack.imgur.com/d0mTK.png) Not ideal (can be probably made better with a bit of transparency or whatever) but if you need it...
I modified the moodle package to fix this bug. LaTeX equations can be used in cloze subquestion fields. See [this fixed issue](https://framagit.org/mattgk/moodle/issues/10). Here is a MWE: ```latex % !TEX TS-program = lualatex \documentclass[10pt,a4paper]{article} \usepackage{moodle} % development version 0.8 \begin{document} \begin{quiz}{Category} \begin{cloze}{Question name} Question text \begin{multi}[vertical] \item[feedback={$7.5K^{0.5}L^{-0.5}$ is correct}]*$7.5K^{0.5}L^{-0.5}$ \item[feedback={$7.5K^{-0.5}L^{0.5}$ is incorrect}] $7.5K^{-0.5}L^{0.5}$ \end{multi} \end{cloze} \end{quiz} \end{document} ``` the resulting PDF is rendered like this [![PDF obtained from MWE](https://i.stack.imgur.com/O3ZuB.png)](https://i.stack.imgur.com/O3ZuB.png) the resulting XML file is ```xml <?xml version="1.0" encoding="UTF-8"?> <!-- This file was generated on 2020-11-10 by LuaLaTeX --> <!-- running on Linux with the package moodle v0.8 --> <quiz> <question type="category"> <category> <text>$course$/top/Category</text> </category> </question> <question type="cloze"> <name format="html"> <text><![CDATA[Question name]]></text> </name> <questiontext format="html"> <text><![CDATA[<p>Question text {1:MULTICHOICE_VS:=\(7.5K^{0.5\}L^{-0.5\}\)#\(7.5K^{0.5\}L^{-0.5\}\) is correct~\(7.5K^{-0.5\}L^{0.5\}\)#\(7.5K^{-0.5\}L^{0.5\}\) is incorrect}</p>]]></text> </questiontext> <defaultgrade>1</defaultgrade> <generalfeedback format="html"><text/></generalfeedback> <penalty>0.10</penalty> <hidden>0</hidden> </question> </quiz> ``` and after import in Moodle (3.5 here with MathJax LaTeX renderer) the question preview looks like that [![Question preview after import of XML in Moodle](https://i.stack.imgur.com/uz7iI.png)](https://i.stack.imgur.com/uz7iI.png)
14,344,286
> > **Possible Duplicate:** > > [Best way to get identity of inserted row?](https://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row) > > > Assume there is a large web application like a social network with many online users. Users continually insert new row to a certain table. This application needs new row's **ID** after each insert, and this **ID** is an auto-increased `int` column. Getting last raw's ID is done by SQL `SELECT IDENT_CURRENT()` as a separate function call via web application for each user. Does it work properly and return correct **ID** if more than one user insert row at the same time?
2013/01/15
[ "https://Stackoverflow.com/questions/14344286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/689779/" ]
Someone in our company used ident\_current where he should have used scope\_identity (and now should be using OUTPUT). It happened that the application was inserting a record at the same time as a data import of millions of records was running. The wrong ids got attached to the child records in the subsequent record import causing a data integrity problem that took a long time to figure out and fix. There is no circumstance where you should be using ident\_current to grab a value you just inserted. It is a **guarantee** of data integrity problems. If you are using a version of SQL server that has OUTPUT available, this is the technique that is preferred. Not only will OUTPUT give you the id just inserted but it can also give you other values inserted, so that you can get values for multiple record inserts more easily as a well as single ones You can also use it to find out what was deleted or updated. So it is an extremely valueable tool. Basically, you set up a table variable with the columns you want, then you use the OUTPUT clause in the INSERT, UPDATE or DELETE, then you can use the table variable afterwards to get the information you need for other processing steps. Some examples to see what you can do with output in an insert statement: ``` DECLARE @MyTableVar table( MyID int, MyName varchar(50)); INSERT MyTable1 (MYName) OUTPUT INSERTED.MyID, INSERTED.MyName INTO @MyTableVar VALUES ('test'); --Display the result set of the table variable. SELECT MyID, MyName FROM @MyTableVar; --Display the result set of the table. Insert into table2 (MyID,test2, test2) SELECT MyID, 'mttest1', 'mytest2' FROM @MyTableVar; Insert into table2 (MyID,field1, InsertedDate) SELECT MyID, s.Field1, getdate() FROM @MyTableVar t join stagingtable s on t.MyName = s.MyName ```
You probably want to use SCOPE\_IDENTITY() instead. Below is a breakdown of the differences between @@IDENTITY, IDENT\_CURRENT() and SCOPE\_IDENTITY (stolen from [here](http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity-of-record/)): > > SELECT @@IDENTITY It returns the last IDENTITY value produced on a > connection, regardless of the table that produced the value, and > regardless of the scope of the statement that produced the value. > @@IDENTITY will return the last identity value entered into a table in > your current session. While @@IDENTITY is limited to the current > session, it is not limited to the current scope. If you have a trigger > on a table that causes an identity to be created in another table, you > will get the identity that was created last, even if it was the > trigger that created it. > > > SELECT SCOPE\_IDENTITY() It returns the last IDENTITY value produced on > a connection and by a statement in the same scope, regardless of the > table that produced the value. SCOPE\_IDENTITY(), like @@IDENTITY, will > return the last identity value created in the current session, but it > will also limit it to your current scope as well. In other words, it > will return the last identity value that you explicitly created, > rather than any identity that was created by a trigger or a user > defined function. > > > SELECT IDENT\_CURRENT(‘tablename’) It returns the last IDENTITY value > produced in a table, regardless of the connection that created the > value, and regardless of the scope of the statement that produced the > value. IDENT\_CURRENT is not limited by scope and session; it is > limited to a specified table. IDENT\_CURRENT returns the identity value > generated for a specific table in any session and any scope. > > > As you can see SCOPE\_IDENTITY() will return the last ID generated by your current connection by a statement that is in scope. Based on what you are asking it sounds like this will fit your needs better.
14,344,286
> > **Possible Duplicate:** > > [Best way to get identity of inserted row?](https://stackoverflow.com/questions/42648/best-way-to-get-identity-of-inserted-row) > > > Assume there is a large web application like a social network with many online users. Users continually insert new row to a certain table. This application needs new row's **ID** after each insert, and this **ID** is an auto-increased `int` column. Getting last raw's ID is done by SQL `SELECT IDENT_CURRENT()` as a separate function call via web application for each user. Does it work properly and return correct **ID** if more than one user insert row at the same time?
2013/01/15
[ "https://Stackoverflow.com/questions/14344286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/689779/" ]
Someone in our company used ident\_current where he should have used scope\_identity (and now should be using OUTPUT). It happened that the application was inserting a record at the same time as a data import of millions of records was running. The wrong ids got attached to the child records in the subsequent record import causing a data integrity problem that took a long time to figure out and fix. There is no circumstance where you should be using ident\_current to grab a value you just inserted. It is a **guarantee** of data integrity problems. If you are using a version of SQL server that has OUTPUT available, this is the technique that is preferred. Not only will OUTPUT give you the id just inserted but it can also give you other values inserted, so that you can get values for multiple record inserts more easily as a well as single ones You can also use it to find out what was deleted or updated. So it is an extremely valueable tool. Basically, you set up a table variable with the columns you want, then you use the OUTPUT clause in the INSERT, UPDATE or DELETE, then you can use the table variable afterwards to get the information you need for other processing steps. Some examples to see what you can do with output in an insert statement: ``` DECLARE @MyTableVar table( MyID int, MyName varchar(50)); INSERT MyTable1 (MYName) OUTPUT INSERTED.MyID, INSERTED.MyName INTO @MyTableVar VALUES ('test'); --Display the result set of the table variable. SELECT MyID, MyName FROM @MyTableVar; --Display the result set of the table. Insert into table2 (MyID,test2, test2) SELECT MyID, 'mttest1', 'mytest2' FROM @MyTableVar; Insert into table2 (MyID,field1, InsertedDate) SELECT MyID, s.Field1, getdate() FROM @MyTableVar t join stagingtable s on t.MyName = s.MyName ```
Another save version ... ``` Insert Atab (na,nu) OUTPUT INSERTED.id values('Text','Add') ``` > > Returns information from, or expressions based on, each row affected > by an INSERT, UPDATE, DELETE, or MERGE statement. These results can be > returned to the processing application for use in such things as > confirmation messages, archiving, and other such application > requirements. The results can also be inserted into a table or table > variable. Additionally, you can capture the results of an OUTPUT > clause in a nested INSERT, UPDATE, DELETE, or MERGE statement, and > insert those results into a target table or view. > > > [Reference](http://msdn.microsoft.com/en-us/library/ms177564%28SQL.105%29.aspx)
72,317
bitcoin noob but here goes. I have a bitcoin address (obviously) and someone has sent me bitcoins. Now I don't have a wallet just the address (public and private) in order to withdraw from an ATM or maybe even purchase stuff? Do I have to create a bitcoin wallet as well? Sorry if that is a REALLY dumb question but I don't know too much about this stuff. Thanks guys
2018/03/13
[ "https://bitcoin.stackexchange.com/questions/72317", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/78785/" ]
You're just puzzling your self. If you want to send your Bitcoin to someone or buying some product. You will need a Bitcoin wallet or you can sweep that address funds to the destination address using e.g. electrum.. I don't much about exchange or how to withdraw your bitcoin from an "ATM" but you have to check localbitcoins.com, they can exchange your bitcoins based on your country.
Get a wallet and import your privkey
72,317
bitcoin noob but here goes. I have a bitcoin address (obviously) and someone has sent me bitcoins. Now I don't have a wallet just the address (public and private) in order to withdraw from an ATM or maybe even purchase stuff? Do I have to create a bitcoin wallet as well? Sorry if that is a REALLY dumb question but I don't know too much about this stuff. Thanks guys
2018/03/13
[ "https://bitcoin.stackexchange.com/questions/72317", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/78785/" ]
By having the private key you can sweep the wallet using a desktop or mobile wallet, I recommend electrum. If you are new to the bitcoin world, visit <https://bitcoin.org> that has a lot of information so you can get up to date and get out of duduas
You're just puzzling your self. If you want to send your Bitcoin to someone or buying some product. You will need a Bitcoin wallet or you can sweep that address funds to the destination address using e.g. electrum.. I don't much about exchange or how to withdraw your bitcoin from an "ATM" but you have to check localbitcoins.com, they can exchange your bitcoins based on your country.
72,317
bitcoin noob but here goes. I have a bitcoin address (obviously) and someone has sent me bitcoins. Now I don't have a wallet just the address (public and private) in order to withdraw from an ATM or maybe even purchase stuff? Do I have to create a bitcoin wallet as well? Sorry if that is a REALLY dumb question but I don't know too much about this stuff. Thanks guys
2018/03/13
[ "https://bitcoin.stackexchange.com/questions/72317", "https://bitcoin.stackexchange.com", "https://bitcoin.stackexchange.com/users/78785/" ]
By having the private key you can sweep the wallet using a desktop or mobile wallet, I recommend electrum. If you are new to the bitcoin world, visit <https://bitcoin.org> that has a lot of information so you can get up to date and get out of duduas
Get a wallet and import your privkey
39,474,480
I'm unfamiliar with angular. But the front end dev working my project insists he wants the json in this way: ``` { "data": [{ "area1": { "rows": [{ "the_desc": "A value 1", "value": "sample value 1" }, { "the_desc": "A value 2", "value": "sample value 2" }, { "the_desc": "A value 3", "value": "other 3" }, { "the_desc": "A value 4", "value": "other 4" }, { "the_desc": "A value 5", "value": "other goats fly" }, { "the_desc": "A value 6", "value": "bla blah" }, { "the_desc": "A value 7", "value": "other 7" }, { "the_desc": "A value 8", "value": "other 8" }] } }, { "area2": { "rows": [{ "the_desc": "A value 9", "value": "sample value 9" }, { "the_desc": "A value 10", "value": "sample value 10" }, { "the_desc": "A value 11", "value": "other 11" }, { "the_desc": "A value 12", "value": "other 12" }, { "the_desc": "A value 13", "value": "other goats fly 13" }, { "the_desc": "A value 14", "value": "bla blah" }, { "the_desc": "A value 15", "value": "other 15" }, { "the_desc": "A value 16", "value": "other 16" }] } }] } ``` I thought we should get rid of the repeating strings like "the\_desc" and "value", and use : ``` { "data": [{ "area1": [ ["1", "2"], ["3", "4"] ] }, { "area2": [ ["21", "22", "a5"], ["23", "24", "b6"] ] }] } ``` But he insists that NG-repeat would not be able to get the inner arrays (they are known column rows of data. Could be [][] table data. Question : is there any issue gettig data like that in angular 1? Without having nested NG repeat. Would it make a difference if I said the columns are fixed for each area? Is there a way to iterate over the rows, and access the columns by index? In our case the number of columns is known for each area (table on page). Reason : less payload from server. Faster network data transfer. Got it with help from two of the answers, experimenting on <https://plnkr.co/edit/DrsXTP4kD0CnyAQwuoSu?p=preview> and the lovely angular error reporting : <https://docs.angularjs.org/error/ngRepeat/dupes?p0=ele%20in%20data.data%5B1%5D.area2%5B0%5D&p1=string:col%203%20A&p2=col%203%20A> . Gist of the solution: In js controller: ``` $scope.data = { "data": [{"area1": [[ "A value 1",... ``` And HTML: ``` <div class= "" ng-repeat="ele in data.data[1].area2 track by $index"> <span class='d2'> {{(ele[0])}} </span><span class='d2'> {{(ele[1])}}... ```
2016/09/13
[ "https://Stackoverflow.com/questions/39474480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1643558/" ]
As a front-end dev, I would choose the first structure as well. In any case, you'd have to use nested ng-repeat like so: ``` <div class="area" ng-repeat="area in data"> <div class="row" ng-repeat="row in area.rows"> <p class="description">{{::row.the_desc}}</p> <p class="value">{{::row.value}}</p> </div> </div> ``` For the second snippet: ``` <div class="area" ng-repeat="area in data"> <div class="row" ng-repeat="(key, value) in area.rows"> <p class="description">{{::key}}</p> <p class="value">{{::value}}</p> </div> </div> ``` For the 3rd snipped, provided that the array structure remains the same and has only two values, we would be able to access them by index. ``` <div class="area" ng-repeat="(key,area) in data"> <!-- Prints area1, area2 if necessary --> <p>{{key}}</p> <!-- Prints 1st and 2nd value of the area array --> <div class="row" ng-repeat="row in area"> <p class="description">{{row[0}}</p> <p class="value">{{row[1]}}</p> </div> </div> ``` Is it possible to achieve this without nested ng-repeat? Not likely. There are too many nested arrays. But honestly, I don't think that storing a "value" in object key is a good practice (even it's possible to display with Angular), so I'd suggest you to follow your dev's advice and use the first structure.
No, not at all, `ng-repeats` can be nested. Even in vanilla Javascript, you could get this data into whatever formation you'd like in order to make `ng-repeat` display it as desired. The last two options you put would actually make this more difficult. For the first configuration, assuming it has been `JSON.parse()`ed: ``` <section ng-repeat="area in data"> <div ng-repeat="row in area.rows"> <p>{{row.the_desc}} is {{row.value}}</p> </div> </section> ``` This iterates over the `data` array, and for each `area` in `data` creates another `ng-repeat` for the `area#.rows` arrays to iterate over the rows. It is even possible to use `ng-repeat` to iterate over keys in an object, which would need to be done with the other two solutions.
39,474,480
I'm unfamiliar with angular. But the front end dev working my project insists he wants the json in this way: ``` { "data": [{ "area1": { "rows": [{ "the_desc": "A value 1", "value": "sample value 1" }, { "the_desc": "A value 2", "value": "sample value 2" }, { "the_desc": "A value 3", "value": "other 3" }, { "the_desc": "A value 4", "value": "other 4" }, { "the_desc": "A value 5", "value": "other goats fly" }, { "the_desc": "A value 6", "value": "bla blah" }, { "the_desc": "A value 7", "value": "other 7" }, { "the_desc": "A value 8", "value": "other 8" }] } }, { "area2": { "rows": [{ "the_desc": "A value 9", "value": "sample value 9" }, { "the_desc": "A value 10", "value": "sample value 10" }, { "the_desc": "A value 11", "value": "other 11" }, { "the_desc": "A value 12", "value": "other 12" }, { "the_desc": "A value 13", "value": "other goats fly 13" }, { "the_desc": "A value 14", "value": "bla blah" }, { "the_desc": "A value 15", "value": "other 15" }, { "the_desc": "A value 16", "value": "other 16" }] } }] } ``` I thought we should get rid of the repeating strings like "the\_desc" and "value", and use : ``` { "data": [{ "area1": [ ["1", "2"], ["3", "4"] ] }, { "area2": [ ["21", "22", "a5"], ["23", "24", "b6"] ] }] } ``` But he insists that NG-repeat would not be able to get the inner arrays (they are known column rows of data. Could be [][] table data. Question : is there any issue gettig data like that in angular 1? Without having nested NG repeat. Would it make a difference if I said the columns are fixed for each area? Is there a way to iterate over the rows, and access the columns by index? In our case the number of columns is known for each area (table on page). Reason : less payload from server. Faster network data transfer. Got it with help from two of the answers, experimenting on <https://plnkr.co/edit/DrsXTP4kD0CnyAQwuoSu?p=preview> and the lovely angular error reporting : <https://docs.angularjs.org/error/ngRepeat/dupes?p0=ele%20in%20data.data%5B1%5D.area2%5B0%5D&p1=string:col%203%20A&p2=col%203%20A> . Gist of the solution: In js controller: ``` $scope.data = { "data": [{"area1": [[ "A value 1",... ``` And HTML: ``` <div class= "" ng-repeat="ele in data.data[1].area2 track by $index"> <span class='d2'> {{(ele[0])}} </span><span class='d2'> {{(ele[1])}}... ```
2016/09/13
[ "https://Stackoverflow.com/questions/39474480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1643558/" ]
No, not at all, `ng-repeats` can be nested. Even in vanilla Javascript, you could get this data into whatever formation you'd like in order to make `ng-repeat` display it as desired. The last two options you put would actually make this more difficult. For the first configuration, assuming it has been `JSON.parse()`ed: ``` <section ng-repeat="area in data"> <div ng-repeat="row in area.rows"> <p>{{row.the_desc}} is {{row.value}}</p> </div> </section> ``` This iterates over the `data` array, and for each `area` in `data` creates another `ng-repeat` for the `area#.rows` arrays to iterate over the rows. It is even possible to use `ng-repeat` to iterate over keys in an object, which would need to be done with the other two solutions.
I believe you need to change your data structure a little. Setting it up like this should help: ``` $scope.data = [{ name: "area1", rows : [{ "the_desc": "A value 1", "value": "sample value 1" }, { "the_desc": "A value 2", "value": "sample value 2" }, { "the_desc": "A value 3", "value": "other 3" }, { "the_desc": "A value 4", "value": "other 4" }, { "the_desc": "A value 5", "value": "other goats fly" }, { "the_desc": "A value 6", "value": "bla blah" }, { "the_desc": "A value 7", "value": "other 7" }, { "the_desc": "A value 8", "value": "other 8" }] }, { name: "area2", "rows": [{ "the_desc": "A value 9", "value": "sample value 9" }, { "the_desc": "A value 10", "value": "sample value 10" }, { "the_desc": "A value 11", "value": "other 11" }, { "the_desc": "A value 12", "value": "other 12" }, { "the_desc": "A value 13", "value": "other goats fly 13" }, { "the_desc": "A value 14", "value": "bla blah" }, { "the_desc": "A value 15", "value": "other 15" }, { "the_desc": "A value 16", "value": "other 16" }] } ``` Then it will be easy to access with `ng-repeat` like so: ``` <div ng-repeat="d in data"> <h1>{{d.name}}</h1> <div ng-repeat="r in d.rows"> {{r.the_desc}} </div> </div> ``` Here's a [Plunker](http://plnkr.co/edit/ihe1JkA5Hb0Uxlz3xem8?p=preview). I'm not sure how you get your data, or if it is hardcoded, but this should at least get you started.
39,474,480
I'm unfamiliar with angular. But the front end dev working my project insists he wants the json in this way: ``` { "data": [{ "area1": { "rows": [{ "the_desc": "A value 1", "value": "sample value 1" }, { "the_desc": "A value 2", "value": "sample value 2" }, { "the_desc": "A value 3", "value": "other 3" }, { "the_desc": "A value 4", "value": "other 4" }, { "the_desc": "A value 5", "value": "other goats fly" }, { "the_desc": "A value 6", "value": "bla blah" }, { "the_desc": "A value 7", "value": "other 7" }, { "the_desc": "A value 8", "value": "other 8" }] } }, { "area2": { "rows": [{ "the_desc": "A value 9", "value": "sample value 9" }, { "the_desc": "A value 10", "value": "sample value 10" }, { "the_desc": "A value 11", "value": "other 11" }, { "the_desc": "A value 12", "value": "other 12" }, { "the_desc": "A value 13", "value": "other goats fly 13" }, { "the_desc": "A value 14", "value": "bla blah" }, { "the_desc": "A value 15", "value": "other 15" }, { "the_desc": "A value 16", "value": "other 16" }] } }] } ``` I thought we should get rid of the repeating strings like "the\_desc" and "value", and use : ``` { "data": [{ "area1": [ ["1", "2"], ["3", "4"] ] }, { "area2": [ ["21", "22", "a5"], ["23", "24", "b6"] ] }] } ``` But he insists that NG-repeat would not be able to get the inner arrays (they are known column rows of data. Could be [][] table data. Question : is there any issue gettig data like that in angular 1? Without having nested NG repeat. Would it make a difference if I said the columns are fixed for each area? Is there a way to iterate over the rows, and access the columns by index? In our case the number of columns is known for each area (table on page). Reason : less payload from server. Faster network data transfer. Got it with help from two of the answers, experimenting on <https://plnkr.co/edit/DrsXTP4kD0CnyAQwuoSu?p=preview> and the lovely angular error reporting : <https://docs.angularjs.org/error/ngRepeat/dupes?p0=ele%20in%20data.data%5B1%5D.area2%5B0%5D&p1=string:col%203%20A&p2=col%203%20A> . Gist of the solution: In js controller: ``` $scope.data = { "data": [{"area1": [[ "A value 1",... ``` And HTML: ``` <div class= "" ng-repeat="ele in data.data[1].area2 track by $index"> <span class='d2'> {{(ele[0])}} </span><span class='d2'> {{(ele[1])}}... ```
2016/09/13
[ "https://Stackoverflow.com/questions/39474480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1643558/" ]
As a front-end dev, I would choose the first structure as well. In any case, you'd have to use nested ng-repeat like so: ``` <div class="area" ng-repeat="area in data"> <div class="row" ng-repeat="row in area.rows"> <p class="description">{{::row.the_desc}}</p> <p class="value">{{::row.value}}</p> </div> </div> ``` For the second snippet: ``` <div class="area" ng-repeat="area in data"> <div class="row" ng-repeat="(key, value) in area.rows"> <p class="description">{{::key}}</p> <p class="value">{{::value}}</p> </div> </div> ``` For the 3rd snipped, provided that the array structure remains the same and has only two values, we would be able to access them by index. ``` <div class="area" ng-repeat="(key,area) in data"> <!-- Prints area1, area2 if necessary --> <p>{{key}}</p> <!-- Prints 1st and 2nd value of the area array --> <div class="row" ng-repeat="row in area"> <p class="description">{{row[0}}</p> <p class="value">{{row[1]}}</p> </div> </div> ``` Is it possible to achieve this without nested ng-repeat? Not likely. There are too many nested arrays. But honestly, I don't think that storing a "value" in object key is a good practice (even it's possible to display with Angular), so I'd suggest you to follow your dev's advice and use the first structure.
I believe you need to change your data structure a little. Setting it up like this should help: ``` $scope.data = [{ name: "area1", rows : [{ "the_desc": "A value 1", "value": "sample value 1" }, { "the_desc": "A value 2", "value": "sample value 2" }, { "the_desc": "A value 3", "value": "other 3" }, { "the_desc": "A value 4", "value": "other 4" }, { "the_desc": "A value 5", "value": "other goats fly" }, { "the_desc": "A value 6", "value": "bla blah" }, { "the_desc": "A value 7", "value": "other 7" }, { "the_desc": "A value 8", "value": "other 8" }] }, { name: "area2", "rows": [{ "the_desc": "A value 9", "value": "sample value 9" }, { "the_desc": "A value 10", "value": "sample value 10" }, { "the_desc": "A value 11", "value": "other 11" }, { "the_desc": "A value 12", "value": "other 12" }, { "the_desc": "A value 13", "value": "other goats fly 13" }, { "the_desc": "A value 14", "value": "bla blah" }, { "the_desc": "A value 15", "value": "other 15" }, { "the_desc": "A value 16", "value": "other 16" }] } ``` Then it will be easy to access with `ng-repeat` like so: ``` <div ng-repeat="d in data"> <h1>{{d.name}}</h1> <div ng-repeat="r in d.rows"> {{r.the_desc}} </div> </div> ``` Here's a [Plunker](http://plnkr.co/edit/ihe1JkA5Hb0Uxlz3xem8?p=preview). I'm not sure how you get your data, or if it is hardcoded, but this should at least get you started.
33,735,319
I have a REST service with a method anotated with `@Produces("application/pdf")`. If an exception occurres on server side, our logic throws custom exception which extends `RuntimeException` and I have: ``` throw new CustomerException(new CustomProblem("something wrong")); ``` What is a best way to return something to the client, who in this case see: ``` Status: 500 Body: No message body writer has been found for response class CustomProblem. ```
2015/11/16
[ "https://Stackoverflow.com/questions/33735319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Previously, I answered a similar question [here](https://stackoverflow.com/a/33708222/1426227). Basically, you can adopt one of the following approaches to handle your exceptions (extracted from [Jersey documentation](https://jersey.java.net/documentation/latest/representations.html#d0e6653) but also applies to RESTEasy or other JAX-RS 2.0 implementations): Extending `WebApplicationException` ----------------------------------- JAX-RS allows to define direct mapping of Java exceptions to HTTP error responses. By extending [`WebApplicationException`](http://docs.oracle.com/javaee/7/api/javax/ws/rs/WebApplicationException.html), you can create application specific exceptions that build a HTTP response with the status code and an optional message as the body of the response. The following exception builds a HTTP response with the [`404`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5) status code: ``` public class CustomerNotFoundException extends WebApplicationException { /** * Create a HTTP 404 (Not Found) exception. */ public CustomerNotFoundException() { super(Responses.notFound().build()); } /** * Create a HTTP 404 (Not Found) exception. * @param message the String that is the entity of the 404 response. */ public CustomerNotFoundException(String message) { super(Response.status(Responses.NOT_FOUND). entity(message).type("text/plain").build()); } } ``` [`WebApplicationException`](http://docs.oracle.com/javaee/7/api/javax/ws/rs/WebApplicationException.html) is a [`RuntimeException`](https://docs.oracle.com/javase/8/docs/api/java/lang/RuntimeException.html) and doesn't need to the wrapped in a `try`-`catch` block or be declared in a `throws` clause: ``` @Path("customers/{customerId}") public Customer findCustomer(@PathParam("customerId") Long customerId) { Customer customer = customerService.find(customerId); if (customer == null) { throw new CustomerNotFoundException("Customer not found with ID " + customerId); } return customer; } ``` Creating `ExceptionMapper`s --------------------------- In other cases it may not be appropriate to throw instances of [`WebApplicationException`](http://docs.oracle.com/javaee/7/api/javax/ws/rs/WebApplicationException.html), or classes that extend [`WebApplicationException`](http://docs.oracle.com/javaee/7/api/javax/ws/rs/WebApplicationException.html), and instead it may be preferable to map an existing exception to a response. For such cases it is possible to use a custom exception mapping provider. The provider must implement the [`ExceptionMapper<E extends Throwable>`](https://docs.oracle.com/javaee/7/api/javax/ws/rs/ext/ExceptionMapper.html) interface. For example, the following maps the JAP [`EntityNotFoundException`](http://docs.oracle.com/javaee/7/api/javax/persistence/EntityNotFoundException.html) to a HTTP [`404`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4.5) response: ``` @Provider public class EntityNotFoundExceptionMapper implements ExceptionMapper<EntityNotFoundException> { @Override public Response toResponse(EntityNotFoundException ex) { return Response.status(404).entity(ex.getMessage()).type("text/plain").build(); } } ``` When an [`EntityNotFoundException`](http://docs.oracle.com/javaee/7/api/javax/persistence/EntityNotFoundException.html) is thrown, the [`toResponse(E)`](https://docs.oracle.com/javaee/7/api/javax/ws/rs/ext/ExceptionMapper.html#toResponse-E-) method of the `EntityNotFoundExceptionMapper` instance will be invoked. The [`@Provider`](https://docs.oracle.com/javaee/7/api/javax/ws/rs/ext/Provider.html) annotation declares that the class is of interest to the JAX-RS runtime. Such class may be added to the set of classes of the [`Application`](https://docs.oracle.com/javaee/7/api/javax/ws/rs/core/Application.html) instance that is configured.
Implement <https://docs.oracle.com/javaee/6/api/javax/ws/rs/ext/ExceptionMapper.html> and put the annotation @Provider to that. Override the toResponse() method and return a Response which is JSON or something meaningful. You can also use @Context to obtain the header passed in the request.
21,307,021
In a Python project I need to provide a user with a single instance of various concepts, lets call them 'dog', 'cat' and 'parrot'. There is some functionality that they share, like sleep(), eat() and is\_dead(), that I would like to place into the concept 'pet' for the purposes of code reuse. There can be multiple pets, but there is only ever one pet of each type. I believe it is not possible to have a Python module inherit from another module, therefore if I wanted to use just modules I would have to throw out the 'pet' concept and have repeated code (sleep, eat, etc) in each of the 'dog', 'cat' and 'parrot' modules. Or create a 'pet' module and then use 'from pet import \*' in each of the other modules, which as far as I am aware is considered bad practice. Alternatively I could create a 'pet' class (derived from a Singleton-implementing base class), and then derive 'dog', 'cat' and 'parrot' classes from that. However I see that most discussion of the Singleton pattern in Python imply that the pattern is not a good idea. So, I want to avoid three areas that I get the impression are bad practice: * Code replication between different source files * The use of 'from x import \*' * The use of the Singleton design pattern However I cannot achieve all three with any of the solutions above. I am tempted to go with the Singleton design-pattern as it seems the 'least bad' option. Is there a way to achieve what I want while avoiding all three problems and without introducing any other bad practice?
2014/01/23
[ "https://Stackoverflow.com/questions/21307021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1472525/" ]
try ``` WHERE Goal_Year*100+month_id_FK <= 201504 ``` alternatively: ``` WHERE GOAL_YEAR < 2015 OR (GOAL_YEAR = 2015 and month_id_FK <= 4) ```
``` select sum(monthly_amount) from table where goaldate<(SELECT CURDATE()) ``` this is not the actual query for your table..but if you do like this you will get the answer you need the sum of monthly amount where the date is before current-date means today. then you can just compare the currentdate with goal date
42,345,658
I have two views in my hive ``` +------------+ | Table_1 | +------------+ | hash | | campaignId | +------------+ +-----------------+ | Table_2 | +-----------------+ | campaignId | | accountId | | parentAccountID | +-----------------+ ``` Now I have to fetch 'Table\_1' data filtered by accountId & parentAccountID, for which I have written the following query: ``` SELECT /*+ MAPJOIN(T2) */ T1.hash, COUNT(T1.campaignId) num_campaigns FROM Table_1 T1 JOIN Table_2 T2 ON T1.campaignId = T2.campaignId WHERE (T2.accountId IN ('aid1', 'aid2') OR T2.parentAccountID IN ('aid1', 'aid2') GROUP BY T1.hash ``` This query is working but slow. Is there any better alternative to this (JOIN)? I am reading Table\_1 from kafka through spark. *Slide Duration is 5 sec* *Window Duration is 2 minutes* While Table\_2 is in RDBMS which spark is reading through jdbc and this has 4500 records. Every 5 sec, kafka pumps in approximately 2K records in CSV format. I need the data to be processed within 5 seconds but currently its taking between 8 to 16 seconds. **As per suggestions:** 1. I have repartitioned Table\_1 by columns campaignId & hash respectively. 2. I have repartitioned Table\_2 by columns accountId & parentAccountID respectively. 3. I have implemented MAPJOIN. But still no improvement. ***NOTE:*** If I remove the window duration, then the process does get executed within time. May be because of less data to process. But that is not the requirement.
2017/02/20
[ "https://Stackoverflow.com/questions/42345658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4692810/" ]
To do it only on weekdays you can use a cron expression like this ``` 0 0 8 ? * MON-FRI * ``` Usage is described [here](https://www.quartz-scheduler.net/documentation/quartz-2.x/tutorial/crontriggers.html) Would look like this for you ``` ITrigger trigger = TriggerBuilder.Create() .WithCronSchedule("0 0 8 ? * MON-FRI *") .Build(); ``` This should fire every day at 8am except for weekend You can use this website to generate your cron expressions: <http://www.cronmaker.com/>
If you want to run it on weekdays without using a cron expression, you can also use: ``` var trigger = TriggerBuilder .Create() .WithSchedule(CronScheduleBuilder .AtHourAndMinuteOnGivenDaysOfWeek(8, 0, DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday)) .Build(); ```
8,130,285
Given a formatted text block in Windows Phone 7.1 project: ``` <StackPanel Orientation="Horizontal"> <TextBlock Foreground="DarkGray" VerticalAlignment="Bottom" Margin="0,0,0,8"> <Run Text="total length "/> <Run Text="{Binding TotalHours}" FontSize="48"/> <Run Text="h "/> <Run Text=":" FontSize="48"/> <Run Text="{Binding TotalMinutes}" FontSize="48"/> <Run Text="m "/> </TextBlock> </StackPanel> ``` It is being previewed correctly in VS designer: ![vs text block](https://i.stack.imgur.com/pezdJ.png) It is already looking not the way I want in Blend: ![blend text block](https://i.stack.imgur.com/uQyVQ.png) It looks just as in Blend (good job Blend team) in emulator and a real device. What adds those spaces before and after big 8 and 45? How can I force my layout to look correctly (like in VS designer)?
2011/11/15
[ "https://Stackoverflow.com/questions/8130285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/645460/" ]
if you write all your `Runs` in the same line, the empty space will go away. Basically a new line here is one empty space on the UI. ``` <TextBlock Foreground="DarkGray" VerticalAlignment="Bottom" Margin="0,0,0,8"><Run Text="total length "/><Run Text="{Binding TotalHours}" FontSize="48"/><Run Text="h "/><Run Text=":" FontSize="48"/><Run Text="{Binding TotalMinutes}" FontSize="48"/><Run Text="m "/></TextBlock> ``` ![enter image description here](https://i.stack.imgur.com/9eVCO.png)
To build off Justin XL's answer, the important part is that you can't have whitespace between the run tags, but whitespace in the tags themselves does't matter... So you can get creative to place runs on separate lines, but not add spaces to the result: ``` <!-- Formatted to prevent adding spaces between runs --> <TextBlock Foreground="DarkGray" VerticalAlignment="Bottom" Margin="0,0,0,8" ><Run Text="total length " /><Run Text="{Binding TotalHours}" FontSize="48" /><Run Text="h " /><Run Text=":" FontSize="48" /><Run Text="{Binding TotalMinutes}" FontSize="48" /><Run Text="m " /></TextBlock> ```
38,248
What do I need to do to change the RPCNFSDCOUNT setting without a full service restart? I need to reload the NFS configuration without restarting the service. The RPCNFSDCOUNT thread count is too low for the workload but I cannot get the management to agree on a schedule for a change window. A normal service can frequently do this with a SIGHUP. I did attempt this with a `kill -HUP $(pidof rpc.mountd)`, but that was unsuccessful in getting the new RPCNFSDCOUNT setting applied from /etc/sysconfig/nfs on this old Fedora 8 box. The man pages for the other NFS daemons incline me to think that HUP'ing those processes won't be of any benefit, and I'm rather reluctant to HUP the kthreadd process that is the parent process of the nfsd threads themselves.
2012/05/09
[ "https://unix.stackexchange.com/questions/38248", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/13577/" ]
And after an obvious mental lapse, I remembered the /proc filesystem. /proc/fs/nfsd, specifically, controls the runtime settings of the nfsd service. In my case, this meant `echo '32' > /proc/fs/nfsd/threads` sets the number of threads to 32.
You can execute `rpc.nfsd` from the command line and specify the number of processes to add or remove if the `nfs` server is already running. From `man 8 rpc.nfsd` ``` /usr/sbin/rpc.nfsd [options] nproc Note that if the NFS server is already running, then the options for specifying host, port, and protocol will be ignored. The number of processes given will be the only option considered, and the number of active nfsd processes will be increased or decreased to match this number. In particular rpc.nfsd 0 will stop all threads and thus close any open connections. ```
19,967,652
I have multiple files that have the extension `.tdx`. Currently my program works on individual files using `$ARGV[0]`, however the number of files are growing and I would like to use a wildcard based upon the file extension. After much research I am at a loss. I would like to read each file individually so the extract from the file is identified by the user. ``` #!C:\Perl\bin\perl.exe use warnings; use FileHandle; open my $F_IN, '<', $ARGV[0] or die "Unable to open file: $!\n"; open my $F_OUT, '>', 'output.txt' or die "Unable to open file: $!\n"; while (my $line = $F_IN->getline) { if ($line =~ /^User/) { $F_OUT->print($line); } if ($line =~ /--FTP/) { $F_OUT->print($line); } if ($line =~ /^ftp:/) { $F_OUT->print($line); } } close $F_IN; close $F_OUT; ``` All the files are in one directory, so I assume I will need to open the directory. I am just not sure how if I need to build an array of files or build a list and chomp it.
2013/11/14
[ "https://Stackoverflow.com/questions/19967652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908294/" ]
You have many options -- 1. Loop over `@ARGV`, allowing the user to pass in a list of files 2. Use [`glob`](http://perldoc.perl.org/functions/glob.html) to pass in a pattern that perl will expand into a list of files (and then loop over that list, as in #1). This can be messy as they have to make sure to quote it so the shell doesn't interpolate it first. 3. Write some wrapper to call your existing script over and over again. There's also a variant of the first one, which is to read from `<>`. This is set to either STDIN, or it'll automatically open the files named in `@ARGV`. See [`eof`](http://perldoc.perl.org/functions/eof.html) for an example of how to use it. As an variant of #2, you can pass in a directory name, and use either `opendir` and `readdir` to loop over the list (making sure to grab only files with your extension, or at the very least ignore `.` and `..`) or append `/*` or `/*.tdx` to it and use `glob` again.
The `glob` function can help you. Just try ``` my @files = glob '*.tdx'; for my $file (@files) { # Process $file... } ``` In list context, `glob` expands its argument to the list of file names that match the pattern. For details, see [glob in perlfunc](http://p3rl.org/glob).
19,967,652
I have multiple files that have the extension `.tdx`. Currently my program works on individual files using `$ARGV[0]`, however the number of files are growing and I would like to use a wildcard based upon the file extension. After much research I am at a loss. I would like to read each file individually so the extract from the file is identified by the user. ``` #!C:\Perl\bin\perl.exe use warnings; use FileHandle; open my $F_IN, '<', $ARGV[0] or die "Unable to open file: $!\n"; open my $F_OUT, '>', 'output.txt' or die "Unable to open file: $!\n"; while (my $line = $F_IN->getline) { if ($line =~ /^User/) { $F_OUT->print($line); } if ($line =~ /--FTP/) { $F_OUT->print($line); } if ($line =~ /^ftp:/) { $F_OUT->print($line); } } close $F_IN; close $F_OUT; ``` All the files are in one directory, so I assume I will need to open the directory. I am just not sure how if I need to build an array of files or build a list and chomp it.
2013/11/14
[ "https://Stackoverflow.com/questions/19967652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908294/" ]
You have many options -- 1. Loop over `@ARGV`, allowing the user to pass in a list of files 2. Use [`glob`](http://perldoc.perl.org/functions/glob.html) to pass in a pattern that perl will expand into a list of files (and then loop over that list, as in #1). This can be messy as they have to make sure to quote it so the shell doesn't interpolate it first. 3. Write some wrapper to call your existing script over and over again. There's also a variant of the first one, which is to read from `<>`. This is set to either STDIN, or it'll automatically open the files named in `@ARGV`. See [`eof`](http://perldoc.perl.org/functions/eof.html) for an example of how to use it. As an variant of #2, you can pass in a directory name, and use either `opendir` and `readdir` to loop over the list (making sure to grab only files with your extension, or at the very least ignore `.` and `..`) or append `/*` or `/*.tdx` to it and use `glob` again.
I never got glob to work. What I ended up doing was building an array based on the file extension .tdx. from there I copied the array to a filelist and read from that. What I ended up with is: ``` #!C:\Perl\bin\perl.exe use warnings; use FileHandle; open my $F_OUT, '>', 'output.txt' or die "Unable to open file: $!\n"; open(FILELIST, "dir /b /s \"%USERPROFILE%\\Documents\\holding\\*.tdx\" |"); @filelist=<FILELIST>; close(FILELIST); foreach $file (@filelist) { chomp($file); open my $F_IN, '<', $file or die "Unable to open file: $!\n"; while (my $line = $F_IN->getline) { Doing Something } close $F_IN; } close $F_OUT; ``` Thank you for your answers they helped in the learning experaince.
19,967,652
I have multiple files that have the extension `.tdx`. Currently my program works on individual files using `$ARGV[0]`, however the number of files are growing and I would like to use a wildcard based upon the file extension. After much research I am at a loss. I would like to read each file individually so the extract from the file is identified by the user. ``` #!C:\Perl\bin\perl.exe use warnings; use FileHandle; open my $F_IN, '<', $ARGV[0] or die "Unable to open file: $!\n"; open my $F_OUT, '>', 'output.txt' or die "Unable to open file: $!\n"; while (my $line = $F_IN->getline) { if ($line =~ /^User/) { $F_OUT->print($line); } if ($line =~ /--FTP/) { $F_OUT->print($line); } if ($line =~ /^ftp:/) { $F_OUT->print($line); } } close $F_IN; close $F_OUT; ``` All the files are in one directory, so I assume I will need to open the directory. I am just not sure how if I need to build an array of files or build a list and chomp it.
2013/11/14
[ "https://Stackoverflow.com/questions/19967652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908294/" ]
You have many options -- 1. Loop over `@ARGV`, allowing the user to pass in a list of files 2. Use [`glob`](http://perldoc.perl.org/functions/glob.html) to pass in a pattern that perl will expand into a list of files (and then loop over that list, as in #1). This can be messy as they have to make sure to quote it so the shell doesn't interpolate it first. 3. Write some wrapper to call your existing script over and over again. There's also a variant of the first one, which is to read from `<>`. This is set to either STDIN, or it'll automatically open the files named in `@ARGV`. See [`eof`](http://perldoc.perl.org/functions/eof.html) for an example of how to use it. As an variant of #2, you can pass in a directory name, and use either `opendir` and `readdir` to loop over the list (making sure to grab only files with your extension, or at the very least ignore `.` and `..`) or append `/*` or `/*.tdx` to it and use `glob` again.
If you're on a Windows machine, putting in `*.tdx` on the command line might not work, nor may `glob` which historically used the shell's globbing abilities. (It now appears that the built in `glob` function now uses `File::Glob`, so that may no longer be an issue). One thing you can do is not use globs, but allow the user to input the directories and suffixes they want. Then use `opendir` and `readdir` to go through the directories yourself. ``` use strict; use warnings; use feature qw(say); use autodie; use Getopt::Long; # Why not do it right? use Pod::Usage; # It's about time to learn about POD documentation my @suffixes; # Hey, why not let people put in more than one suffix? my @directories; # Let people put in the directories they want to check my $help; GetOptions ( "suffix=s" => \@suffixes, "directory=s" => \@directories, "help" => \$help, ) or pod2usage ( -message => "Invalid usage" ); if ( not @suffixes ) { @suffixes = qw(tdx); } if ( not @directories ) { @directories = qw(.); } if ( $help ) { pod2usage; } my $regex = join, "|", @suffixes; $regex = "\.($regex)$"; # Will equal /\.(foo|bar|txt)$/ if Suffixes are foo, bar, txt for my $directory ( @directories ) { opendir my ($dir_fh), $directory; # Autodie will take care of this: while ( my $file = readdir $dir_fh ) { next unless -f $file; next unless $file =~ /$regex/; ... Here be dragons ... } } ``` This will go through all of the directories your user input and then examines each entry. It uses the suffixes your user inputs (With `.tdx` being the default) to create a regular expression to check against the file name. If the file name matches the regular expression, do whatever you wanted to do with that file.
72,276,679
I have a set of data of 2000+ people with repeated measurements over multiple years between 2000-2022 (some people have data for the full time period whereas others only for a subset of these years). Within a single year, each person can only fall into one of four groups: 0, 1, 2, or 3. I want to quantify how many times each person changes grouping within their individual sampling period. The data is laid out like this (image attached): [![enter image description here](https://i.stack.imgur.com/yDCq8.png)](https://i.stack.imgur.com/yDCq8.png) So for this example dataset, the code would tell me that person 1 has had 3 changes (from group 1 to group 2 in 2011, then from group 2 back to group 1 and lastly back to group 2 in 2015) whereas for group 1 the code should tell me there have been 0 changes. I don't need the loop to tell me which years have the changes for now, only the total amount of changes in grouping per person. I was thinking about a loop that goes something like "if X does not equal previous number then add 1 to a count" but I've never done something like this before and not quite sure how to lay this code out. Would appreciate any help :) Edit: This is the R syntax version of the data as suggested by @GregorThomas ``` structure(list(ID = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4), Year = c(2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2001, 2002, 2003, 2004, 2001, 2002, 2003, 2004, 2005, 2007, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021), Culture_Grouping = c(1, 1, 1, 1, 1, 1, 3, 3, 3, 1, 3, 3, 0, 1, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 2, 0, 0, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)), row.names = c(NA, -50L), class = c("tbl_df", "tbl", "data.frame")) ```
2022/05/17
[ "https://Stackoverflow.com/questions/72276679", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15249707/" ]
You can achieve it without any loop: ```r aggregate(Group ~ ID, df, \(x) sum(diff(x) != 0)) # ID Group # 1 1 3 # 2 2 0 ``` --- Its `dplyr` equivalent is: ```r library(dplyr) df %>% group_by(ID) %>% summarise(Group = sum(diff(Group) != 0)) %>% ungroup() ``` Or more simplified with `count()`: ```r df %>% count(ID, wt = diff(Group) != 0) ``` --- ##### Data ```r df <- data.frame(ID = c(rep(1, 6), rep(2, 2)), Year = c(2010:2015, 2012:2013), Group = c(1,2,1,1,1,2,1,1)) ```
`data.table` option: ``` library(data.table) setDT(df)[, uniqueN(rleid(Culture_Grouping)) - 1, ID] ``` Output: ``` ID V1 1: 1 3 2: 2 2 3: 3 3 4: 4 2 ```
4,076,566
I'm trying to figure out a way to detect an occurrence of rollback in a MySQL stored procedure so I could handle the situation accordingly from a PHP script, but so far I can not find any solution. My stored procedure looks like this: ``` delimiter | create procedure multi_inserts( IN var1 int(11), . . . IN string1 text ) BEGIN declare exit handler for sqlexception rollback; declare exit handler for sqlwarning rollback; START TRANSACTION; insert into table1(a,b,c,d) values(var1,var2,var3,var4); insert into table2(e,f,g) values(var5,var6,string1); COMMIT; END delimiter ; ``` I did a rollback test on this procedure and it did rollback but I got no false. I want my stored procedure to throw some kind of error message if the transaction failed, so I could handle it like this: ``` $result = mysql_query($procedure); if(!$result) { //rollback occured do something } ``` Is there a way to detect rollback in MySQL? Am I missing something? Any reply will be appreciated. Thanks for reading. --- **Thanks to your advices I fixed this problem. Here's what I did:** Stored Procedure ``` delimiter | create procedure multi_inserts( IN var1 int(11), . . . IN string1 text ) BEGIN declare exit handler for sqlexception sqlwarning BEGIN rollback; select -1; END; START TRANSACTION; insert into table1(a,b,c,d) values(var1,var2,var3,var4); insert into table2(e,f,g) values(var5,var6,string1); COMMIT; END delimiter ; ``` If I use out variable instead of select -1, it gives me this error: > > OUT or INOUT argument is not a > variable or NEW pseudo-variable in > BEFORE trigger > > > I don't know what did I wrong, but I couldn't fix this problem. PHP script ``` $result=mysqli_query($con,$procedure); if(is_object($result)) { //rollback happened do something! } ``` If the SP is successful it throws true.
2010/11/02
[ "https://Stackoverflow.com/questions/4076566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/494574/" ]
You would usually do this PHP-side if you wanted to catch errors. Read <http://php.net/manual/en/pdo.transactions.php> for more information.
Hey do one thing, use OUTPUT variable and return 1 or 0 as result form SP and do what ever you want on this flag.
4,076,566
I'm trying to figure out a way to detect an occurrence of rollback in a MySQL stored procedure so I could handle the situation accordingly from a PHP script, but so far I can not find any solution. My stored procedure looks like this: ``` delimiter | create procedure multi_inserts( IN var1 int(11), . . . IN string1 text ) BEGIN declare exit handler for sqlexception rollback; declare exit handler for sqlwarning rollback; START TRANSACTION; insert into table1(a,b,c,d) values(var1,var2,var3,var4); insert into table2(e,f,g) values(var5,var6,string1); COMMIT; END delimiter ; ``` I did a rollback test on this procedure and it did rollback but I got no false. I want my stored procedure to throw some kind of error message if the transaction failed, so I could handle it like this: ``` $result = mysql_query($procedure); if(!$result) { //rollback occured do something } ``` Is there a way to detect rollback in MySQL? Am I missing something? Any reply will be appreciated. Thanks for reading. --- **Thanks to your advices I fixed this problem. Here's what I did:** Stored Procedure ``` delimiter | create procedure multi_inserts( IN var1 int(11), . . . IN string1 text ) BEGIN declare exit handler for sqlexception sqlwarning BEGIN rollback; select -1; END; START TRANSACTION; insert into table1(a,b,c,d) values(var1,var2,var3,var4); insert into table2(e,f,g) values(var5,var6,string1); COMMIT; END delimiter ; ``` If I use out variable instead of select -1, it gives me this error: > > OUT or INOUT argument is not a > variable or NEW pseudo-variable in > BEFORE trigger > > > I don't know what did I wrong, but I couldn't fix this problem. PHP script ``` $result=mysqli_query($con,$procedure); if(is_object($result)) { //rollback happened do something! } ``` If the SP is successful it throws true.
2010/11/02
[ "https://Stackoverflow.com/questions/4076566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/494574/" ]
You can add an output param and then set it to the value you want in your exit handlers. Here's an example using your proc: ``` delimiter $$ create procedure multi_inserts( IN var1 int(11), . . . IN string1 text, OUT p_return_code tinyint unsigned ) BEGIN DECLARE exit handler for sqlexception BEGIN -- ERROR set p_return_code = 1; rollback; END; DECLARE exit handler for sqlwarning BEGIN -- WARNING set p_return_code = 2; rollback; END; START TRANSACTION; insert into table1(a,b,c,d) values(var1,var2,var3,var4); insert into table2(e,f,g) values(var5,var6,string1); COMMIT; -- SUCCESS set p_return_code = 0; END $$ delimiter ; ```
You would usually do this PHP-side if you wanted to catch errors. Read <http://php.net/manual/en/pdo.transactions.php> for more information.
4,076,566
I'm trying to figure out a way to detect an occurrence of rollback in a MySQL stored procedure so I could handle the situation accordingly from a PHP script, but so far I can not find any solution. My stored procedure looks like this: ``` delimiter | create procedure multi_inserts( IN var1 int(11), . . . IN string1 text ) BEGIN declare exit handler for sqlexception rollback; declare exit handler for sqlwarning rollback; START TRANSACTION; insert into table1(a,b,c,d) values(var1,var2,var3,var4); insert into table2(e,f,g) values(var5,var6,string1); COMMIT; END delimiter ; ``` I did a rollback test on this procedure and it did rollback but I got no false. I want my stored procedure to throw some kind of error message if the transaction failed, so I could handle it like this: ``` $result = mysql_query($procedure); if(!$result) { //rollback occured do something } ``` Is there a way to detect rollback in MySQL? Am I missing something? Any reply will be appreciated. Thanks for reading. --- **Thanks to your advices I fixed this problem. Here's what I did:** Stored Procedure ``` delimiter | create procedure multi_inserts( IN var1 int(11), . . . IN string1 text ) BEGIN declare exit handler for sqlexception sqlwarning BEGIN rollback; select -1; END; START TRANSACTION; insert into table1(a,b,c,d) values(var1,var2,var3,var4); insert into table2(e,f,g) values(var5,var6,string1); COMMIT; END delimiter ; ``` If I use out variable instead of select -1, it gives me this error: > > OUT or INOUT argument is not a > variable or NEW pseudo-variable in > BEFORE trigger > > > I don't know what did I wrong, but I couldn't fix this problem. PHP script ``` $result=mysqli_query($con,$procedure); if(is_object($result)) { //rollback happened do something! } ``` If the SP is successful it throws true.
2010/11/02
[ "https://Stackoverflow.com/questions/4076566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/494574/" ]
You would usually do this PHP-side if you wanted to catch errors. Read <http://php.net/manual/en/pdo.transactions.php> for more information.
``` <?php try { $user='root'; $pass=''; $dbh = new PDO('mysql:host=localhost;dbname=dbname', $user, $pass, array(PDO::ATTR_PERSISTENT => true)); echo "Connected\n"; } catch (Exception $e) { die("Unable to connect: " . $e->getMessage()); } try { $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->beginTransaction(); $dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')"); $dbh->exec("insert into salarychange (id, amount, changedate) values (23, 50000, NOW())"); $dbh->commit(); } catch (Exception $e) { $dbh->rollBack(); echo "Failed: " . $e->getMessage(); } ?> ```
4,076,566
I'm trying to figure out a way to detect an occurrence of rollback in a MySQL stored procedure so I could handle the situation accordingly from a PHP script, but so far I can not find any solution. My stored procedure looks like this: ``` delimiter | create procedure multi_inserts( IN var1 int(11), . . . IN string1 text ) BEGIN declare exit handler for sqlexception rollback; declare exit handler for sqlwarning rollback; START TRANSACTION; insert into table1(a,b,c,d) values(var1,var2,var3,var4); insert into table2(e,f,g) values(var5,var6,string1); COMMIT; END delimiter ; ``` I did a rollback test on this procedure and it did rollback but I got no false. I want my stored procedure to throw some kind of error message if the transaction failed, so I could handle it like this: ``` $result = mysql_query($procedure); if(!$result) { //rollback occured do something } ``` Is there a way to detect rollback in MySQL? Am I missing something? Any reply will be appreciated. Thanks for reading. --- **Thanks to your advices I fixed this problem. Here's what I did:** Stored Procedure ``` delimiter | create procedure multi_inserts( IN var1 int(11), . . . IN string1 text ) BEGIN declare exit handler for sqlexception sqlwarning BEGIN rollback; select -1; END; START TRANSACTION; insert into table1(a,b,c,d) values(var1,var2,var3,var4); insert into table2(e,f,g) values(var5,var6,string1); COMMIT; END delimiter ; ``` If I use out variable instead of select -1, it gives me this error: > > OUT or INOUT argument is not a > variable or NEW pseudo-variable in > BEFORE trigger > > > I don't know what did I wrong, but I couldn't fix this problem. PHP script ``` $result=mysqli_query($con,$procedure); if(is_object($result)) { //rollback happened do something! } ``` If the SP is successful it throws true.
2010/11/02
[ "https://Stackoverflow.com/questions/4076566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/494574/" ]
You can add an output param and then set it to the value you want in your exit handlers. Here's an example using your proc: ``` delimiter $$ create procedure multi_inserts( IN var1 int(11), . . . IN string1 text, OUT p_return_code tinyint unsigned ) BEGIN DECLARE exit handler for sqlexception BEGIN -- ERROR set p_return_code = 1; rollback; END; DECLARE exit handler for sqlwarning BEGIN -- WARNING set p_return_code = 2; rollback; END; START TRANSACTION; insert into table1(a,b,c,d) values(var1,var2,var3,var4); insert into table2(e,f,g) values(var5,var6,string1); COMMIT; -- SUCCESS set p_return_code = 0; END $$ delimiter ; ```
Hey do one thing, use OUTPUT variable and return 1 or 0 as result form SP and do what ever you want on this flag.
4,076,566
I'm trying to figure out a way to detect an occurrence of rollback in a MySQL stored procedure so I could handle the situation accordingly from a PHP script, but so far I can not find any solution. My stored procedure looks like this: ``` delimiter | create procedure multi_inserts( IN var1 int(11), . . . IN string1 text ) BEGIN declare exit handler for sqlexception rollback; declare exit handler for sqlwarning rollback; START TRANSACTION; insert into table1(a,b,c,d) values(var1,var2,var3,var4); insert into table2(e,f,g) values(var5,var6,string1); COMMIT; END delimiter ; ``` I did a rollback test on this procedure and it did rollback but I got no false. I want my stored procedure to throw some kind of error message if the transaction failed, so I could handle it like this: ``` $result = mysql_query($procedure); if(!$result) { //rollback occured do something } ``` Is there a way to detect rollback in MySQL? Am I missing something? Any reply will be appreciated. Thanks for reading. --- **Thanks to your advices I fixed this problem. Here's what I did:** Stored Procedure ``` delimiter | create procedure multi_inserts( IN var1 int(11), . . . IN string1 text ) BEGIN declare exit handler for sqlexception sqlwarning BEGIN rollback; select -1; END; START TRANSACTION; insert into table1(a,b,c,d) values(var1,var2,var3,var4); insert into table2(e,f,g) values(var5,var6,string1); COMMIT; END delimiter ; ``` If I use out variable instead of select -1, it gives me this error: > > OUT or INOUT argument is not a > variable or NEW pseudo-variable in > BEFORE trigger > > > I don't know what did I wrong, but I couldn't fix this problem. PHP script ``` $result=mysqli_query($con,$procedure); if(is_object($result)) { //rollback happened do something! } ``` If the SP is successful it throws true.
2010/11/02
[ "https://Stackoverflow.com/questions/4076566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/494574/" ]
You can add an output param and then set it to the value you want in your exit handlers. Here's an example using your proc: ``` delimiter $$ create procedure multi_inserts( IN var1 int(11), . . . IN string1 text, OUT p_return_code tinyint unsigned ) BEGIN DECLARE exit handler for sqlexception BEGIN -- ERROR set p_return_code = 1; rollback; END; DECLARE exit handler for sqlwarning BEGIN -- WARNING set p_return_code = 2; rollback; END; START TRANSACTION; insert into table1(a,b,c,d) values(var1,var2,var3,var4); insert into table2(e,f,g) values(var5,var6,string1); COMMIT; -- SUCCESS set p_return_code = 0; END $$ delimiter ; ```
``` <?php try { $user='root'; $pass=''; $dbh = new PDO('mysql:host=localhost;dbname=dbname', $user, $pass, array(PDO::ATTR_PERSISTENT => true)); echo "Connected\n"; } catch (Exception $e) { die("Unable to connect: " . $e->getMessage()); } try { $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $dbh->beginTransaction(); $dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')"); $dbh->exec("insert into salarychange (id, amount, changedate) values (23, 50000, NOW())"); $dbh->commit(); } catch (Exception $e) { $dbh->rollBack(); echo "Failed: " . $e->getMessage(); } ?> ```
20,379,490
I'm trying to get numbers from a String. Numbers only separated by space. This code works a lot of case except I've got two numbers separated with only one space. ``` Pattern pattern = Pattern.compile("(^|\\s)[0-9]+(\\s|$)"); Matcher matcher = pattern.matcher(value); while (matcher.find()) { numericResquest.add(Integer.parseInt(matcher.group().trim())); } ``` For example: * **OK**: 11 rre 12 * **OK**: 11 12 *(two spaces between the numbers)* * **Can't find 11** test 12 11 rre *(only one space between the numbers)* Thank you
2013/12/04
[ "https://Stackoverflow.com/questions/20379490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3045086/" ]
This is relative to the current digit, which will give you incorrect results for anything except when the digit is `'0'`: ``` add dl, 47 ; display underscore mov ah, 2 int 21h ``` You're also pushing and popping `dx` in the wrong places (relative to where you're changing its value). A better approach would be: ``` top: int 21h ; print digit push dx ; save dx mov dl,'_' mov ah, 2 int 21h ; print underscore pop dx ; restore dx inc dl ; next digit loop top ```
This one works fine: ``` ; 0_9.asm ; assemble with "nasm -f bin -o 0_9.com 0_9.asm" org 0x100 ; .com files always start 256 bytes into the segment mov cx, 9 ; counter mov dl, "0" ; 0 top: push dx push cx mov ah, 2 int 21h mov dl, "_" ; display underscore mov ah, 2 int 21h pop cx pop dx inc dl loop top mov dl, "9" ; display 9 mov ah, 2 int 21h mov ah, 4ch ; "terminate program" sub-function mov al,00h int 21h ```
2,445,883
For a continuous bijective function from $\Bbb R$ to $\Bbb R$ is a homeomorphism, can we generalise it?
2017/09/26
[ "https://math.stackexchange.com/questions/2445883", "https://math.stackexchange.com", "https://math.stackexchange.com/users/421463/" ]
Let $c\_{00}$ be the space of all sequences $(x\_n)\_{n\in\mathbb N}$ of complex numbers such that $n\gg0\implies x\_n=0$. Here, consider the distance$$d\bigl((x\_n)\_{n\in\mathbb N},(y\_n)\_{n\in\mathbb N}\bigr)=\max\_{n\in\mathbb N}|x\_n-y\_n|.$$Finally, define$$\begin{array}{rccc}f\colon&c\_{00}&\longrightarrow&c\_{00}\\&(x\_n)\_{n\in\mathbb N}&\mapsto&\left(\dfrac{x\_n}n\right)\_{n\in\mathbb N}.\end{array}$$Then $f$ is bijective and continuous. However, $f^{-1}$ is discontinuous, and therefore $f$ is *not* a homeomorphism.
if we choose the domain R with discrete topology and range also R with standard topology then identity function is a continuous bijection but not a homeomorphism.
61,392,058
In [this](https://scriptsandstatistics.wordpress.com/2018/04/26/how-to-plot-venn-diagrams-using-r-ggplot2-and-ggforce/) tutorial, it says ``` source("http://www.bioconductor.org/biocLite.R") biocLite("limma") library(limma) ``` Which return various errors. Is this trying to download and install from bioconductor, and if so, is there another way?
2020/04/23
[ "https://Stackoverflow.com/questions/61392058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5783745/" ]
The answer by @dc37 is correct, and corresponds to what you find on the BioConductor webpage. Because it is both a relatively common task, and one that can be done on the command-line too, I fairly recently added a helper script to the GitHub repo of [littler](https://github.com/eddelbuettel/littler/blob/master/inst/examples/installBioc.r) and now I can just do ``` edd@rob:~$ installBioc.r limma Bioconductor version 3.10 (BiocManager 1.30.10), R 3.6.3 (2020-02-29) Installing package(s) 'limma' trying URL 'https://bioconductor.org/packages/3.10/bioc/src/contrib/limma_3.42.2.tar.gz' Content type 'application/x-gzip' length 1494662 bytes (1.4 MB) ================================================== downloaded 1.4 MB * installing *source* package ‘limma’ ... ** using staged installation ** libs ccache gcc -I"/usr/share/R/include" -DNDEBUG -fpic -g -O3 -Wall -pipe -pedantic -std=gnu99 -c init.c -o init.o ccache gcc -I"/usr/share/R/include" -DNDEBUG -fpic -g -O3 -Wall -pipe -pedantic -std=gnu99 -c normexp.c -o normexp.o normexp.c: In function ‘fit_saddle_nelder_mead’: normexp.c:165:78: warning: ISO C forbids passing argument 9 of ‘nmmin’ between function pointer and ‘void *’ [-Wpedantic] 165 | nmmin(3, par, parsOut, Fmin, normexp_m2loglik_saddle, fail, abstol, intol, &ex, alpha, beta, gamma, trace, fncount, maxit); | ^~~ In file included from normexp.c:12: /usr/share/R/include/R_ext/Applic.h:73:51: note: expected ‘void *’ but argument is of type ‘void (*)()’ 73 | int *fail, double abstol, double intol, void *ex, | ~~~~~~^~ ccache gcc -I"/usr/share/R/include" -DNDEBUG -fpic -g -O3 -Wall -pipe -pedantic -std=gnu99 -c weighted_lowess.c -o weighted_lowess.o ccache gcc -Wl,-S -shared -L/usr/lib/R/lib -Wl,-Bsymbolic-functions -Wl,-z,relro -o limma.so init.o normexp.o weighted_lowess.o -L/usr/lib/R/lib -lR installing to /usr/local/lib/R/site-library/00LOCK-limma/00new/limma/libs ** R ** inst ** byte-compile and prepare package for lazy loading ** help *** installing help indices ** building package indices ** installing vignettes ** testing if installed package can be loaded from temporary location ** checking absolute paths in shared objects and dynamic libraries ** testing if installed package can be loaded from final location ** testing if installed package keeps a record of temporary installation path * DONE (limma) The downloaded source packages are in ‘/tmp/downloaded_packages’ edd@rob:~$ ```
This tutorial was using the previous version of Bioconductor, now with version 3.10, you have to use `BiocManager` instead of `BiocLite` and pass the following command (as described here: <https://bioconductor.org/packages/release/bioc/html/limma.html>): ```r if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") BiocManager::install("limma") ``` More informations on `BiocManager` and `Bioconductor` can be found here: <https://bioconductor.org/install/>
64,982,766
I am trying to do batch insertion to a table and then read full objects back with their newly generated `id`s. ```java private List<Customer> saveCustomer(List<Customer> customerList, Long shopId) { AtomicInteger index = new AtomicInteger(); SqlParameterSource[] paramsArray = new MapSqlParameterSource[customerList.size()]; for (Customer customer : customerList) { MapSqlParameterSource params = new MapSqlParameterSource(); params.addValue("shop_id", shopId); params.addValue("customer_name", pallet.getName()); params.addValue("email", pallet.getEmail()); params.addValue("contact_number", pallet.getContactNumber()); paramsArray[index.getAndIncrement()] = params; } String sql = "INSERT INTO \"Customer\" " + "(shop_id, customer_name, email, contact_number) " + "VALUES (:shop_id, :customer_name, :email, :contact_number) " + "RETURNING id, shop_id, customer_name, email, contact_number "; return namedParameterJdbcTemplate.getJdbcOperations().query(sql, paramsArray, new CustomerRowMapper()); } ``` However, this method gives me following error: `org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of org.springframework.jdbc.core.namedparam.MapSqlParameterSource. Use setObject() with an explicit Types value to specify the type to use`. See stack trace below. ``` PreparedStatementCallback; bad SQL grammar [INSERT INTO "Customer" (shop_id, customer_name, email, contact_number) VALUES (:shop_id, :customer_name, :email, :contact_number) RETURNING id, shop_id, customer_name, email, contact_number ]; nested exception is org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of org.springframework.jdbc.core.namedparam.MapSqlParameterSource. Use setObject() with an explicit Types value to specify the type to use. org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [INSERT INTO "Customer" (shop_id, customer_name, email, contact_number) VALUES (:shop_id, :customer_name, :email, :contact_number) RETURNING id, shop_id, customer_name, email, contact_number ]; nested exception is org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of org.springframework.jdbc.core.namedparam.MapSqlParameterSource. Use setObject() with an explicit Types value to specify the type to use. at org.springframework.jdbc.support.SQLStateSQLExceptionTranslator.doTranslate(SQLStateSQLExceptionTranslator.java:101) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:81) at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1443) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:633) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:669) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:700) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:712) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:763) ``` Everything would be fine if I just wanted to do batch insertion without reading it back. Then I would use ```java namedParameterJdbcTemplate.batchUpdate(sql, paramsArray); ``` However, I also need to read inserted values back with their `id`s but not sure what `namedParameterJdbcTemplate` method I can use. TLDR: I want to do batch insertion and then read inserted rows back using `namedParameterJdbcTemplate` but cannot find the right method for this. Does `namedParameterJdbcTemplate` provide batch insertion and selection in a single method?
2020/11/24
[ "https://Stackoverflow.com/questions/64982766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10717279/" ]
I got something to work. ```java private List<Customer> saveCustomer(List<Customer> customerList, Long shopId) { List<Object[]> batch = customers.stream() .map(customer -> new Object[] {shopId, customer.getName(), customer.getEmail(), customer.getContactNumber()}) .toList(); String sql = "INSERT INTO \"Customer\" " + "(shop_id, customer_name, email, contact_number) " + "values :batch" + "RETURNING id, shop_id, customer_name, email, contact_number "; return namedParameterJdbcTemplate.query(sql, new MapSqlParameterSource("batch", batch), new CustomerRowMapper()); } ``` Would love to know if there's a better way **Note:** each element of each `Object[]` is a parameter getting passed and there's a hard cap of 65535 parameters which can be passed at once
As I can see from the methods of `namedParameterJdbcTemplate` you can't execute batch operation and waiting for something back. What you can do is to execute statement in 1 sql request. Just combine your values if your database supports such syntax: ``` INSERT INTO Customer (shop_id, customer_name, email, contact_number) VALUES (value_list_1), (value_list_2), ... (value_list_n); ``` Then just use `JDBCTemplate.update` with the GeneratedKeyHolder argument. This might help you: [identity from sql insert via jdbctemplate](https://stackoverflow.com/questions/1665846/identity-from-sql-insert-via-jdbctemplate)
6,387,628
I have the following table below and am supposed to convert it to 2NF. ![Convert table to 2NF](https://i.stack.imgur.com/skzRH.png) I have an answer to this where I have gone: > > SKILLS: Employee, Skill > > > LOCATION: Employee, Current Work > Location > > > I have a feeling I'm wrong with this ^above^ though. Also can someone explain what the differences are between 1NF, 2NF and 3NF. I know 1 comes first and you have to break it all up into smaller tables but would like a really good description to help me understand better. Thanks
2011/06/17
[ "https://Stackoverflow.com/questions/6387628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733809/" ]
I am new to learning 2NF but I have solved the answer like this. Let me know if this is correct so that I can understand my mistake and practice more. ![enter image description here](https://i.stack.imgur.com/BQwhf.jpg) Only two tables. Thanks
``` Employee Table EmployeeID | Name 1 | Jones 2 | Bravo 3 | Ellis 4 | Harrison Skills Table SkillId | Skill 1 | Typing 2 | Shorthand 3 | Whittling 4 | Light Cleaning 5 | Alchemy 6 | Juggling Location Table LocationId | Name 1 | 114 Main Street 2 | 73 Industrial Way EmployeeSkill Table EmployeeId | LocationId | SkillId | SkillName 1 | 1 | 1 | Typing 1 | 1 | 2 | Shorthand 1 | 1 | 3 | Whittling 2 | 2 | 4 | Light Cleaning 3 | 2 | 5 | Alchemy 3 | 2 | 6 | Juggling 4 | 2 | 4 | Light Cleaning ``` In the EmployeeSkill table the primary key would be EmployeeId + LocationId, this gives you the skill they have at that location. Including the SkillName column violates 3NF in this example. This practice is actually used sometimes in database design (and called "denormalization") in order to reduce joins to increase performance reading data that is commonly used together. Ususally this is only done in tables used for reporting.
3,138,294
I would like to determine if my program is running on a version of Windows Server. Apparently, `System.Environment` does not contain information about the fact that Windows is a server version (there is no such info in the [OS version object](https://stackoverflow.com/questions/860459/determine-os-using-the-environment-osversion-object-c)). I know that I can use `SystemInformation.TerminalServerSession` to check whether my program is running on a Remote Desktop (see also [this question](https://stackoverflow.com/questions/159910/determine-if-a-program-is-running-on-a-remote-desktop)), but this will also be true if the user is simply accessing a plain client Windows machine remotely. So is there a supported way of determining if the code is running on a server or on a client machine? I don't mind using P/Invoke if needed. Note: I don't want to search for the `"Server"` string in the product name, since this will probably not work on some systems because of the localization.
2010/06/29
[ "https://Stackoverflow.com/questions/3138294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4597/" ]
Thanks to pointers provided by Nick's answer, I've finally found what I was looking for. The function [IsOS(OS\_ANYSERVER)](http://msdn.microsoft.com/en-us/library/bb773795(v=VS.85).aspx) does exactly what I need. Here is the sample code which should work for any OS version (including pre-Vista, since we import the `IsOS` function by ordinal from `shlwapi.dll`): ``` class OS { public static bool IsWindowsServer() { return OS.IsOS (OS.OS_ANYSERVER); } const int OS_ANYSERVER = 29; [DllImport("shlwapi.dll", SetLastError=true, EntryPoint="#437")] private static extern bool IsOS(int os); } ```
You can p/invoke the following Win32 functions: [GetProductInfo](http://msdn.microsoft.com/en-us/library/ms724358.aspx) for Vista/Windows Server 2008+ [GetVersionEx](http://msdn.microsoft.com/en-us/library/ms724451(VS.85).aspx) for Windows 2000+ BJ Rollison has a [good post](http://www.testingmentor.com/imtesty/2010/03/03/programmatically-detecting-the-operating-system-version-part-ii/) and [sample code](http://www.testingmentor.com/automation/CodeSnippetLibrary.htm) about this on his blog.
3,138,294
I would like to determine if my program is running on a version of Windows Server. Apparently, `System.Environment` does not contain information about the fact that Windows is a server version (there is no such info in the [OS version object](https://stackoverflow.com/questions/860459/determine-os-using-the-environment-osversion-object-c)). I know that I can use `SystemInformation.TerminalServerSession` to check whether my program is running on a Remote Desktop (see also [this question](https://stackoverflow.com/questions/159910/determine-if-a-program-is-running-on-a-remote-desktop)), but this will also be true if the user is simply accessing a plain client Windows machine remotely. So is there a supported way of determining if the code is running on a server or on a client machine? I don't mind using P/Invoke if needed. Note: I don't want to search for the `"Server"` string in the product name, since this will probably not work on some systems because of the localization.
2010/06/29
[ "https://Stackoverflow.com/questions/3138294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4597/" ]
You can p/invoke the following Win32 functions: [GetProductInfo](http://msdn.microsoft.com/en-us/library/ms724358.aspx) for Vista/Windows Server 2008+ [GetVersionEx](http://msdn.microsoft.com/en-us/library/ms724451(VS.85).aspx) for Windows 2000+ BJ Rollison has a [good post](http://www.testingmentor.com/imtesty/2010/03/03/programmatically-detecting-the-operating-system-version-part-ii/) and [sample code](http://www.testingmentor.com/automation/CodeSnippetLibrary.htm) about this on his blog.
There's supposed to be a set of of 'Version Helper Functions' defined in the VersionHelpers.h header file of the WinAPI in assembly Kernel32.DLL. The one that, according to the documentation, should work for your case is IsWindowsServer(void). Description is here: <http://msdn.microsoft.com/en-us/library/windows/desktop/dn424963%28v=vs.85%29.aspx> In c#, the code would like this (untested): ``` using System.Runtime.InteropServices; public static class MyClass { [DllImport("Kernel32.dll")] public static extern Boolean IsWindowsServer(); } ``` And then the consumption code would simply be: ``` bool is_it_a_server = MyClass.IsWindowsServer(); ``` I've never used any of these functions so let me know how it works...
3,138,294
I would like to determine if my program is running on a version of Windows Server. Apparently, `System.Environment` does not contain information about the fact that Windows is a server version (there is no such info in the [OS version object](https://stackoverflow.com/questions/860459/determine-os-using-the-environment-osversion-object-c)). I know that I can use `SystemInformation.TerminalServerSession` to check whether my program is running on a Remote Desktop (see also [this question](https://stackoverflow.com/questions/159910/determine-if-a-program-is-running-on-a-remote-desktop)), but this will also be true if the user is simply accessing a plain client Windows machine remotely. So is there a supported way of determining if the code is running on a server or on a client machine? I don't mind using P/Invoke if needed. Note: I don't want to search for the `"Server"` string in the product name, since this will probably not work on some systems because of the localization.
2010/06/29
[ "https://Stackoverflow.com/questions/3138294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4597/" ]
You can p/invoke the following Win32 functions: [GetProductInfo](http://msdn.microsoft.com/en-us/library/ms724358.aspx) for Vista/Windows Server 2008+ [GetVersionEx](http://msdn.microsoft.com/en-us/library/ms724451(VS.85).aspx) for Windows 2000+ BJ Rollison has a [good post](http://www.testingmentor.com/imtesty/2010/03/03/programmatically-detecting-the-operating-system-version-part-ii/) and [sample code](http://www.testingmentor.com/automation/CodeSnippetLibrary.htm) about this on his blog.
`IsWindowsServer` is an *inline* function in `VersionHelpers.h`. You can find and read that header file on your computer. It uses the API function `VerifyVersionInfoW`. There is no function `IswindowsServer` in `kernel32.dll`.
3,138,294
I would like to determine if my program is running on a version of Windows Server. Apparently, `System.Environment` does not contain information about the fact that Windows is a server version (there is no such info in the [OS version object](https://stackoverflow.com/questions/860459/determine-os-using-the-environment-osversion-object-c)). I know that I can use `SystemInformation.TerminalServerSession` to check whether my program is running on a Remote Desktop (see also [this question](https://stackoverflow.com/questions/159910/determine-if-a-program-is-running-on-a-remote-desktop)), but this will also be true if the user is simply accessing a plain client Windows machine remotely. So is there a supported way of determining if the code is running on a server or on a client machine? I don't mind using P/Invoke if needed. Note: I don't want to search for the `"Server"` string in the product name, since this will probably not work on some systems because of the localization.
2010/06/29
[ "https://Stackoverflow.com/questions/3138294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4597/" ]
You can p/invoke the following Win32 functions: [GetProductInfo](http://msdn.microsoft.com/en-us/library/ms724358.aspx) for Vista/Windows Server 2008+ [GetVersionEx](http://msdn.microsoft.com/en-us/library/ms724451(VS.85).aspx) for Windows 2000+ BJ Rollison has a [good post](http://www.testingmentor.com/imtesty/2010/03/03/programmatically-detecting-the-operating-system-version-part-ii/) and [sample code](http://www.testingmentor.com/automation/CodeSnippetLibrary.htm) about this on his blog.
I had the same issue, albeit in scripting. I have found this value; I am querying it using WMI: ``` https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx Win32_OperatingSystem ProductType Data type: uint32 Access type: Read-only Additional system information. Work Station (1) Domain Controller (2) Server (3) ``` I tested this for the following operating system versions: * Windows XP Professional SP3 * Windows 7 Enterprise * Windows 8.1 Pro * Windows 8.1 Enterprise * Windows 10 Pro 10.0.16299 * Windows Server 2003 R2 Standard Edition * Windows Server 2003 R2 Standard Edition x64 * Windows Server 2008 R2 Standard * Windows Server 2012 Datacenter * Windows Server 2012 R2 Datacenter Find my example batch file below. Lucas. ``` for /f "tokens=2 delims==" %%a in ( 'wmic.exe os get producttype /value' ) do ( set PRODUCT_TYPE=%%a ) if %PRODUCT_TYPE%==1 set PRODUCT_TYPE=Workstation if %PRODUCT_TYPE%==2 set PRODUCT_TYPE=DomainController if %PRODUCT_TYPE%==3 set PRODUCT_TYPE=Server echo %COMPUTERNAME%: %PRODUCT_TYPE% ``` You can easily do this in C#: ``` using Microsoft.Management.Infrastructure; ... string Namespace = @"root\cimv2"; string className = "Win32_OperatingSystem"; CimInstance operatingSystem = new CimInstance(className, Namespace); ```
3,138,294
I would like to determine if my program is running on a version of Windows Server. Apparently, `System.Environment` does not contain information about the fact that Windows is a server version (there is no such info in the [OS version object](https://stackoverflow.com/questions/860459/determine-os-using-the-environment-osversion-object-c)). I know that I can use `SystemInformation.TerminalServerSession` to check whether my program is running on a Remote Desktop (see also [this question](https://stackoverflow.com/questions/159910/determine-if-a-program-is-running-on-a-remote-desktop)), but this will also be true if the user is simply accessing a plain client Windows machine remotely. So is there a supported way of determining if the code is running on a server or on a client machine? I don't mind using P/Invoke if needed. Note: I don't want to search for the `"Server"` string in the product name, since this will probably not work on some systems because of the localization.
2010/06/29
[ "https://Stackoverflow.com/questions/3138294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4597/" ]
Thanks to pointers provided by Nick's answer, I've finally found what I was looking for. The function [IsOS(OS\_ANYSERVER)](http://msdn.microsoft.com/en-us/library/bb773795(v=VS.85).aspx) does exactly what I need. Here is the sample code which should work for any OS version (including pre-Vista, since we import the `IsOS` function by ordinal from `shlwapi.dll`): ``` class OS { public static bool IsWindowsServer() { return OS.IsOS (OS.OS_ANYSERVER); } const int OS_ANYSERVER = 29; [DllImport("shlwapi.dll", SetLastError=true, EntryPoint="#437")] private static extern bool IsOS(int os); } ```
There's supposed to be a set of of 'Version Helper Functions' defined in the VersionHelpers.h header file of the WinAPI in assembly Kernel32.DLL. The one that, according to the documentation, should work for your case is IsWindowsServer(void). Description is here: <http://msdn.microsoft.com/en-us/library/windows/desktop/dn424963%28v=vs.85%29.aspx> In c#, the code would like this (untested): ``` using System.Runtime.InteropServices; public static class MyClass { [DllImport("Kernel32.dll")] public static extern Boolean IsWindowsServer(); } ``` And then the consumption code would simply be: ``` bool is_it_a_server = MyClass.IsWindowsServer(); ``` I've never used any of these functions so let me know how it works...
3,138,294
I would like to determine if my program is running on a version of Windows Server. Apparently, `System.Environment` does not contain information about the fact that Windows is a server version (there is no such info in the [OS version object](https://stackoverflow.com/questions/860459/determine-os-using-the-environment-osversion-object-c)). I know that I can use `SystemInformation.TerminalServerSession` to check whether my program is running on a Remote Desktop (see also [this question](https://stackoverflow.com/questions/159910/determine-if-a-program-is-running-on-a-remote-desktop)), but this will also be true if the user is simply accessing a plain client Windows machine remotely. So is there a supported way of determining if the code is running on a server or on a client machine? I don't mind using P/Invoke if needed. Note: I don't want to search for the `"Server"` string in the product name, since this will probably not work on some systems because of the localization.
2010/06/29
[ "https://Stackoverflow.com/questions/3138294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4597/" ]
Thanks to pointers provided by Nick's answer, I've finally found what I was looking for. The function [IsOS(OS\_ANYSERVER)](http://msdn.microsoft.com/en-us/library/bb773795(v=VS.85).aspx) does exactly what I need. Here is the sample code which should work for any OS version (including pre-Vista, since we import the `IsOS` function by ordinal from `shlwapi.dll`): ``` class OS { public static bool IsWindowsServer() { return OS.IsOS (OS.OS_ANYSERVER); } const int OS_ANYSERVER = 29; [DllImport("shlwapi.dll", SetLastError=true, EntryPoint="#437")] private static extern bool IsOS(int os); } ```
`IsWindowsServer` is an *inline* function in `VersionHelpers.h`. You can find and read that header file on your computer. It uses the API function `VerifyVersionInfoW`. There is no function `IswindowsServer` in `kernel32.dll`.
3,138,294
I would like to determine if my program is running on a version of Windows Server. Apparently, `System.Environment` does not contain information about the fact that Windows is a server version (there is no such info in the [OS version object](https://stackoverflow.com/questions/860459/determine-os-using-the-environment-osversion-object-c)). I know that I can use `SystemInformation.TerminalServerSession` to check whether my program is running on a Remote Desktop (see also [this question](https://stackoverflow.com/questions/159910/determine-if-a-program-is-running-on-a-remote-desktop)), but this will also be true if the user is simply accessing a plain client Windows machine remotely. So is there a supported way of determining if the code is running on a server or on a client machine? I don't mind using P/Invoke if needed. Note: I don't want to search for the `"Server"` string in the product name, since this will probably not work on some systems because of the localization.
2010/06/29
[ "https://Stackoverflow.com/questions/3138294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4597/" ]
Thanks to pointers provided by Nick's answer, I've finally found what I was looking for. The function [IsOS(OS\_ANYSERVER)](http://msdn.microsoft.com/en-us/library/bb773795(v=VS.85).aspx) does exactly what I need. Here is the sample code which should work for any OS version (including pre-Vista, since we import the `IsOS` function by ordinal from `shlwapi.dll`): ``` class OS { public static bool IsWindowsServer() { return OS.IsOS (OS.OS_ANYSERVER); } const int OS_ANYSERVER = 29; [DllImport("shlwapi.dll", SetLastError=true, EntryPoint="#437")] private static extern bool IsOS(int os); } ```
I had the same issue, albeit in scripting. I have found this value; I am querying it using WMI: ``` https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx Win32_OperatingSystem ProductType Data type: uint32 Access type: Read-only Additional system information. Work Station (1) Domain Controller (2) Server (3) ``` I tested this for the following operating system versions: * Windows XP Professional SP3 * Windows 7 Enterprise * Windows 8.1 Pro * Windows 8.1 Enterprise * Windows 10 Pro 10.0.16299 * Windows Server 2003 R2 Standard Edition * Windows Server 2003 R2 Standard Edition x64 * Windows Server 2008 R2 Standard * Windows Server 2012 Datacenter * Windows Server 2012 R2 Datacenter Find my example batch file below. Lucas. ``` for /f "tokens=2 delims==" %%a in ( 'wmic.exe os get producttype /value' ) do ( set PRODUCT_TYPE=%%a ) if %PRODUCT_TYPE%==1 set PRODUCT_TYPE=Workstation if %PRODUCT_TYPE%==2 set PRODUCT_TYPE=DomainController if %PRODUCT_TYPE%==3 set PRODUCT_TYPE=Server echo %COMPUTERNAME%: %PRODUCT_TYPE% ``` You can easily do this in C#: ``` using Microsoft.Management.Infrastructure; ... string Namespace = @"root\cimv2"; string className = "Win32_OperatingSystem"; CimInstance operatingSystem = new CimInstance(className, Namespace); ```
3,138,294
I would like to determine if my program is running on a version of Windows Server. Apparently, `System.Environment` does not contain information about the fact that Windows is a server version (there is no such info in the [OS version object](https://stackoverflow.com/questions/860459/determine-os-using-the-environment-osversion-object-c)). I know that I can use `SystemInformation.TerminalServerSession` to check whether my program is running on a Remote Desktop (see also [this question](https://stackoverflow.com/questions/159910/determine-if-a-program-is-running-on-a-remote-desktop)), but this will also be true if the user is simply accessing a plain client Windows machine remotely. So is there a supported way of determining if the code is running on a server or on a client machine? I don't mind using P/Invoke if needed. Note: I don't want to search for the `"Server"` string in the product name, since this will probably not work on some systems because of the localization.
2010/06/29
[ "https://Stackoverflow.com/questions/3138294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4597/" ]
`IsWindowsServer` is an *inline* function in `VersionHelpers.h`. You can find and read that header file on your computer. It uses the API function `VerifyVersionInfoW`. There is no function `IswindowsServer` in `kernel32.dll`.
There's supposed to be a set of of 'Version Helper Functions' defined in the VersionHelpers.h header file of the WinAPI in assembly Kernel32.DLL. The one that, according to the documentation, should work for your case is IsWindowsServer(void). Description is here: <http://msdn.microsoft.com/en-us/library/windows/desktop/dn424963%28v=vs.85%29.aspx> In c#, the code would like this (untested): ``` using System.Runtime.InteropServices; public static class MyClass { [DllImport("Kernel32.dll")] public static extern Boolean IsWindowsServer(); } ``` And then the consumption code would simply be: ``` bool is_it_a_server = MyClass.IsWindowsServer(); ``` I've never used any of these functions so let me know how it works...
3,138,294
I would like to determine if my program is running on a version of Windows Server. Apparently, `System.Environment` does not contain information about the fact that Windows is a server version (there is no such info in the [OS version object](https://stackoverflow.com/questions/860459/determine-os-using-the-environment-osversion-object-c)). I know that I can use `SystemInformation.TerminalServerSession` to check whether my program is running on a Remote Desktop (see also [this question](https://stackoverflow.com/questions/159910/determine-if-a-program-is-running-on-a-remote-desktop)), but this will also be true if the user is simply accessing a plain client Windows machine remotely. So is there a supported way of determining if the code is running on a server or on a client machine? I don't mind using P/Invoke if needed. Note: I don't want to search for the `"Server"` string in the product name, since this will probably not work on some systems because of the localization.
2010/06/29
[ "https://Stackoverflow.com/questions/3138294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4597/" ]
I had the same issue, albeit in scripting. I have found this value; I am querying it using WMI: ``` https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx Win32_OperatingSystem ProductType Data type: uint32 Access type: Read-only Additional system information. Work Station (1) Domain Controller (2) Server (3) ``` I tested this for the following operating system versions: * Windows XP Professional SP3 * Windows 7 Enterprise * Windows 8.1 Pro * Windows 8.1 Enterprise * Windows 10 Pro 10.0.16299 * Windows Server 2003 R2 Standard Edition * Windows Server 2003 R2 Standard Edition x64 * Windows Server 2008 R2 Standard * Windows Server 2012 Datacenter * Windows Server 2012 R2 Datacenter Find my example batch file below. Lucas. ``` for /f "tokens=2 delims==" %%a in ( 'wmic.exe os get producttype /value' ) do ( set PRODUCT_TYPE=%%a ) if %PRODUCT_TYPE%==1 set PRODUCT_TYPE=Workstation if %PRODUCT_TYPE%==2 set PRODUCT_TYPE=DomainController if %PRODUCT_TYPE%==3 set PRODUCT_TYPE=Server echo %COMPUTERNAME%: %PRODUCT_TYPE% ``` You can easily do this in C#: ``` using Microsoft.Management.Infrastructure; ... string Namespace = @"root\cimv2"; string className = "Win32_OperatingSystem"; CimInstance operatingSystem = new CimInstance(className, Namespace); ```
There's supposed to be a set of of 'Version Helper Functions' defined in the VersionHelpers.h header file of the WinAPI in assembly Kernel32.DLL. The one that, according to the documentation, should work for your case is IsWindowsServer(void). Description is here: <http://msdn.microsoft.com/en-us/library/windows/desktop/dn424963%28v=vs.85%29.aspx> In c#, the code would like this (untested): ``` using System.Runtime.InteropServices; public static class MyClass { [DllImport("Kernel32.dll")] public static extern Boolean IsWindowsServer(); } ``` And then the consumption code would simply be: ``` bool is_it_a_server = MyClass.IsWindowsServer(); ``` I've never used any of these functions so let me know how it works...
3,138,294
I would like to determine if my program is running on a version of Windows Server. Apparently, `System.Environment` does not contain information about the fact that Windows is a server version (there is no such info in the [OS version object](https://stackoverflow.com/questions/860459/determine-os-using-the-environment-osversion-object-c)). I know that I can use `SystemInformation.TerminalServerSession` to check whether my program is running on a Remote Desktop (see also [this question](https://stackoverflow.com/questions/159910/determine-if-a-program-is-running-on-a-remote-desktop)), but this will also be true if the user is simply accessing a plain client Windows machine remotely. So is there a supported way of determining if the code is running on a server or on a client machine? I don't mind using P/Invoke if needed. Note: I don't want to search for the `"Server"` string in the product name, since this will probably not work on some systems because of the localization.
2010/06/29
[ "https://Stackoverflow.com/questions/3138294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4597/" ]
`IsWindowsServer` is an *inline* function in `VersionHelpers.h`. You can find and read that header file on your computer. It uses the API function `VerifyVersionInfoW`. There is no function `IswindowsServer` in `kernel32.dll`.
I had the same issue, albeit in scripting. I have found this value; I am querying it using WMI: ``` https://msdn.microsoft.com/en-us/library/aa394239(v=vs.85).aspx Win32_OperatingSystem ProductType Data type: uint32 Access type: Read-only Additional system information. Work Station (1) Domain Controller (2) Server (3) ``` I tested this for the following operating system versions: * Windows XP Professional SP3 * Windows 7 Enterprise * Windows 8.1 Pro * Windows 8.1 Enterprise * Windows 10 Pro 10.0.16299 * Windows Server 2003 R2 Standard Edition * Windows Server 2003 R2 Standard Edition x64 * Windows Server 2008 R2 Standard * Windows Server 2012 Datacenter * Windows Server 2012 R2 Datacenter Find my example batch file below. Lucas. ``` for /f "tokens=2 delims==" %%a in ( 'wmic.exe os get producttype /value' ) do ( set PRODUCT_TYPE=%%a ) if %PRODUCT_TYPE%==1 set PRODUCT_TYPE=Workstation if %PRODUCT_TYPE%==2 set PRODUCT_TYPE=DomainController if %PRODUCT_TYPE%==3 set PRODUCT_TYPE=Server echo %COMPUTERNAME%: %PRODUCT_TYPE% ``` You can easily do this in C#: ``` using Microsoft.Management.Infrastructure; ... string Namespace = @"root\cimv2"; string className = "Win32_OperatingSystem"; CimInstance operatingSystem = new CimInstance(className, Namespace); ```
23,237,692
I use PyDev in Eclipse and have a custom source path for my Python project: *src/main/python*/. The path is added to the PythonPath. Now, i want to use the library pyMIR: <https://github.com/jsawruk/pymir>, which doesn't has any install script. So I downloaded it and and included it direclty into my project as a Pydev package, the complete path to the pyMIR is: *src/main/python/music/pymir*. In the music package (*src/main/python/music*), now i want to use the library and import it via: `from pymir import AudioFile`. There appears no error, so class AudioFile is found. Afterward, I want to read an audio file via: `AudioFile.open(path)` and there i get the error "Undefined variable from import: open". But when I run the script, it works, no error occurs. Furthermore, when I look in the pyMIR package, there are also unresolved import errors. For example: `from pymir import Frame` in the class AudioFile produces the error: "Unresolved import: Frame", when I change it to `from music.pymir import Frame`, the error disappears, but then I get an error when it runs: "type object 'Frame' has no attribute 'Frame'". 1. What I have to change, another import or how to include a Pydev package? 2. When I make a new project with a standard path "src", then no "unresolved impor" errors appear. Where is the difference to *src/main/python*? Because I changed the path of source folders to *src/main/python*. Thanks in advance.
2014/04/23
[ "https://Stackoverflow.com/questions/23237692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I tried to download and install the pymir package. There is one project structure that works for me: ``` project/music/ project/music/pymir/ project/music/pymir/AudioFile project/music/pymir/... project/music/audio_files/01.wav project/music/test.py ``` The test.py: ``` import numpy from pymir import AudioFile filename = "audio_files/01.wav" print "Opening File: " + filename audiofile = AudioFile.open(filename) frames = audiofile.frames(2048, numpy.hamming) print len(frames) ``` If I moved 'test.py' out from 'music' package, I haven't found a way to make it work. The reason why the project structure is sensitive and tricky is, in my opinion, the pymir package is not well structured. E.g., the author set module name as "Frame.py" and inside the module a class is named "Frame". Then in "\_\_init\_\_.py", codes are like "from Frame import Frame". And in "AudioFile.py", codes are "from pymir import Frame". I really think the naming and structure of the current pymir is messy. Suggest you use this package carefully
add **"\_\_init\_\_.py"** empty file in base folder location and it works
23,237,692
I use PyDev in Eclipse and have a custom source path for my Python project: *src/main/python*/. The path is added to the PythonPath. Now, i want to use the library pyMIR: <https://github.com/jsawruk/pymir>, which doesn't has any install script. So I downloaded it and and included it direclty into my project as a Pydev package, the complete path to the pyMIR is: *src/main/python/music/pymir*. In the music package (*src/main/python/music*), now i want to use the library and import it via: `from pymir import AudioFile`. There appears no error, so class AudioFile is found. Afterward, I want to read an audio file via: `AudioFile.open(path)` and there i get the error "Undefined variable from import: open". But when I run the script, it works, no error occurs. Furthermore, when I look in the pyMIR package, there are also unresolved import errors. For example: `from pymir import Frame` in the class AudioFile produces the error: "Unresolved import: Frame", when I change it to `from music.pymir import Frame`, the error disappears, but then I get an error when it runs: "type object 'Frame' has no attribute 'Frame'". 1. What I have to change, another import or how to include a Pydev package? 2. When I make a new project with a standard path "src", then no "unresolved impor" errors appear. Where is the difference to *src/main/python*? Because I changed the path of source folders to *src/main/python*. Thanks in advance.
2014/04/23
[ "https://Stackoverflow.com/questions/23237692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I tried to download and install the pymir package. There is one project structure that works for me: ``` project/music/ project/music/pymir/ project/music/pymir/AudioFile project/music/pymir/... project/music/audio_files/01.wav project/music/test.py ``` The test.py: ``` import numpy from pymir import AudioFile filename = "audio_files/01.wav" print "Opening File: " + filename audiofile = AudioFile.open(filename) frames = audiofile.frames(2048, numpy.hamming) print len(frames) ``` If I moved 'test.py' out from 'music' package, I haven't found a way to make it work. The reason why the project structure is sensitive and tricky is, in my opinion, the pymir package is not well structured. E.g., the author set module name as "Frame.py" and inside the module a class is named "Frame". Then in "\_\_init\_\_.py", codes are like "from Frame import Frame". And in "AudioFile.py", codes are "from pymir import Frame". I really think the naming and structure of the current pymir is messy. Suggest you use this package carefully
1. unzip the folder `pymir` to `site-packages`, make sure the path like ``` site-packages\pymir site-packages\pymir\AudioFile.py site-packages\pymir\Frame.py site-packages\pymir\... ``` 2. comment the content of the file `__init__.py` ``` #from AudioFile import AudioFile #from Frame import Frame #from Spectrum import Spectrum ``` 3. test it ``` import numpy as np import matplotlib.pyplot as plt from pymir.AudioFile import AudioFile filename = '../wavs/cxy_6s_mono_16KHz.wav' audiofile = AudioFile.open(filename) plt.plot(audiofile) plt.show() frames = audiofile.frames(2048, np.hamming) print(len(frames)) ```
17,867
I've just came across a comment from a (probably Christian) > > I recently stumbled upon a Hadith that said this too! > > > Musnad Ahmad 16245—[Mua’wiya said]: I saw the prophet sucking on the tongue or the lips of Al-Hassan son of Ali, may the prayers of Allah be upon him. For no tongue or lips that the prophet sucked on will be tormented (by hell fire) > > > Which I can't even believe. This is disgusting and I do believe this is not real. So I searched for a while. What I came across is > > ولن يعذب لسان او شفتان مصهما رسول الله صلى الله عليه وسلم > > > Referenced from musnad imam ahmad. v: 4. p: 91 — kanz-ul haqaiq. p: 62 And made a few more search and found the following Arabic websites discussing this issue [http://www.hurras.org](http://www.hurras.org/vb/showthread.php?t=34&s=f4f87d6889c8e10bb919f5735dc3b785) [http://aljame3.net](http://aljame3.net/ib/index.php?s=3ac76b90ccf7b730230b256d8436dfee&showtopic=7144&st=0&p=33423&) However, I have no Arabic background to understand them. Can anyone shed some light about this issue?
2014/10/08
[ "https://islam.stackexchange.com/questions/17867", "https://islam.stackexchange.com", "https://islam.stackexchange.com/users/8751/" ]
There are two commonly used narrations about the said matter. First is the one you've mentioned in *Musnad Ahmed*. Second is from *[al-Adab al-Mufrad](http://sunnah.com/urn/2311800)* of al-Bukhari. Both of these reports are not authentic. The *sanad* for the first one is: > > حَدَّثَنَا هَاشِمُ بْنُ الْقَاسِمِ، حَدَّثَنَا حَرِيزٌ، عَنْ عَبْدِ > الرَّحْمَنِ ابْنِ أَبِي عَوْفٍ الْجُرَشِيِّ، عَنْ مُعَاوِيَةَ، قَالَ: > رَأَيْتُ رَسُولَ اللَّهِ > > > Abdul Rahman bin Abi Awf is unknown [said by Abul Hasan al-Qatan al-Fasi] and wasn't known to be a narrator of *hadith*. The second narrations *sanad* is: > > حَدَّثَنَا إِبْرَاهِيمُ بْنُ الْمُنْذِرِ قَالَ‏:‏ حَدَّثَنِي ابْنُ > أَبِي فُدَيْكٍ قَالَ‏:‏ حَدَّثَنِي هِشَامُ بْنُ سَعْدٍ، عَنْ نُعَيْمِ > بْنِ الْمُجْمِرِ، عَنْ أَبِي هُرَيْرَةَ > > > Hisham bin Saed is weak as was said by Yahya bin Maen, and weakened by an-Nasai. Hence, both reports have problems. It should be noted that Arabs used to suck on their children's tongues to lower the child's thirst (*ash-Shifa* of Qadhi Iyad).
Your question is indeed so interesting. I found some similar matter(s) with some or even much differences. In truth, as a view of Shia and based on what I found: The apostle of Allah (peace be upon him and his family) put his tongue in Imam Hassan’s mouth (when Hassan was a newborn), then Imam Hassan sucked it. Or as another issue, it is narrated that: (briefly) > > Someday Imam Hassan was (so) thirsty, he asked his grandfather some > water with much importunity; well, there was no water; afterwards The > Prophet (pbuh) put his tongue in Hassan’s mouth, then he became > completely satisfied (for his thirst). / Imam Hassan (a.s.) always was > saying regarding this miracle (of The Prophet) that: thirst never > overcome me after sucking The Prophet’s tongue (as his grandfather)… > > > مناقب الامام امیرالمومنین علی بن ابی طالب علیه السلام ، از محمد بن > سلیمان کوفی، ص 232، ح 698. > > > Accordingly, it could be counted as an accepted hadith as a miracle of the apostle of Allah (peace be upon him and his family). Even there is another similar narration which has narrated concerning Imam Hussein (a.s.) which has mentioned in short as below > > … Imam Hussein (a.s.) didn’t lactate, since his mother’s (Hazrat > Fatimah-a-Zahra) breast milk was dry; So, Ibn Shahr Ashub quoted that > … then The Prophet (pbuh) came, and put his finger in Hussein’s mouth, > and he was sucking the Prophet’s finger. Moreover it has narrated > that the apostle of Allah put his tongue in Hussein’s mouth (feeding…) > … > > > **Conclusion:** It can be considered as an acceptable matter by noting it as A MIRACLE OF THE PROPHET (pbuh) that Prophet Muhammad put his tongue in his grandson in order to feed him… , not as what is said somehow else. --- References: * [www.yjc.ir](http://www.yjc.ir/fa/news/5077361/%D9%88%D8%B5%DB%8C%D8%AA-%D8%A7%D9%85%D8%A7%D9%85-%D8%AD%D8%B3%D9%86%D8%B9-%D8%AF%D8%B1-%D8%A2%D8%AE%D8%B1%DB%8C%D9%86-%D9%84%D8%AD%D8%B8%D8%A7%D8%AA%E2%80%8C-%D8%B9%D9%85%D8%B1) * [www.ashoora.ir](http://www.ashoora.ir/%D8%AF%D8%A7%D9%86%D8%B4%D9%86%D8%A7%D9%85%D9%87-%D8%A7%D9%85%D8%A7%D9%85-%D8%AD%D8%B3%D9%86-%D8%B9/article/805.html) * [www.askdin.com](http://www.askdin.com/thread34836.html)
11,983,959
Google's docs say to use this kind of code to ensure new code is not executed on old platforms: ``` if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } ``` But when I do that, Eclipse still gives me warnings: "Call requires API level 11 (current min is 7)". What I want is to have my minimum version set to something lower than Honeycomb, have the above conditional statement protect me from running new code on old devices, and *not* have compiler warnings. How do I do it?
2012/08/16
[ "https://Stackoverflow.com/questions/11983959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1205506/" ]
Add `@TargetApi(11)` before method.
`@TargetApi()` seems to be the best way to do this, Look up this [page](http://tools.android.com/recent/lintapicheck)
11,983,959
Google's docs say to use this kind of code to ensure new code is not executed on old platforms: ``` if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } ``` But when I do that, Eclipse still gives me warnings: "Call requires API level 11 (current min is 7)". What I want is to have my minimum version set to something lower than Honeycomb, have the above conditional statement protect me from running new code on old devices, and *not* have compiler warnings. How do I do it?
2012/08/16
[ "https://Stackoverflow.com/questions/11983959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1205506/" ]
Add `@TargetApi(11)` before method.
Java Annotations can only be applied to [declarations](http://en.wikipedia.org/wiki/Declaration_%28computer_programming%29) and not to [statements](http://en.wikipedia.org/wiki/Statement_%28computer_science%29). The example in the [lint documentation](http://tools.android.com/recent/lintapicheck) is cheating by beginning the `if` block with a variable declaration.
11,983,959
Google's docs say to use this kind of code to ensure new code is not executed on old platforms: ``` if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); } ``` But when I do that, Eclipse still gives me warnings: "Call requires API level 11 (current min is 7)". What I want is to have my minimum version set to something lower than Honeycomb, have the above conditional statement protect me from running new code on old devices, and *not* have compiler warnings. How do I do it?
2012/08/16
[ "https://Stackoverflow.com/questions/11983959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1205506/" ]
`@TargetApi()` seems to be the best way to do this, Look up this [page](http://tools.android.com/recent/lintapicheck)
Java Annotations can only be applied to [declarations](http://en.wikipedia.org/wiki/Declaration_%28computer_programming%29) and not to [statements](http://en.wikipedia.org/wiki/Statement_%28computer_science%29). The example in the [lint documentation](http://tools.android.com/recent/lintapicheck) is cheating by beginning the `if` block with a variable declaration.
70,969,608
creation of meatFarm errored: Error encoding arguments: Error: types/values length mismatch (count={"types":2,"values":4}, value={"types":["address","address"],"values":["0xd9145CCE52D386f254917e481eB44e9943F39138","0xd8b934580fcE35a11B58C6D73aDeE468a2833fa8","",""]}, code=INVALID\_ARGUMENT, version=abi/5.5.0) i encounter above error which require 4 values but types is only 2. wondering what have I missing. [![enter image description here](https://i.stack.imgur.com/oLtgk.png)](https://i.stack.imgur.com/oLtgk.png) ``` pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract meatFarm { mapping(address => uint256[]) public stakingBalance; mapping(address => bool) public isStaking; mapping(address => uint256) public startTime; mapping(address => uint256) public meatBalance; string public name = "MeatFarm"; IERC721 public cdnoToken; IERC20 public meatToken; event Stake(address indexed from, uint256 indexed); event Unstake(address indexed from, uint256 indexed); event YieldWithdraw(address indexed to, uint256 amount); constructor( IERC721 _cdnoToken, IERC20 _meatToken ) { cdnoToken = _cdnoToken; meatToken = _meatToken; } } ```
2022/02/03
[ "https://Stackoverflow.com/questions/70969608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14409844/" ]
It looks that you are passing two empty arguments. I'm able to deploy it in Remix, using your code, with arguments: ``` "0xd9145CCE52D386f254917e481eB44e9943F39138","0xd8b934580fcE35a11B58C6D73aDeE468a2833fa8" ```
Not code probelm is remix version updated bugged!
51,959,944
I am getting below exception only in android 9, after reinstalling everything looks good, ***Exception:*** ``` android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1... ``` Code: ``` Cursor cursor = database.query(......); if(cursor == null || cursor.getCount() < 0) { //Here is the error Log.d("Error", "count : null"); return ""; } ``` Edited: ``` java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:354) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383) at java.util.concurrent.FutureTask.setException(FutureTask.java:252) at java.util.concurrent.FutureTask.run(FutureTask.java:271) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:764) Caused by: android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1 at android.database.sqlite.SQLiteConnection.nativeExecuteForCursorWindow(Native Method) at android.database.sqlite.SQLiteConnection.executeForCursorWindow(SQLiteConnection.java:859) at android.database.sqlite.SQLiteSession.executeForCursorWindow(SQLiteSession.java:836) at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:62) at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:149) at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:137) ``` Thanks in advance guys
2018/08/22
[ "https://Stackoverflow.com/questions/51959944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9528882/" ]
Try this [new constructor method](https://i.stack.imgur.com/rU4kS.png) above API 28. Maybe you should set a limited windowSizeBytes for CursorWindow and try-catch the exception. Related cts code (<https://android.googlesource.com/platform/cts/+/master/tests/tests/database/src/android/database/sqlite/cts/SQLiteCursorTest.java>) : ```java public void testRowTooBig() { mDatabase.execSQL("CREATE TABLE Tst (Txt BLOB NOT NULL);"); byte[] testArr = new byte[10000]; Arrays.fill(testArr, (byte) 1); for (int i = 0; i < 10; i++) { mDatabase.execSQL("INSERT INTO Tst VALUES (?)", new Object[]{testArr}); } // Now reduce window size, so that no rows can fit Cursor cursor = mDatabase.rawQuery("SELECT * FROM TST", null); CursorWindow cw = new CursorWindow("test", 5000); AbstractWindowedCursor ac = (AbstractWindowedCursor) cursor; ac.setWindow(cw); try { ac.moveToNext(); fail("Exception is expected when row exceeds CursorWindow size"); } catch (SQLiteBlobTooBigException expected) { } } ``` Others: > > Since this article was originally published, we’ve added new APIs in > the Android P developer preview to improve the behavior above. The > platform now allows apps to disable the ⅓ of a window heuristic and > configure CursorWindow size. > > > Ref Link: <https://medium.com/androiddevelopers/large-database-queries-on-android-cb043ae626e8>
I found how to use length() and substr() to request only 1MB (the max for CursorWindow is 2MB), maybe it will [help](https://stackoverflow.com/questions/59348784/sqliteblobtoobigexception-still-occurs-after-dividing-the-request-in-chunks-of-1). Also, you could use `context.getContentResolver().query()` with a selection that only includes the \_id column, that way you won't load data related to the other columns.
51,959,944
I am getting below exception only in android 9, after reinstalling everything looks good, ***Exception:*** ``` android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1... ``` Code: ``` Cursor cursor = database.query(......); if(cursor == null || cursor.getCount() < 0) { //Here is the error Log.d("Error", "count : null"); return ""; } ``` Edited: ``` java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:354) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383) at java.util.concurrent.FutureTask.setException(FutureTask.java:252) at java.util.concurrent.FutureTask.run(FutureTask.java:271) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:764) Caused by: android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1 at android.database.sqlite.SQLiteConnection.nativeExecuteForCursorWindow(Native Method) at android.database.sqlite.SQLiteConnection.executeForCursorWindow(SQLiteConnection.java:859) at android.database.sqlite.SQLiteSession.executeForCursorWindow(SQLiteSession.java:836) at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:62) at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:149) at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:137) ``` Thanks in advance guys
2018/08/22
[ "https://Stackoverflow.com/questions/51959944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9528882/" ]
Try this [new constructor method](https://i.stack.imgur.com/rU4kS.png) above API 28. Maybe you should set a limited windowSizeBytes for CursorWindow and try-catch the exception. Related cts code (<https://android.googlesource.com/platform/cts/+/master/tests/tests/database/src/android/database/sqlite/cts/SQLiteCursorTest.java>) : ```java public void testRowTooBig() { mDatabase.execSQL("CREATE TABLE Tst (Txt BLOB NOT NULL);"); byte[] testArr = new byte[10000]; Arrays.fill(testArr, (byte) 1); for (int i = 0; i < 10; i++) { mDatabase.execSQL("INSERT INTO Tst VALUES (?)", new Object[]{testArr}); } // Now reduce window size, so that no rows can fit Cursor cursor = mDatabase.rawQuery("SELECT * FROM TST", null); CursorWindow cw = new CursorWindow("test", 5000); AbstractWindowedCursor ac = (AbstractWindowedCursor) cursor; ac.setWindow(cw); try { ac.moveToNext(); fail("Exception is expected when row exceeds CursorWindow size"); } catch (SQLiteBlobTooBigException expected) { } } ``` Others: > > Since this article was originally published, we’ve added new APIs in > the Android P developer preview to improve the behavior above. The > platform now allows apps to disable the ⅓ of a window heuristic and > configure CursorWindow size. > > > Ref Link: <https://medium.com/androiddevelopers/large-database-queries-on-android-cb043ae626e8>
Try to scale bitmap: ``` Bitmap.createScaledBitmap ```
51,959,944
I am getting below exception only in android 9, after reinstalling everything looks good, ***Exception:*** ``` android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1... ``` Code: ``` Cursor cursor = database.query(......); if(cursor == null || cursor.getCount() < 0) { //Here is the error Log.d("Error", "count : null"); return ""; } ``` Edited: ``` java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:354) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383) at java.util.concurrent.FutureTask.setException(FutureTask.java:252) at java.util.concurrent.FutureTask.run(FutureTask.java:271) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:764) Caused by: android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1 at android.database.sqlite.SQLiteConnection.nativeExecuteForCursorWindow(Native Method) at android.database.sqlite.SQLiteConnection.executeForCursorWindow(SQLiteConnection.java:859) at android.database.sqlite.SQLiteSession.executeForCursorWindow(SQLiteSession.java:836) at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:62) at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:149) at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:137) ``` Thanks in advance guys
2018/08/22
[ "https://Stackoverflow.com/questions/51959944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9528882/" ]
This worked for me, you have to put it on your Main Activity. ``` try { Field field = CursorWindow.class.getDeclaredField("sCursorWindowSize"); field.setAccessible(true); field.set(null, 100 * 1024 * 1024); //the 100MB is the new size } catch (Exception e) { e.printStackTrace(); } ```
Try this [new constructor method](https://i.stack.imgur.com/rU4kS.png) above API 28. Maybe you should set a limited windowSizeBytes for CursorWindow and try-catch the exception. Related cts code (<https://android.googlesource.com/platform/cts/+/master/tests/tests/database/src/android/database/sqlite/cts/SQLiteCursorTest.java>) : ```java public void testRowTooBig() { mDatabase.execSQL("CREATE TABLE Tst (Txt BLOB NOT NULL);"); byte[] testArr = new byte[10000]; Arrays.fill(testArr, (byte) 1); for (int i = 0; i < 10; i++) { mDatabase.execSQL("INSERT INTO Tst VALUES (?)", new Object[]{testArr}); } // Now reduce window size, so that no rows can fit Cursor cursor = mDatabase.rawQuery("SELECT * FROM TST", null); CursorWindow cw = new CursorWindow("test", 5000); AbstractWindowedCursor ac = (AbstractWindowedCursor) cursor; ac.setWindow(cw); try { ac.moveToNext(); fail("Exception is expected when row exceeds CursorWindow size"); } catch (SQLiteBlobTooBigException expected) { } } ``` Others: > > Since this article was originally published, we’ve added new APIs in > the Android P developer preview to improve the behavior above. The > platform now allows apps to disable the ⅓ of a window heuristic and > configure CursorWindow size. > > > Ref Link: <https://medium.com/androiddevelopers/large-database-queries-on-android-cb043ae626e8>
51,959,944
I am getting below exception only in android 9, after reinstalling everything looks good, ***Exception:*** ``` android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1... ``` Code: ``` Cursor cursor = database.query(......); if(cursor == null || cursor.getCount() < 0) { //Here is the error Log.d("Error", "count : null"); return ""; } ``` Edited: ``` java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:354) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383) at java.util.concurrent.FutureTask.setException(FutureTask.java:252) at java.util.concurrent.FutureTask.run(FutureTask.java:271) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:764) Caused by: android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1 at android.database.sqlite.SQLiteConnection.nativeExecuteForCursorWindow(Native Method) at android.database.sqlite.SQLiteConnection.executeForCursorWindow(SQLiteConnection.java:859) at android.database.sqlite.SQLiteSession.executeForCursorWindow(SQLiteSession.java:836) at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:62) at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:149) at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:137) ``` Thanks in advance guys
2018/08/22
[ "https://Stackoverflow.com/questions/51959944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9528882/" ]
Try to scale bitmap: ``` Bitmap.createScaledBitmap ```
I found how to use length() and substr() to request only 1MB (the max for CursorWindow is 2MB), maybe it will [help](https://stackoverflow.com/questions/59348784/sqliteblobtoobigexception-still-occurs-after-dividing-the-request-in-chunks-of-1). Also, you could use `context.getContentResolver().query()` with a selection that only includes the \_id column, that way you won't load data related to the other columns.
51,959,944
I am getting below exception only in android 9, after reinstalling everything looks good, ***Exception:*** ``` android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1... ``` Code: ``` Cursor cursor = database.query(......); if(cursor == null || cursor.getCount() < 0) { //Here is the error Log.d("Error", "count : null"); return ""; } ``` Edited: ``` java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:354) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383) at java.util.concurrent.FutureTask.setException(FutureTask.java:252) at java.util.concurrent.FutureTask.run(FutureTask.java:271) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:764) Caused by: android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1 at android.database.sqlite.SQLiteConnection.nativeExecuteForCursorWindow(Native Method) at android.database.sqlite.SQLiteConnection.executeForCursorWindow(SQLiteConnection.java:859) at android.database.sqlite.SQLiteSession.executeForCursorWindow(SQLiteSession.java:836) at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:62) at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:149) at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:137) ``` Thanks in advance guys
2018/08/22
[ "https://Stackoverflow.com/questions/51959944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9528882/" ]
This worked for me, you have to put it on your Main Activity. ``` try { Field field = CursorWindow.class.getDeclaredField("sCursorWindowSize"); field.setAccessible(true); field.set(null, 100 * 1024 * 1024); //the 100MB is the new size } catch (Exception e) { e.printStackTrace(); } ```
I found how to use length() and substr() to request only 1MB (the max for CursorWindow is 2MB), maybe it will [help](https://stackoverflow.com/questions/59348784/sqliteblobtoobigexception-still-occurs-after-dividing-the-request-in-chunks-of-1). Also, you could use `context.getContentResolver().query()` with a selection that only includes the \_id column, that way you won't load data related to the other columns.
51,959,944
I am getting below exception only in android 9, after reinstalling everything looks good, ***Exception:*** ``` android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1... ``` Code: ``` Cursor cursor = database.query(......); if(cursor == null || cursor.getCount() < 0) { //Here is the error Log.d("Error", "count : null"); return ""; } ``` Edited: ``` java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:354) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383) at java.util.concurrent.FutureTask.setException(FutureTask.java:252) at java.util.concurrent.FutureTask.run(FutureTask.java:271) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) at java.lang.Thread.run(Thread.java:764) Caused by: android.database.sqlite.SQLiteBlobTooBigException: Row too big to fit into CursorWindow requiredPos=0, totalRows=1 at android.database.sqlite.SQLiteConnection.nativeExecuteForCursorWindow(Native Method) at android.database.sqlite.SQLiteConnection.executeForCursorWindow(SQLiteConnection.java:859) at android.database.sqlite.SQLiteSession.executeForCursorWindow(SQLiteSession.java:836) at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:62) at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:149) at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:137) ``` Thanks in advance guys
2018/08/22
[ "https://Stackoverflow.com/questions/51959944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9528882/" ]
This worked for me, you have to put it on your Main Activity. ``` try { Field field = CursorWindow.class.getDeclaredField("sCursorWindowSize"); field.setAccessible(true); field.set(null, 100 * 1024 * 1024); //the 100MB is the new size } catch (Exception e) { e.printStackTrace(); } ```
Try to scale bitmap: ``` Bitmap.createScaledBitmap ```
42,580,229
This is a follow on from my previous question, in that this is much more specific with examples and data. I have a 304 by 448 array of ice data (in polar stereographic projection), of which the netcdf can be obtained [here](https://1drv.ms/u/s!ApWaJaYUUERKjqAxv-o8m2_QloFURA). The corresponding lat/lon points of each grid box can be found in this [file](https://1drv.ms/u/s!ApWaJaYUUERKjqAyamPgIuanhe9YYQ). I would like to transform this data onto a regular lat/lon grid (say 180x360) where each grid box is a degree. Is there any python way of doing this? Etc using Basemap, or alternatively using CDO (climate data operators)? Many thanks in advance. James
2017/03/03
[ "https://Stackoverflow.com/questions/42580229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4173437/" ]
If you first add the grid to the data file with, e.g., ``` ncks -A -v lat,lon NSIDC_LatLon.nc sample.nc ``` Then you can use NCO's [ncremap](http://nco.sf.net/nco.html#ncremap) to regrid that with, e.g., ``` ncremap -i sample.nc -d 1x1.nc -o out.nc ``` Unfortunately this will require the current snapshot of NCO (rather than a released version) because the input files contained dimensions in an unusual order that I just patched NCO to handle. A sample of the regridded output is [here](http://dust.ess.uci.edu/tmp/out.nc). At the OP's request I regridded his file then uploaded it ([here](http://dust.ess.uci.edu/tmp/NSIDC_1x1.nc)). I didn't have a 1x1 dataset sitting around so I first created a 1x1 grid file as shown in the manual, then regridded with that (with ncremap -g option): ``` ncremap -i ~/NSIDC.nc -g ${DATA}/grids/180x360_SCRIP.20150901.nc -o ~/NSIDC_1x1.nc ```
Usually the command to do this in CDO would be ``` cdo remapcon,r360x180 in.nc out.nc ``` instead of con=conservative remapping, you can use bil=bilinear, nn=nearest neighbour, con2=2nd order conservative remapping. According to this posting, <https://code.mpimet.mpg.de/boards/1/topics/8302?r=8326> the latest versions of cdo should be able to handle polar stereographic projections.
39,073,109
I wrote some code to take a picture and save it on external storage. If I run the app, and make the picture I get File Not Found Exception. Here is my code: ``` public class CameraActivity extends BaseActivity { //variables for navigation drawer private String[] navMenuTitles; private TypedArray navMenuIcons; //request code private static final int ACTIVITY_START_CAMERA_APP = 1777; //ImageView for the thumbnail private ImageView mPhotoCapturedImageView; //File for folder private File folder; //variable for timestamp String timeStamp = ""; //Requestcode for external Storage Permission final int REQ_CODE_EXTERNAL_STORAGE_PERMISSION = 42; //FloatAction Button to save the picture private FloatingActionButton save; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_camera); /* * Initialize nav draw items */ //load title from String.xml navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); //load icons from String.xml navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons); //set title and icons set(navMenuTitles, navMenuIcons); //initialize ImageView mPhotoCapturedImageView = (ImageView) findViewById(R.id.imgViewThumbNail); //creat new intent for the camera app Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); //creat and set a timestamp timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); //check if permission granted if (ActivityCompat.checkSelfPermission(CameraActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { if (folder == null) { createFolder(); } } else { ActivityCompat.requestPermissions(CameraActivity.this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_CODE_EXTERNAL_STORAGE_PERMISSION); } /* //create a file with timestamp as title and save it in the folder File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "MyIdea" + File.separator + "IdeaGallery" + File.separator + "IMG_" + timeStamp + ".jpg"); */ intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(folder)); //start the camera app startActivityForResult(intent, ACTIVITY_START_CAMERA_APP); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { //Check that request code matches ours: if (requestCode == ACTIVITY_START_CAMERA_APP) { File foto = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/", "MyIdea/IdeaGalery/" + "IMG_" + timeStamp + ".jpg"); Bitmap bitmap = decodeSampledBitmapFromFile(foto.getPath(), 1000, 700); mPhotoCapturedImageView.setImageBitmap(bitmap); MediaScannerConnection.scanFile(CameraActivity.this, new String[]{foto.getPath()}, new String[]{"image/jpeg"}, null); //Get our saved file into a bitmap object: //File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +File.separator + "MyIdea" + File.separator + "IdeaGallery" + File.separator + "IMG_" + timeStamp + ".jpg"); //Bitmap photoCapturedBitmap = BitmapFactory.decodeFile(mImageFileLocation); } } public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // BEST QUALITY MATCH //First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); // Calculate inSampleSize, Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; options.inPreferredConfig = Bitmap.Config.RGB_565; int inSampleSize = 1; if (height > reqHeight) { inSampleSize = Math.round((float)height / (float)reqHeight); } int expectedWidth = width / inSampleSize; if (expectedWidth > reqWidth) { inSampleSize = Math.round((float)width / (float)reqWidth); } options.inSampleSize = inSampleSize; // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(path, options); } private void createFolder() { folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/", "MyIdea/IdeaGalery/" + "IMG_" + timeStamp + ".jpg"); folder.mkdir(); Toast.makeText(getApplicationContext(), "Folder created", Toast.LENGTH_LONG).show(); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQ_CODE_EXTERNAL_STORAGE_PERMISSION && grantResults.length > 0 && grantResults [0] == PackageManager.PERMISSION_GRANTED) { createFolder(); } } } ``` The Permission at Android Manifest were set als ``` <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> ``` Can somebody help please help me to find the bug?
2016/08/22
[ "https://Stackoverflow.com/questions/39073109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4906597/" ]
As a work around they suggest to use your own spring bean. From [Hibernate JIRA HHH-6190](https://hibernate.atlassian.net/browse/HHH-6190) ``` public class HibernateStatisticsFactoryBean implements FactoryBean<Statistics> { @Autowired private EntityManagerFactory entityManagerFactory; @Override public Statistics getObject() throws Exception { SessionFactory sessionFactory = ((HibernateEntityManagerFactory) entityManagerFactory).getSessionFactory(); return sessionFactory.getStatistics(); } @Override public Class<?> getObjectType() { return Statistics.class; } @Override public boolean isSingleton() { return true; } } ``` Then you can export this as MBean: [From Spring Doc](http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/jmx.html#jmx-mbean-server)
By default, the Hibernate statistics mechanism is not enabled, so you need to activate it using the following configuration property: `<property name="hibernate.generate_statistics" value="true"/>` To expose the Hibernate metrics via JMX, you also need to set the hibernate.jmx.enabled configuration property: `<property name="hibernate.jmx.enabled" value="true"/>` It is recommended to use Hibernate 5.4.2+ this mechanism seem broken in previous version.
4,844,077
I am currently using the `popen` function in code that is compiled by two compilers: MS Visual Studio and gcc (on linux). I might want to add gcc (on MinGW) later. The function is called `popen` for gcc, but `_popen` for MSVS, so i added the following to my source code: ``` #ifdef _MSC_VER #define popen _popen #define pclose _pclose #endif ``` This works, but i would like to understand whether there exists a standard solution for such problems (i recall a similar case with `stricmp`/`strcasecmp`). Specifically, i would like to understand the following: 1. Is `_MSC_VER` the right flag to depend on? I chose it because i have the impression that linux environment is "more standard". 2. If i put these `#define`'s in some header file, is it important whether i `#include` it before or after `stdio.h` (for the case of `popen`)? 3. If `_popen` is defined as a macro itself, is there a chance my `#define` will fail? Should i use a "new" token like `my_popen` instead, for that reason or another? 4. Did someone already do this job for me and made a good "portability header" file that i can use? 5. Anything else i should be aware of?
2011/01/30
[ "https://Stackoverflow.com/questions/4844077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509868/" ]
1. Better to check for a windows-specific define (\_WIN32 perhaps) because mingw won't have it either. popen() is standardised (it's a [part of the Single UNIX® Specification v2](http://pubs.opengroup.org/onlinepubs/007908799/xsh/popen.html)) 2. No; so long as the macro is defined before its first use it does not matter if \_popen() is not defined until later. 3. No; what you have is fine even if \_popen is a macro. 4. It's been done many times but I don't know of a freely-licensed version you can use.
1. `_MSC_VER` is the correct macro for detecting the MSVC compiler. You can use `__GNUC__` for GCC. 2. If you are going to use `popen` as your macro ID, I suggest you `#include` it after, because of 3. 3. If you `#include` it after `stdio.h`, it should work AFAIK, but better safe than sorry, no? Call it `portable_popen` or something. 4. Many projects (including some of mine) have a portability header, but it's usually better to roll your own. I'm a fan of doing things yourself if you have the time. Thus you know the details of your code (easier to debug if things go wrong), and you get code that is tailored to your needs. 5. Not that I know of. I do stuff like this all the time, without problems.
4,844,077
I am currently using the `popen` function in code that is compiled by two compilers: MS Visual Studio and gcc (on linux). I might want to add gcc (on MinGW) later. The function is called `popen` for gcc, but `_popen` for MSVS, so i added the following to my source code: ``` #ifdef _MSC_VER #define popen _popen #define pclose _pclose #endif ``` This works, but i would like to understand whether there exists a standard solution for such problems (i recall a similar case with `stricmp`/`strcasecmp`). Specifically, i would like to understand the following: 1. Is `_MSC_VER` the right flag to depend on? I chose it because i have the impression that linux environment is "more standard". 2. If i put these `#define`'s in some header file, is it important whether i `#include` it before or after `stdio.h` (for the case of `popen`)? 3. If `_popen` is defined as a macro itself, is there a chance my `#define` will fail? Should i use a "new" token like `my_popen` instead, for that reason or another? 4. Did someone already do this job for me and made a good "portability header" file that i can use? 5. Anything else i should be aware of?
2011/01/30
[ "https://Stackoverflow.com/questions/4844077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509868/" ]
The way you are doing it is fine (with the `#ifdef` etc) but the macro that you test isn't. `popen` is something that depends on your operating system and not your compiler. I'd go for something like ``` #if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 2) /* system has popen as expected */ #elif defined(YOUR_MACRO_TO DETECT_YOUR_OS) # define popen _popen # define pclose _pclose #elif defined(YOUR_MACRO_TO DETECT_ANOTHER_ONE) # define popen _pOpenOrSo # define pclose _pclos #else # error "no popen, we don't know what to do" #endif ```
1. `_MSC_VER` is the correct macro for detecting the MSVC compiler. You can use `__GNUC__` for GCC. 2. If you are going to use `popen` as your macro ID, I suggest you `#include` it after, because of 3. 3. If you `#include` it after `stdio.h`, it should work AFAIK, but better safe than sorry, no? Call it `portable_popen` or something. 4. Many projects (including some of mine) have a portability header, but it's usually better to roll your own. I'm a fan of doing things yourself if you have the time. Thus you know the details of your code (easier to debug if things go wrong), and you get code that is tailored to your needs. 5. Not that I know of. I do stuff like this all the time, without problems.
4,844,077
I am currently using the `popen` function in code that is compiled by two compilers: MS Visual Studio and gcc (on linux). I might want to add gcc (on MinGW) later. The function is called `popen` for gcc, but `_popen` for MSVS, so i added the following to my source code: ``` #ifdef _MSC_VER #define popen _popen #define pclose _pclose #endif ``` This works, but i would like to understand whether there exists a standard solution for such problems (i recall a similar case with `stricmp`/`strcasecmp`). Specifically, i would like to understand the following: 1. Is `_MSC_VER` the right flag to depend on? I chose it because i have the impression that linux environment is "more standard". 2. If i put these `#define`'s in some header file, is it important whether i `#include` it before or after `stdio.h` (for the case of `popen`)? 3. If `_popen` is defined as a macro itself, is there a chance my `#define` will fail? Should i use a "new" token like `my_popen` instead, for that reason or another? 4. Did someone already do this job for me and made a good "portability header" file that i can use? 5. Anything else i should be aware of?
2011/01/30
[ "https://Stackoverflow.com/questions/4844077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509868/" ]
1. `_MSC_VER` is the correct macro for detecting the MSVC compiler. You can use `__GNUC__` for GCC. 2. If you are going to use `popen` as your macro ID, I suggest you `#include` it after, because of 3. 3. If you `#include` it after `stdio.h`, it should work AFAIK, but better safe than sorry, no? Call it `portable_popen` or something. 4. Many projects (including some of mine) have a portability header, but it's usually better to roll your own. I'm a fan of doing things yourself if you have the time. Thus you know the details of your code (easier to debug if things go wrong), and you get code that is tailored to your needs. 5. Not that I know of. I do stuff like this all the time, without problems.
Instead of ending up with cluttered files containing `#ifdef`..`#else`..`#endif` blocks, I'd prefer a version using different files for different platforms: * put the OS dependent definitions in one file per platform and `#define` a macro `my_popen` * `#include` this file in your platform-agnostic code * never call the OS functions directly, but the `#define` that you created (i.e. `my_popen`) * depending on your OS, use different headers for compilation (e.g. `config/windows/mydefines.h` on windows and `config/linux/mydefines.h` on linux, so set the include path appropriate and always `#include "mydefines.h"`) That's a much cleaner approach than having the OS decision in the source itself. If the methods you're calling behave different between windows and linux, decide which one shall be the behavior you're using (i.e. either **always** windows behavior or **always** linux behavior) and then create wrapper methods to achieve this. For that, you'll also need not only two `mydefines.h` files but also to `myfunctions.c` files that reside in the `config/OSTYPE` directories. Doing it that way, you also get advantages when it comes to diff the linux and the windows version: you could simply diff two files while doing a diff on the linux and windows blocks of the **same** file could be difficult.
4,844,077
I am currently using the `popen` function in code that is compiled by two compilers: MS Visual Studio and gcc (on linux). I might want to add gcc (on MinGW) later. The function is called `popen` for gcc, but `_popen` for MSVS, so i added the following to my source code: ``` #ifdef _MSC_VER #define popen _popen #define pclose _pclose #endif ``` This works, but i would like to understand whether there exists a standard solution for such problems (i recall a similar case with `stricmp`/`strcasecmp`). Specifically, i would like to understand the following: 1. Is `_MSC_VER` the right flag to depend on? I chose it because i have the impression that linux environment is "more standard". 2. If i put these `#define`'s in some header file, is it important whether i `#include` it before or after `stdio.h` (for the case of `popen`)? 3. If `_popen` is defined as a macro itself, is there a chance my `#define` will fail? Should i use a "new" token like `my_popen` instead, for that reason or another? 4. Did someone already do this job for me and made a good "portability header" file that i can use? 5. Anything else i should be aware of?
2011/01/30
[ "https://Stackoverflow.com/questions/4844077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509868/" ]
1. Better to check for a windows-specific define (\_WIN32 perhaps) because mingw won't have it either. popen() is standardised (it's a [part of the Single UNIX® Specification v2](http://pubs.opengroup.org/onlinepubs/007908799/xsh/popen.html)) 2. No; so long as the macro is defined before its first use it does not matter if \_popen() is not defined until later. 3. No; what you have is fine even if \_popen is a macro. 4. It's been done many times but I don't know of a freely-licensed version you can use.
Instead of ending up with cluttered files containing `#ifdef`..`#else`..`#endif` blocks, I'd prefer a version using different files for different platforms: * put the OS dependent definitions in one file per platform and `#define` a macro `my_popen` * `#include` this file in your platform-agnostic code * never call the OS functions directly, but the `#define` that you created (i.e. `my_popen`) * depending on your OS, use different headers for compilation (e.g. `config/windows/mydefines.h` on windows and `config/linux/mydefines.h` on linux, so set the include path appropriate and always `#include "mydefines.h"`) That's a much cleaner approach than having the OS decision in the source itself. If the methods you're calling behave different between windows and linux, decide which one shall be the behavior you're using (i.e. either **always** windows behavior or **always** linux behavior) and then create wrapper methods to achieve this. For that, you'll also need not only two `mydefines.h` files but also to `myfunctions.c` files that reside in the `config/OSTYPE` directories. Doing it that way, you also get advantages when it comes to diff the linux and the windows version: you could simply diff two files while doing a diff on the linux and windows blocks of the **same** file could be difficult.
4,844,077
I am currently using the `popen` function in code that is compiled by two compilers: MS Visual Studio and gcc (on linux). I might want to add gcc (on MinGW) later. The function is called `popen` for gcc, but `_popen` for MSVS, so i added the following to my source code: ``` #ifdef _MSC_VER #define popen _popen #define pclose _pclose #endif ``` This works, but i would like to understand whether there exists a standard solution for such problems (i recall a similar case with `stricmp`/`strcasecmp`). Specifically, i would like to understand the following: 1. Is `_MSC_VER` the right flag to depend on? I chose it because i have the impression that linux environment is "more standard". 2. If i put these `#define`'s in some header file, is it important whether i `#include` it before or after `stdio.h` (for the case of `popen`)? 3. If `_popen` is defined as a macro itself, is there a chance my `#define` will fail? Should i use a "new" token like `my_popen` instead, for that reason or another? 4. Did someone already do this job for me and made a good "portability header" file that i can use? 5. Anything else i should be aware of?
2011/01/30
[ "https://Stackoverflow.com/questions/4844077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/509868/" ]
The way you are doing it is fine (with the `#ifdef` etc) but the macro that you test isn't. `popen` is something that depends on your operating system and not your compiler. I'd go for something like ``` #if defined(_POSIX_C_SOURCE) && (_POSIX_C_SOURCE >= 2) /* system has popen as expected */ #elif defined(YOUR_MACRO_TO DETECT_YOUR_OS) # define popen _popen # define pclose _pclose #elif defined(YOUR_MACRO_TO DETECT_ANOTHER_ONE) # define popen _pOpenOrSo # define pclose _pclos #else # error "no popen, we don't know what to do" #endif ```
Instead of ending up with cluttered files containing `#ifdef`..`#else`..`#endif` blocks, I'd prefer a version using different files for different platforms: * put the OS dependent definitions in one file per platform and `#define` a macro `my_popen` * `#include` this file in your platform-agnostic code * never call the OS functions directly, but the `#define` that you created (i.e. `my_popen`) * depending on your OS, use different headers for compilation (e.g. `config/windows/mydefines.h` on windows and `config/linux/mydefines.h` on linux, so set the include path appropriate and always `#include "mydefines.h"`) That's a much cleaner approach than having the OS decision in the source itself. If the methods you're calling behave different between windows and linux, decide which one shall be the behavior you're using (i.e. either **always** windows behavior or **always** linux behavior) and then create wrapper methods to achieve this. For that, you'll also need not only two `mydefines.h` files but also to `myfunctions.c` files that reside in the `config/OSTYPE` directories. Doing it that way, you also get advantages when it comes to diff the linux and the windows version: you could simply diff two files while doing a diff on the linux and windows blocks of the **same** file could be difficult.
32,266,602
I am trying to get the edited image from UIImagePickerController, but there is no UIImagePickerControllerEditedImage key in the editingInfo dictionary. What's wrong? ``` let pickerController = UIImagePickerController() pickerController.delegate = self pickerController.allowsEditing = true if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) { pickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary self.presentViewController(pickerController, animated: true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) { println(editingInfo) if let editedImage = editingInfo[UIImagePickerControllerEditedImage] as? UIImage { } } ``` editingInfo outputs ``` [UIImagePickerControllerOriginalImage: <UIImage: 0x7f8f15a1f0e0> size {1500, 1001} orientation 0 scale 1.000000, UIImagePickerControllerCropRect: NSRect: {{994, 514}, {501, 487}}, UIImagePickerControllerReferenceURL: assets-library://asset/asset.JPG?id=900A4F75-A88F-4332-AAC8-2BD3A2B1514A&ext=JPG] ```
2015/08/28
[ "https://Stackoverflow.com/questions/32266602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1037295/" ]
I suspect you've got a few minor issues that have compounded each other: 1. Your terminal emulation is set to "Windows-1252" or "ISO-8859-1". It should be set to "UTF-8". 2. You've copied and pasted the output into another file to perform a hex dump. This copies the text as rendered on screen. The hex dump seems to contain additional control characters which may have come from the clipboard. 3. Your hex dump is in big endian mode, which makes it difficult to see words or decode UTF-8 by eye. When I fetch "<http://www.tripadvisor.it/ShowUserReviews-g187849-d2263221-r233247966-Sant_Eustorgio-Milan_Lombardy.html>", with my terminal set to "UTF-8" and my locale set to "en\_GB.UTF-8" (You should set it to which ever region is correct for you but ensure it ends in ".UTF-8"), the file is correctly saved as UTF-8 and displays in `vim`, `cat` and `less`.
I think `set fileencoding=utf-8` is the wrong option for you, as it sets the encoding for the written file. The displayed encoding is set with `set encoding=utf-8`, so you should try this instead.
58,392,789
I'm developing a new Web API on EfCore 3 and .net core 3 and not able to start this because of an error "Method 'ApplyServices' in type 'Microsoft.EntityFrameworkCore.SqlServer.Infrastructure.Internal.SqlServerOptionsExtension' from assembly 'Microsoft.EntityFrameworkCore.SqlServer, Version=3.0.0.0' does not have an implementation. I should note that ApplicationContext that I inject to my project is located in another project (.net core 3 too). Debugging showed that application is crashed in this part of code --> ``` services .AddDbContext<ApplicationContext>(options => options.UseSqlServer(connectionString)); ``` Here you can see All StartUp Class ``` public Startup(IConfiguration configuration) { _configuration = configuration; } private readonly IConfiguration _configuration; public void ConfigureServices(IServiceCollection services) { services.AddOptions(); var connectionString = _configuration.GetConnectionString("DefaultConnection"); services .AddDbContext<ApplicationContext>(options => options.UseSqlServer(connectionString)); services.AddControllers() .SetCompatibilityVersion(CompatibilityVersion.Latest) .AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); services.AddHostedService<MigratorHostedService>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseCors("AllowAll"); app.UseStaticFiles(); app.UseRouting(); } ``` Here is MigratorHostedService ``` private readonly IServiceProvider _serviceProvider; public MigratorHostedService(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public async Task StartAsync(CancellationToken cancellationToken) { using (var scope = _serviceProvider.CreateScope()) { var myDbContext = scope.ServiceProvider.GetRequiredService<ApplicationContext>(); await myDbContext.Database.MigrateAsync(); } } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; ``` Here is Program ``` private const int Port = ...; public static async Task Main() { var cts = new CancellationTokenSource(); var host = Host.CreateDefaultBuilder(); host.ConfigureWebHostDefaults(ConfigureWebHost); await host.Build() .RunAsync(cts.Token) .ConfigureAwait(false); } private static void ConfigureWebHost(IWebHostBuilder builder) { builder.UseUrls($"http://*:{Port}"); builder.UseStartup<Startup>(); builder.UseDefaultServiceProvider((context, options) => { options.ValidateOnBuild = true; }); } ``` As .net core 3 is new, I haven't found solution of this problem Also my project packages: ``` <Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.0</TargetFramework> <NoWarn>$(NoWarn);NU1605</NoWarn> </PropertyGroup> <ItemGroup> <PackageReference Include="JetBrains.Annotations" Version="2019.1.3" /> <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="3.0.0-preview-18579-0056" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.0.0-preview.19080.1" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="3.0.0-preview.19080.1" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.0.0-preview.19080.1" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.6" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.0.0"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> <PackageReference Include="Microsoft.NETCore.DotNetAppHost" Version="3.0.0" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Utils" Version="3.0.0" /> <PackageReference Include="Newtonsoft.Json" Version="12.0.2" /> </ItemGroup> </Project> ``` ApplicationContext ``` public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options) { } ```
2019/10/15
[ "https://Stackoverflow.com/questions/58392789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10279513/" ]
The **spread syntax** expects an **iterable object** > > **Spread syntax allows an iterable** such as an array expression or string > to be expanded in places where zero or more arguments (for function > calls) or elements (for array literals) are expected, or an object > expression to be expanded in places where zero or more key-value pairs > (for object literals) are expected. > > > <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax> The **Object.assign()** method expects an **Object** - it doesn't have to be iterable. > > The **Object.assign()** method is used to copy the values of all > enumerable own properties **from one or more source objects** to a target > object. It will return the target object. > > > <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign> **Iterables**: <https://javascript.info/iterable> So it seems it's quite the contrary to what you suggested: the **spread syntax** is less general than the **Object.assign()** method, as it requires a stricter type of items to work correctly.
You cannot spread objects like that. Refer to this <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax>
35,549,022
Recently I have read a lot about formal verification and I am fascinated by the topic. Yet I cannot figure out the following: Formal verification requires a formal specification so h**ow can be abstract interpretation used on any source code in compilers, when there is no formal specification of the program?** Translation from a text in a foreign language that seems correct (and again does not seem to require a formal spec.) > > If a program is represented by its control flow chart, then each > branch represents a program state (can be more than one - e.g. in a > loop a branch is traversed multiple times) and abstract intepretation > creates static semantics that approximates the set of this states. > > > Here an article about abstract interpretation as a formal verification technique: <http://www.di.ens.fr/~cousot/publications.www/Cousot-NFM2012.pdf>
2016/02/22
[ "https://Stackoverflow.com/questions/35549022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/970696/" ]
One can do "concrete interpretation" by building an interpreter for a language, that computes results according to the language specification manual. (The fact that the language manuals are informal leaves the correctness of such an interpreter in permanent doubt). Abstract interpretation only requires that one have a good understanding of the program semantics, and an idea about what is worthwhile abstracting. You can get this by taking the interpreter above, and replacing actual computation with an abstraction of the computation, e.g., you can decide to represent all integer values as "positive", "zero", "negative", or "unknown". You can still compute with this, now producing qualitative results. More importantly, you can compute with this without necessarily having actual program inputs (perhaps just abstracted values). I note that the abstract interpreter is also completely untrustworthy in a formal sense, because you are still computing using the informal reference manual as a guide as to what the language will do. Now, by running such an abstract program, you may discover that it makes mistakes (e.g., dereferences a null value) with the variables controlling that null value not being "undefined". In that case, you can suggest there is a bug in the program; you may not be right, but this might produce useful results. Nowhere does abstract interpretation in practice tell you what the program computes formally because you are still using an informal reference manual. If the manual were to become a formal document, and your abstract interpreter is derived from by provably correct steps, then we might agree that an abstract interpretation of the program is a kind of specification modulo the abstraction for what the *program* actually does. Nowhere does abstract interpretation provide with access to a formal specification of the *intention* for the program. So you cannot use it by itself to prove the program "correct" with respect to the specification.
Abstract interpretation is a method used to statically gain understanding on how a software will behave. It never comes alone - there's always some goal which includes abstract interpretation as one of its components. An example of such a goal is formal verification, in which a static technique (for example, abstract interpretation) is used to obtain information about the code and then compare it to a provided specification. This is why verification requires specifications - you need something to compare it to.
46,065,063
I'm using spring boot security to help me to make authentication... ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> @Configuration @EnableWebSecurity public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .cors().and().csrf().disable().authorizeRequests() .anyRequest().authenticated().and().httpBasic(); } } ``` I have a rest service to make login (on my controller) thats a post request that i send email and password and i like to use this service to make the authentication... But i'm new on spring-boot / java... Can some one help me to make that right way? Thanks.
2017/09/06
[ "https://Stackoverflow.com/questions/46065063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4175402/" ]
You can turn the problem around and add the ',' to the start of the next output. There is no need to remove it afterwards. However you don't want the comma for the first output. ``` $addComma = ''; // should be empty for the first lines. foreach($loop1 as $val1){ $showvalone = $val1['data1']; echo $addComma."[".$showvalone; /* Here is the second MySQL query connected with 1st query */ foreach($loop2 as $val2){ $showvaltwo[] = $val2['data2']; } echo implode(",",$showvaltwo); echo "]"; $addComma = " , "; // any lines following will finish off this output } ```
Rather than output the information directly you could put it in to a variable as a string. This will allow you to rtrim the last comma after the loop, then echo the information. ``` // Declare variable to hold the string of information. $values = ""; /* Here is the mysql query */ foreach($loop1 as $val1) { $showvalone = $val1['data1']; $values .= "[".$showvalone; /* Here is the second MySQL query connected with 1st query */ foreach($loop2 as $val2) { $showvaltwo[] = $val2['data2']; } $values .= implode(",",$showvaltwo); $values .= "] , "; } // Remove the last comma and spaces from the string. $values = rtrim($values, ' , '); // Output the information. echo $values; ```
46,065,063
I'm using spring boot security to help me to make authentication... ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> @Configuration @EnableWebSecurity public class SpringSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .cors().and().csrf().disable().authorizeRequests() .anyRequest().authenticated().and().httpBasic(); } } ``` I have a rest service to make login (on my controller) thats a post request that i send email and password and i like to use this service to make the authentication... But i'm new on spring-boot / java... Can some one help me to make that right way? Thanks.
2017/09/06
[ "https://Stackoverflow.com/questions/46065063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4175402/" ]
You can turn the problem around and add the ',' to the start of the next output. There is no need to remove it afterwards. However you don't want the comma for the first output. ``` $addComma = ''; // should be empty for the first lines. foreach($loop1 as $val1){ $showvalone = $val1['data1']; echo $addComma."[".$showvalone; /* Here is the second MySQL query connected with 1st query */ foreach($loop2 as $val2){ $showvaltwo[] = $val2['data2']; } echo implode(",",$showvaltwo); echo "]"; $addComma = " , "; // any lines following will finish off this output } ```
I have my own version in removing "," at the end and instead of adding a "." ``` $numbers = array(4,8,15,16,23,42); /* defining first the "." in the last sentence instead of ",". In preparation for the foreach loop */ $last_key = end($ages); // calling the arrays with "," for each array. foreach ($ages as $key) : if ($key === $last_key) { continue; // here's the "," ends and last number deleted. } echo $key . ", "; endforeach; echo end($ages) . '.' ; // adding the "." on the last array ```
53,771,053
I have a `RecyclerView` that does not scroll inside a `ConstraintLayout`, the items are set but they don't move. I believe the problem is in the XML because the information is all there and the second item is cut down. So can anyone see if there is a problem with my `xml` layouts **This is my `product.xml` where I have the `RecyclerView`** ``` <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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:background="#fafafa" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/constraintLayout" android:layout_width="match_parent" android:layout_height="200dp" android:background="@color/colorBackgroundProducts" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <TextView android:id="@+id/textView24" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="32dp" android:layout_marginEnd="32dp" android:gravity="center" android:text="You need at leat € 1.000 on your Account Balance to add an Investment Account" android:textColor="#5e657b" android:textSize="13sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <androidx.cardview.widget.CardView android:id="@+id/cardView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="80dp" android:layout_marginEnd="16dp" app:cardCornerRadius="20dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:id="@+id/textView25" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="24dp" android:layout_marginBottom="24dp" android:text="My Account Balance" android:textColor="#5e657b" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/textView26" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="8dp" android:text="€ 5.000,00" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="@+id/textView25" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="@+id/textView25" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.cardview.widget.CardView> <TextView android:id="@+id/textView27" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:text="+ Add fund to your account " android:textColor="#00ce7c" android:textStyle="bold" app:layout_constraintEnd_toEndOf="@+id/cardView" app:layout_constraintStart_toStartOf="@+id/cardView" app:layout_constraintTop_toBottomOf="@+id/cardView" /> </androidx.constraintlayout.widget.ConstraintLayout> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_marginTop="8dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/constraintLayout"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/productsRv" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:background="@color/colorWhite" android:layoutAnimation="@anim/layout_animation_fall_down" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:spanCount="1" tools:listitem="@layout/row_product" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout> ``` **This is my row product where I have the item layout** ``` <?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView 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_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginBottom="40dp" app:cardCornerRadius="20dp" android:layout_height="240dp"> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_marginTop="20dp" android:layout_height="wrap_content"> <Button android:id="@+id/percentage_tae" android:layout_width="74dp" android:layout_height="37dp" android:layout_marginStart="16dp" android:text="2,5% TAE" android:textColor="@color/blank" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/account_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:text="My Account" android:textStyle="bold" android:textColor="#0a0f35" android:textSize="17sp" app:layout_constraintBottom_toBottomOf="@+id/percentage_tae" app:layout_constraintStart_toEndOf="@+id/percentage_tae" app:layout_constraintTop_toTopOf="@+id/percentage_tae" /> <TextView android:id="@+id/conditionsButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="16dp" android:text="Conditions" android:textColor="@color/colorIban" app:layout_constraintBottom_toBottomOf="@+id/account_name" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="@+id/account_name" /> <TextView android:id="@+id/textView29" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="23dp" android:text="Interest payment period" app:layout_constraintStart_toStartOf="@+id/percentage_tae" app:layout_constraintTop_toBottomOf="@+id/percentage_tae" /> <TextView android:id="@+id/interestPaymentPeriodText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Daily" app:layout_constraintBottom_toBottomOf="@+id/textView29" app:layout_constraintEnd_toEndOf="@+id/conditionsButton" app:layout_constraintTop_toTopOf="@+id/textView29" /> <TextView android:id="@+id/textView31" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="12dp" android:text="Deposit maturity" app:layout_constraintStart_toStartOf="@+id/textView29" app:layout_constraintTop_toBottomOf="@+id/textView29" /> <TextView android:id="@+id/deposityMaturiryInvestmentText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="8dp" android:layout_marginBottom="8dp" android:text="1 Year" app:layout_constraintBottom_toBottomOf="@+id/textView31" app:layout_constraintEnd_toEndOf="@+id/interestPaymentPeriodText" app:layout_constraintTop_toTopOf="@+id/textView31" /> <TextView android:id="@+id/textView33" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="12dp" android:text="Minimium Investment" app:layout_constraintStart_toStartOf="@+id/textView31" app:layout_constraintTop_toBottomOf="@+id/textView31" /> <Button android:id="@+id/addInvestmentAccount" android:layout_width="0dp" android:layout_height="52dp" android:layout_marginTop="8dp" android:layout_marginBottom="16dp" android:background="@drawable/selector_button_green" android:text="Add investment account" android:textAllCaps="false" android:textColor="@color/blank" android:textSize="16sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="@+id/minimumInvestmentText" app:layout_constraintStart_toStartOf="@+id/textView33" app:layout_constraintTop_toBottomOf="@+id/textView33" /> <TextView android:id="@+id/minimumInvestmentText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="€ 1.000" app:layout_constraintBottom_toBottomOf="@+id/textView33" app:layout_constraintEnd_toEndOf="@+id/deposityMaturiryInvestmentText" app:layout_constraintTop_toTopOf="@+id/textView33" app:layout_constraintVertical_bias="0.0" /> <View android:id="@+id/view5" android:layout_width="0dp" android:layout_height="1dp" android:layout_marginTop="13dp" android:background="#e8e8e8" app:layout_constraintEnd_toEndOf="@+id/conditionsButton" app:layout_constraintStart_toStartOf="@+id/percentage_tae" app:layout_constraintTop_toBottomOf="@+id/percentage_tae" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.cardview.widget.CardView> ```
2018/12/13
[ "https://Stackoverflow.com/questions/53771053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10778725/" ]
In .csprog change Project Sdk From Microsoft.NET.Sdk To Microsoft.NET.Sdk.Web
This is what I normally do and works all the time: * Right click the folder => Select Add > New File => Select Razor Page and modify the "Name" section to match my controller method name. If it doesn't work for you, how about creating files "Deactivate.cshtml" and "Reactivate.cshtml" using normal means (Finder in MacOS, Window Explorer in Windows, or command prompt), copy them to your Project\Templates\RazorPageGenerator folder, and add them to your project by right click the folder in VS2017 => Select Add > Add Files from Folder