texts
sequence
tags
sequence
[ "Windows multiprocessing", "As I have discovered windows is a bit of a pig when it comes to multiprocessing and I have a questions about it.\n\nThe pydoc states you should protect the entry point of a windows application when using multiprocessing.\n\nDoes this mean only the code which creates the new process?\n\nFor example\n\nScript 1\n\nimport multiprocessing\n\ndef somemethod():\n while True:\n print 'do stuff'\n\n# this will need protecting\np = multiprocessing.Process(target=somemethod).start()\n\n# this wont\nif __name__ == '__main__':\n p = multiprocessing.Process(target=somemethod).start()\n\n\nIn this script you need to wrap this in if main because the line in spawning the process.\nBut what about if you had?\n\nScript 2\n\nfile1.py\n\nimport file2\nif __name__ == '__main__':\n p = Aclass().start()\n\n\nfile2.py\n\nimport multiprocessing\nITEM = 0\ndef method1():\n print 'method1'\n\nmethod1()\n\nclass Aclass(multiprocessing.Process):\n def __init__(self):\n print 'Aclass'\n super(Aclass, self).__init__()\n\n def run(self):\n print 'stuff'\n\n\nWhat would need to be protected in this instance?\nWhat would happen if there was a if __main__ in File 2, would the code inside of this get executed if a process was being created?\n\nNOTE: I know the code will not compile. It's just an example." ]
[ "python", "windows", "multiprocessing" ]
[ "Setting Volume Host Path from Docker Run command", "I have a DockerFile that defines two volumes...\n\nVOLUME /XXX/XXX1\nVOLUME /XXX/XXX2\n\n\nI am running...\n\ndocker build -t XXX .\n\n\nFollowed by...\n\ndocker run XXX:latest —v XXX:XXX\n\n\nI can see the Volume Bindings in the Rider Docker window but the don't have the Host Paths set. \n\nIf I manually update them in the Rider IDE the application works as expected when started.\n\nWhy aren't my Host Paths being set by the command?\nWhat is the correct way to do this?" ]
[ "docker", "docker-compose" ]
[ "My jquery menu focus function is not working", "I'm sorry but I just started to learn jquery and Im struggling with a most basic thing\njsfiddle : http://jsfiddle.net/ufvakggn/ \n\nHere is my function :\n\nvar active = $('nav ul li');\n\nactive.focus(function() {\n $(this).children('ul').toggleClass('active');\n})\n\n\nbasically I want to navigate with tab through my menu. I thought the best way to do this is to use a toggleclass on children element when a parent element has focus. But I can't make this work\n\nupdate : actually I made some progress with \n\nvar active = $('.has-sub a');\n\nactive.focus(function() {\n $('nav ul ul').toggleClass('active');\n})\n\n\nstill trying to find a way to tab through every element and not activating all submenus when I focus something" ]
[ "javascript", "jquery", "html", "css" ]
[ "Converting an Image to RGBA Mat", "I am making an app for exposure fusion but I have a small hiccup on my ZTE test device. On the Pixel emulator, I am able to take an Image from the ImageReader and convert it to a Mat and then back to a Bitmap to be displayed in an ImageView. This is the code:\n\n int width = image.getWidth();\n int height = image.getHeight();\n\n Image.Plane yPlane = image.getPlanes()[0];\n Image.Plane uPlane = image.getPlanes()[1];\n Image.Plane vPlane = image.getPlanes()[2];\n\n ByteBuffer yBuffer = yPlane.getBuffer();\n ByteBuffer uBuffer = uPlane.getBuffer();\n ByteBuffer vBuffer = vPlane.getBuffer();\n\n int ySize = yBuffer.remaining();\n int uSize = uBuffer.remaining();\n int vSize = vBuffer.remaining();\n\n int uvPixelStride = uPlane.getPixelStride();\n\n Mat yuvMat = new Mat(height + (height / 2), width, CvType.CV_8UC1);\n\n byte[] data = new byte[ySize + uSize + vSize];\n yBuffer.get(data, 0, ySize);\n uBuffer.get(data, ySize, uSize);\n vBuffer.get(data, ySize + uSize, vSize);\n\n if (uvPixelStride == 1) {\n yuvMat.put(0, 0, data);\n\n Mat rgb = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC4);\n\n Imgproc.cvtColor(yuvMat, rgb, Imgproc.COLOR_YUV420p2RGBA);\n\n return rgb;\n\n\nNow, for the ZTE, the pixel stride for the U and V planes are 2 but I can't seem to get it to display correctly.\n\n\n\nThis is the code I'm using right now:\n\nMat yuv = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC1);\n yuv.put(0, 0, data);\n\n Mat rgb = new Mat(image.getHeight(), image.getWidth(), CvType.CV_8UC4);\n Imgproc.cvtColor(yuv, rgb, Imgproc.COLOR_YUV2RGBA_NV21);\n\n return rgb;\n\n\nAny help would be greatly appreciated." ]
[ "java", "android", "image", "opencv", "image-processing" ]
[ "Combining information from multiple lines based on overlapping positions", "I am looking to combine information from multiple lines based on specific conditions.\n\nThis is my output:\n\nATAT 0 2 2\nTATA 1 3 2\nATAT 2 4 2\nTATA 3 5 2\nGGGG 7 9 2\nCCCC 11 13 2\nGGGG 32 34 2\n\n\nThe first column is a substring,\nsecond column is the start position of the substring within the larger string,\nthird column is the end position of the substring,\nfourth column is the number of 2 character units within the substring (ATAT has two units of \"AT\"). \n\nMy goal is to combine adjacent substrings and output the new substring, position, and sum. For example, in the above output there are two cases of \"ATAT\" that are adjacent (1st and 3rd rows). We know they are adjacent because the end position of the first ATAT is the start position of the second \"ATAT.\"\nSo my desired output would look like: \n\nATATATAT 0 4 4\nTATATATA 1 5 4\nGGGG 7 9 2\nCCCC 11 13 2\nGGGG 32 34 2\n\n\nNote that the new positions for each string are the start position for the first string encountered and the end position for the last string encountered.\n\nMy hunch is that this could be done by\n1) making a dictionary of these values such that (ATAT:0,2,2)\n2) iterate over the original file and pull out instance where the substrings match and where the start of one is equal to the end of the other,\n3) print the summed + concatenated results to a new file. \n\nHowever, this seems rather un-elegant. Are there any more efficient ways to accomplish this? Thanks. \n\nEDIT: @cdlane, when using the following input and script below (adjusted to deal with comma delimiter):\nINPUT: \n\nAT,0,2\nTA,1,3\nAT,2,4\nTA,3,5\nAT,4,6\nTA,5,7\nAG,6,8\nGG,7,9\nGG,8,10\nGG,9,11\nGC,10,12\nCC,11,13\nCC,12,14\nCC,13,15\nCG,14,16\nGC,15,17\nCT,16,18\nTG,17,19\nGC,18,20\nCT,19,21\nTG,20,22\nGA,21,23\nAC,22,24\nCG,23,25\nGG,24,26\nGA,25,27\nAC,26,28\nCG,27,29\nGT,28,30\nTT,29,31\nTT,30,32\nTG,31,33\nGG,32,34\nGG,33,35\nGG,34,36\n\n\nOUTPUT:\n ('ATAT', '0', '4')\n ('TATA', '1', '5')\n ('GC', '10', '12')\n ('CCCC', '11', '15')\n ('CC', '12', '14')\n ('CG', '14', '16')\n ('GC', '15', '17')\n ('CT', '16', '18')\n ('TG', '17', '19')\n ('GC', '18', '20')\n ('CT', '19', '21')\n ('TG', '20', '22')\n ('GA', '21', '23')\n ('AC', '22', '24')\n ('CG', '23', '25')\n ('GG', '24', '26')\n ('GA', '25', '27')\n ('AC', '26', '28')\n ('CG', '27', '29')\n ('GT', '28', '30')\n ('TT', '29', '31')\n ('TT', '30', '32')\n ('TG', '31', '33')\n ('GGGG', '32', '36')\n ('GG', '33', '35')\n ('AT', '4', '6')\n ('TA', '5', '7')\n ('AG', '6', '8')\n ('GGGG', '7', '11')\n ('GG', '8', '10')" ]
[ "python", "string", "bioinformatics" ]
[ "jQuery pulsate background animation", "i can not discover why my added code to the exist plugin not works.\nI've added the functionality to animate the background on the target, but it doesn't work.\n\nthis is the function that i have added into the plugin.\n\n var pulseBackground = function(options, el) {\n console.log('anim::logger');\n $(el).animate(\n {\n backgroundColor: options.animFixedBackgroundColor\n },\n {\n duration: options.duration / 2,\n complete: function() {\n el.animtimer = setTimeout(function() {\n $(el).animate({backgroundColor: $(el).css(\"background-color\")}, {\n duration: options.duration / 2,\n complete: function() {\n el.animtimer = setTimeout(pulseBackground(options, el), options.interval);\n }\n });\n }, options.returnDelay);\n }\n }\n );\n\n var innerfunc = function() {\n pulseBackground(options, el);\n };\n\n if (el.animtimer) {\n clearTimeout(el.animtimer);\n }\n\n el.animtimer = setTimeout(innerfunc, options.interval);\n};\n\n\nWhat was my mistake, any suggestions ?\n\nDEMO: http://jsfiddle.net/C9X4J/\n\nRegards Sascha" ]
[ "javascript", "jquery", "css" ]
[ "Java Layering Images", "I'm trying to set a backdrop image then have things go on top of that backdrop image but the problem I'm running into is that the backdrop is layering over everything else. I'm hoping someone can show me how to layer images properly.\n\nThe code I have so far for painting the background is this,\n\n@Override\npublic void paint(Graphics g) {\n super.paint(g);\n Graphics2D g2d = (Graphics2D) g;\n DoAnimation();\n if (bInGame) {\n PlayGame(g2d);\n } else {\n ShowIntroScreen(g2d);\n }\n g.drawImage(ii, 5, 5, this);\n //g.drawImage(Background, 0, 0, null);\n Toolkit.getDefaultToolkit().sync();\n g.dispose();\n}\n\n\nThe g.drawImage that has Background in when active will be the only thing that appears but when I comment it out everything else shows up again. I've tried putting my background into a separate file in hopes that it will just put it behind everything else" ]
[ "java", "image", "background" ]
[ "jQuery ajax beforeSend", "I have a simple AJAX call that is executing a function on the beforeSend and on complete. They execute fine but the beforeSend is \"seemingly\" not executed until after the success.\n\nOn the beforeSend there is a \"Please wait\" notification. If I put a break after the function in the beforeSend then it will show that notification and then hit the success. Without the break point then it will sit there and think while waiting for the response and then my please wait notification will appear for a fraction of a second after the success is hit.\n\nThe desired functionality is to have the notification appear as soon as the request is sent so it displays while it is waiting for the response.\n\n $.ajax({\n type : 'POST',\n url : url,\n async : false,\n data : postData,\n beforeSend : function (){\n $.blockUI({\n fadeIn : 0,\n fadeOut : 0,\n showOverlay : false\n });\n },\n success : function (returnData) {\n //stuff\n },\n error : function (xhr, textStatus, errorThrown) {\n //other stuff\n },\n complete : function (){\n $.unblockUI();\n }\n });" ]
[ "javascript", "jquery", "jquery-blockui" ]
[ "React Navigation, adding a top tabbar to a bottom tabbar?", "I am trying to add a top tabbar, that is visible when I am at my Discover Tab. How would I go about doing this? Thankful for any help!\nThis is how I have set up my bottom tabbar:\n\n export const Tabs = TabNavigator({\n Discover: {\nscreen: DiscoverScreen,\nnavigationOptions: {\n tabBar: {\n label: \"Discover\",\n icon: ({tintColor}) => <Icon name=\"list\" size={20} color={tintColor}/>\n }\n},\n},\n\n Tickets: {\nscreen: TicketScreen,\nnavigationOptions: {\n tabBar: {\n label: \"Tickets\",\n icon: ({tintColor}) => <Icon name=\"photo\" size={20} color={tintColor}/>\n }\n},\n},\nMyProfile: {\nscreen: MyProfile,\nnavigationOptions: {\n tabBar: {\n label: \"Profile\",\n icon: ({tintColor}) => <Icon name=\"account-circle\" size={20} color={tintColor}/>\n }\n},\n},\n}, {\n tabBarComponent: NavigationComponent,\ntabBarPosition: 'bottom',\ntabBarOptions: {\nbottomNavigationOptions: {\n labelColor: 'red',\n rippleColor: 'white',\n tabs: {\n Discover: {\n barBackgroundColor: '#37474F'\n },\n MyProfile: {\n barBackgroundColor: '#00796B'\n },\n }\n}\n\n\n}\n});" ]
[ "reactjs", "react-native", "react-navigation" ]
[ "C# program hangs on Socket.Accept()", "I created a server \"middleman\" application that uses sockets and multi-threading techniques (ServerListener is run in a new thread). I found early on that when I would use the Socket.Accept() method, the program would hang indefinitely, waiting for that connection to happen. The problem is, as far as I can tell there is no reason for it not to. \n\nI spent a good portion of the day trying lots of different things to make it work, and somewhere something changed because it suddenly started working for a while. However, as soon as I accidentally chose a different data source than \"localhost\" for the client application, the problem popped back up again. I have tried running the program without the firewall OR antivirus running, but no luck. The client program IS set to connect on port 10000. Here is my code:\n\n public void ServerListener() {\n UpdateStatus(\"Establishing link to server\");\n server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n server.Bind(new IPEndPoint(IPAddress.Any, defaultPort));\n server.Listen(queue);\n UpdateStatus(\"Accepting Connections\");\n while (true) {\n Socket client = default(Socket);\n try {\n client = server.Accept();\n if (client != null) {\n ++count;\n UpdateCount(count.ToString());\n new Thread(\n () => {\n Client myclient = new Client(client, defaultPort, this);\n }\n ).Start();\n }\n }\n catch( Exception ex ){\n MessageBox.Show(ex.ToString());\n client.Close();\n }\n }\n }\n\n\nIt will run just fine right up until server.Accept(), then hangs. As stated, it did work for a while earlier, but is now hanging again. I've tried to see if any other programs are using port 10000, and they aren't. I went over and over this with a friend, and we couldn't find the problem. Please help!\n\nEDIT To be clear, I do know that Accept is a blocking call. The client program makes the connection on port 10000, but this program keeps on waiting on the Accept as if nothing happened. It did work for a time, so I know the connection is working like it is supposed to from the client program's end. However, I can't fathom why this program is now acting like that connection never happens, and continues to wait on the Accept." ]
[ "c#", "multithreading", "sockets" ]
[ "EmberJS How to capture enter key in login form", "I'm new to EmberJS/Handlebars and I have a login form that I'd like the user to be able to submit via the enter key. What's the proper way to capture that event and submit my form?" ]
[ "ember.js", "handlebars.js" ]
[ "Clearing redux state on logout NGRX", "actions \n\nimport { createAction } from '@ngrx/store';\n\nexport const logOut = createAction('[APP] LOGOUT');\n\n\nReducers\n\nimport { createReducer, on } from '@ngrx/store';\nimport * as LogoutActions from '../actions';\n\nexport const clearStateReducer = createReducer(\n on(LogoutActions.logOut, state => {\n return (state = undefined);\n })\n);\n\n\napp.module\n\nStoreModule.forRoot(reducers, { metaReducers: [clearStateReducer] }),\n\n\nI'm trying to reset the state on clicking the logout button. I did clear the localstorage but I also need to clear redux state. So followed this example https://medium.com/@moneychaudhary/how-to-reset-the-state-or-clear-the-store-on-logout-in-ngrx-store-d2bd6304f8f3\nBut I get error on metareducers, I need somehelp in fixing this.Thank you. I have attached the error screenshot" ]
[ "angular", "redux", "ngrx", "ngrx-reducers" ]
[ "How to make a image to be draggable html", "I have three buttons which add images to a div on my site. Now I want the added image to make so that I can drag it in my div. I doesn't has to be a div, it can be a canvas, I just want the images are added to be draggable. \n\nSnippet :\n\n\r\n\r\nfunction addimage() {\r\n var img = document.createElement(\"img\");\r\n img.src = \"http://bricksplayground.webs.com/brick.PNG\";\r\n img.height = 50;\r\n img.width = 100;\r\n //optionally set a css class on the image\r\n var class_name = \"foo\";\r\n img.setAttribute(\"class\", class_name);\r\n\r\n document.getElementById(\"myDiagramDiv\").appendChild(img);\r\n //document.body.appendChild(img);\r\n}\r\n<div class=\"col-sm-7 text\">\r\n <h1><strong>Div for the images</strong></h1>\r\n <div class=\"description\">\r\n <div id=\"myDiagramDiv\" draggable=\"true\" style=\"width:600px; height:400px; background-color: #DAE4E4;\"></div>\r\n </div>\r\n</div>\r\n<div class=\"col-sm-5 text\">\r\n <div class=\"description\">\r\n <h1><strong>Text</strong></h1>\r\n </div>\r\n <button type=\"button\" class=\"btn-primary\" onclick=\"addimage();\">Dodaj sto za 2 osobe</button>\r\n <button type=\"button\" class=\"btn-primary\" onclick=\"addimage();\">Dodaj sto za 4 osobe</button>\r\n <button type=\"button\" class=\"btn-primary\" onclick=\"addimage();\">Dodaj sto za vise od 4 osobe</button>\r\n</div>" ]
[ "javascript", "jquery", "html", "css", "jquery-ui" ]
[ "Pagination in CGridView in yii", "I wanna show data through CGridView with pagination..\n\nHere the problem is that the dataprovider is an array ratherthan CArrayDataProvider or CDataProvider..\n\nHow to add pagination if dataprovider is an array as shown below\n\n$this->widget('zii.widgets.grid.CGridView', array(\n 'id'=>'family-record-grid',\n 'dataProvider'=>$arr[1],\n\n 'enableSorting' => false,\n 'columns'=>\n array()\n ));" ]
[ "php", "yii", "pagination" ]
[ "Objective-C – Getting a UIWebView dynamic size.height after a potential modification of document content", "I'm dynamically resizing my UIWebView depending on the content in it. If there is alot of content it might span the height of the UIWebView to 1000px and if content is less it might span to 500px (so the UIWebView will have any arbitrary heigh from 0-n px). The code I'm using to find out the UIWebView height after it has loaded the document is this:\n\n- (void)webViewDidFinishLoad:(UIWebView *)webView {\n\n // Change the height dynamically of the UIWebView to match the html content\n CGRect webViewFrame = webView.frame;\n webViewFrame.size.height = 1;\n webView.frame = webViewFrame;\n CGSize fittingSize = [webView sizeThatFits:CGSizeZero];\n webViewFrame.size = fittingSize;\n webViewFrame.size.width = 276; // Making sure that the webView doesn't get wider than 276 px\n webView.frame = webViewFrame;\n\n float webViewHeight = webView.frame.size.height;\n}\n\n\nThis works perfectly. But to add to the complexity I'm using javascript (jquery) to check if there is an image in the document that is wider than 276 pixels (the width of my UIWebView). \n\nIF there is an image that is wider I add a class to the img tag named \"oversized\" and have a css rule that will scale the image properly so it will not be wider than 276 pixels. Since the javascript runs after the document has finished loading I can not longer \"catch\" the UIWebView height. How can I get the new document height after the javascript has been run?\n\nThe javascript I'm using looks like this:\n\n<script type='text/javascript' src='http://code.jquery.com/jquery-1.4.2.js'></script> \n<script type='text/javascript'>\n<![CDATA[ \n$(window).load(function(){\n $(document).ready(function() { \n $('img').each(function(e) { \n if ($(this).width() > 276) { \n $(this).parent().addClass('oversized');\n } \n }); \n }); \n}); \n//]]>\n</script>\n\n\nAnd the CSS:\n\n.oversized * { \n border: 2px solid red;\n width: 100%;\n height: auto;\n}" ]
[ "javascript", "objective-c", "css", "uiwebview" ]
[ "Yii2 Update Profile Photo", "I have here an Edit Profile page where user can change his/her profile photo/avatar. \n\n\n\nThe avatar displayed is the photo of the current user (of course) and when I click the Update Avatar button, the user can select an image, and then the selected image will preview replacing the current user avatar. \n\n\n\nHere's the code in my view:\n\n<div class=\"fileUpload btn btn-warning\">\n <span>Update Avatar</span>\n <input type=\"file\" accept=\"image/*\" onchange=\"loadFile(event)\" class=\"upload\"/>\n</div>\n<script>\n var loadFile = function(event) {\n var output = document.getElementById('output');\n output.src = URL.createObjectURL(event.target.files[0]);\n };\n</script>\n\n\nThe problem is that, whenever I click the Update button at the end of the form, the avatar does not change. I know that this is because it's all in the front end. How do I get the newly selected image and save it to the database? Or are there other implementation aside from this one? \n\nBTW, I chose this method because I want to preview the image before and after selection. I tried Kartik's FileInput widget but I don't know where to put the onchange=\"loadFile(event)\" event in the plugin.\n\nIf you need more code, like my action controller or the model, just let me know.\n\nI really need help in this one." ]
[ "php", "ajax", "yii2", "avatar" ]
[ "Implement cucmber with protracor test", "I have tried to implement very simple cucumber with protractor example ,but get errors in feature file ,Here is my code\n\ni'm useing node version v6.10.2 , protractor version Version 5.1.1 and cucumber version 2.4.0\n\nprotractor.conf.js file \n\nvar prefix = 'src/test/javascript/'.replace(/[^/]+/g,'..');\n\nexports.config = {\nseleniumServerJar: prefix + 'node_modules/protractor/selenium/selenium-server-standalone-2.52.0.jar',\nchromeDriver: prefix + 'node_modules/protractor/selenium/chromedriver',\nallScriptsTimeout: 20000,\n\nframeworkPath: require.resolve('protractor-cucumber-framework'),\n\ndirectConnect: true,\n\nbaseUrl: 'http://localhost:8099/',\n\ncucumberOpts: {\n require: 'step_definitions/stepDefinitions.js',\n format: 'summary'\n },\n\nspecs: [\n 'features/*.feature'\n ]\n\n\n};\n\nthe feature file that get error \n\n Feature: Running Protractor and Cucumber\n\n Scenario: Protractor and Cucumber Test\n Given I go to home page\n\n\nthe stepDefinition js file\n\n module.exports = function() {\n\nthis.Given(/^I go to home page$/, function(site, callback) {\n browser.get(site)\n .then(callback);\n});\n\n\n}\n\nbut when i going to run by $ gulp protractor I get the following error\n\n [16:01:21] Using gulpfile ~/git/adap_gateway/gulpfile.js\n [16:01:21] Starting 'protractor'...\n Using ChromeDriver directly...\n [launcher] Running 1 instances of WebDriver\n [launcher] Error: /home/ali/git/adap_gateway/src/test/javascript/features\n /attack.feature:1\n (function (exports, require, module, __filename, __dirname) { Feature:\n Running Protractor and Cucumber \n ^^^^^^^^^^\n SyntaxError: Unexpected identifier\n at createScript (vm.js:56:10)\n at Object.runInThisContext (vm.js:97:10)\n at Module._compile (module.js:542:28)\n at Object.Module._extensions..js (module.js:579:10)\n at Module.load (module.js:487:32)\n at tryModuleLoad (module.js:446:12)\n at Function.Module._load (module.js:438:3)\n at Module.require (module.js:497:17)\n at require (internal/module.js:20:19)\n at /home/ali/git/adap_gateway/node_modules/jasmine/lib/jasmine.js:71:5\n [launcher] Process exited with error code 100\n [16:01:21] gulp-notify: [JHipster Gulp Build] Error: protractor exited \n with code 100\n [16:01:22] Finished 'protractor' after 936 ms\n [16:01:22] E2E Tests failed\n\n\nCan anyone please help me to fix the error?" ]
[ "selenium", "protractor", "cucumber" ]
[ "$(document).ready firing before the DOM is loaded", "I'm working on a nav bar using Bootstrap 4.0. I have a pillbox nav bar and I wrote a javascript function to automatically detect the current page and add the active class to the right pillbox. I set the function to run when the DOM is ready but it runs before any of the HTML in the BODY is loaded. Essentially the script fails to find any elements with the 'nav-link' class at runtime and does nothing. If I add the async attribute to the script however, it works as expected. \n\nfunction main () {\n\n$nav = $('nav-link');\n\n$('.nav-link').each( function () {\n var currentPage = location.href.split(\"/\").slice(-1);\n var currentLink = $(this).attr('href').slice(2);\n console.log(currentPage);\n console.log(currentLink);\n\n if (currentLink == currentPage) { \n $(this).addClass('active');\n } else {\n $(this).removeClass('active');\n }\n\n});\n\n\n}\n\n$(document).ready(main());\n\n\nThis is my HTML file.\n\n<html lang=\"en\">\n<head>\n <!-- Required meta tags -->\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n <title>Home</title>\n <!-- Library CDNs -->\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js\" integrity=\"sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1\" crossorigin=\"anonymous\"></script>\n <!-- Custom JS -->\n <script async type=\"text/javascript\" src='checkNavActive.js'></script>\n <!-- Bootstrap CSS -->\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" crossorigin=\"anonymous\">\n <!-- Custom CSS -->\n <link rel=\"stylesheet\" href=\"./wikiCSS.css\">\n</head>\n\n<body>\n\n<div>\n <ul class=\"nav nav-pills\">\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\".\\Home.html\">Home</a>\n </li>\n <li class=\"nav-item dropdown\">\n <a class=\"nav-link dropdown-toggle\" href=\".\\DryLab.html\" data-toggle=\"dropdown\" role=\"button\" aria-haspopup=\"true\" aria-expanded=\"false\">DryLab</a>\n <div class=\"dropdown-menu\">\n <a class=\"dropdown-item\" href=\".\\DryLab.html\" >DryLab</a>\n <a class=\"dropdown-item\" href=\"#\">Another action</a>\n <a class=\"dropdown-item\" href=\"#\">Something else here</a>\n </div>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\".\\WetLab.html\">WetLab</a>\n </li>\n </ul>\n</div>\n\n\n<div class=\"container title\">\n <div class=\"row\">\n <div class=\"col text-center\">\n <h1>Home</h1>\n </div>\n </div>\n</div>\n\n\n</body>" ]
[ "javascript", "jquery", "html", "twitter-bootstrap" ]
[ "Get all kendo dropdown inside a div", "I am struggling to get all kendo dropdowns inside a div.\n\nIf I use\n\n$(\".k-list-container\").each(function () { \n var elementId = this.id.split(\"-\")[0]; \n var cb = $(\"#\" + elementId).data(\"kendoDropDownList\"); \n if(cb){ \n // do operation on dropdown \n } \n}\n\n\nit gets all kendo drop down of page, I want to get only for a div.\n\nI tried \n\n$(\"#mydiv .k-list-container\").each(function () {\n\n\nand several other selectors but it did not work out." ]
[ "jquery", "kendo-ui" ]
[ "What exactly is going on in the ->unique() function for Laravel migrations?", "In my create_users_table.php migration in my laravel set up there is the following line:\n\n$table->string('email')->unique();\n\n\nwithin the larger context of:\n\npublic function up()\n{\n Schema::create('users', function (Blueprint $table) {\n $table->increments('id');\n $table->string('name');\n $table->string('email')->unique();\n $table->string('password');\n $table->rememberToken();\n $table->timestamps();\n });\n}\n\n\nI understand that $table is an object of the class Blueprint, and that string is likely a method of that class because it takes parameters. What I don't understand is how a method of a class can have a method (string('email')->unique()??) as if it were an object. What is going on here?" ]
[ "php", "oop", "laravel-5" ]
[ "How can we initiate another jQuery plugin inside jQuery Datatable call results instead of page ready function?", "For my web application, iam using jQuery datatable with ajax to fetch data from database.Actually 'icheck' is initiated in jQuery page ready function.What the problem is after calling datatable or any filter or search happens in datatable, getting data correctly and icheck check boxes are showing as normal check boxes.\nHow can i recall the icheck plugin call inside datatable call.My Code is as follows\n\n<table id=\"viewcat\" class=\"table table-bordered table-striped mar-bottom0 mydatatable\">\n <thead>\n <tr>\n <th style=\"width: 9%\"><input type=\"checkbox\" class=\"minimal\" id=\"bulkDelete\" /> <button type=\"submit\" id=\"deleteTriger\" name=\"submit\" class=\"btn btn-primary btn-xs hor-align\" value=\"Delete Selected\" >Delete</button></th>\n <th style=\"width: 2%\">Sl.no</th>\n <th style=\"width: 15%\">Category Name</th> \n <th style=\"width: 20%\">Reference Links</th>\n <th style=\"width: 25%\">Image</th>\n <th style=\"width: 15%\"></th>\n <th style=\"width: 10%\"></th>\n </tr>\n </thead> \n</table>\n\n\nScript is as follows\n\n<script>\n $(function (){ \n $(\"#viewcat\").DataTable({\n \"fnRowCallback\" : function(nRow, aData, iDisplayIndex){ \n $(\"td:nth-child(2)\", nRow).append(aData[7]);\n return nRow;\n }, \n \"processing\": true,\n \"serverSide\": true,\n \"order\": [ 2, \"asc\" ],\n \"aoColumnDefs\": [ { \"bSortable\": false, \"aTargets\": [ 0, 1, 4, 5 ,6] } ],\n \"ajax\":{\n url :\"maincategory/viewdata.php\", // json datasource\n type: \"post\", \n error: function(){ \n $(\".viewcat-error\").html(\"\");\n $(\"#viewcat\").append('<tbody class=\"viewcat-error\"><tr><th colspan=\"7\">No data found in the server</th></tr></tbody>');\n $(\"#viewcat_processing\").css(\"display\",\"none\"); \n }\n }\n });\n\n });\n</script>\n\n\nPlease help me to fix it.." ]
[ "javascript", "php", "jquery", "jquery-plugins", "datatables" ]
[ "Java, FileReader() only seems to be reading the first line of text document?", "I'm still in the process of learning so please correct me if I'm misunderstanding, but shouldn't the FileReader object return the entire contents of a text file? \n\nI have a snippet of code here where I'm simple trying to take the contents of a short .txt file, and print it using system.out.println() \n\npublic class Main {\n\n public static void main(String[] args) throws FileNotFoundException, IOException {\n\n File testDoc = new File(\"C:\\\\Users\\\\Te\\\\Documents\\\\TestDocument.txt\");\n BufferedReader reader = new BufferedReader(new FileReader(testDoc));\n Scanner in = new Scanner(new FileReader(testDoc));\n\n\n try {\n System.out.println(reader.readLine());\n } finally {\n reader.close();\n }\n }\n}\n\n\nThe .txt file contains only 3 lines, formatted like so:\n\nsome text here, more text and stuff\nnew estonian lessons\nword = new word\n\n\nHowever the program is only printing the first line in the file.\n\nsome text here, more text and stuff\n\n\nWhat is causing this, and how do I correct it? \n\nI've tried reading the documentation, as well as searching through Stackoverflow, but I haven't been able to find the solution to this problem." ]
[ "java", "bufferedreader", "filereader" ]
[ "Angular component show always the root view", "When I try to go to /contacts it works but it shows the html code of the AppComponent (app.component.html) and not ContactsComponent (contacts.component.html), I don't knows if the problem is in routes or somethings else .\n\napp-routing.module.ts :\n\n import { NgModule } from '@angular/core';\n import { RouterModule, Routes } from '@angular/router';\n import { ContactsComponent } from './contacts/contacts.component';\n\n const routes: Routes = [\n { path: 'contacts', component: ContactsComponent }\n ];\n\n @NgModule({\n imports: [RouterModule.forRoot(routes)],\n exports: [RouterModule]\n })\n export class AppRoutingModule { }\n\n\napp.module.ts :\n\nimport { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { HttpClientModule } from '@angular/common/http';\nimport { AppRoutingModule } from './app-routing.module';\nimport { AppComponent } from './app.component';\nimport {MatFormFieldModule} from '@angular/material/form-field';\nimport {MatTableModule} from '@angular/material/table';\nimport {MatInputModule} from '@angular/material/input';\nimport { ContactsComponent } from './contacts/contacts.component';\nimport { BrowserAnimationsModule } from '@angular/platform-browser/animations';\nimport {FormsModule} from '@angular/forms';\n\n@NgModule({\n declarations: [\n AppComponent,\n ContactsComponent\n ],\n imports: [\n BrowserModule,\n HttpClientModule,\n AppRoutingModule,\n MatFormFieldModule,\n MatTableModule,\n MatInputModule,\n BrowserModule,\n FormsModule,\n BrowserAnimationsModule,\n BrowserModule,\n FormsModule,\n AppRoutingModule\n ],\n bootstrap: [AppComponent]\n})\nexport class AppModule { }" ]
[ "angular", "angular8" ]
[ "Can itemprop from one div refer to items in another div?", "I am struggling to solve what I had guessed would be an easy problem. I am not sure if it's solely a Schema.org issue, or if I am failing to understand the syntax of divs.\n\nI am adding markup to an article using the schema article markup:\n\n<div itemscope itemtype=\"http://schema.org/article\">\n\n\nThis div encompasses all of the content on the page, and I close it at the bottom of the page.\n\nNested within that div, a few paragraphs down, is another div, which is <div itemscope itemtype=\"http://schema.org/EducationalOrganization\"> and within that div is <span itemprop=\"http://schema.org/audience\"> parents </span>.\n\nI would like to know how I need to markup the word parents to indicate that the \"audience\" property should be applied to the \"article\" itemtype.\n\nI would post all of my HTML, but there's a lot of text. Hopefully this makes sense to someone. I am pretty sure all of my tags are formatted correctly by HTML standards." ]
[ "microdata" ]
[ "How to split a string into array with regex (by commas that are NOT within the brackets)?", "I need to split a string into array. \n\nString test = \"test (18,2,3) ,(,Test (,)), Test\"; \n\n\nI am expecting to split by commas that are NOT within the brackets. This is what I need\n\n test (18,2,3)\n (,Test (,)) \n Test \n\n\nI tried \n\n String test = \"test (18,2,3) , (,Test (,)) , Test\"; \n String colVals [] = test.split(\"[^(.*,.*)] | ,\");\n System.out.println(colVals[0]);\n System.out.println(colVals[1]);\n System.out.println(colVals[2]); \n\n\nBut the result was not what I was expecting" ]
[ "java", "regex" ]
[ "Making the #include square", "I'm trying to write a makefile using CC on Solaris 10. [Only the first bit of that really matters, I think]. I have the following rule for foo.o:\n\nfoo.o: foo.cc common_dependencies.h\n CC -c foo.cc -I../../common\n\n\nUnfortunately, common_dependencies.h includes all sorts of idiosyncratic trash, in directories not named '.' or '../../common' . Is this just going to have to be a brute force makefile where I ferret out all of the dependency paths? All of the dependencies are somewhere under '../..', but sometimes 1-level down and sometimes 2-levels down.\n\n-Thanks Neil" ]
[ "makefile" ]
[ "Firebase: cloud firestore rules: permission denied", "My collection /users/ has the following access rule defined:\n\n allow read: if isCurrentUser(userId) || isDoctor() || isAdmin();\n allow write: if (isCurrentUser(userId) && !isModifyingPermissions() );\n\n function isModifyingPermissions(){\n return request.resource.data.keys().hasAny([\"permissions\"]);\n }\n\n\nA document within the users collection has a series of properties:\n\n\nname\nemail\npermissions\n...\n\n\nTest:\n\n\nperform a non-destructive update of the connected user's matching document\nmyDocument.update({name: 'Hello Stackoverflow'});\n\n\nObserved behavior:\n\n\nIf the existing resource has the \"permissions\" property, then the update is denied\nIf the existing resource doesn't have the \"permissions\" property, then the update is allowed\n\n\nExpected behavior:\n - if the requested update contains the \"permissions\" property, then the update is denied\n - hatever the existing object contains, allow the update as long as it doesn't contain the \"permissions\" property.\n\nI'm using Angular5 (Ionic3) with Angularfire.\n\nIs my expectation wrong?" ]
[ "angular", "firebase", "google-cloud-firestore" ]
[ "How do I mass update a field for models in an array?", "I’m using Rails 4.2.7. How do I mass update a field of an array of my models without actually saving that information to the database? I tried\n\nmy_objcts_arr.update_all(my_object: my_object)\n\n\nbut this results in the error\n\nNoMethodError: undefined method `update_all' for #<Array:0x007f80a81cae50>\n\n\nI realize I could iteraet over the array and update each object individually, but I figure there's a slicker, one-line way in Ruby taht I'm not aware of." ]
[ "ruby-on-rails", "arrays", "ruby", "model", "updates" ]
[ "power bi year over year comparison and line chart", "I want a custom table/matrix in power bi displaying the year over year data and also a line chart displaying the same. i have all the year information in one column i.e both 2018 and 2019 data in one column. I want to perform an aggregate operation on another column and make the comparison for each of the month in the previous year \n\nThe checkout date column has all the date information for both years. The caring attitude column has the data for which i want to perform aggregation based on month\n\nThis is how i want the data to be displayed in the power bi\n\nThis is the line chart i want. Year over Year comparison of those values\n\nIn Excel I manually add the goal values in the rows and then create a graph" ]
[ "powerbi", "data-visualization", "powerquery", "linechart" ]
[ "Restricting dimensions of ImageFileField data", "I'm trying to make it so that the ImageFileField only accepts image files of a set dimension. I found another post on here which suggest hijacking the 'clean' method in a form, but I was wondering if it would be simpler to create a custom field type instead? \n\nHas anyone got any code snippets which I might be able to use in order to do this? I don't want the image files to be resized at all, just uploaded as they are if they are the correct size.\n\nMuch appreciated!" ]
[ "django", "django-admin" ]
[ "Match Username (field from mysql table) To Session ID In PHP", "How do i do it? I'v tried all different ways but I just cant do it!\n\nBasically, im trying to pull out information from the \"starters table\" and display only the logged in users data.\n\nHere is the code which gives me an error message in which I cannot solve:\n\n <?php\nsession_start();\nrequire_once '../database.php';\nif (isset($_SESSION['myusername'])){\necho \"Welcome \".$_SESSION['myusername'];\n}\n?>\n\n<?php\ninclude '../database.php';\n\n$userid = $_SESSION[\"myusername\"];\n\n#the where clause is where im stuck at the moment!\n\nLine 50:\n$result = mysql_query(\"SELECT Recipename, Ingredients, Method, Time FROM starters WHERE username = $_SESSION['myusername']\");\n\necho \"<table border='0'><table border width=65%> <tr><th>Recipie Name</th><th>Ingredients</th><th>Method</th><th>Time</th></tr>\";\n\n while($row = mysql_fetch_array($result))\n{\n echo \"<tr>\";\n echo \"<td>\" . $row['Recipename']. \"</td>\";\n echo \"<td>\" . $row['Ingredients']. \"</td>\";\n echo \"<td>\" . $row['Method']. \"</td>\";\n echo \"<td>\" . $row['Time']. 'minutes'.\"</td>\";\n\necho \"</tr>\";\n}\necho \"</table>\";\n\n ?>\n</table>\n\n\nthe error message i get is the following:\n\n Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/jahedhus/public_html/cook/usersloggedin/starters.php on line 50\n\n\nline 50 is the select statement!\nI would really appreciate your help,\nThanks so much!" ]
[ "php", "syntax-error" ]
[ "Only get single value from list executereader", "I am trying to read values form my database. But why am I getting only values with no column name?\nthis is my controller. that returns the values in JSON\n\n SqlCommand cmd = con.CreateCommand();\n\n cmd.CommandText = \"SELECT DISTINCT State FROM MyDBtable\";\n\n con.Open();\n List<string> StateList = new List<string>();\n SqlDataReader reader = cmd.ExecuteReader();\n\n while (reader.Read())\n {\n StateList.Add(reader[0].ToString());\n }\n\n return Json(new\n {\n myTable = StateList\n }, JsonRequestBehavior.AllowGet);\n\n\nand this is my JSON\n\n{\"myTable\":[\"VA\",\"CA\"]}\n\n\nWhere as, it's suppose to give me \n\n{\"myTable\":[{\"State\":\"VA\"},{\"State\":\"CA\"}]}\n\n\nWhy is it not reading and printing State" ]
[ "c#", "json", "sql-server-2008", "list", "executereader" ]
[ "Generic list in java to hold any objects", "I am new to Java.\nI want to make an array List which will be able to hold any objects.\nI am wondering how to achie this. I am trying to use Class, but I am not sure how do I get the object from that. Here is what I am tring to do\n\n<T> List<T> ConvertToList(<Map <String, List<Long>>map, Class<T> clazz)\n{\n//I want to extract all values from the map and store into an object as refered\n//by clazz and put that into list.\n\n...\n...\nList<T> list = new ArrayList<T>();\n}\n\n\nIs it possible and if yes how to do that?" ]
[ "java", "list", "generics" ]
[ "Adding two column values in SQL Server to populate a third column, can this be done without a trigger/stored procedure?", "I have a very specific question regarding this. I know I can use SUM to sum the values of the two columns, however, there are some other requirements that need to be handled other than just running a basic query.\n\n\nA third column needs to be present in the table which will contain the value of the two columns.\nThis third column needs to be updated whenever a row is created or either of the two values in the other columns are updated.\n\n\nCan this be done by setting a default value in the column with some sort of reference to update whenever either of the other two columns are updated? That would be the easiest solution. Or, do I need a trigger/stored procedure combination that will fire and run whenever a row is created or one of those two columns is updated? If so, how would I go about implementing that?\n\nThis is the table creation:\n\nCREATE TABLE [dbo].[haems_callLog]\n(\n [month] [int] NOT NULL,\n [year] [int] NOT NULL,\n [total] [int] NOT NULL CONSTRAINT [DF_haems_callLog_total] DEFAULT ((0)),\n [station] [nvarchar](4) NOT NULL CONSTRAINT [DF_haems_callLog_station] DEFAULT (N'-'),\n [station1_Total] [int] NOT NULL CONSTRAINT [DF_haems_callLog_station1_total] DEFAULT ((0)),\n [station2_Total] [int] NOT NULL CONSTRAINT [DF_haems_callLog_station2_total] DEFAULT ((0))\n) ON [PRIMARY]\n\n\nThe total fields default to \"0\". At the creation of a record, only the month, year, station, and either the station1_Total or station2_Total columns will be fed data. The total column then needs to take the value of either station1_Total or station2_Total and in addition to the \"0\" default of the other column be populated with the summed value. \n\nWhen a record is updated, either of those two columns could be changed, which then needs to be reflected in the summed value in the total column.\n\nThanks in advance for the help and guidance!" ]
[ "sql-server", "stored-procedures", "triggers" ]
[ "Passing lamda to std::find", "Probably its a late night struggle, but I am stuck with a simple thing here guys:\nint main()\n{\n std::vector<int> v{1,2,3,4,5 };\n int N;\n std::cin>>N;\n auto it = std::find(v.begin(), v.end(), [=](auto it)\n {\n return it*it == N;\n });\n}\n\nI just want the first value whose square is N, and compiler erred with:\nerror C2678: binary '==': no operator found which takes a left-hand operand of type 'int' (or there is no acceptable conversion)\n\nPlease hint what am I missing here?" ]
[ "c++", "c++11", "lambda", "find" ]
[ "Spark - Collect kafka offsets to driver before writing", "I have a high volume kafka topic that I'd like to write the batch offsets from. I'm currently using the following method. stream in this case is an InputDStream (I end up using the GenericRecord values in a DStream earlier).\n\nval my_offsets = stream.foreachRDD { rdd =>\n val offsetRanges = rdd.asInstanceOf[HasOffsetRanges].offsetRanges\n rdd.foreachPartition { iter =>\n val o: OffsetRange = offsetRanges(TaskContext.get.partitionId)\n val tOffsets = (o.topic, o.partition, o.untilOffset)\n\n writeOffsetsToMyDatasource(tOffsets)\n }\n}\n\n\nHowever this results in a write to whatever given datastore (MySQL, ZK, Hbase, etc) once per kafka partition which can have undesirable results when trying to do small time batches with a large number of partitions.\n\nI cannot find a way to collect the offsetRanges to the driver, which would be much preferred, as one write per batch (for mysql, for example) with values specified would save a lot of unnecessary writes." ]
[ "scala", "apache-spark", "apache-kafka", "spark-streaming" ]
[ "Blurry image in firefox using background size?", "I've created a twitter background button using background image:\n\nhtml:\n\n<span class=\"twitterSocial\"><a href=\"#\"></a></span>\n\n\nTo cope with retina display screen, I made the original background image slightly bigger (64px by 64px) and reduce the size using css background-size. The image display in chrome is sharp but in Firefox the image looks blur, even though I've made the image slightly bigger....\n\ncss:\n\n.twitterSocial a {\n background: url(\"http://oncorz.com/ci/css/newTheme/images/twitter_icon.png\") no-repeat scroll center center / contain rgba(0, 0, 0, 0);\n display: block;\n float: left;\n height: 39px;\n opacity: 1;\n transition: all 0.4s ease 0s;\n width: 39px;\n}\n\n\nhttp://codepen.io/vincentccw/pen/krqLC" ]
[ "html", "css", "background-size" ]
[ ".htaccess to redirect 2 different domain names to seperate \"landing pages\"", "Upon request I have reformulated my question for clarity so others might benefit better from the answers.\n\nI have 3 domains for the company I work for:\n\nbizwizprint.com (the main website that is hosted on a shared server)\n\nbizwizsigns.com (secondary domain with no hosting attached)\n\nboatwiz.com (tertiary domain with no hosting attached)\n\nThe goal is to get my second and third domains to redirect to the first domain onto their own respective landing pages.\n\nFirst Step: At the domain registrar, change the DNS \"A Records\" of the second and third domains to resolve to the same IP address that the main website is hosted on.\n\nSecond Step: Create a \"Site Alias\" on the main website server for the second and third domains, they will point to the root directory where the main website files reside.\n\nThird Step: Create or edit an .htaccess file that will redirect the requests for the second and third domains and point them to the landing pages that I have created for them.\n\nThe question: What rules do I add to htaccess?\n\nEssentially, I would like to have a user type in \"boatwiz.com\" in the address bar and the browser will literally GO TO \"bizwizprint.com/boatwiz.html\".\n\nPlease note: I do not want any rewrite rules that will change the actual URL to boatwiz.\n\nThe reason for this is that it is a temporary thing. Eventually there will be an actual \"boatwiz\" website and \"bizwizsigns\" website and they will most likely be very different in structure. I don't want it to appear that I have three domains with all the same content, or have people make any bookmarks that I will need to redirect yet again in the future." ]
[ ".htaccess", "mod-rewrite" ]
[ "Catch exceptions with logging in console using Rails", "There is the following code:\n\n if Rails.env.production? \n rescue_from ArgumentError, ActiveRecord::RecordInvalid do |exp| \n render_error(message: t('exceptions.incorrect_request_params'))\n end\n end\n\n def render_error(params)\n @error_message = params[:message]\n render 'shared/error', status: params[:status] || :bad_request\n end\n\n\nI catch the exceptions using this code, it works good, but when it happens I can't see the reason of this event in console - I just see something like this:\n\nI, [2015-08-30T05:55:24.068366 #24617] INFO -- : Rendered shared/error.json.jbuilder (0.2ms)\nI, [2015-08-30T05:55:24.068615 #24617] INFO -- : Completed 503 Service Unavailable in 289ms (Views: 1.1ms | ActiveRecord: 2.1ms)\n\n\nHow can I render template and also to write in console? Thanks in advance!" ]
[ "ruby-on-rails" ]
[ "Twitter API Error: 'internal server error'", "I tried to use Twitter API to post a tweet using Javascript. Details Below\n\nBase String \n\n\n POST&http%3A%2F%2Fapi.twitter.com%2F1%2Fstatuses%2Fupdate.json&oauth_consumer_key%3DXXXXXXXXXXX%26oauth_nonce%3D9acc2f75c97622d1d2b4c4fb4124632b1273b0e0%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1305227053%26oauth_token%3D159970118-XXXXXXXXXXXXXXXXXXXXXXX%26oauth_version%3D1.0%26status%3DHello\n\n\nHeader\n\n\n OAuth\n oauth_nonce=\"9acc2f75c97622d1d2b4c4fb4124632b1273b0e0\",\n oauth_signature_method=\"HMAC-SHA1\",\n oauth_timestamp=\"1305227053\",\n oauth_consumer_key=\"XXXXXXXXXXXXXXXXX\",\n oauth_token=\"159970118-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\",\n oauth_signature=\"IWuyoPJBrfY03Hg5QJhDRtPoaDs%3D\",\n oauth_version=\"1.0\"\n\n\nI used POST method with body \"status=Hello\"\n\nBut i get a INTERNAL SERVER ERROR.. IS there any mistake on my side ?? Thanks in advance.\n\nJavascript code used\n\nh is the header given above\n\ntweet=\"Hello\"\n\nencodeURLall is user defined which is working in all other occasions.\n\nvar xhr = new XMLHttpRequest();\nxhr.open(\"POST\",\"http://api.twitter.com/1/statuses/update.json\", false);\nxhr.setRequestHeader(\"Authorization\",h);\n\nxhr.onreadystatechange = function() {\n\n if (xhr.readyState == 4 )\n {\n console.log(\"STATUS=\"+xhr.status); \n console.log(\"RESPONSE=\"+xhr.responseText); \n }\n}\n\nxhr.send(\"status=\"+encodeURLall(tweet));\n\n}" ]
[ "javascript", "twitter", "xmlhttprequest", "google-chrome-extension", "twitter-oauth" ]
[ "Asp.Net Core Set Default API Versioning", "I'm using Asp.Net Core as a Rest API Service. I need to have API Versioning. Actually, I set in the Startup following settings and It's work correctly but when I set to default Version It's not working on.\n\nservices.AddVersionedApiExplorer(\n options =>\n {\n options.GroupNameFormat = \"'v'VVV\";\n options.SubstituteApiVersionInUrl = true;\n options.AssumeDefaultVersionWhenUnspecified = true;\n options.DefaultApiVersion = new ApiVersion(1, 0);\n });\nservices.AddApiVersioning(\n options =>\n {\n options.ReportApiVersions = true;\n options.AssumeDefaultVersionWhenUnspecified = true;\n options.DefaultApiVersion = new ApiVersion(1, 0);\n })\n .AddMvc(\n options =>\n {\n options.RespectBrowserAcceptHeader = true;\n })\n .AddXmlSerializerFormatters();\n\n\nand set Attribute in Controllers like this:\nVersion 1:\n\n[ApiController]\n[Route(\"v{version:apiVersion}/[controller]\")]\n[ApiVersion(\"1.0\")]\npublic class UsersController : ControllerBase\n{\n [HttpGet(\"log\")]\n public string Get()\n {\n return $\"{DateTime.Now}\";\n }\n}\n\n\nVersion 2:\n\n[ApiController]\n[Route(\"v{version:apiVersion}/[controller]\")]\n[ApiVersion(\"2.0\")]\npublic class UsersController : ControllerBase\n{\n [HttpGet(\"log\")]\n public string Get()\n {\n return $\"{DateTime.Now}\";\n }\n}\n\n\nI can get the result as fllowing urls:\n\nhttp://localhost:5000/v1/users/log => Status Code: 200\n\nhttp://localhost:5000/v2/users/log => Status Code: 200\n\nBut http://localhost:5000/users/log => Status Code: 404\n\nHow I can set the default API in Versioning?\n\nThanks, everyone for taking the time to try and help explain" ]
[ "asp.net", ".net", "api", "asp.net-core", "versioning" ]
[ "silverlight deserialization issue if order is not provided in datamember attribute!", "the silverlight is compaining \"the formatter threw an exception when desealizing ....\"\n\nbasically what i have come to conclusion is , that , on the server's datamodel classes if datamember's order attribute is not defined , the silverlight formatter (and the server serialiser) does not work correctly.\n\nwhen i used linq2sql to generate the model classes , they had order attribute and every thing worked fine \n\nbut when i used entity framwork , which does not has the order in datamember attribute the formatter complaint .\n\nnow , first solution is , how can i instruct the entity framework to put the order attribute of datamember\n\nsecond is , that how do i make the formatter work if order is not present.\n\nthanks\n\nJamal.\n\nP.S\none more thing i found with entity framework generated classes is , there is an attribute in DataContract ,\n\n[DataContractAttribute(IsReference=true)]\n\n\nwhile for linq2sql that attribute is not there\n\n[global::System.Runtime.Serialization.DataContractAttribute()]" ]
[ "silverlight", "wcf", "linq-to-sql", "entity-framework", "silverlight-4.0" ]
[ "SQL query to match Lego design with pieces and quantity of pieces", "I am trying to find the fastest/less complicated way to get a result for the following problem.\n\nI have a DB of (for example) Lego Kits, where each Kit has a description and a list of Lego pieces needed and how many of them. An user can insert his collection of Lego pieces and then ask what Kit he can build with his pieces and what else he can build if he buys other pieces (maybe a first limit is that he can buy only 1 type of piece).\n\nWhat I have is roughly this:\n\nLegoDesign\n- id\n- name\n\nLegoBlock\n- id\n- type\n- weight\n- description\n\nLegoBlockForDesign\n- LegoDesign.id\n- LegoBlock.id\n- numberOfPiecesNeeded\n\nCollection\n(- User.id)\n- LegoBlock.id\n- quantityAvailable\n\n\nFor example, the DB contains the LegoDesign for StarWar's Death Star. LegoBlock contains a long list of pieces like \"2x2 black square\" or \"small wheel\" etc. LegoBlockForDesign assign the LegoBlocks to the LegoDesign of he Death Star (for example 1000 pieces of \"2x2 black square\"). \nThe Table collection instead contains what pieces the user has.\nNow the problem here is that I have to query for the Design with the pieces the user has which means 1st checking for the LegoBlock.id and then checking for the numberOfPiecesNeeded since I could have some 2x2 black square pieces but not enough to build the Death Star. This is the first query. The second one should check for Design that contains the block I have plus some blocks I don't have in my collection. This means that I should check for LegoBlock in my possession but with less than the right amount and for Design with blocks not in my possession. The latter needs a limit that could be set manually. I was thinking to let the user pick between a limit on the number of pieces to buy (ie max 30 pieces) or a limit on difficulty of pieces (ie. no \"special block\" to buy, like some special wheel or character present only in specific Design (the characters of Star Wars, for example)).\n\nI'm not entirely sure it can be done in SQL, especially because I have to check for quantities and not only for the existence of the block.\n\nEDIT:\nI've added LegoBlock.type and LegoBlock.weight. This way I can define type = common,rare,unique to define normal pieces or specific ones (like the Star Wars characters that can be defined rare. I don't want to buy those pieces since they can be used only on the StarWars' Design). Weight instead can be used to give a priority (I like blue, so I would prefer to see the Design where I have to buy blue pieces)." ]
[ "mysql", "sql" ]
[ "Grouped bins with multiple y axis", "I have a data frame with five columns and five rows. the data frame looks like this:\n\ndf <- data.frame(\n day=c(\"m\",\"t\",\"w\",\"t\",\"f\"),\n V1=c(5,10,20,15,20),\n V2=c(0.1,0.2,0.6,0.5,0.8),\n V3=c(120,100,110,120,100),\n V4=c(1,10,6,8,8)\n)\n\n\nI want to do some plots so I used the ggplot and in particular the geom_bar:\n\nggplot(df, aes(x = day, y = V1, group = 1)) + ylim(0,20)+ geom_bar(stat = \"identity\")\nggplot(df, aes(x = day, y = V2, group = 1)) + ylim(0,1)+ geom_bar(stat = \"identity\")\nggplot(df, aes(x = day, y = V3, group = 1)) + ylim(50,200)+ geom_bar(stat = \"identity\")\nggplot(df, aes(x = day, y = V4, group = 1)) + ylim(0,15)+ geom_bar(stat = \"identity\")\n\n\nMy question is, How can I do a grouped ggplot with geom_bar with multiple y axis? I want at the x axis the day and for each day I want to plot four bins V1,V2,V3,V4 but with different range and color. Is that possible?\n\nEDIT\n\nI want the y axis to look like this:" ]
[ "r", "ggplot2", "axis" ]
[ "Neither dispatchKeyEvent or onKeyListener capturing events in Android?", "My code is not reporting any key events except DELETE and ENTER (maybe others), yet it should be reporting all keys. I have another app using dispatchKeyEvent and it works fine. I've tried matching the targetSDK, buildAPI, and minimum to that app in case it was an api bug as mentioned elsewhere, but none of that seemed to make any difference. I have not built the other app since updating AndroidSDK to 4.4.\n\nIs there something I am missing?\n\npublic boolean dispatchKeyEvent(KeyEvent event) {\n Log.e(\"TEST\",\"test \" + \" \"+event.getKeyCode());\n return super.dispatchKeyEvent(event);\n}\n\n\nDoes nothing for most keys (letters, tab, etc) now ↑" ]
[ "android", "keyboard", "onkeylistener" ]
[ "ndb returning a StructuredProperty subproperty by querying for a StructuredProperty", "Hi I'm confused about how to return a StructuredProperty property (mouthful):\n\nSay I have this example from the ndb tutorial:\n\nclass Address(ndb.Model):\n type = ndb.StringProperty() # E.g., 'home', 'work'\n street = ndb.StringProperty()\n city = ndb.StringProperty()\n\nclass Contact(ndb.Model):\n name = ndb.StringProperty()\n addresses = ndb.StructuredProperty(Address, repeated=True)\n\nguido = Contact(name='Guido',\n addresses=[Address(type='home',\n city='Amsterdam'),\n Address(type='work',\n street='Spear St',\n city='SF')])\n\nguido.put()\n\n\nI want to be able to query for city Amsterdam and have it return the type \"home\".\n\nso if I did the query:\n\nContact.query(Contact.address == Address(city='Amsterdam'))\n\n\nI would want it to return Home." ]
[ "google-app-engine", "database-design", "python-2.7", "app-engine-ndb" ]
[ ".NET: Advice for updating solution to .NET 4", "We have a solution containing an ASP.NET MVC web app, a web forms website project, a windows service and a heap of class libraries.\n\nWe are being upgraded to use VS2010 and would like to use all the new goodness in .NET 4.\n\nAre there any issues we need to consider here? Can anyone provide any advice?" ]
[ ".net", "asp.net-mvc", ".net-4.0" ]
[ "Data frame typecasting entire column to character from numeric", "Suppose I have a data.frame that's completely numeric. If I make one entry of the first column a character (for example), then the entire first column will become character.\n\nQuestion: How do I reverse this. That is, how do I make it such that any character objects inside the data.frame that are \"obviously\" numeric objects are forced to be numeric?\n\nMWE:\n\ntest <- data.frame(matrix(rnorm(50),10))\nis(test[3,1])\ntest[1,1] <- \"TEST\"\nis(test[3,1])\nprint(test)\n\n\nSo my goal here would be to go FROM the way that test is now, TO a state of affairs where test[2:10] is numeric. So I guess I'm asking for a function that does this over an entire data.frame." ]
[ "r", "casting", "dataframe", "numeric" ]
[ "Subset Data Frame to Exclude 28 Different Months in R Using dplyr", "I have a data frame consisting of monthly volumes beginning 2004-01-01 and ending 2019-12-01. I need to apply a filter that will delete rows that equal certain dates. My problem is that there's 28 dates I need to filter out and they arent consecutive. What I have right now works, but isn't efficient. I am using dplyr's filter function.\n\nI currently have 28 variables, d1-d28, which are the dates that I would like filtered out and then I use\n\ndf<-data%>%dplyr::filter(Date!=d1 & Date!=d2 & Date!=d3 .......Date!=d28)\n\n\nI would like to put the dates of interest, the d1-d28, into a data.frame and just reference the data.frame in my filter code. \n\nI've tried:\n\ndf<-data%>%dplyr::filter(!Date %in% DateFilter) \n\n\nWhere DateFilter is a data.frame with 1 column and 28 rows of the dates I want filtered, but I get an an error where it says the length of the objects don't match. \n\nIs there any way I can do this with dplyr?" ]
[ "r", "filter", "dplyr" ]
[ "saving CSV with UTF-16BE encoding in PHP", "I am trying to write a CSV file with a character encoding set to UTF-16BE from a MySQL database encoded in UTF-8. \n\nMy code is: \n\n$f = fopen('file.csv', 'w');\n$firstLineKeys = false;\n\n// UTF-16BE BOM\nfwrite($f, chr(254) . chr(255));\n\nforeach ($lines as $line)\n{\n $lineEncoded = [];\n\n foreach ($line as $key => $value) \n {\n $key = mb_convert_encoding($key, 'UTF-16BE', \"auto\");\n $value = mb_convert_encoding($value, 'UTF-16BE', \"auto\");\n $lineEncoded[$key] = $value;\n }\n\n if (empty($firstLineKeys))\n {\n $firstLineKeys = array_keys($lineEncoded);\n\n fputcsv($f, $firstLineKeys);\n\n $firstLineKeys = array_flip($firstLineKeys);\n }\n\n fputcsv($f, array_merge($firstLineKeys, $lineEncoded));\n}\n\nfclose($f);\n\n\nWhen I open the file in OpenOffice it try's to import it with a character set of Unicode but the fields are a mess... when I switch the import character set to UTF-8 it looks correct.\n\nAny help would be apprecated thanks" ]
[ "php", "mysql", "csv", "unicode", "encoding" ]
[ "When to use factory method", "I know this question has been asked many times, but I still have a very simple question, what is the purpose of using a factory method if the initiation of an object is simple.\nInterface Animal{\n eat();\n}\n\nclass Dog implements Animal{\n\n public void eat(){System.out.println("dog eat");}\n}\n\nAssume I have a concrete Cat class and fish class implement the Animal interface.\nSo in this case, is it necessary to make 3 Factory to create the animals? I think we only use the factory method when the initialization is difficult." ]
[ "design-patterns", "factory-pattern" ]
[ "Active Directory access denied exception on DirectoryEntry.Invoke ChangePassword", "Following MVC web api code works without errors\n\ndirectoryEntry.Invoke(\"SetPassword\", \"desired password\");\ndirectoryEntry.CommitChanges();\n\n\nBut same application/service account get an error when attempting \n\ndirectoryEntry.Invoke(\"ChangePassword\", \"old password\", \"new password\");\ndirectoryEntry.CommitChanges();\n\n\nError details:\nSystem.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))\n\nDoes invoking ChangePassword require different permissions that SetPassword?" ]
[ "c#", "active-directory" ]
[ "How to insert message at the beginning of an Azure storage queue?", "How can we insert messages to the front of a Azure storage queue (essentially using it as a stack for the messages inserted in the queue front) ?" ]
[ "azure", "azure-storage", "azure-storage-queues", "azure-storage-emulator" ]
[ "The Flash Builder debugger failed to connect to the running application", "I know this has been posted a few times like here:\nFlash player debugger not working\nbut I have uninstalled flash player and tried to reinstall an older version of flash player 10.1 which I believe worked with my 4.5 version of Flash Builder. But I go to \nhttp://flashplayerversion.com/\nand it still says I have mac 12.0.0.44 debugger version installed in Firefox. How can I get the older version of the flash player to install? Is there something I should uninstall to make sure my system installs FP 10.1?" ]
[ "flash-builder" ]
[ "how to display routes programmatically?", "Is there a way to display the routes in a Rails view (pretty much like Rails routes does in Rails 5)?" ]
[ "ruby-on-rails", "ruby-on-rails-5" ]
[ "Character is stored inplace of an integer", "Character is stored in place of an integer\n\n /* C program to find strong number using Structure and Pointers*/\n\n#include<stdio.h>\n#include<stdlib.h>\n\nstruct strg {\n long int a;\n}*strgvar;\n\nint strong(int);\n\nint main() {\n int result;\n strgvar = (struct strg*) malloc(sizeof(struct strg));\n printf(\"Enter the number ...\\n\");\n scanf(\"%ld\", &strgvar -> a);\n result = strong(strgvar -> a);\n if(result == strgvar->a) {\n printf(\"Its a strong number !\");\n }\n else {\n printf(\"Its not a strong number !\");\n }\n return 0;\n} \n\nint strong (int a) {\n int fact, r, n, sum = 0;\n while(a != 0) {\n r = r % 10;\n for(int i =0; i <= r; i++) {\n fact = fact * i;\n }\n sum = sum + fact;\n n = n/ 10;\n }\n return sum;\n}\n\n\n\n\nWhile running this program , the input integer is not storing in the variable.But while entering any character it prints \"Its a strong number!\"\n\nExample:\n\n\n case 1:\n \n Enter the number... 234\n \n 2\n \n 178\n \n er\n \n fg yu8 . case 2: Enter the number ...e\n\n\nIts a strong number!" ]
[ "c", "struct", "scanf" ]
[ "What do dollar, at-sign and semicolon characters in Perl parameter lists mean?", "I have encountered a number of Perl scripts in the codebase at my job. Some of them contain subroutines with the following syntax oddity:\n\nsub sum($$$) {\n my($a,$b,$m)=@_;\n for my $i (0..$m) {\n $$a[$i] += $$b[$i] if $$b[$i] > 0;\n }\n}\n\nsub gNode($$;$$) {\n my($n,$l,$s,$d) = @_;\n return (\n \"Node name='$n' label='$l' descr='$d'\" ,\n $s ? (\"Shape type='$s' /\") : (),\n '/Node'\n );\n}\n\nsub gOut($$@) {\n my $h = shift;\n my $i = shift;\n if ($i > 0) {\n print $h (('')x$i, map '<'.$_.'>', @_);\n } else {\n print $h map '<'.$_.'>', @_;\n }\n}\n\n\nLeaving aside the question of what these subroutines are meant to do (I'm not entirely sure myself...), what do the sequences of characters in the 'parameter list' position mean? Viz. the $$$, $$;$$ and $$@ sequences in these examples.\n\nI have a very limited understanding of Perl, but I believe that the my($a,$b,$m)=@_; line in the first example (sum) unpacks the parameters passed to the subroutine into the $a, $b and $m local variables. This suggests that the $$$ indicates the arity and type signature of sum (it expects three scalars, in this case). This would potentially suggest that gOut expects two scalars and an array. Is this the correct interpretation?\n\nEven if the above interpretation is correct, I'm lost as to the meaning of the semicolon in the second routine (gNode)." ]
[ "perl", "parameters" ]
[ "Why Are Files Copied By VBScript FileCopy Turning Up Empty?", "I have this script that picks up video files placed in an "Inbox" folder and copies it to both a separate local processing folder as well as a backup folder on a NAS.\nThe strange thing I'm discovering is that 90% of the files being copied to the local processing folders are all empty, unplayable, 0KB files but all of the copies in the backup folder on the NAS are intact and plays fine.\nThis is even weirder when you notice in the code, attached below, that the first CopyFile is called to copy the source file to the local folder and the second CopyFile called to copy the source file to the NAS runs after it.\nWhat is going on here? Why is the first copying process causing empty files but the second isn't?\nThe getNextAvailableFileName() only checks if a filename exists and appends a "(#)" tag to the end of the filename and doesn't appear to affect the copying process as the file names remain similar on both the NAS and local folders.\ndirPath_video = '[Local Processing Folder]\nnasPath_video = '[NAS Backup Folder]\n\nSet fso = CreateObject("Scripting.FileSystemObject")\nif sourceFromNASStorage then \n ' ... Inactive Code ...\nelse\n newFileName = getNextAvailableFileName(dirPath_video,fileName,"")\n fso.CopyFile filePath_original, dirPath_video&"\\"&newFileName\nend if\nfso.CopyFile filePath_original, nasPath_video&"\\"&newFileName\nif fso.FileExists(nasPath_video&"\\"&newFileName) then fso.DeleteFile(filePath_original) end if" ]
[ "windows", "vbscript", "file-copying" ]
[ "Creating a central log out view controller in storyboard", "I am working with Parse, and one thing I have implemented in my app is their built in PFLogInViewController. This controller will be presented at two times in the application - when the app first starts and the user is not logged in, and when the user taps the \"Log out\" button of my application (logging out takes them back to the PFLogInViewController, as you are required to sign in to use the app). I would like to set this up using Storyboard, as that is how the rest of my app is laid out. How could I set up a central view controller (a PFLogInViewController) that is accessed at these two times? I have already Subclassed PFLogInViewController and set it up, I just need advice on how to place it in Storyboard and how to connect it to my views. To make this question help as many people as possible, the general theme of my question is how does one establish a central Login/ViewController that can be accessed at different points in the application using Storyboard. Attached is the basic idea of what I'm trying to accomplish. I haven't been able to successfully segue to the initial TabBarController, and I'm not sure how I should make the LoginController the initial ViewController if I can't segue. I am programming in Swift, if it matters." ]
[ "ios", "cocoa-touch", "parse-platform", "uistoryboard", "uistoryboardsegue" ]
[ "DIV background won't stay in one place", "Is there something wrong with my code that makes this green css div block not show up in the exact same place on each page?\n\nOn the index page it's perfect, right under the nav bar. But on the page \"This\" it's not in same place. The stripe also changes position with any additional content. Why is that if it's set to relative? Isn't it floating and other content shouldn't disrupt its postioning? I'm so confused. PLEASE take pity on me as I am not great at CSS as you will see from my code: \n\n/* green stripe */\n.stripe\n{\n\n padding: 0.25rem 9999rem;\n background-color: #4ea647;\n z-index: 889;\n position: relative;\n top: -1200px;\n left: -500px;\n height: 50px;\n\n}\n\n\nTHIS IS THE SITE:\n\nhttps://andrea-levin-7gzp.squarespace.com/" ]
[ "css", "background", "position" ]
[ "Why is the diff of two datetime objects so?", "datetime1 = '2020-08-19 10:13:19'\ndatetime2 = '2020-08-19 19:00:00'\n\ndiff = datetime1 - datetime2\n\nThe diff is a timedelta object, with:\ndiff.days = -1\ndiff.seconds = 54766 = 15.22 hours\n\nThere are only about 9 hours diff between the two datetimes. Why does it show the number of days is '1' and 15.22 hours? How to understand the diff of two datetimes?" ]
[ "python", "datetime" ]
[ "How to get collection of items depending on specific category using Firebase RealTime DataBase", "I have an application that consists of two tables or collections [coupons, categories] in Realtime Database firebase and I want to get all coupons that belong to a specific category id\nhow could I fetch this data? so I mean implement one to many relationships in firebase\nDatabase\n+ categories\n - 1605426969\n - count: 0\n - createdDate: 1605426969\n - id: 1605426969\n - imageUri: "https://placeholder.png"\n - 160542456\n - count: 0\n - createdDate: 1605426969\n - id: 160542456\n - imageUri: "https://placeholder.png"\n \n+ coupons\n - 1605515952\n - category\n - 1605426969\n - count: 0\n - createdDate: 1305426969\n - id: 1605426969\n - imageUri: "https://placeholder.png"\n - code: "L1150" \n - description: "my description"\n - id: 1605515952\n - imageUri: "https://avatar.png"\n -url: "https://www.google.com/"\n - 16055151325\n - category\n - 1605426969\n - count: 0\n - createdDate: 1305426969\n - id: 1605426969\n - imageUri: "https://placeholder.png"\n - code: "L1150" \n - description: "my description"\n - id: 16055151325\n - imageUri: "https://avatar.png"\n - url: "https://www.google.com/"\n\n\nso I tried to fetch it like below but it does not work could you help me.\n\n//...\nconst app = Firebase.initializeApp(firebaseConfig)\nconst categoryRef = app.database().ref().child('categories')\nconst couponRef = app.database().ref().child('coupons')\n\nconst coupons = couponRef.orderByChild('category').equalTo('1605426969');\n\nconsole.log(coupons);" ]
[ "javascript", "firebase", "vue.js", "firebase-realtime-database" ]
[ "SQL Database is locked?", "I'm using sqlite3 and DB browser for SQLite. My code:\n\ndef createuser(user,password,dbname):\n sql_insert = \"INSERT INTO login VALUES \n('{user}','{password}')\".format(user=user, password=password)\n print sql_insert\n conn = sqlite3.connect(dbname)\n c = conn.cursor()\n c.execute(sql_insert)\n # Save (commit) the changes\n conn.commit()\n\n\nHowever I get the error that the database is locked. I don't know what to do as it was working yesterday. When I execute the SQL code in the database browser to display the values in the table 'login', which is where these values go, sometimes the values I enter in this program appear, and sometimes they don't. This is a bit from a longer code that will post below, however the error messages only refers to this function. \n\nimport sqlite3\nDEBUG = True\n# sets up database\n\n\ndef setup():\n conn = sqlite3.connect('Practice.db')\n c = conn.cursor()\n c.execute('''CREATE TABLE login\n (Username text, Password text )''')\n conn.commit()\n\n\n# main function\ndef main(dbname, user, password, hummus):\n conn = sqlite3.connect('Practice.db')\n c = conn.cursor()\n if hummus == \"newuser\":\n print \"Creating user {user}\".format(user=user)\n createuser(user, password, dbname)\n else:\n print \"Not running\"\n pass\n\n\n # Create table\n # c.execute('''CREATE TABLE login\n # (Username text, Password text )''')\n\n # Insert a row of data\n # c.execute(\"INSERT INTO username VALUES \n # ('raw_input()','BUY','RHAT',100,35.14)\")\n\n# creates new user in table 'username'\n\n\n# creates new user in table 'username'\ndef createuser(user,password,dbname):\n sql_insert = \"INSERT INTO login VALUES \n('{user}','{password}')\".format(user=user, password=password)\n print sql_insert\n conn = sqlite3.connect(dbname)\n c = conn.cursor()\n c.execute(sql_insert)\n # Save (commit) the changes\n conn.commit()\n\n # We can also close the connection if we are done with it.\n # Just be sure any changes have been committed or they will be \nlost.\n conn.close()\n\n\nif __name__ == '__main__':\n #setup()\n #exit()\n if DEBUG:\n db = 'Practice.db'\n user = 'tim'\n password = 'massimo'\n pass_check = True\n main(db, user, password, 'newuser')\n\n else:\n db = 'Practice.db'\n user = raw_input('Enter username ')\n password = raw_input('Enter password ')\n pass_check = raw_input('verify password ')\n if not password == pass_check:\n print ('Passwords do not match. ')\n\n main(db, user, password, 'newuser')\n #conn = sqlite3.connect(dbname)\n #conn.commit()\n #elif perform == (\"login\",'Login'):\n\n\n\n\n\n\n\n #main(db, user, password, action)\n\n\nEDIT \n\nBecause I was running from a local host, the issue is that I had the data base open at the same time I was trying to add to it. DB Browser for SQLite blocks this." ]
[ "python", "sql", "sqlite" ]
[ "Binary to Decimal converter works backwards", "I have created a basic program for converting 8-bit binary to decimal, but when I run the program, it works backwards, e.g. if I enter the binary number '00000001' the program will return 128. Here is my code:\n\nbinaryvalue=input(\"Please enter your 8 bit binary number.\")\n\nbinaryvalue=str(binaryvalue)\n\nif len(binaryvalue) <= 8:\n\n print(\"Your number is accurate.\")\n value_index=0\n total=0\n print(\"Your number is valid.\")\n for i in range(len(binaryvalue)):\n total = total + (int(binaryvalue[value_index])) * 1 * (2**(value_index))\n value_index = value_index+1\n print(\"Your decimal number is: \"+str(total))" ]
[ "python", "binary", "decimal", "converter" ]
[ "New Relic/Varnish integration - how to show second instance?", "I have succesfully install the plugins to show Varnish statuses on New Relic, following this guide here:\n\nhttps://github.com/varnish/newrelic_varnish_plugin\n\nThe problem is, when I install it to my second web server (using the same API key), nothing new show up in New Relic but the varnish[default] instance.\n\nDoes anyone know how to setup a second instance in this case?\n\nThanks alot.\n\nHiep." ]
[ "plugins", "varnish", "newrelic" ]
[ "css footer menu display:table and items not balanced", "Hi i am trying to write a footer which should have balanced width items because of their width.\n\nIn my example , if the sentence is long, it s seems that there is a more large padding. \"Blog\" has a little padding, \"First column very long\" has a large one.\n\nThx for the help.\n\n<div class=footer>\n<UL>\n<LI>First column very long</LI>\n<LI>Contact us</LI>\n<LI>Blog</LI>\n<LI>Privacy policy very large title</LI>\n<LI>why?</LI>\n<LI>The last sentence</LI>\n</UL>\n</div>\n\n\n.footer{\nwidth:100%;\n border: 1px solid yellow;\n }\n .footer ul\n{\n list-style-type:none;\ndisplay:table;\nwidth:100%;\nbox-sizing:border-box;\n-moz-box-sizing:border-box;\n-webkit-box-sizing:border-box;\npadding:0;\n}\n\n.footer ul li\n{\n display:table-cell;\ntext-align:center;\nborder:1px solid red;\n}\n\n\nhttps://jsfiddle.net/rtjposu9/" ]
[ "css", "width", "display" ]
[ "How to create a record in ember.js while throwing a required data to it's relationship?", "Please help me. I have a two model which are foo and bar models. I was trying to create a record on /foos endpoint using the POST /foos. However\n the post POST /foos has a requirement of relationships.bar.data.id=1,2,3. Please see my code below for /components/foo-bar.js. My question is how to create a foo record and declaring those ids to it's relationship?\n\n/components/foo-bar.js\n\n foo.setProperties({\n bar: [1213,1231]\n });\n\n\n /models/foo.js\n import DS from 'ember-data';\n\n export default DS.Model.extend({\n bar: DS.belongsTo('bar', { async: true }),\n });\n\n /models/bar.js\n import DS from 'ember-data';\n\n export default DS.Model.extend({\n foos: DS.hasMany('foo', { async: true }),\n });" ]
[ "ember.js", "ember-data", "ember-cli" ]
[ "How do you rename a MongoDB database? (the current status)", "I was readind this questions \"How do you rename a MongoDB database?\" How do you rename a MongoDB database?\n\nDoes anyone know how is the status now. Can we rename the database or still the same problem?" ]
[ "mongodb" ]
[ "How to retrieve data from a SQL Server database in C#?", "I have a database table with 3 columns firstname, Lastname and age. In my C# Windows application I have 3 textboxes called textbox1... I made my connectivity to my SQL Server using this code:\n\nSqlConnection con = new SqlConnection(\"Data Source = .;\n Initial Catalog = domain;\n Integrated Security = True\");\ncon.Open();\nSqlCommand cmd = new SqlCommand(\"Select * from tablename\", con);\n\n\nI'd like to get values from my database; if I give a value in textbox1 it has to match the values in the database and retrieve other details to the corresponding textboxes.\n\nI tried this method but it's not working:\n\ncmd.CommandText = \"select * from tablename where firstname = '\" + textBox1.Text + \"' \";\n\n\nHow can I do it to retrieve all the other values to the textboxes?" ]
[ "c#", "sql", "sql-server" ]
[ "saving a value from another table in a oracle trigger", "I'm writting a trigger and I'm crushing with a wall, 'cause I need to save a value from another table in a variable, and then substract that value to a column of another table, I'm working with a trigger but it doesn't work :(\n\nThis is my code:\n\ncreate or replace trigger tg_update_total_new_product\nafter insert on detalle_comanda \nfor each row\ndeclare\n var_precio numeric;\nbegin\n var_precio := (select precio from producto where id=:new.producto_id);\n update comanda set precuenta=precuenta+var_precio where id=:new.comanda_id;\nEND;\n\n\nThe error code is the next:\n\nTrigger TG_UPDATE_TOTAL_NEW_PRODUCT compiled\n\nLINE/COL ERROR\n--------- -------------------------------------------------------------\n4/20 PLS-00103: Encountered the symbol \"SELECT\" when expecting one of the following: ( - + case mod new not null <an identifier> <a double-quoted delimited-identifier> <a bind variable> continue avg count current exists max min prior sql stddev sum variance execute forall merge time timestamp interval date <a string literal with character set specification> <a number> <a single-quoted SQL string> pipe <an alternatively-quoted string literal with character set specification> <an alternat\n4/73 PLS-00103: Encountered the symbol \")\" when expecting one of the following: . ( * @ % & - + ; / at for mod remainder rem <an exponent (**)> and or group having intersect minus order start union where connect || indicator multiset \n6/4 PLS-00103: Encountered the symbol \"end-of-file\" when expecting one of the following: end not pragma final instantiable persistable order overriding static member constructor map \nErrors: check compiler log\n\n\nThat table is a middle-one, then I have the total of the sale in another table, and I want that, when someone add a product, the total is added... I've been thinking in a function, or a view, but I don't know why this isn't working...\nPlease help!\nThanks!" ]
[ "sql", "database", "oracle", "database-trigger" ]
[ "how to select row using mysql, php and json", "I have a problem getting a format that I need in JSON. \n\nThis is the code I am using:\n\n<?php\n\n$con = mysqli_connect(\"localhost\", \"******\", \"******\");\nif (!$con) {\n die('Could not connect: '.mysqli_error());\n}\nmysqli_select_db(\"highchart\", $con);\n$query = mysqli_query(\"SELECT * FROM trafico\");\n$category = array();\n$category['name'] = 'Time';\n$series1 = array();\n$series1['name'] = 'Tx';\n$series2 = array();\n$series2['name'] = 'Rx';\n\nwhile ($r = mysqli_fetch_array($query)) {\n $category['data'][] = $r['time_1m'];\n $series1['data'][] = $r['Tx'];\n $series2['data'][] = $r['Rx'];\n}\n$result = array();\narray_push($result, $category);\narray_push($result, $series1);\narray_push($result, $series2);\nprint json_encode($result, JSON_NUMERIC_CHECK);\nmysqli_close($con);\n\n?>\n\n\nThis is what I am expecting to get as a result:\n\n[{\n\"name\": \"Time\",\n\"data\": [\"2018-03-28 17:57:01\", \"2018-03-28 17:58:01\", \"2018-03-28 17:59:01\", \"and so on....\"]\n}, {\n\"name\": \"Tx\",\n\"data\": [1025.14, 1056.14, 1035.14, 1042.14, 1038.14, and so on...]\n}, {\n\"name\": \"Rx\",\n\"data\": [52, 54, 51, 49, 46, 48, 53, 56, , and so on...]\n}]\n\n\nbut the result I am getting at the moment is:\n\n[{\"name\":\"Time\"},{\"name\":\"Tx\"},{\"name\":\"Rx\"}]\n\n\nI can't figure out why I'm not getting the result I'm looking for.\nAny help is greatly appreciated." ]
[ "php", "mysql", "json" ]
[ "How to use classes of a maven project (packaging -> maven-plugin) in another maven project (packaging -> jar)", "I have created a maven plugin. I have some classes in the plugin, which I want to make available to the plugin client after execution.\n\nThe problem is that a project of type maven-plugin is also a jar, so I simply can't use maven-jar-plugin and maven-install-plugin to install the jar (having the classes) as a dependency.\n\nAny ideas on how to do this?" ]
[ "maven-2" ]
[ "Cluster Graph Visualization using python", "I am assembling different visualization tools that are available in python language. I found the Treemap. (http://pypi.python.org/pypi/treemap/1.05) \n\nCan you suggest some other tools that are available. I am exploring different ways of visualization of web data." ]
[ "python", "visualization", "data-visualization" ]
[ "How to display an alert box?", "The following code actually submits and with the same i need to display an alert box showing message has been sent.\n\nCode : \n\n<input type=\"button\" class=\"Jdvs_Btn\" onclick=\"send_reply('SEND_REPLY', <? echo $clsSurvey->feedback_id?>);\" value=\"SEND\" style=\"font-weight:bold;width:95px;height:30px;float:left; margin-right:5px;\" />\n\n\nAnd the Javascript\n\nCode:\n\nif(action == \"SEND_REPLY\")\n{\nif( frm.email.value == \"\" )\n{\n alert(\"Please fill your email.\");\n frm.email.focus();\n return false;\n} \nelse if( validateEmailAddress(frm.email.value) == false )\n{\n alert(\"Please fill a valid email.\");\n frm.email.focus();\n return;\n}\nelse if ((tinymce.EditorManager.get('content_to_send').getContent()) == '')\n{\n alert(\"Please enter content to send.\");\n return;\n}\nelse\n{\n frm.form_action.value = action;\n frm.submit(); \n alert('Message Sent Successfully');\n}\n\n\n}\n\nThe code for mailing is:\nThis is where the validation and other are done, i need to display an alert box here\nCode:\n\nfunction sendReply()\n{\n echo $this->feedback_id;\n $this->checkAndUpdateReply($this->feedback_id,$this->content_to_send);\n $Message = nl2br($this->content_to_send);\n $mailMessage = \"\n <html>\n <head>\n <title>constant('_SHORT_PRODUCT_NAME') - Feedback Mail</title>\n </head>\n <body>\";\n $Message = nl2br($this->content_to_send);\n $mailMessage.= $Message.\"\n <table border='0' cellpadding='0' cellspacing='0'width='100%'>\n <tr>\n <td style='$css_class' align='left'><br/>Email: \"._EMAIL_INFO.\"</td>\n </tr>\n <tr>\n <td style='$css_height' align='left'><br /><b>Note</b>:- This is an automatically generated email , Please dont reply back to this mail.</td>\n </tr>\n </table>\n </body>\n </html>\"; \n $mailSubject= constant('_SHORT_PRODUCT_NAME').' - FeedBack Reply';\n $clsEmailTempalte = new clsEmailTemplate($connect, \"\"); \n $clsEmailTempalte->sendMail($mailSubject,$mailMessage,$this->email);\n}" ]
[ "javascript", "php" ]
[ "Is it possible to draw a KineticJS shape directly on canvas context?", "I am writing a small game using the Jaws framework. I would like to use KineticJS to draw some shapes on my canvas context. Is it possible to draw the shapes directly on a context without creating a Stage and a Layer first?\nSomething like\n\nvar circle = new Kinetic.Circle({...params...);\ncircle.draw(myContext);" ]
[ "canvas", "html5-canvas", "kineticjs" ]
[ "SQL query for table update", "I am quite new to SQL. I have one table with three columns.\n\nPerson\n{\n varchar Name,\n varchar Address,\n int Order\n}\n\n\nI am using this table for hibernate mapping. I want to orders to stored in starting from 0. I found NPE issues in my application, for which I found root cause from following thread.\nhttp://www.intertech.com/Blog/hibernate-why-are-there-nulls-in-my-collection/.\n\nRoot cause.\nMy Order column doesn't have sequential values. It has values something like this 0,2,5... for Person let's say for John. I want to update this table such that it will have sequential values for Order column for each Person. Any help, greatly appreciated." ]
[ "sql", "hibernate" ]
[ "Change image resolution but keep physical size", "is there any possibility to change an image's resolution on clientside (using CSS, Javascript, whatever) but keep it's size on the screen?\n\nExample: I want to dispaly a 1920x1080 image with a resolution of 20x10 at a size of 200x100. Just using a img element, set it's source and width/height to 20x10 surely works, but now I'd like to display the scaled image at a size of 200x100.\n\nIs that somehow possible without generating a new image on server-side?" ]
[ "javascript", "html", "css" ]
[ "Remove DIV tag from string with attribute 'width'", "See post:\nhttps://stackoverflow.com/questions/20657177/how-to-remove-div-tag-from-html-editor-contents-in-asp-net#=\n\nThe post I refer to contains an answer to remove all div tags from a string. When a string contains multiple div tags I only want to remove div tags from that string where div attribute 'width' is set to (for example) 100px \n\nHow can I adjust below regex to meet my requirement?\n\nstring divTag = \"div\";\n objNews.Article = Server.HtmlEncode(Regex.Replace(ckedi.Content.Trim().ToString(), \"(</?)\" + divTag + @\"((?:\\s+.*?)?>)\", \"\"));\n\n\nThank you\n\nFrederik" ]
[ "html", "asp.net", "regex" ]
[ "Replace a string in a macro variable?", "I have a macro where I pass in an argument and use that define a new variable based on the name of the input:\n\n#define DO_X(x) char _do_x_var_ ## x; /* other things */\n\n\nThe problem is if I pass in a struct variable, it breaks:\n\nDO_X(some_struct->thing)\n\n\nbecomes:\n\nchar _do_x_var_some_struct->thing; /* other things */\n\n\nEDIT: What I want it to evaluate to is:\n\nchar _do_x_var_some_struct__thing; /* other things */\n\n\n(or any valid variable name containing something similar to the input)\n\nWhat I actually want is for these to work:\n\n#define DO_X(x) for(char _do_x_var_ ## x; /*things*/)\nDO_X(x){\n DO_X(y) {\n /*things*/\n }\n}\n\nDO_X(object->x){\n DO_X(object->y) {\n /*things*/\n }\n}\n\n\nbut for these to fail:\n\n#define DO_X(x) for(char _do_x_var_ ## x; /*things*/)\nDO_X(x){\n DO_X(x) { // <-- multiple definition of _do_x_var_x\n /*things*/\n }\n}\n\nDO_X(object->x){\n DO_X(object->x) { // <-- multiple definition of _do_x_var_object__x (or whatever)\n /*things*/\n }\n}\n\n\nIs there some way to make this work? Maybe replacing -> with __ or something? I've found ways to concatenate, but not replace strings.." ]
[ "c", "macros", "c-preprocessor", "string-concatenation", "stringification" ]
[ "Rails rspec - trying to test if an HTTP delete changes a boolean field from false to true", "I'm new to Ruby on Rails.\n\nI have a Project controller with a method that flags a project in the database to be deleted at a later date. The code is as follows:\n\ndef destroy\n @project.update(:flag_for_deletion => true);\n\n respond_to do |format|\n format.html { redirect_to projects_path,\n :notice => 'Project was successfully destroyed.' }\n end\nend\n\n\nI have a corresponding rspec test:\n\ndescribe \"DELETE destroy\" do\n it \"flags the requested project for deletion\" do\n project = Project.create! valid_attributes\n expect {\n delete :destroy, {:id => project.to_param}, valid_session\n }.to change(project, :flag_for_deletion).from(false).to(true)\n end\nend\n\n\nI receive the following upon running bundle exec rspec:\n\n1) ProjectsController DELETE destroy flags the requested project for deletion\n\nFailure/Error:\n expect {\n delete :destroy, {:id => project.to_param}, valid_session\n }.to change(project, :flag_for_deletion).from(false).to(true)\n\n expected #flag_for_deletion to have changed from false to true, but did not change\n # ./spec/controllers/projects_controller_spec.rb:141:in `block (3 levels) in <top (required)>'\n\n\nThe corresponding ruby/rails generated Project model is:\n\nclass Project < ActiveRecord::Base\n validates :title, :presence => true\n has_many :items, :dependent => :destroy\nend\n\n\nCan anyone provide any insight into what I'm doing wrong?\n\n(Please note, this is my first Stackoverflow question post, so please be patient with any mistakes)\n\nThanks!" ]
[ "ruby-on-rails", "ruby", "rspec" ]
[ "Can an NXT brick really be programmed with Enchanting and adaption of Scratch?", "I want my students to use Enchanting a derivative of Scratch to program Mindstorm NXT robots to drive a pre-programmed course, follow a line and avoid obstacles. (Two state, five state and proportional line following.) Is Enchanting developed enough for middle school students to program these behaviors?" ]
[ "mit-scratch" ]
[ "Vue.js DOM not updating when trying to clear dictionary", "jsfiddle\n\nI have a dictionary that is being rendered by a v-for loop, and I want to set the dictionary to a blank dictionary. I've tried using this.dict = {} and using Vue.delete on all keys, and these update the dictionary in the console but the DOM is not re-rendered. How can I clear this dictionary so that it is re-rendered in the DOM.\n\nhtml\n\n<ol>\n <li v-for=\"item in Object.keys(todos)\">\n <label>{{item}}:{{todos[item]}}</label>\n </li>\n</ol>\n<button v-on:click = \"reset()\">reset</button>\n\n\njs\n\nnew Vue({\n el: \"#app\",\n data: {\n todos: {\"a\" : \"b\"}\n },\n methods: {\n reset: function(){\n this.todos = {};\n console.log(this.todos);\n Vue.delete(todos, \"a\");\n Vue.set(todos, \"a\", \"\");\n }.bind(this)\n }\n})" ]
[ "vue.js" ]
[ "How to improve Hough Circle Transform to detect a circle made up of scattered points", "I have a very basic code that uses the standardized HoughCircles command in openCV to detect a circle. However, my problem is that my data (images) are generated using an algorithm (for the purpose of data simulation) that plots a point in the range of +-15% (randomly in this range) of r (where r is the radius of the circle, that has been randomly generated to be between 5 and 10 (real numbers)) and does so for 360 degrees using the equation of a circle. (Attached a sample image).\nhttp://imgur.com/a/iIZ1N\nNow using the Hough circle command, I was able to detect a circle of approximately the same radius by manually playing around with the parameters (by settings up trackbars, inspired from a github code of the same nature) but I want to automate the process as I have over a 1000 images that I want to do this over and over on. Is there a better way to do that? Or if anyone has any suggestions, I would highly appreciate them as I am a beginner in the field of image processing and have a physics background rather than a CS one.\nA rough sample of my code (without trackbars etc is below):\n\nMat img = imread(\"C:\\\\Users\\\\walee\\\\Documents\\\\MATLAB\\\\plot_2 .jpeg\", 0);\nMat cimg,copy;\ncopy = img;\nmedianBlur(img, img, 5);\nGaussianBlur(img, img, Size(1, 5), 1.1, 0);\n\ncvtColor(img, cimg, COLOR_GRAY2BGR);\nvector<Vec3f> circles;\nHoughCircles(img, circles, HOUGH_GRADIENT,1, 10, 94, 57, 120, 250);\nfor (size_t i = 0; i < circles.size(); i++)\n{\n Vec3i c = circles[i];\n circle(cimg, Point(c[0], c[1]), c[2], Scalar(0, 0, 255), 1, LINE_AA);\n circle(cimg, Point(c[0], c[1]), 2, Scalar(0, 255, 0), 1, LINE_AA);\n}\nimshow(\"detected circles\", cimg);\nwaitKey();\nreturn 0;" ]
[ "opencv", "image-processing", "feature-detection", "hough-transform" ]
[ "cannot read property of undefined when calling method on collection mongodb", "I'm trying to work out the basic infrastructure of a post ajax call to save something in my db, under a collection named 'ranges'.\n\n\nWhen I just run node connection.js I get \n\" Cannot read property 'ranges' of undefined\", did I create that collection wrong? \nIs it necessary to create it before inserting? I read somewhere that MongdoDB should create the collection for you if doesn't exist.\nShould I db.close() my connection function at some point?\nWhen I export the DB, does it automatically export the reference to the collection underneath it? \n\n\nconnection.js\n\nMongoClient = require('mongodb').MongoClient,\nServer = require('mongodb').Server;\nvar url = 'mongodb://localhost:27017/test';\nvar db = MongoClient.connect(url, function (err, db) {\nif (err) {\n console.log('Unable to connect to the mongoDB server. Error:', err);\n} else {\n console.log('Connection established to', url);\n db.createCollection(\"ranges\");\n\n}});\n\ndoSomething = function() {\ndb.ranges.insert ({\"hello\" : \"world\"});\n};\n\nmodule.exports = db;\n\n\napp.js\n\nvar express = require('express');\ncors = require('cors');\nvar app = express();\napp.use('/', express.static('/public'));\napp.use(cors());\nvar db = require('./connection');\n\napp.get('/', function(req, res){\nres.send('Got a GET request');\n });\n\napp.post('/', function(req, res){\nres.send('Got a POST request');\n\n});\n\n\napp.listen(3000,function(){\nconsole.log(\"Server started successfully at Port 3000!\");\n});" ]
[ "mongodb", "export", "database" ]
[ "Rails Devise No Method Error for Registrations for Stripe Checkout", "I'm trying to create a registration form for paying for an event using stripe. But I'm getting an error when I submit the form. \n\nThis is the error I'm getting:\n\nNoMethodError in Users::RegistrationsController#create\nundefined method `to_sym' for nil:NilClass\n\nExtracted source (around line #7):\n\ndef create\n super do |resource|\n if params[:objective]\n resource.objective_id = params[:objective]\n if resource.objective_id == 1 \n\n\nHere's my controller: \n\nclass ApplicationController < ActionController::Base\n# Prevent CSRF attacks by raising an exception.\n# For APIs, you may want to use :null_session instead.\nprotect_from_forgery with: :null_session\n\nbefore_action :configure_permitted_parameters, if: :devise_controller?\n# whitelist the following form fields so that we can process them\nprotected\n def configure_permitted_parameters\n devise_parameter_sanitizer.permit(:sign_up) { |r| r.permit(:stripe_card_token, :password, :password_confirmation, :email, :first_name, :last_name, :company, :street, :city, :state, :zip, :phone, :roadshowcity, :comments) }\n end\nend\n\n\nMy Registrations Controller (where I'm currently getting the error): \n\nclass Users::RegistrationsController < Devise::RegistrationsController\n # Extend default devise gem behavior so that users\n # signing up with the registration form (roadshow)\n # save with a special stripe subscription function.\n # Otherwise Devise signs up user as usual.\n def create\n super do |resource| **<====Error here(NoMethodError undefined method `to_sym' for nilclass)**\n if params[:objective]\n resource.objective_id = params[:objective]\n if resource.objective_id == 1\n resource.save_with_registration\n else\n resource.save\n end \n end\n end\n end\nend \n\n\nMy Model: \n\nclass User < ActiveRecord::Base\n # Include default devise modules. Others available are:\n # :confirmable, :lockable, :timeoutable and :omniauthable\n devise :database_authenticatable, :registerable,\n :recoverable, :rememberable, :trackable, :validatable\n\n belongs_to :regis\n\n attr_accessor :stripe_card_token, :id\n # If user passes validations (email, pass, etc.),\n # Call stripe and tell stripe to set up a subscription\n def save_with_registration\n if valid?\n @product_price = Objective.find(objective_id)\n customer = Stripe::Customer.create(email: email, card: stripe_card_token, description: stripe_card_token.to_s)\n\n charge = Stripe::Charge.create(\n :customer => customer.id,\n :amount => 900,\n :currency => \"usd\",\n :description => \"Registration\"\n )\n self.stripe_customer_token = customer.id\n save! <----- Error here(no method!)\n end\n end\nend" ]
[ "ruby-on-rails", "devise", "stripe-payments" ]
[ "py. 'decimal' mod.: why flags on context rather than numbers", "Here is an example to explain what I'm on about:\n\nc = Decimal(10) / Decimal(3)\nc = Decimal(10) / Decimal(2)\n\n\nIf I do this, then print c, the inexact and rounded flags are raised. Even though the result is accurate. Shouldn't flags therefore be attributes of numbers rather than the context? This problem is especially apparent when I program lengthy calculation using a stack.\n\nTo pose a more meaningful question: How do I properly deal with this?\nIt seems I have to keep track of everything manually. If I clear flags before calculations, I would lose some informations about numbers calculated before. Which may now appear accurate. This is especially annoying when working with numbers like 1.0000000154342. \n\nFor a critical application, it would be really nice to be sure about what is accurate and what isn't. It would also be nice to not have the wrong flags raised, just because it looks bad.\n\nIt still assume there is a good rationale behind this, which I haven't understood. I'd be thankful for an explanation." ]
[ "python", "decimal" ]
[ "Evaluating code blocks in Rebol3", "I'm trying to improve the Sliding Tile Puzzle example by making the starting positions random.\n\nThere's a better way to do this--\"It is considered bad practice to convert values to strings and join them together to pass to do for evaluation.\"--but the approach I took was to try to generate Rebol3 source, and then evaluate it. I have it generating correctly, I think:\n\nrandom/seed now\narr: random collect [ repeat tilenum 9 [ keep tilenum ] ]\nhgroup-data: copy {}\nrepeat pos 9 [\n curtile: (pick arr pos)\n append hgroup-data either curtile = 9\n [ reduce \"x: box tilesize gameback \" ]\n [ rejoin [ { p \"} curtile {\" } ] ]\n if all [(pos // 3) = 0 pos != 9] [ append hgroup-data \" return^/\" ]\n]\nprint hgroup-data\n\n\n...outputs something like:\n\n p \"4\" x: box tilesize gameback p \"5\" return\n p \"3\" p \"7\" p \"1\" return\n p \"2\" p \"8\" p \"6\" \n\n\n...which if I then copy and paste into this part, works correctly:\n\nview/options [\n hgroup [ \nPASTE-HERE\n ]\n] [bg-color: gameback]\n\n\nHowever, if I try to do it dynamically:\n\nview/options [\n hgroup [ \n hgroup-data\n ]\n] [bg-color: gameback]\n\n\n...(also print hgroup-data, do hgroup-data, and load hgroup-data), I get this error:\n\n** GUI ERROR: Cannot parse the GUI dialect at: hgroup-data\n\n\n...(or at: print hgroup-data, etc., depending on which variation I tried.)\n\nIf I try load [ hgroup-data ] I get:\n\n** Script error: extend-face does not allow none! for its face argument\n** Where: either if forever -apply- apply init-layout make-layout actor all foreach do-actor unless -apply- apply all build-face -apply- apply init-layout make-layout actor all foreach do-actor if build-face -apply- apply init-layout make-layout actor all foreach do-actor unless make-face -apply- apply case view do either either either -apply-\n** Near: either all [\n word? act: dial/1\n block? body: get dial...\n\n\nHowever, if I use the syntax hgroup do [ hgroup-data ], the program runs, but there are no buttons: it appears to be somehow over-evaluated, so that the return values of the functions p and box and so on are put straight into the hgroup as code.\n\nSurely I'm missing an easy syntax error here. What is it?" ]
[ "rebol3", "expression-evaluation" ]
[ "Stretch to fill VideoView, aspect ratio of VideoView", "I try to stretch video in aim to fill videoview. The target is to create view that in device look like the first pic (like it look in layout preview). \n\nMost of the answers to this questions refer to this link. \n\nI tried this but I still didn't fill video view. \n\nThis my layout code : \n\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\" \n android:background=\"@drawable/search_gren_screen\">\n\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:orientation=\"horizontal\" >\n\n <Button\n android:id=\"@+id/go_back\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_gravity=\"center\"\n android:layout_weight=\"1\"\n android:onClick=\"onclick\"\n android:text=\"Try again\" />\n\n <Button\n android:id=\"@+id/back_to_pick_song\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_weight=\"1\"\n android:text=\"Select another song\" \n android:onClick=\"onclick\" />\n\n <Button\n android:id=\"@+id/btn_continue\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_gravity=\"center\"\n android:layout_weight=\"1\"\n android:onClick=\"onclick\"\n android:text=\"Amazing, continue!\" />\n </LinearLayout>\n\n <FrameLayout \n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\">\n <VideoView \n android:id=\"@+id/videoView1\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:layout_alignParentBottom=\"true\"\n android:layout_alignParentLeft=\"true\"\n android:layout_alignParentRight=\"true\"\n android:layout_alignParentTop=\"true\"\n android:layout_gravity=\"center\" />\n </FrameLayout>\n</LinearLayout>\n\n\nHere you have a preview of my declared layout: \n\n\n\nHowever, the result on the device is different:" ]
[ "android", "android-videoview", "aspect-ratio" ]
[ "How are these nested vectors connected?", "I've written a piece of code, which creates a vector 'scoreboard' that contains 3 seperate vectors of size 3, all containing the symbol ? at all indices 0-2. When i now execute a 'vector-set!' on the first vector of scoreboard, to change its first element to a 'X, vectors 2 and 3 will change too. How does this occur?\n\n(define scoreboard (make-vector 3 (make-vector 3 '?)))\n(define (display-scoreboard)\n(display (vector-ref scoreboard 0))\n(newline)\n(display (vector-ref scoreboard 1))\n(newline)\n(display (vector-ref scoreboard 2))\n(newline))\n\n(define (X! pos)\n(cond\n((>= 3 pos) (vector-set! (vector-ref scoreboard 0) (- pos 1) 'X))\n))\n\n(display-scoreboard)\n(X! 1)\n(newline)\n(display-scoreboard)\n\n\noutput:\n\n#(? ? ?)\n#(? ? ?)\n#(? ? ?)\n\n#(X ? ?)\n#(X ? ?)\n#(X ? ?)\n\n\nDesired output:\n\n#(? ? ?)\n#(? ? ?)\n#(? ? ?)\n\n#(X ? ?)\n#(? ? ?)\n#(? ? ?)" ]
[ "scheme", "racket", "r5rs" ]
[ "httpmodules - configure to run only once?", "I've created a httpmodule but it seems to be getting called on every request within a page.\n\nCan it configured to run only once or for a certain file type? \n\nAt the minute when a request is made to load an image it runs the module etc..\n\nAny ideas,\n\nThanks," ]
[ "asp.net", "httpmodule" ]
[ "How to update rails page content using AJAX when select changes?", "I have a @course form that belongs_to a lesson, and each lesson has_many gradable_items. The lesson_id is selected via a drop menu. When the user changes the lesson select, the nested inputs representing each gradable_item must be updated. This is doable with a page refresh and passing the lesson_id as url param...so, that that lessons gradable_items exist as nested inputs, where they can then be graded (and saved as graded_items). But, seems AJAX is perfect for this.\n\nThe code below is not working...and I'm wondering what I'm missing.\n\n\ncourse_lesson_id - the select menu where the lesson is chosen\n\"/gradable_items_input?lesson=#{el.val()}\" - the url to the gradable_items_inputs.js.erb template that ajax should inject into the view where the function call was originated.\ngradable_items_container - is where AJAX should inject the code returned from the template\n\n\nThe alert() triggers as expected, and the class is added but not removed...since I never get success.\n\nWhat I am expecting to occur is this:\nThe select menu is changed, this triggers the function. The function grabs the id of the selected item in the lesson_id menu and then goes to the gradable_items_inputs url using the lesson_id as a url param. When this template is accessed it queries the db in the Course controller using the gradable_items_inputs action. This query uses url param for the lesson_id to filter records and populate the gradable_items_inputs.js.erb file. Then, when success...AJAX puts the code from the gradable_items_inputs template inside the div with id #gradable_items_container.\n\nIs my thought process here flawed? I guess the answer must be yes...since it is not working.\n\n jQuery ->\n el = $(\"#course_lesson_id\")\n el.on \"change\", ->\n $.ajax \"/gradable_items_inputs?lesson=#{el.val()}\",\n beforeSend: ->\n $(\"#ajax_tell\").addClass \"is-fetching\"\n\n success: (response) ->\n $(\"#gradable_items_container\").html(response)\n\n complete: (response) ->\n $(\"#ajax_tell\").removeClass \"is-fetching\"\n\n error: ->\n $(\"#{ajax_tell}\").html \"<p>ERROR</p>\"\n\n timeout: 3000\n alert \"test\"\n\n\nThe gradable_items_inputs.js.erb file:\n\n $('#gradable_items_container').html('\n\n<% @gradable_items.each do |gradable_item| %>\n <%= f.simple_fields_for :graded_items do |graded_item| %> \n\n <p>\n <%= gradable_item.name %>\n <%= graded_item.input :gradable_item_id, input_html: { value: gradable_item.id, }, as: :hidden %>\n <%= graded_item.input :grade, collection: gradescales(@course), label: false %>\n </p>\n\n <% end %> \n <% end %>\n\n ');\n\n\ncourses_controller.rb\n\n def gradable_items_inputs\n @lesson = Lesson.find(params[:lesson])\n\n respond_to do |format|\n format.js { }\n end\n end" ]
[ "ruby-on-rails", "ajax", "json", "jquery", "ruby-on-rails-4" ]
[ "jquery simple slideToggle not working as expected", "This is a simple toggle. The weird thing is that, the event happens when I click anywhere.\n\nThis is what my jquery code looks like:\n\n$(document).on('click', $('#create_customer'), function(){\n $('#create_customer_form').slideToggle('slow');\n })\n\n\nHere is a jsfiddle: https://jsfiddle.net/p8q0uw80/" ]
[ "jquery" ]
[ "Algorithm to compute a spanning tree using minimal broadcast messages", "For an assignment, I have to come up with a way to modify this algorithm in such a way that I can remove one of the messages used to reduce message complexity, yet still maintain algorithm correctness. I'm honestly not sure how to do this, since as far as I can tell, every node needs to know which of its neighbors are connected to it in the tree, and which are not.\n\nI should add that this is to be done using a synchronous system\n\nHere's the original algorithm:\n\nInitially parent = null, children = empty, and other = empty\n\nUpon receiving no message:\n if p_i = p_r, and parent = null then\n send M to all neighbors\n parent := p_i\n\nupon receiving M from neighor p_j:\n if parent = null then\n parent := p_j\n send \"parent\" to p_j\n send M to all neighbors except p_j\n else send \"already\" to p_j\n\nupon receiving \"parent\" from neighor p_j:\n add p_j to children\n if children union other contains all neighbors except parent, then terminate\n\nupon receiving \"other\" from neighbor p_j:\n add p_j to other\n if children union other contains all neighbors except parent, then terminate\n\n\nI need to remove the \"already\" message... so my first step was to remove the last block of code and the line \"else send \"already\" to p_j\". But now what? As far as I understand this (and that's not terribly well), I can't just let a processor run forever waiting to hear back from all of its neighbors. I can't terminate it arbitrarily either because the tree may not be done building yet.\n\nAny tip on how I can accomplish this?" ]
[ "algorithm", "computer-science", "distributed-computing" ]
[ "When should I call cmd.Process.Release() explicitly?", "I could not know when the command will return the result, and a default timer is set. Then I have this question.\n\nsigChan := make(os.Signal, 1)\nsignal.Notify(sigChan, SIGCHLD)\ncmd := exec.Command(...)\ncmd.Start()\nselect {\n case <-time.After(1e9):\n // kill the process and release?\n case <-sigChan:\n // the process has been terminated\n}" ]
[ "go" ]
[ "Autohotkey: MsgBox \"Done\" after Run", "I have a python script I want ran on a shortcut key, but I want the Msgbox to tell me it's done once it finishes. How do I do that? \n\nI've tried putting the MsgBox, Done in different places like so\n\nF8::Runwait, C:\\python36\\python.exe \"C:\\Users\\jason\\Google Drive\\pycharm\\test.py\"; \nMsgBox, Done\nF9::Run, C:\\python36\\python.exe \"C:\\Users\\jason\\Google Drive\\pycharm\\test1.py\"; \nMsgBox, Done1\n\n\nDidn't see any examples of this in the Run or MsgBox section of the docs. \n\nWould like a \"Done\" after any hotkeys are executed." ]
[ "autohotkey", "msgbox" ]
[ "UI Elements Missing Text After Segue When Called Asynchronously", "I'm faced with an interesting dilemma today in building my network analysis application for a college class. Calling performSegue from an asynchronous DispatchQueue is making the text of some of the UI in the destination view controller blank. Buttons, labels, etc. All just as though they had their text properties set to empty strings.\n\nI'll explain further.\n\nI've got a custom Swift class, called Globals, which is used to house (obviously) global variables that need to be read and written application-wide.\n\nI've got a UIViewController that acts as a loading screen for my application.\n\nI've got a UIViewController that loads at the completion of that loading screen.\n\nI have a URLSession running in a separate Swift class that gets called by the loading screen view controller. Its purpose is to download a small file of known size and, by measuring the time it took to download it, deliver a speed estimate. Here's that function:\n\nfunc testSpeed() {\n\n Globals.shared.dlStartTime = Date()\n\n if Globals.shared.currentSSID == \"\" {\n Globals.shared.bandwidth = 0\n Globals.shared.DownComplete = true\n } else {\n\n let url = URL(string: \"[EXAMPLE]\")\n let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)\n let task = session.downloadTask(with: url!)\n\n task.resume()\n }\n}\n\npublic func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {\n\n Globals.shared.dlFileSize = (Double(totalBytesExpectedToWrite) * 8) / 1000\n\n let progress = (Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)) * 100.0\n\n Globals.shared.dlprogress = Int(progress)\n}\n\npublic func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {\n\n let elapsed = Double( Date().timeIntervalSince(Globals.shared.dlStartTime))\n Globals.shared.bandwidth = Int(Globals.shared.dlFileSize / elapsed)\n Globals.shared.DownComplete = true\n Globals.shared.dataUse! += (Globals.shared.dlFileSize! / 8000)\n}\n\n\nAs you can see, the URLSession uses the delegates URLSessionDelegate and URLSessionDownloadDelegate to pass the download progress to the loading screen, which lets the user know how things are going.\n\nAs you can also see, there is a global Boolean variable, DownComplete, which lets the rest of the application know when the process is finished.\n\nBack to the loading screen. There's a completion label called progressLabel along with a custom radial progress view called MainProgress. Here's the code:\n\noverride func viewDidAppear(_ animated: Bool) {\n\n [...]\n\n Networking().testSpeed()\n updateProgress()\n}\n\nfunc updateProgress() {\n DispatchQueue.global().async {\n while Globals.shared.DownComplete == false {\n DispatchQueue.main.sync {\n self.progressLabel.text = String(Globals.shared.dlprogress) + \"%\"\n self.MainProgress.animate(fromAngle: self.MainProgress.angle, toAngle: Double(Globals.shared.dlprogress)\n }\n }\n self.performSegue(withIdentifier: \"LoadCompleteSegue\", sender: self)\n }\n}\n\n\nThe idea is to run a while loop which waits until the process is complete before loading the next view controller. \n\nBut to not block the main thread, the while loop has to be run asynchronously.\n\n...But to update the UI correctly, those calls have to be made in a synchronous block.\n\n......But to not skip the process entirely, the performSegue has to be done in the same thread as the while loop. And I think that's what's causing my problem.\n\nI've got a screenshot of the next view controller below, where I've outlined areas where there should be text in red boxes. Because what baffles me is that it doesn't affect all the UI elements, just a few.\n\nScreenshot: Missing Elements\n\nEDIT:\n\nI know the code isn't the cleanest, but this is my \"testgrounds\" Git branch. Bear with me please." ]
[ "ios", "swift", "xcode", "multithreading", "grand-central-dispatch" ]
[ "Trigger AJAX on the Select All Check boxes Primefaces DataTable", "I need to execute a backing bean method when the user selects that checkbox on the top (the one that selects all the check-boxes).\n\nI'm talking about this one:\n\n\n\nAs for the regular check boxes:\n\n\n\nI was able to execute a backing bean method by adding the following tags inside the <p:dataTable><p:dataTable/>:\n\n<p:ajax event=\"rowSelectCheckbox\" listener=\"#{beanJanela.atualizaVariacaoSaldo}\" update=\"variacaoSaldo\" />\n<p:ajax event=\"rowUnselectCheckbox\" listener=\"#{beanJanela.atualizaVariacaoSaldo}\" update=\"variacaoSaldo\" />\n\n\nIt almost seems like it would be a matter of just adding another <p:ajax .. /> with an event like rowSelectAllCheckbox, unfortunately that event does not exist. \n\nSo how would I go about executing #{beanJanela.atualizaVariacaoSaldo} when that first checkbox is selected? Thank you." ]
[ "ajax", "jsf", "primefaces" ]
[ "Is it possible to get two dimensional array in node.js?", "In node.js i am retrieving the values from two collections(momgoDB) and i want to store them into two dimensional array. Is this possible? If yes then how it is please help me.\n\nnode.js\n\nrouter.post('/manage-product', function(req, res){\n vr1 = req.body.code1;\n vr = req.body.code;\n var um = ObjectId(req.body.userId);\n var findProducts = function(db, callback) {\n var cursor =db.collection('proInfo').find({userId:um, purchased:{$ne:vr}, contributed:{$ne:vr1}}).toArray(function(err, docs){\n if(err){\n callback(new Error(\"Some problem\"));\n }else{\n callback(null,docs);\n } \n });\n };\n\n MongoClient.connect(url, function(err, db) {\n assert.equal(null, err);\n findProducts(db, function(err,docs) {\n db.close();\n console.log(docs);\n\n var findPurchaserInfo = function(db, callback) {\n var owner_id = um;\n var cursor =db.collection('purchased').find({ownerId:um.toString().trim()}).toArray(function(err, docs1){\n if(err){\n callback(new Error(\"Some problem\"));\n } else {\n callback(null,docs1);\n } \n });\n }; \n MongoClient.connect(url, function(err, db) {\n assert.equal(null, err);\n findPurchaserInfo (db, function(err,docs1) {\n db.close();\n console.log(docs1);\n });\n }); \n });\n }); \n});\n\n\nFirst collection(proInfo) values are stored in docs and second collection(purchased)values are stored in docs1. Now i want to store them in one array. I think it is two dimensional array. In docs1 i am getting \n[ { _id: 5733006ace25b9682abb7c89,\n quantity: '1',\n store: 'amazon',\n purchasedPerson: 'vinay',\n email: '[email protected]',\n message: 'I purchased this item for you',\n terms: 'yes',\n purchasedItemID: '5732c8e6599bfcc031013925',\n purchasedDate: '2016-05-11T09:50:17.718Z',\n ownerId: '56fe44836ce2226431f5388f' },\n { _id: 5733397f3e102e40365bb5de,\n quantity: '1',\n store: 'amazon',\n purchasedPerson: 'Admin',\n email: '[email protected]',\n message: 'I purchased this item for you',\n terms: 'yes',\n purchasedItemID: '5732c95d599bfcc031013929',\n purchasedDate: '2016-05-11T13:53:45.606Z',\n ownerId: '56fe44836ce2226431f5388f' } ] \n\nand in `docs` i am getting \n\n`[ { _id: 5732c95d599bfcc031013929,\nProduct_Name: 'Home City Gloria Three Seater Sectional Sofa (Brown)',\nBrand: 'Home In The City',\nColor: '',\nImage: 'http://ecx.images-amazon.com/images/I/31zClnoqO0L._SX300_QL70_.jpg',\n\nPrice: '28,279.00',\nRating: '',\nDescription: '',\nCategory: 'Home & Kitchen',\nUrl: 'http://www.amazon.in/Home-City-Gloria-Seater-Sectional/dp/B018QWEL1W/r\nef=lp_5689464031_1_6?s=kitchen&ie=UTF8&qid=1462946106&sr=1-6',\nuserId: 56fe44836ce2226431f5388f,\npurchased: 'yes',\ncontributed: '' },\n{ _id: 5732c8e6599bfcc031013925,\nProduct_Name: 'Symphony Diet 12T 12-Litre Air Cooler (White)',\nBrand: 'Symphony',\nColor: '',\nImage: 'http://ecx.images-amazon.com/images/I/31YqUvEFvLL._SY300_QL70_.jpg',\n\nPrice: '6,100.00',\nRating: '3.5 out of 5 stars',\nDescription: 'Standard Water Storage With Powerful Cooling The Symphony Diet\n12t cooler is a compact air cooler for your home. This device is efficient and\nperfect for day-to-day use. ',\nCategory: 'Home & Kitchen',\nUrl: 'http://www.amazon.in/Symphony-Diet-12-Litre-Cooler-White/dp/B00IYD419Q\n/ref=sr_1_1?s=kitchen&ie=UTF8&qid=1462945947&sr=1-1&keywords=cooler',\nuserId: 56fe44836ce2226431f5388f,\npurchased: 'yes',\ncontributed: '' } ]`\n\n\nnow i want to store them like var resultOfTwo['product']['purchase'] like this." ]
[ "node.js", "mongodb" ]
[ "Text-decoration:none and text-shadow conflict", "Even though text-decoration is none, applying a text-shadow to a link appears to - on hover - show the shadow of an invisible underline (Chrome only, Firefox ok). JSFiddle.\n\nHTML:\n\n<a class=\"bill-area\" href=\"#\" title=\"Watch\">\n <div class=\"watch\"><h2>Watch</h2></div>\n</a>​\n\n\nCSS:\n\na {color:#00C; text-decoration:none}\na:hover {text-decoration:underline}\na:active {color:#F00;}\n.bill-area {width:580px; height:300px;display:inline-block; background:#eee}\n.watch {position:absolute; top:60px; left:200px; display:block;}\n.watch h2 {text-align:center; color:#333; text-shadow:0 0 1px rgba(255, 255, 255, 0.6),0 2px 1px #154C77;}\n.bill-area:hover div h2 {text-decoration:none;}\n\n\nComment out the text-shadow to see the difference." ]
[ "google-chrome", "css", "text-decorations" ]
[ "Use External jars in hadoop with hbase", "How do I access external jars in mapper function while doing mapreduce with hbase in JAVA? I am able to access the objects requiring external jars in the main class but not in the mapper class." ]
[ "java", "hadoop", "mapreduce", "hbase" ]