texts
sequence | tags
sequence |
---|---|
[
"problem with train function neural networks in matlab",
"I have a problem with train function\n\n??? Error using ==> network.train\nTargets are incorrectly sized for network.\nMatrix must have 2 columns.\nError in ==> tfarst1 at 14\n[net,tr]=train(net,min_max,f);\n\n>> whos\nName Size Bytes Class\nFs 1x1 8 double array\nd 22050x1 176400 double array\nf 1x432 3456 double array\nh 1x1 8 double array\nh1 1x1 8 double array\nm 432x12 41472 double array\nmin_max 432x2 6912 double array\nnet 1x1 85013 network object\ns 55512x1 888192 double array (complex)\nGrand total is 92380 elements using 1201469 bytes\n\n\nI only have one output for each row how can I fix it?and this is my code\n\nclear;clc\nFs=11025;\nd=wavread('alhai.wav');\ns=specgram(d,512,Fs,kaiser(500,5),400);\ns=s(:);\nm=melcepst(s,Fs);\nmin_max=minmax(m);\n[h h1] = size(m);\nf=ones(1,h);\nnet=newff(min_max,[5 1],{'tansig','purelin'},'trainlm');\nnet.trainParam.show=500;\nnet.trainParam.goal=1e-5;\nnet.trainParam.epochs=5000;\n[net,tr]=train(net,min_max,f);"
] | [
"matlab",
"neural-network"
] |
[
"How to provide .lib file whose location isn't fixed?",
"Let me elaborate the question.\nI've a solution file, let's call it testapp.sln and I build this solution as follows,\n\ndevenv.exe C:\\fd1\\fd2\\fd3\\fd4\\testapp.sln \\build Debug|Win32\n\nThe thing is because of few modifications in this project, I now need to use some new functions from another .lib file whose name isn't fixed. The name of the folder in which this .lib resides is not constant. It is based on platform, debug/release, x86/x64 etc. \nFor example,\n\n\nWhile compiling for Win7 Debug, location of lib file might be\nc:\\fd1\\_obj_win7_32_debug_uwin\\new.lib\nWhile compiling for Windows 8 x64 Debug, location of lib file might be\nc:\\fd1\\_obj_win8_64_debug_uwin\\new.lib\n\n\nSo how I can provide the location of lib file either in .sln or via command-line?\n\nThanks"
] | [
"c++",
"windows",
"visual-studio"
] |
[
"Iteration through a 3D array using a 2D query window by using Numpy transpose",
"This question is a generalized version of a question which I have asked before:\nReshaping a Numpy Array into lexicographical list of cubes of shape (n, n, n)\nThe question is, given an nd-array of shape (x, y, z) and a query window (p, q), with the restriction that x % p == 0 and y % q == 0, how do I transpose the matrix in such a way that it has shape (p, q, -1) and maintains the ordering proposed in the original question. The idea is that I can quickly take slices of a specific shape instead of having to iterate to the relevant indices.\nIn the original post, this answer was proposed:\nN = 4\na = np.arange(N**3).reshape(N,N,N)\n\nb = a.reshape(2,N//2,2,N//2,N).transpose(1,3,0,2,4).reshape(N//2,N//2,N*4)\n\nwith output:\nprint(b):\n\n[[[ 0 1 2 3 8 9 10 11 32 33 34 35 40 41 42 43]\n [ 4 5 6 7 12 13 14 15 36 37 38 39 44 45 46 47]]\n\n [[16 17 18 19 24 25 26 27 48 49 50 51 56 57 58 59]\n [20 21 22 23 28 29 30 31 52 53 54 55 60 61 62 63]]]\n\n\nThis would correspond to input shape (4, 4, 4), query shape (2, 2) and output shape (2, 2, -1).\nThe accepted answer in the original question is close to what I need, but its output shape is dependent on the shape of the nd-array. That is not the behavior that I am looking for as I'd like to use any query shape (p, q) for any input shape (x, y, z).\nI am not very proficient in using Numpy transpose to implement these kinds of operations (I have tried to use this answer and generalize its myself without success), so it would be greatly appreciated if, when answered, the answer could be supplemented with a bit of an explanation about the approach which the answerer took or point to some resources which could help me out with this!\nHope that makes it clear!"
] | [
"python",
"numpy"
] |
[
"convert .htaccess to web.config on iis",
"please could anyone help me. I have a.htaccess file that worked locally on php application uisng zend frame work. Now my application is hosted on windows with iis6.0. My application doest not load when open it on the browser. i quess there is a way one can convert .htaccess file to web.config file. \nthis is the re-write case-http://localhost/app \n( will be re-written as: http://localhost/app/auth/login). it is a zend frame work application.All i want to do is to convert this .htaccess to web.config \nCan anyone help me? here is my code:\n\nSetEnv APPLICATION_ENV development\n\nRewriteEngine On\nRewriteCond %{REQUEST_FILENAME} -s [OR]\nRewriteCond %{REQUEST_FILENAME} -l [OR]\nRewriteCond %{REQUEST_FILENAME} -d\nRewriteRule ^.*$ - [NC,L]\nRewriteRule ^.*$ index.php [NC,L]"
] | [
"php",
"iis",
".htaccess"
] |
[
"AngularJS input states not working in asp",
"<%@ Page Language=\"C#\" AutoEventWireup=\"true\" CodeBehind=\"Login.aspx.cs\" Inherits=\"Staffing_Tool.Login\" %>\n\n<!DOCTYPE html>\n\n<html>\n<head runat=\"server\">\n <script src=\"scripts/angular.min.js\" type=\"text/javascript\"></script>\n <link href=\"Styles/Login.css\" rel=\"stylesheet\" />\n <title>Login</title>\n</head>\n<body data-ng-app=\"\">\n <form runat=\"server\" name=\"myForm\" novalidate>\n <div class=\"circle logo\">\n <span></span><p>Welcome<br/>to<br/>MCBC Staffing Tool</p>\n </div>\n <div class=\"loginForm\">\n <h4> Login Information</h4>\n <input type=\"text\" class=\"text\" name=\"userName\" placeholder=\"Enter Username\" data-ng-model=\"userName\" required/>\n <span data-ng-show=\"myForm.userName.$touched && myForm.userName.$invalid\">Username is required.</span>\n <input type=\"password\" name=\"password\" class=\"text\" placeholder=\"Enter Password\" data-ng-model=\"password\" required/>\n <span data-ng-show=\"myForm.password.$touched && myForm.password.$invalid\">Password is required.</span>\n <a href=\"#\">Forgot your password?</a>\n <asp:Button ID=\"btnLogin\" runat=\"server\" CssClass=\"btn blue animate\" Text=\"Log in\"></asp:Button>\n </div>\n </form>\n</body>\n</html>\n\n\nI am new to angularJS, and above is a simple login form I have created in asp.\nEverything is working fine but error span for input fields are not working.\n\nFirst I thought, angularJS itself is not working so I added a h1 tag as follows after my userName field to test that:\n\n<h1>{{userName}}</h1>\n\n\nAnd its showing the value typed in the field.\n\nThen I tried following:\n\n<h1>{{myForm.userName.$valid}}</h1>\n\n\nBut it's not showing anything.\n\nThen I tried placing the html part of my code (leaving the first line), in a simple .html file and ran it, and everything worked smoothly.\n\nPlease let me know why its not working in .aspx file."
] | [
"html",
"asp.net",
"angularjs"
] |
[
"Dynamically Delete Elements WIthin an R loop",
"Ok guys, as requested, I will add more info so that you understand why a simple vector operation is not possible. It's not easy to explain in few words but let's see. I have a huge amount of points over a 2D space. \nI divide my space in a grid with a given resolution,say, 100m. The main loop that I am not sure if it's mandatory or not (any alternative is welcomed) is to go through EACH cell/pixel that contains at least 2 points (right now I am using the method quadratcount within the package spatstat). \nInside this loop, thus for each one of this non empty cells, I have to find and keep only a maximum of 10 Male-Female pairs that are within 3 meters from each other. The 3-meter buffer can be done using the \"disc\" function within spatstat. To select points falling inside a buffer you can use the method pnt.in.poly within the SDMTools package. All that because pixels have a maximum capacity that cannot be exceeded. Since in each cell there can be hundreds or thousands of points I am trying to find a smart way to use another loop/similar method to:\n1)go trough each point at a time 2)create a buffer a select points with different sex 3)Save the closest Male-Female (0-1) pair in another dataframe (called new_colonies) 4)Remove those points from the dataframe so that it shrinks and I don't have to consider them anymore 5) as soon as that new dataframe reaches 10 rows stop everything and go to the next cell (thus skipping all remaining points. Here is the code that I developed to be run within each cell (right now it takes too long):\n\nhead(df,20):\n\n X Y Sex ID\n2 583058.2 2882774 1 1\n3 582915.6 2883378 0 2\n4 582592.8 2883297 1 3\n5 582793.0 2883410 1 4\n6 582925.7 2883397 1 5\n7 582934.2 2883277 0 6\n8 582874.7 2883336 0 7\n9 583135.9 2882773 1 8\n10 582955.5 2883306 1 9\n11 583090.2 2883331 0 10\n12 582855.3 2883358 1 11\n13 582908.9 2883035 1 12\n14 582608.8 2883715 0 13\n15 582946.7 2883488 1 14\n16 582749.8 2883062 0 15\n17 582906.4 2883317 0 16\n18 582598.9 2883390 0 17\n19 582890.2 2883413 0 18\n20 582752.8 2883361 0 19\n21 582953.1 2883230 1 20\n\n\nInside each cell I must run something according to what I explained above..\n\nfor(i in 1:dim(df)[1]){\n\nnew_colonies <- data.frame(ID1=0,ID2=0,X=0,Y=0) \n\ndiscbuff <- disc(radius, centre=c(df$X[i], df$Y[i])) \n\n#define the points and polygon\npnts = cbind(df$X[-i],df$Y[-i])\npolypnts = cbind(x = discbuff$bdry[[1]]$x, y = discbuff$bdry[[1]]$y)\nout = pnt.in.poly(pnts,polypnts)\nout$ID <- df$ID[-i]\n\nif (any(out$pip == 1)) {\n\npnt.inBuffID <- out$ID[which(out$pip == 1)] \ncond <- df$Sex[i] != df$Sex[pnt.inBuffID]\n\nif (any(cond)){\n\neucdist <- sqrt((df$X[i] - df$X[pnt.inBuffID][cond])^2 + (df$Y[i] - df$Y[pnt.inBuffID][cond])^2)\n\nIDvect <- pnt.inBuffID[cond]\nnew_colonies_temp <- data.frame(ID1=df$ID[i], ID2=IDvect[which(eucdist==min(eucdist))], \n X=(df$X[i] + df$X[pnt.inBuffID][cond][which(eucdist==min(eucdist))]) / 2, \n Y=(df$Y[i] + df$Y[pnt.inBuffID][cond][which(eucdist==min(eucdist))]) / 2)\n\nnew_colonies <- rbind(new_colonies,new_colonies_temp)\n\nif (dim(new_colonies)[1] == maxdensity) break\n\n}\n}\n}\n\nnew_colonies <- new_colonies[-1,]\n\n\nAny help appreciated!\nThanks\nFrancesco"
] | [
"list",
"r",
"for-loop",
"foreach",
"dataframe"
] |
[
"how to secure an azure web app using a palo alto networks ngf",
"I am trying to secure an azure web app using a palo alto networks ngf. I wanted to place my web app in an App Service Environment but my boss wouldn't allow me to. Is there a way of achieving this without using an ASE?"
] | [
"azure",
"azure-virtual-network"
] |
[
"AVPlayer seekToTime playing from beginning",
"I'm trying to use AVPlayer to play audio from external URL (.mp3 files stored in Amazon S3).\n\nI can make the player play and stop the audio perfectly, but when I try to resume it, it starts every time from the start.\n\nMy code for play / pause and resume are the following\n\nfunc playAudio(index: Int) {\n if(self.currentAudioIndex == index) {\n self.resumePlayback()\n }\n\n self.currentAudioIndex = index;\n let selectedAudio = self.audios[index]\n let url = selectedAudio.url!\n self.playerItem = AVPlayerItem( URL:NSURL( string:url ) )\n self.player = AVPlayer(playerItem:self.playerItem)\n self.player.rate = 1.0;\n self.player.play()\n}\n\nfunc pauseAudio(index: Int) {\n if(self.currentAudioIndex != index) {\n return\n }\n\n self.playerLastTime = self.player.currentTime()\n self.player.pause()\n}\n\nfunc resumePlayback() {\n let timeScale = self.player.currentItem.asset.duration.timescale;\n let seconds = CMTimeGetSeconds(self.playerLastTime!)\n let time = CMTimeMakeWithSeconds(seconds, timeScale)\n self.player.seekToTime(time, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero)\n self.player.play()\n}\n\n\nAny help would be greatly appreciated!"
] | [
"ios",
"iphone",
"avplayer"
] |
[
"Rotate image in RenderScript",
"I need to rotate a image in renderscript and I have the following code:\n\nprivate ScriptC_flip mScript;\nButton flip = (Button)view.findViewById(R.id.flipVertical);\nflip.setOnClickListener(new OnClickListener() {\n @Override\n public void onClick(View v) {\n mScript.set_direction(1);\n flip();\n }\n});\nmBitmapIn = loadBitmap(R.drawable.face2);\n\nin = (ImageView) view.findViewById(R.id.displayin);\nin.setImageBitmap(mBitmapIn);\n\ncreateScript();\n\n\nThe following functions are needed:\n\nprotected void flip() {\n mScript.invoke_filter();\n mOutAllocation.copyTo(mBitmapIn);\n\n mRS.destroy();\n mInAllocation.destroy();\n mOutAllocation.destroy();\n mScript.destroy();\n\n createScript();\n in.invalidate();\n}\n\nprivate void createScript() {\n mRS = RenderScript.create(getActivity());\n\n mInAllocation = Allocation.createFromBitmap(mRS, mBitmapIn,\n Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);\n mOutAllocation = Allocation.createTyped(mRS, mInAllocation.getType());\n\n mScript = new ScriptC_flip(mRS, getResources(), R.raw.flip);\n mScript.set_width(mBitmapIn.getWidth());\n mScript.set_height(mBitmapIn.getHeight());\n mScript.set_gIn(mInAllocation);\n mScript.set_gOut(mOutAllocation);\n mScript.set_gScript(mScript);\n\n}\n\nprivate Bitmap loadBitmap(int resource) {\n final BitmapFactory.Options options = new BitmapFactory.Options();\n options.inPreferredConfig = Bitmap.Config.ARGB_8888;\n return BitmapFactory.decodeResource(getResources(), resource, options);\n}\n\n\nThis is my RenderSCript code:\n\n#pragma version(1)\n#pragma rs java_package_name(com.example.android.rs.hellocompute)\n\nrs_allocation gIn;\nrs_allocation gOut;\nrs_script gScript;\nint width;\nint height;\nint direction = 0; // 0 - flip horizontally, 1 - flip vertically\nfloat rotation;\n\nvoid init(){\n rotation = 0.0f;\n}\n\nvoid root(const uchar4 *v_in, uchar4 *v_out, const void *usrData, uint32_t x, uint32_t y) {\n if(direction == 4){ // rotate right\n const uchar4 *element = rsGetElementAt(gIn, x, y);\n float4 color = rsUnpackColor8888(*element);\n float4 output = {color.r, color.g, color.b};\n *v_out = rsPackColorTo8888(output);\n\n rs_matrix4x4 matrix;\n rsMatrixLoadIdentity(&matrix);\n rsMatrixTranslate(&matrix, 100.0f, 100.0f, 0.0f);\n rsMatrixRotate(&matrix, rotation++, 0.0f, 0.0f, 1.0f);\n // rsgProgramVertexLoadModelMatrix(&matrix);\n }else if(direction == 5){ // rotate right\n const uchar4 *element = rsGetElementAt(gIn, y, height - x);\n float4 color = rsUnpackColor8888(*element);\n float4 output = {color.r, color.g, color.b};\n *v_out = rsPackColorTo8888(output);\n }\n}\n\nvoid filter() {\n rsForEach(gScript, gIn, gOut, 0);\n}\n\n\nIf I try to decomment this line:\n\n// rsgProgramVertexLoadModelMatrix(&matrix);\n\n\nI get an error that this method does not exist. Why is this happening? I used it in other renderscript examples. the only difference is that over there i had an RSSurfaceView, here, i set the result on a image view. Now how can i make it rotate? If i set the \"direction\" to 5, then it rotates right with 90degrees. If i try with \"direction\" = 4, it doesn't do anything. I took this from an example where it would rotate a mesh over and over again"
] | [
"android",
"matrix",
"rotation",
"imageview",
"renderscript"
] |
[
"Can sync grpc tell me how many requests are not handled?",
"In grpc 1.26.0(not necessary), c++ server(necessary).\nI just build a sync grpc server with ResourceQuota'MaxThreads set. If clients requests too frequently, there will be some requests not be executed.\nHow can I get the number and the suspending time of these requests? Or is there some metrics?\nThank you all."
] | [
"c++",
"grpc"
] |
[
"Laravel 4 how to pass URI Parameters to Model function",
"I have this route, want to pass the uri parameters in Laravel:\n\nRoute::group(array('prefix' => 'view/'), function(){\n Route::get('news/listings/{limLow}/{limTop}', function() {\n return Model::Foo($limLow, $limTop);\n });\n});\n\n\nIn my Foo function Foo(param1=null, param2=null){} the variables param1 and 2 are null, as if no variable assigned to the parameters event though an url of something like view/news/listings/1/10 is requested.\n\nMy usual approach is go through a controller first, pass the uri variable in the controller, then go to the model, but I'm trying a direct approach here, is it possible?"
] | [
"php",
"laravel-4"
] |
[
"How can I separate parts of a list in the navbar?",
"Here is my simple sign up page I tried to make. I need help figuring out how to put home, about, help on the left side of the navbar and sign in on the far right side of the bar. I want them on the same navbar but I couldn't find anything on how to separating them or put them on separate sides of the page.\n\nI'm pretty new to html and css so any other tips that can help improve the quality of my first web page would help alright peaces SO peeps.\n\n<html>\n<head>\n <title> Sample Sign up App</title>\n <script></script>\n <!-- Latest compiled and minified CSS -->\n <link rel=\"stylesheet\" href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css\">\n <link rel=\"stylesheet\" href=\"sign up form css.css\">\n</head>\n<body>\n\n<nav class=\"nav navbar-left\">\n <div class=\"nav\">\n <ul class=\"nav nav-pills\">\n <li role=\"presentation\"><a href=\"#\">Home</a></li>\n <li role=\"presentation\"><a href=\"#\">About</a></li>\n <li role=\"presentation\"><a href=\"#\">Help</a></li>\n <li role =\"presentation\"><a href=\"#\">Sign in</a></li>\n </ul>\n </div>\n </nav>\n\n\n\n\n<div class =\"container\">\n<div class = \"jumbotron\">\n<h2 id=\"jumbo-welcome\"> Sign up to Sample App today!</h2>\n<br>\n<form>\n <div class=\"form-group\">\n <label for=\"exampleInputEmail1\">Email address</label>\n <input type=\"email\" class=\"form-control\" id=\"exampleInputEmail1\" placeholder=\"Enter email\">\n </div>\n <div class=\"form-group\">\n <label for=\"exampleInputFile\">Username</label>\n <input type=\"text\" class=\"form-control\" id=\"exampleInputFile\" placeholder=\"Username\">\n </div>\n <div class=\"form-group\">\n <label for=\"exampleInputPassword1\">Password</label>\n <input type=\"password\" class=\"form-control\" id=\"exampleInputPassword1\" placeholder=\"Password\">\n </div>\n <br>\n <button type=\"submit\" class=\"btn btn-default\" id = \"submit-button\">Sign up</button>\n</form>\n</div>\n</div>\n\n</body>\n</html>\n\n\nCSS for the page\n\nnav {\n margin: auto;\n width: 1980px;\n height:45px;\n .border;\n .shadow;\n}\n.nav ul {\n list-style: none;\n background-color: #444;\n text-align: center;\n padding: 0;\n margin: 0;\n}\n.nav li {\n font-family: 'Oswald', sans-serif;\n font-size: 1.2em;\n line-height: 32px;\n height: auto;\n border-bottom: 1px solid #888;\n}\n\n.nav a {\n text-decoration: none;\n color: #fff;\n display: block;\n}\n\n .nav2 li{\nfont-family: 'Oswald', sans-serif;\n font-size: 1.2em;\n line-height: 32px;\n height: auto;\n border-bottom: 1px solid #888;\n }\n\n.jumbotron{\n display:block;\n position:fixed;\n width:40%;\n height:66%;\n top: 20%;\n margin-left:20%;\n margin-right:auto;\n}\n.form-group{\n display:block;\n margin-left: 15%;\n margin-right:15%;\n}\n.jumbotron #submit-button{\n display:block;\n margin-left:40%;\n margin-right:35%;\n}\n#jumbo-welcome{\n text-align:center;\n}\n\nbody {\n line-height: 1;\n background:#F2F2F2;\n background-image: url(\"http://tech-rx.com/wp-content/uploads/2014/05/background.jpg\");\n}"
] | [
"html",
"css",
"twitter-bootstrap",
"navbar"
] |
[
"Cloud Firestore - How to paginate data with RXJS",
"I would like to get data from the Cloud Firestore collection (limited to 10), and then after clicking the "load more" button, I would like to get another piece of collection and concat with the previous result.\nMy code is (base on https://firebase.google.com/docs/firestore/query-data/query-cursors):\nimport { Component, OnDestroy, OnInit } from '@angular/core';\nimport { User } from '../../../shared/models/user';\nimport { UsersService } from '../../../shared/services/users.service';\nimport { Subscription } from 'rxjs';\n\n@Component({\n selector: 'app-users',\n templateUrl: './users.component.html',\n styleUrls: ['./users.component.scss']\n})\nexport class UsersComponent implements OnInit, OnDestroy {\n\n users: User[];\n lastInResponse: any;\n subscription:Subscription;\n\n constructor(private usersService: UsersService) { }\n\n ngOnInit(): void {\n this.subscription = this.usersService.getUsers()\n .subscribe(\n res => {\n this.lastInResponse = res[res.length - 1]; // the last object in response\n this.users = res;\n }\n )\n }\n\n ngOnDestroy() {\n this.subscription.unsubscribe();\n }\n\n loadMore() {\n this.subscription = this.usersService.loadMoreData('users', this.lastInResponse)\n .subscribe(\n res => {\n this.lastInResponse = res[res.length - 1];\n this.users = this.users.concat(res); //concat new values with prevoius\n }\n );\n \n }\n\n}\n\nIt works fine, but I would like to clean my code and subscribe to users collection with a more reactive style, like this:\nimport { Observable } from 'rxjs';\n.\n.\n.\n.\n\nusers$: Observable<User[]>;\n.\n.\n.\n.\n\nngOnInit(): void {\n this.users$ = this.usersService.getUsers();\n}\n\nand then use the "async" pipe in the HTML template.\nMy question is how could I refactor my code? Especially how to extract the last object in response and then pass it to loadMore() method and finally concat another value with previous.\nThank You."
] | [
"angular",
"firebase",
"rxjs"
] |
[
"Best approach in Designing Rainfall_data Table in MYSQL Database",
"I am designing a database that is intended to store daily rainfall data from various stations. i have to store daily records regardless whether it rained or not i.e if there were rains i indicated the millimeters reading from the rain - gauges and if were no rains i just indicate zero.\n\nThe approaches i have in mind is that i have the following fields in my \"rainfall_data\" table:\n\nOption 1 :\n\nid| station | year | month | day1 | day2 | day1 | day3| day4 | day5 ....| day31\n\nOption 2\n\nid| station | year | month | day |\n\nI do have a feeling that Option1 is better since i will have less rows in my \"rainfall_data\" table\n\nLooking for advise. Thanks"
] | [
"mysql"
] |
[
"php cURL how to process all the request on the page",
"when I make a GET request with curl to a remote web server I own in the access log I only see one request (the initial one) if I visit with a real browser I get the initial request plus all the other GET requests like css, images, js etc..\n\nIs there a way for cURL to actually act like a browser and process all the page?\nIsn't it supposed to do this? Otherwise what is the response output, the html code only?"
] | [
"php",
"curl"
] |
[
"How to get action_propability() in stable baselines 3",
"I am just getting started self-studying reinforcement-learning with stable-baselines 3. My long-term goal is to train an agent to play a specific turn-based boardgame. Currently I am quite overwhelmed with new stuff, though.\nI have implemented a gym-environment that I can use to play my game manually or by having it pick random actions.\nCurrently I am stuck with trying to get a model to hand me actions in response to an observation. The action-space of my environment is a DiscreteSpace(256). I create the model with the environment as model = PPO('MlpPolicy', env, verbose=1). When I later call model.predict(observation) I do get back a number that looks like an action. When run repeatedly I get different numbers, which I assume is to be expected on an untrained model.\nUnfortunately in my game most of the actions are illegal in most states and I would like to filter them and pick the best legal one. Or simply dump the output result for all the actions out to get an insight on what's happening.\nIn browsing other peoples code I have seen references to model.action_probability(observation). Unfortunately method is not part of stable baselines 3 as far as I can tell. The guide for migration from stable baselines 2 to v3 only mentions it not being implemented [1].\nCan you give me a hint on how to go on?"
] | [
"python",
"stable-baselines"
] |
[
"Mapping image onto a sphere in Three.js",
"I'm currently using Three.js to try and create something. I've got a sphere, and I'm trying to map the eyeball image here onto it.\n\nThe problem I have is that the result looks like this:-\n\n\n\nHow can I get it to map properly without looking stretched? My code for creating the sphere and mapping the texture is below:-\n\n var geometry = new THREE.SphereGeometry(0.5,100,100);\n var material = new THREE.MeshPhongMaterial( { map: THREE.ImageUtils.loadTexture('eyeballmap.jpg',THREE.SphericalRefractionMapping) } );\n var eyeball = new THREE.Mesh( geometry, material );\n eyeball.overdraw = true;\n eyeball.castShadow = true;\n scene.add( eyeball );\n\n\nHopefully somebody can help?"
] | [
"javascript",
"three.js",
"webgl"
] |
[
"PHP PostgreSQL prepared statement without parameters",
"I was wondering if it's possible to prepare statements using PHP's pgsql library that do not require parameters.\n\nI'm really used to preparing all my SQL statements in the beginning of a program instead of when I need them so my code always looks similar to this\n\n<?php\n\n $pgsqlCon = // code to connect\n\n\n // prepare SQL statements\n\n $sql = \"SELECT * FROM table01 \" .\n \"WHERE t01_idno >= $1\";\n pg_prepare($pgsqlCon, \"table01_cur\", $sql);\n\n $sql = \"SELECT * FROM table02 \" .\n \"WHERE t02_idno = $1\";\n pg_prepare($pgsqlCon, \"table02_sel\", $sql);\n\n\n // start main\n\n $table01 = pg_execute($pgsqlCon, \"table01_cur\", array('1'));\n while ($row = pg_fetch_row($table01)) {\n echo \"<span>found something<br /></span>\";\n }\n\n $table02 = pg_execute($pgsqlCon, \"table02_sel\", array('1'));\n while ($row = pg_fetch_row($table02)) {\n echo \"<span>found something else<br /></span>\";\n }\n\n\n?>\n\n\nSo I would like to prepare statements that don't require parameters in this way as well if that is possible."
] | [
"php",
"postgresql",
"prepared-statement"
] |
[
"On physical back button pressed how to go to device's home screen?",
"From mainactivity of my apps, if I press the device's back button I want the user to be taken to the device's home screen to view icons of all other apps.\nI used the following code but it goes to another activity in myApps.\n\n@Override\npublic void onBackPressed() {\n\n finish();\n System.exit(0);\n}"
] | [
"java",
"android"
] |
[
"Extremely slow SELECT statement with WHERE on a FK field",
"I have this query below, and it's extremely slow. It takes almost 2 minutes for run to return 3,008 records out of a table with 99 million records. The first query where it gets \"Article\" data is super fast, less than 1 second and always returns 1 record. It's the second query that's the problem. I don't really want to JOIN these queries. The first one is so quick, and (in my real query) I'm setting more than just @ArticleID for further use.\n\nThe query execution plan says it has 75% for it on a clustered key lookup on IX_Name, which didn't make sense to me because I'm not even doing anything with name fields here. Furthermore, Id and ArticleID are both indexes on ArticleAuthor, so I'm not sure what I'm doing wrong. I can't do much with IX_Name being the clustered index...my boss created this table and said to do that.\n\nDECLARE @DOI VARCHAR(72) = '10.1140/EPJC/S10052-012-1993-2'\n\nDECLARE @ArticleID VARCHAR(12) \n\nSELECT \n @ArticleID = A.Id\nFROM\n Article A \nLEFT JOIN \n JournalName JN WITH (NOLOCK) ON JN.Id = A.JournalId \nWHERE \n A.DOI = @DOI\n\nPRINT 'GOT ARTICLE DATA ' + format(getdate(), 'yyyy-MM-dd HH:mm:ss.fff')\n\nSELECT \n AA.Id \nFROM \n [ArticleWarehouseTemp]..ArticleAuthor AA WITH (NOLOCK)\nWHERE \n AA.ArticleID = @ArticleID \n\nPRINT 'GOT ARTICLEAUTHOR DATA ' + format(getdate(), 'yyyy-MM-dd HH:mm:ss.fff')\n\n\nPlease help! This is driving me insane. I've attached the table structure and indexes here too.\n\nCREATE TABLE [dbo].[ArticleAuthor]\n(\n[Id] [int] IDENTITY(1,1) NOT NULL,\n[ArticleId] [int] NOT NULL,\n[FullName] [nvarchar](128) NULL,\n[LastName] [nvarchar](64) NULL,\n[FirstName] [nvarchar](64) NULL,\n[FirstInitial] [nvarchar](1) NULL,\n[OrcId] [varchar](36) NULL,\n[IsSequenceFirst] [bit] NULL,\n[SequenceIndex] [smallint] NULL,\n[CreatedDate] [smalldatetime] NULL CONSTRAINT [DF_ArticleAuthor_CreatedDate] DEFAULT (getdate()),\n[UpdatedDate] [smalldatetime] NULL,\n[Affiliations] [varbinary](max) NULL\n) ON [ArticleAuthorFileGroup] TEXTIMAGE_ON [ArticleAuthorFileGroup]\nGO\n\nSET ANSI_PADDING OFF\nGO\n\nALTER TABLE [dbo].[ArticleAuthor] WITH CHECK \n ADD CONSTRAINT [FK_ArticleId] \n FOREIGN KEY([ArticleId]) REFERENCES [dbo].[Article] ([Id])\nGO\n\nALTER TABLE [dbo].[ArticleAuthor] CHECK CONSTRAINT [FK_ArticleId]\nGO\n\nCREATE NONCLUSTERED INDEX [IX_ID] \nON [dbo].[ArticleAuthor] ([Id] ASC)\n\nCREATE NONCLUSTERED INDEX [IX_ArticleID] \nON [dbo].[ArticleAuthor] ([ArticleId] ASC)\n\nCREATE CLUSTERED INDEX [IX_Name] \nON [dbo].[ArticleAuthor] ([LastName] ASC, [FirstName] ASC, [FirstInitial] ASC)"
] | [
"sql",
"sql-server",
"tsql",
"sql-server-2014-express"
] |
[
"Spring MVC form example without JSP",
"Can a Spring MVC form example work without any JSP files? I am working on a project which is using htm templates and i wish to use Spring MVC forms in it. So is it possible to include Spring MVC forms without having JSP files?"
] | [
"java",
"jsp",
"spring-mvc"
] |
[
"How do I get the percentile for a row in a pandas dataframe?",
"Example DataFrame Values - \n\n0 78\n1 38\n2 42\n3 48\n4 31\n5 89\n6 94\n7 102\n8 122\n9 122 \n\nstats.percentileofscore(temp['INCOME'].values, 38, kind='mean')\n15.0\n\nstats.percentileofscore(temp['INCOME'].values, 38, kind='strict')\n10.0\n\nstats.percentileofscore(temp['INCOME'].values, 38, kind='weak')\n20.0\n\nstats.percentileofscore(temp['INCOME'].values, 38, kind='rank')\n20.0\n\ntemp['INCOME'].rank(pct=True)\n1 0.20 (Only showing the 38 value index)\n\ntemp['INCOME'].quantile(0.11)\n37.93\n\ntemp['INCOME'].quantile(0.12)\n38.31999999999999\n\nBased on the results above, you can see none of the methods are consistent\nwith the pd.quantiles() method.\n\n\nI need to get the percentile for one column for each row in a dataframe (255M rows) but can't find any functions/methods that return the 'linear interpolation' method that they use in pd.quantile & np.percentile. \n\nI've tried the following methods/functions - \n\n.rank(pct=True)\n\n\nThis method only returns the values ranked in order, not using the percentile method that I'm looking for. Inconsistent with pd.quantiles \n\nscipy.stats.percentileofscore \n\n\nThis method almost is closer to what I'm looking for but still is not 100% consistent with the 'linear interpolation' method for some reason. Related question to this problem with no real answer\n\nI've looked through every SO answer that is related to this question but none of them use the same interpolation method that I need to use so please do not mark this as a duplicate unless you can verify they're using the same method. \n\nAt this point my last option is to just find the bin cut-offs for all 100 percentiles and apply it that way or calculate the linear interpolation myself but this seems very inefficient and will take forever to apply to 255M records. \n\nAny other suggestions to do this? \n\nThanks!"
] | [
"python",
"pandas",
"numpy",
"scipy",
"percentile"
] |
[
"F# Binding to output while carrying the state",
"I am trying to use a Computation Expression to build a list of actions. I need to bind to a value that gets returned from the getFood action so that I can register a later step to consume it.\ntype Food =\n | Chicken\n | Rice\n\ntype Step =\n | GetFood of Food\n | Eat of Food\n | Sleep of duration:int\n\ntype Plan = Plan of Step list\n\ntype PlanBuilder () =\n\n member this.Bind (plan:Plan, f) =\n f plan\n member this.Yield _ = Plan []\n member this.Run (Plan x) = Plan (List.rev x)\n\n [<CustomOperation("eat")>]\n member this.Eat (Plan p, food) =\n printfn "Eat"\n Plan ((Eat food)::p)\n\n [<CustomOperation("sleep")>]\n member this.Sleep (Plan p, duration) =\n printfn "Sleep"\n Plan ((Sleep duration)::p)\n\nlet plan = PlanBuilder()\n\nlet rng = System.Random(123)\n\n\nlet getFood (Plan p) =\n printfn "GetFood"\n let randomFood = \n if rng.NextDouble() > 0.5 then\n Food.Chicken\n else\n Food.Rice\n (Plan ((GetFood randomFood)::p)), randomFood\n\nlet testPlan =\n plan {\n let! food = getFood // <-- This is what I am trying to get to work\n sleep 10\n eat food\n }\n\nI believe the problem is with the Bind but I can't figure out what it is.\n(*\nExample result\ntestPlan =\n (GetFood Chicken,(\n (Sleep 10,(\n EatFood Chicken\n ))\n ))\n*)"
] | [
"f#",
"monads",
"computation-expression"
] |
[
"Random start place snake",
"I have been looking into this tutorial:\nhttp://blog.new-bamboo.co.uk/2009/12/30/html5-canvas-snake-game\n\nBut I am for some reason not able to figure out how to make the snake start a random place each time..\n\nAny ideas how to do this?"
] | [
"javascript"
] |
[
"QWebSocketServer and connect from Safari",
"i make test echo server in QT ..same as example http://doc.qt.io/qt-5/qtwebsockets-echoserver-example.html\n\nin Chrome, Firefox, Opera connect correct without problems...\n\nonly in Safari when i want connect to server, so no connection is created and trycreated websocket is disconnected..\n\nany help what i doing wrong? Or any setting in safari which i have disabled or???\n\nthanks for any help"
] | [
"javascript",
"qt",
"websocket",
"safari"
] |
[
"Why does my floodfill not fill image completly?",
"I have a feeling this has something to do with the pixel counting, however I cant seem to figure out how to extend the matching to cover the entire shape.\nsee Image example:\nI have added a running example here:\nWorking site\nThis is the flood fill function 1:\n function getPixel(imageData, x, y) {\n if (x < 0 || y < 0 || x >= imageData.width || y >= imageData.height) {\n return [-1, -1, -1, -1];\n } else {\n const offset = (y * imageData.width + x) * 4;\n return imageData.data.slice(offset, offset + 4);\n }\n }\n\nSet pixel color\n function setPixel(imageData, x, y, color) {\n const offset = (y * imageData.width + x) * 4;\n imageData.data[offset + 0] = color[0];\n imageData.data[offset + 1] = color[1];\n imageData.data[offset + 2] = color[2];\n imageData.data[offset + 3] = color[0];\n }\n\nfind color function:\n function colorsMatch(a, b) { \n \n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];\n \n }\n\nPopulate pixel array\n function floodFill(ctx, x, y, fillColor) {\n \n const imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height); \n \n const targetColor = getPixel(imageData, x, y); \n \n if (!colorsMatch(targetColor, fillColor)) {\n \n const pixelsToCheck = [x, y];\n while (pixelsToCheck.length > 0) {\n const y = pixelsToCheck.pop();\n const x = pixelsToCheck.pop();\n\n const currentColor = getPixel(imageData, x, y);\n if (colorsMatch(currentColor, targetColor)) {\n setPixel(imageData, x, y, fillColor); \n pixelsToCheck.push(x + 1, y);\n pixelsToCheck.push(x - 1, y);\n pixelsToCheck.push(x, y + 1);\n pixelsToCheck.push(x, y - 1);\n }\n } \n \n ctx.putImageData(imageData, 0, 0);\n \n }\n }\n\nIt works fine but leaves a few pixels on the side un filled,"
] | [
"jquery",
"image",
"canvas",
"png",
"flood-fill"
] |
[
"How to Add Table Filter with JS?",
"I've been trying to add a search filter to a table using JavaScript, I've downloaded jQuery on my computer as well as for browser but the search filter still won't work. \n\n\r\n\r\nvar $rows = $('#table tr');\r\n$('#search').keyup(function() {\r\n var val = $.trim($(this).val()).replace(/ +/g, '' ).toLowerCase();\r\n\r\n $rows.show().filter(function() {\r\n var text = $(this).text().replace(/\\s+/g, ' ').toLowerCase();\r\n return !~text.indexOf(val);\r\n }).hide();\r\n});\r\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\r\n<header id=\"top\">\r\n <!--id \"top\" for a \"return to top of page\" button-->\r\n <h1>\r\n <!--header-->\r\n CryptoCost<img width=\"25\">\r\n <font size=\"4\"><span class=\"Priceandmarketcap\">Live Cryptocurrency Prices & Market Capitalization</span></font>\r\n <font size=\"2\"><span class=\"SearchCoinsHead\">Search Coins: \r\n <font><input type=\"text\" id=\"search\" class=\"light-table-filter\" placeholder=\"BTC..\"></font></span></font>\r\n </h1>\r\n</header>\r\n<br>\r\n<!--vertical whitespace-->\r\n\r\n<span class=\"indextable\">\r\n <table id=\"table\">\r\n <tr>\r\n <th>#</th> <!--table headers-->\r\n <th>Coins</th>\r\n <th>Price</th>\r\n <th>24H Change</th>\r\n <th>24H Volume</th>\r\n <th>Market Cap</th>\r\n <th>Circulating Coin Supply</th>\r\n </tr>\r\n <tr> <!--start of new row-->\r\n <td>1</td> <!--coin number-->\r\n <td><a href=\"BTCprice.html\"> <img src=\"\" width=\"15\"> BTC </a></td> \r\n <!--icon & ticker-->\r\n <td><big>$7000</big></td> <!--price-->\r\n <td><big>-15%</big></td> <!--24H % Change-->\r\n <td><big>30,284 BTC</big></td> <!--24H Volume-->\r\n <td><big>$117,727,059,656</big></td> <!--Market Cap-->\r\n <td><big>16,946,875 BTC</big></td> <!--Circulating Coin Supply-->\r\n </tr>\r\n <tr>\r\n <td>2</td>\r\n <td><a href=\"ETHprice.html\"> ETH </a></td>\r\n <td><big>$400</big></td>\r\n <td><big>+32%</big></td>\r\n <td><big>98,497,625 ETH</big></td>\r\n <td><big>$37,143,553,062</big></td>\r\n <td><big>98,497,625 ETH</big></td>\r\n </tr>\r\n <tr>\r\n <td>3</td>\r\n <td><a href=\"LTCprice.html\"> <img src=\"\" width=\"15\"> LTC </a></td>\r\n <td><big>$120</big></td>\r\n <td><big>-40%</big></td>\r\n <td><big>55,849,820 LTC</big></td>\r\n <td><big>$6,269,309,798</big></td>\r\n <td><big>55,849,820 LTC</big></td>\r\n </tr>\r\n </table>\r\n </span>"
] | [
"javascript",
"jquery",
"html",
"css",
"html-table"
] |
[
"Refused to set unsafe header \"Origin\" when using xmlHttpRequest of Google Chrome",
"Got this error message:\nRefused to set unsafe header \"Origin\"\n\nUsing this code:\n\n function getResponse() {\n document.getElementById(\"_receivedMsgLabel\").innerHTML += \"getResponse() called.<br/>\";\n if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {\n receiveReq.open(\"GET\", \"http://L45723:1802\", true, \"server\", \"server123\"); //must use L45723:1802 at work.\n receiveReq.onreadystatechange = handleReceiveMessage;\n receiveReq.setRequestHeader(\"Origin\", \"http://localhost/\");\n receiveReq.setRequestHeader(\"Access-Control-Request-Origin\", \"http://localhost\");\n receiveReq.timeout = 0;\n var currentDate = new Date();\n var sendMessage = JSON.stringify({\n SendTimestamp: currentDate,\n Message: \"Message 1\",\n Browser: navigator.appName\n });\n receiveReq.send(sendMessage);\n\n }\n }\n\n\nWhat am I doing wrong? What am I missing in the header to make this CORS request work?\n\nI tried removing the receiveReq.setRequestHeader(\"Origin\", ...) call but then Google Chrome throws an access error on my receiveReq.open() call...\n\nWhy?"
] | [
"ajax",
"xmlhttprequest",
"comet",
"cors"
] |
[
"POST array from multi select missing its closing bracket",
"This is a really strange problem. I've got a form with a couple of fields, of which one of them is a multi select that looks like this:\n\n<select name=\"age_group[]\" multiple=\"multiple\">\n // options\n</select>\n\n\nWhen posting to the server, the key of the multi select in the $_POST array looks like this:\n\nage_group[\n\n\nWhy did the closing bracket got stripped? Also, the field is not saved as an array, but a string for some reason. When console.log() the object I send to the server with jQuery, it all looks okay, and that very field is indeed an array.\n\nPOST header:\n\n\n POST /ajax.php HTTP/1.1\n Host: ds.local\n Connection: keep-alive\n Content-Length: 188\n Accept: application/json, text/javascript, /; q=0.01\n Origin: http://ds.local\n X-Requested-With: XMLHttpRequest\n User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) > Chrome/29.0.1547.66 Safari/537.36\n Content-Type: application/x-www-form-urlencoded; charset=UTF-8\n Referer: http://ds.local/\n Accept-Encoding: gzip,deflate,sdch\n Accept-Language: en-US,en;q=0.8\n Cookie: PHPSESSID=9bniv5i558oslo6ne4ev59hdp6\n\n\nPOST data, human-readable\n\naction: search\nentity: DrugStats\ndata[name]:\ndata[substance]:\ndata[atc_code]:\ndata[year]: n/a\ndata[gender]: n/a\ndata[age_group[]][]: 3\ndata[county]: n/a\n\n\nPOST data, encoded\n\naction=search&entity=DrugStats&data%5Bname%5D=&data%5Bsubstance%5D=&data%5Batc_code%5D=&data%5Byear%5D=n%2Fa&data%5Bgender%5D=n%2Fa&data%5Bage_group%5B%5D%5D%5B%5D=3&data%5Bcounty%5D=n%2Fa\n\n\nProcessing code\n\n$.ajax({\n url: 'ajax.php',\n type: 'post',\n dataType: 'json',\n data: {\n 'action': 'search',\n 'entity': $(entity).data('entity'),\n 'data': data,\n 'page': page\n },\n success: function(data) {\n // code\n },\n complete: function() {\n // code\n }\n });"
] | [
"php",
"jquery",
"html",
"post",
"multi-select"
] |
[
"How to make a route in react native?",
"The routers Is not working, I tryed many forms but not worked, can someone help me?\n\nthe following error is: Device: (487:41) undefined is not an object (evaluating '_this2.props.navigation.navigate')\n\nimport { createDrawerNavigator, createAppContainer } from \"react-navigation\";\nimport Noturno from './containerNoturno.js';\nimport Linhas from './Linhas.js';\nimport LSaida from './LinhasSaida.js';\nimport Main from './containerDiurno.js';\nimport Ajuda from './Ajuda.js';\nimport Sobre from './sobre.js';\nimport Intro from './intro.js';\nimport GalopolisSantaCoronaNoturno from './Noturno/GalopolisSantaCorona.js';\n\nconst AppNavigator = createDrawerNavigator({\nMenu: { screen: Main },\nNoturno: { screen: Noturno },\nLinhas: { screen: Linhas },\nLinhas_Saida: { screen: LSaida },\nAjuda: { screen: Ajuda },\nSobre: { screen: Sobre },\nGalopolis_Noturno: { screen: GalopolisSantaCoronaNoturno },\n});\nexport default createAppContainer(AppNavigator);\n\n\nhere is the other code:\n\n <TouchableOpacity\n onPress={() => this.props.navigation.navigate('Noturno')}\n style={styles.fab}>\n <Image\n source={require('../assets/noite.png')}\n style={{ width: 50, height: 50 }}\n />\n </TouchableOpacity>\n\n\nPlease open the follow link and help me..."
] | [
"react-native",
"react-router",
"url-routing",
"screen"
] |
[
"Tooltip gives wrong values in my heatmap diagram",
"Im trying to create a toolip on my Heatmap Graph.The Heatmap Graph and the Tooltip are working but the Tooltip is giving me the wrong values. The output of the Tooltip always gives me the value:\n\n"The exact value is: undefined"\n\nAlso in the Debug console its giving me a Message:\n\n"rbug/1173575, non-JS module files deprecated."\n\nWhat is wrong here?\n var tooltip = d3.select("#container")\n .append("div")\n .style("position", "absolute")\n .style("visibility", "hidden")\n .style("background", "#ffffff")\n\nsvg.selectAll()\n .data(mapData.data, function(d) {return d.group +':'+ d.variable;})\n .enter()\n .append("rect")\n .attr("x", function(d) { return x(d.variable) })\n .attr("y", function(d) { return y(d.group) })\n .attr("width", x.bandwidth() )\n .attr("height", y.bandwidth() )\n .style("fill", function(d) { return colour(d.value)})\n .on("mouseover", function(d){\n return tooltip.style("visibility", "visible");\n })\n .on("mousemove", function(d){\n tooltip.html("The exact value is: " + d.value)\n return tooltip.style("top", (d3.pointer(this)[1]) + "px").style("left",(d3.pointer(this)[0]+30) + "px");\n })\n .on("mouseleave", function(d){\n return tooltip.style("visibility", "hidden");\n }) \n\n <script src="https://d3js.org/d3.v6.js"></script>\n <div id="container"> </id>"
] | [
"javascript",
"d3.js"
] |
[
"exporting function in dll",
"I have made a dll and exported the functions inside it using \n_declspec(dllexport) at the extreme left of the function definition. \nlike : \n\n_declspec(dllexport) void func1(char*p);\n\n\nIs this correct method to export functions as somewhere?\n\nI have read about _stdcall like:\n\n_declspec(dllexport) void _stdcall func1(char*p);\n\n\nor\n\n_declspec(dllexport) void _cdecl func1(char*p); \n\n\nPlease explain the difference between these three as I am confused ."
] | [
"c",
"dll"
] |
[
"What exactly is HttpResponse.Content.Headers.ContentDisposition?",
"Can I store values like the version number of a file in HttpResponse.Content.Headers.ContentDisposition?\n\nI need to write the version number of a file in the headers or somewhere else because I want to find out if the client has stored the newest version of a certain file on his iOS/Android smart phone.\n\nFor example: Today, the client downloads the very first time a file named MyFile.txt from a server. Tomorrow, the client needs to check if there is a new version of MyFile.txt on the server. If yes, download it. If no, don't download it.\n\nWhere can I store the version number of a text file so that the client can find out if the file on the server is newer than the stored version?\n\nIs it possible to store it in HttpResponse.Content.Headers.ContentDisposition or is it necessary that I always create a new file and file name, for example MyFileVersion1.txt, MyFileVersion2.txt, ...?\n\nThis is how I download a file. I use new ContentDisposition(httpResponse.Content.Headers.ContentDisposition.ToString()).FileName to get the file name.\n\nstring DownloadFile = await DownloadFileAsync(URL);\n\nasync Task<string> DownloadFileAsync(string fileUrl)\n{\nvar _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };\n\ntry\n{\n using (var httpResponse = await _httpClient.GetAsync(fileUrl))\n {\n if (httpResponse.StatusCode == HttpStatusCode.OK)\n {\n string localfilename = new ContentDisposition(httpResponse.Content.Headers.ContentDisposition.ToString()).FileName;\n byte[] byteresponse = await httpResponse.Content.ReadAsByteArrayAsync();\n string documentsPathnew = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);\n string localPathnew = Path.Combine(documentsPathnew, localfilename);\n File.WriteAllBytes(localPathnew, byteresponse);\n return \"Saved file: \" + localfilename;\n }\n else\n {\n return \"Url is invalid\";\n }\n }\n}\ncatch (Exception)\n{\n return \"Exception. Something went wrong.\";\n}\n}"
] | [
"c#"
] |
[
"Entity Framework with table join to another database with Code First",
"I have an EF code first application. I have a column PersonId that I need to join with another database (warehouse) table Persons which contains all the people in our organization.\n\nI have read that one solution is to use a view then make my entity model from the view but this seems quite painful if we have a PersonId column in many tables.\n\nHow best to return back all rows from table A joined with a table B from another database on key column PersonId, really to return PersonDisplayName from table B?\n\nThere has got to be a best practice for this situation?"
] | [
"c#",
"entity-framework",
"entity-framework-6",
"code-first"
] |
[
"converting ObjectId as type:String from mongoexport back to type:ObjectId after ingesting into Mongo Database",
"What has been done:\n\nI have exported a collection from my database using mongoexport as CSV. I found that the _id field is exported as String (ObjectId(5eeb6f8e0795936999a10110)). Note missing "". It should be like this ObjectId("5eeb6f8e0795936999a10110")\nI have done some text processing on the CSV file and made a new collection with exported _id as the new field (display_id).\nI have imported the new collection using mongoimport.\n\nNow the problem is display_id is imported as a String, not as mongo ObjectId. How to convert this String to ObjectId?\nI read this article where we can convert from String to Int but in my case, I think I also have to do some processing on String and then convert to ObjectId."
] | [
"python-3.x",
"mongodb",
"mongodb-query"
] |
[
"Projector remote control - control Flash presentation",
"please can somebody tell me how remote control works? I have to create presentation in Flash platform using ActionScript 3. How to listen keys from remote control to show next slide, prev slide, pause, play etc? Is it like normal keys?\n\nthanks for info"
] | [
"actionscript-3",
"flash",
"controls",
"projector",
"remote-control"
] |
[
"Adding multiple attachments to email sent through Windows command line",
"Is there a way to do this? I can easily add multiple email recipients but haven't been able to specify multiple attachments in any similar way.\n\nThe code format I'm currently using is:\n\n\"[...]\\outlook.exe\" /a \"[...].txt\" /m \"[recipient1]; [recipient2]&subject=[subject]&body=[body]\"\n\nTo add a second attachment, I've tried adding semicolons, commas, removing the quotations and just listing the filepaths, adding the second filepath in quotations, etc., all with no luck. Is it possible at all to do this?"
] | [
"windows",
"email",
"batch-file",
"command-line",
"email-attachments"
] |
[
"Just upgraded to Xcode 6.2 - bundle identifier nearly impossible to enter",
"I just upgraded to Xcode v6.2, and the bundle identifier field is nearly impossible to use. After each character I type, it loses focus. \n\nAm I doing something totally stupid, or is this a bug in Xcode?\n\nUPDATE: This issue also affects the Build and version fields.\n\nAlso, after changing the values in info.plist, it still does not work properly for me on the General tab."
] | [
"ios",
"iphone",
"xcode-6.2"
] |
[
"JQUERY AJAX - function success returns \"UNDEFINED\" with CFC query",
"I have a problem with implementing AJAX in my form for linking drop down lists. I use ColdFusion (CFC file) for retrieving results from a query. The function is working and I retrieve the results in JSON format:\n\n[ { \"ID\" : \"APEX\",\n \"VALUE\" : \"Apex (not defined)\"\n },\n { \"ID\" : \"AVI\",\n \"VALUE\" : \"Plane (not defined)\"\n },\n { \"ID\" : \"TRAIN 1\",\n \"VALUE\" : \"Train 1st class\"\n },\n { \"ID\" : \"VOIT\",\n \"VALUE\" : \"Car\"\n },\n { \"ID\" : \"ZERO\",\n \"VALUE\" : \"Cost 0 (not defined)\"\n }\n]\n\n\nI do not know if this JSON is correct in order to be used in the jquery script.\n\nIn the JQUERY script the success function doesn't retrieve these results and console.log(result) displays \"undefined\". If I try to do console.log(result.length), the error is displayed.\n\nIn Firebug I can see that the query has been done and the response is the JSON below.\n\nMy JQuery script in my CFM file:\n\n$().ready(function() {\n $.ajax({\n type: 'GET',\n url: 'transport.cfc',\n data: {\n method: 'getTransports',\n CITY_TO: 'LUX',\n CITY_FROM: 'UWP'\n },\n dataType: 'json',\n contentType: 'application/json',\n\n success: function(result) {\n var select = $(\"##transp\");\n select.empty();\n select.append(\n new Option('Select transport', '-1')\n );\n console.log(result) // displays \"undifined\"\n\n /* GENERATES BUG\n $.each(result, function(i, item) {\n select.append(\n new Option(item.ID, item.VALUE)\n );\n });*/\n },\n\n error: function(xhr, message) {\n alert('ajax request failed');\n console.log(xhr, message);\n }\n });\n});\n\n\nI am using Jquery version 1.1.2. I tried to use the last version, but the result is the same. I also tried the following solution proposed on a forum: \"replace json by jsonp\". By doing that, the results are displayed in the console, thanks to console.log(result), but the loop each is not ok and the error 'ajax request failed' appears \n\nI do not know how to solve the problem, can anyone help me to solve it?"
] | [
"jquery",
"ajax",
"coldfusion"
] |
[
"How to filter soft deleted items in Spring Data's findAll() method?",
"Recently i learned there is @Where annotation, and i can successfully use it on my @Entity class. Looks like this filter will be applied in to every query.\nAnd i faced the problem when i try to get this soft-deleted entity as element of collection in another @Entity. \n\n\n Unable to find SoftDeletedEntity with id xx (through reference chain ...\n\n\nNow i want to try to use this @Where filter only on SpringData repo's findAll() method. I tried the following, but it did not work.\n\n public interface MyEntity extends JpaRepository<MyEntity, Long> {\n\n @Where(clause = \"is_deleted = 'false'\")\n @Override\n List<MyEntity> findAll();\n}\n\n\nIs it possible at all?"
] | [
"hibernate",
"spring-data",
"spring-data-jpa"
] |
[
"How can I avoid code duplication with many small classes?",
"I have different classes called English, Spanish, French, etc.:\n\nClass English{\n String name = \"English\";\n String alias = \"ENG\";\n}\n\nClass French{\n String name = \"French\";\n String alias = \"Fre\";\n}\n\n\nSimilarly other language classes.\n\nAnd one more class called Language:\n\nClass Language{\n String name = \"\";\n String alias = \"\";\n}\n\n\nDepending upon my requirements I want to cast English/French/Spanish to my Language class.\n\nClass ABC{\n\n main(){\n Language lan = new Language();\n Object obj = getObject(1);\n if(obj instanceof English){\n lan.name = ((English)obj).name;\n lan.aliasName = ((English)obj).aliasName;\n }\n }\n\n}\n\n\nIf I have 10 languages, do I need to write the same code for 10 different languages?\nIn this case, how can I make a single method and pass those arguments as parameters?\nSomething like this:\n\nsetVariablesForLanguage(String className, Object obj)\n\n\nHere i showed only 2 variables but my class will contain more than 100 variables..\nMy actual rewquirment is I want to set the my Language variables From one of those languages.."
] | [
"java",
"oop",
"casting"
] |
[
"Attempt to sort pandas df returns multiindex error",
"Relatively new to python, I'm trying to use pandas sort_values() to sort my df by a specific column. But I'm getting an error about multiindexing, but I don't think I've created a multiindex have I? Here is the data I'm practicing with. I want to see all data organized by \"diggies\" in ascending. \n\n\n \n \n df\n \n \n\n\n letters digits diggies\n0 A 1 7\n1 B 2 3\n2 C 3 20\n\n\n\n \n \n df.sort_values(by=\"diggies\")\n ValueError: Cannot sort by column diggies in a multi-index you need to explicitly provide all the levels\n \n \n\n\nHave I unintentionally created a multiindex? Interestingly, I was able to run sort from another practice data set I imported from a CSV. I though the difference might ahve been the data types, but they are both combinations of either \"objects\" or \"int64\". \n\nAny tips on why I'm getting this error and how to get around it? Thanks\n\n***added info\n\n\n MultiIndex(levels=[['digits', 'letters', 'diggies']],\n labels=[[1, 0, 2]])"
] | [
"python",
"pandas",
"sorting"
] |
[
"Concatenate Embedding layer with Feature vectors in Keras",
"I'm new to Keras and I'm trying to classify text into a Binary category. I'm using the Embedding layer with pre-trained vectors, and I'm trying to concatenate a vector with a set of additional featuers.\nThe input is as follow:\n\nText, Label\n\nembedding Shape: (5000, 60, 300) - 60 is the number of words, 300 the embedding dim.\n\ninput vec features shape: (5000, 15)\n\n\nThe model until now is:\n# Load embeddings and drop them out\nint_sequences_input = keras.Input(shape=(None,), dtype="int64")\nembedding_layer = layers.Embedding(\n vocab_size,\n embedding_dim,\n embeddings_initializer=keras.initializers.Constant(embedding_matrix),\n trainable=False,\n)\nembedded_sequences = embedding_layer(int_sequences_input)\n\ndrop = layers.Dropout(0.45)(embedded_sequences)\n# Convultional nets\nconv1d = layers.Conv1D(256, 2, padding="same", activation="relu", strides=1)(drop)\nconv1d = layers.Conv1D(256, 3, padding="same", activation="relu", strides=1)(conv1d)\npooling = layers.GlobalMaxPooling1D()(conv1d)\n\ninput_feats = keras.Input(shape=xtrain_feats.shape)\nmerged = layers.Concatenate()([pooling, input_feats])\n\ndense1 = layers.Dense(32, activation="relu", kernel_regularizer=regularizers.l2(l2=1e-3))(pooling)\ndrop2 = layers.Dropout(1/6.)(dense1)\n\ndense2 = layers.Dense(1, activation="sigmoid")(drop2)\n\n\nmodel = Model([int_sequences_input, input_feats], dense2)\n# model = Model(int_sequences_input, dense2)\nmodel.compile(optimizer='adam',\n loss='binary_crossentropy',\n metrics=['accuracy'])\n\nThe error I'm getting is on the Shapes on the Concatenate method. But I'm having a hard time figuring out how to correct this.\nHappy to get any help here!"
] | [
"python",
"keras",
"deep-learning",
"nlp"
] |
[
"knapsack variation using recursion in Java",
"I have searched around this site and read through the many knapsack problems but they are all different from mine unfortunately, so I am asking my questions here.\n\nI have a list of weights (in descending order) and a desired capacity. For example, (11,8,7,6,5,3,2,1) and 20 respectively. I need to find and display every combination that reaches the desired capacity (20).\n\nI need to do this using recursion, so the method I'm thinking to do is to simply call the function twice: once having added in the next item, and once having not. However, I could not get this to work and feel now as if I am off track.\n\nAfter some tinkering, I am now almost completed with the assignment. It is due today at 11 pm, so I would very much appreciate a second pair of eyes on my code.\n\nI have the following input for my variables: capacity = 20 and the array called weights has values (20 11 8 7 6 5 3 2 1).\n\nMy DESIRED outputs are: (20, 11 8 1, 11 7 2, 11 6 3, 11 6 2 1, 11 5 3 1, 8 7 5, 8 6 5 1, 8 6 3 2 1, 7 6 5 2).\n\nWhen they are output, each comma will represent a new line. As my code runs through it produces all above solutions EXCEPT 11 6 2 1. I have tried adding print statements among other things but cannot seem to find any reason as to why this one path it being missed. I have attached my new method for it below. The only parts missing is main (which simply makes the array and capacity and sets their values accordingly and calls the function the first time) and sum and display which are detailed below the code. \n\npublic static boolean knapSackProblem(int capacity, int counter, int []knapSack, int[] weights)\n { \n boolean solution = false;\n\n if(counter >= weights.length) // makes sure you don't go out of bounds\n {\n solution = false;\n return solution; // no more items to check\n }\n\n if((weights[counter] == capacity) && (counter < weights.length))\n {\n\n System.out.print(weights[counter] + \"\\n\"); // print the weight that equals the capacity\n counter++; //increase counter to prevent from just displaying the first number\n\n }\n\n if(sum(knapSack) > capacity)\n {\n System.out.print(\" sum too large reached\\n\"); // test statement\n\n solution = false; // number is too big exit\n return solution; // don't call function again\n\n }\n\n if(capacity == (sum(knapSack) + weights[counter]))\n {\n\n knapSack[counter] = weights[counter]; //add the value into the knapSack array\n display(knapSack);\n knapSack[counter] = 0; // removes winning value so it can continue\n //System.out.print(\"Valid answer displayed\\n\");\n\n\n }\n\n\n if(capacity > (sum(knapSack) + weights[counter]))\n { \n knapSack[counter] = weights[counter];//add it in call again\n\n solution = knapSackProblem(capacity, counter + 1, knapSack, weights);\n\n if(!solution)\n {\n knapSack[counter] = 0;\n knapSackProblem(capacity, counter + 1, knapSack, weights);\n }\n\n\n }\n\n else if(capacity < (sum(knapSack) + weights[counter]))\n {\n\n knapSackProblem(capacity, counter +1 , knapSack, weights); \n\n\n }\n return solution;\n\n\n} \n\n\nThe two missing functions are: \n\n\nsum: which simply is a for loop and adds all values in the knapSack array before returning the value.\ndisplay: which goes through and displays all numbers in the array that are not 0 (since 0 will never be provided)\n\n\nThank you so much for your help.\n\nNOTE: I know my current solution is not nearly the most elegant and this current version will get me an A for sure but I would really love to learn ways to improve this code so any tips and or solutions are very appreciated!"
] | [
"java",
"arrays",
"recursion"
] |
[
"Can we set or edit the content of a com.google.android.gms.vision.text.Text.TextBlock?",
"As per Google Documentation of OCR TextBlock it contains these methods.\n\n\ngetBoundingBox()\ngetComponents()\ngetCornerPoints()\ngetLanguage()\ngetValue()\n\n\nIs there any way to setValue() for TextBlock?\n\nThanks in advance."
] | [
"android",
"textblock"
] |
[
"Compiler Warning C4251: Problem exporting a class in a *.dll",
"EDIT: Forgive my noobish-ness, I haven't ever implemented a wrapper .dll before! :S\n\nI've been tinkering a bit with some of the recently released Kinect Sensor hacks (namely OpenKinect and OpenNI) and I'm now trying to wrap the functionality in a *.dll for use in various \"test\" programs that I hope to write.\n\nSo far I've set up a *.dll project and have got a lot of the library functionality in, however I'm getting C4251 compiler warnings all over the place.\n\nIn the project settings I've got the OpenNI.lib file statically linked, so far my library header looks like this:\n\n#ifdef LIBKINECT_EXPORTS\n#define LIBKINECT_API __declspec(dllexport)\n#else\n#define LIBKINECT_API __declspec(dllimport)\n#endif\n\n// This class is exported from the LibKinect.dll\nclass LIBKINECT_API CLibKinect\n{\npublic:\n\n CLibKinect(void);\n ~CLibKinect(void);\n\n bool Init(void);\n\nprotected:\n\nprivate:\n\n xn::Context m_xContext;\n xn::DepthGenerator m_xDepthGen;\n};\n\n\nAnd my stdafx.h file contains:\n\n#pragma once\n\n#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers\n// Windows Header Files:\n#include <windows.h>\n\n#include <XnOpenNI.h>\n#include <XnCodecIDs.h>\n#include <XnCppWrapper.h>\n\n\nNow I've attempted to create a windows console app to test the library and I get lots of error C2653: 'xn' : is not a class or namespace name errors. I was hoping that in the application I would only have to include and link to the wrapper *.dll not all of the OpenNI stuff as well, so as to hide the underlying implementation, is this incorrect?"
] | [
"c++",
"dll",
"dllexport",
"kinect"
] |
[
"Unable to catch Mysql2::Error in Rails",
"Currently testing the following code:\n\ndef db_check\n begin \n schema_call = ActiveRecord::Base.establish_connection(\n :adapter => 'mysql2',\n :host => 'localhost',\n :database => 'dev_db',\n :username => 'dev_user',\n :password => 'dev_pw').connection.execute(\"SELECT * FROM schema_migrations LIMIT 1\")\n\n if schema_call\n render :status => 200, :file => \"public/success.html\"\n else\n render :status => 500, :file => \"public/query_fail.html\"\n end\n rescue Exception => e\n puts \"#{e.class} ;; #{e.message}\"\n logger.debug \"#{e.class}\"\n render :status => 500, :file => \"public/500.html\"\n end\nend\n\n\nThe eventual goal is to have a call to a MySQL server to see if 1) the server is still up and 2) if the database is available. If the connection doesn't work, an Error is thrown, so I put the code in a rescue block. Unfortunately, even when I use rescue Exception, which I understand to be advised against, I still get a Mysql2::Error message in the browser (I also tried rescue Mysql2:Error, which had no effect).\n\nThe duplication of error logging in the rescue is extra attempts to get additional information to work with, but nothing has worked so far. Anyone know how to catch this error?\n\nUPDATE: also, for additional context, testing the code with MySQL not running currently (condition if the DB server is down), get back the following:\n\nMysql2::Error\nCan't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)\n\nwhich makes partial sense, given the server is off, but I still don't understand why it isn't rescuing the error."
] | [
"ruby-on-rails",
"ruby"
] |
[
"How to take %,/ and ^ in KeyCombination in javafx keyevent",
"I have value in combo box that start with <,<=,>,>=,~,/,% and ^ . So what basically i am doing is when user press tab on that combox and inputs any key then generate combobox result based on first letter of keypressed.\nI have successfully managed all digit,letter keys and <,<=,>,>=,~ keys but not able to get %,/ and ^. \n\nBelow is code for getting all above special keystrokes on shift combination\n\nList<String> combination = Arrays.asList(\"<\",\"<=\",\">\",\">=\",\"~\",\"?\");\n for(String keyComb : combination) {\n KeyCharacterCombination keyCombo = new KeyCharacterCombination(keyComb, KeyCombination.SHIFT_DOWN);\n if(keyCombo.match(event)) {\n System.out.println(\"in key combination\");\n String key = keyCombo.getCharacter();\n String pastString = null;\n ComboBox<String> comboBox = (ComboBox<String>) event\n .getSource();\n pastString = comboBox.getValue();\n ObservableList<String> traversalItems = comboBox.getItems();\n comboBox.setValue(getSelectedItem(key, pastString,\n traversalItems));\n }\n }"
] | [
"javafx",
"keycode"
] |
[
"How to run an external application from Qt program?",
"I'm trying to run an external exe from my Qt app. It's an \"autorun application\" and it has three buttons: one is suppose to run an external installer which is an .exe app.\n\nI tried:\n\nsystem(\"Setup.exe\")\n\n\nIt works but it displays terminal when running the installer. I also tried:\n\nQProcess::startDetached(\"Setup.exe\");\n\n\nand also tried:\n\nQProcess *process = new QProcess(this);\nprocess->start(\"Setup.exe\");\n\n\nbut neither works (nothing happens, there are no logs in the console output as well). Can someone point me what I'm doing wrong or suggest a better solution?\n\nThanks."
] | [
"qt",
"qprocess"
] |
[
"Select all input tags where type is not checkbox",
"I need CSS selector that match all input tags where type is not checkbox.\n\nThis match:\n\n<input value=\"Meow!\" />\n\n<input type=\"password\" />\n\n...but this does not:\n\n<input type=\"checkbox\" />\n\nBecause type is checkbox!\n\nThis is what I have at the moment:\n\ninput:not(type=\"checkbox\")\n\nUnfortunately, it does not work!\n\nSo here comes my questions:\n\n\nHow to fix my CSS3 selector?\nIs it possible without CSS3 and JavaScript?\nIs it possible without CSS3, but with use of JavaScript?\n\n\nThanks in any advice!"
] | [
"javascript",
"css",
"input",
"css-selectors"
] |
[
"Drupal 8 \"Display settings\" tab missing from all content types",
"On a certain Drupal 8 site (8.5.6), the \"Display settings\" tab is missing from the bottom vertical tabs of every content type. I must have deleted, disabled, uninstalled, or broken something. Have tried everything I can think of, but nothing helps. I have googled, checked documentation, compared to non-impaired sites, asked coworkers, etc. Many hours spent. Maybe missing something obvious. Suggestions for getting it back will be much appreciated."
] | [
"drupal-8"
] |
[
"Deleted Loopback Model Property Still There",
"I have this object called 'ctx.instance' which has the following properties:\n\nfirstName: 'Ron',\nlastName: 'Santo',\nminor: true,\naccepted: false,\nemailChanged: false,\norganizationId: 000000000000000001000001,\nisDeleted: false,\nuserId: 55e17a46e410f9603cea515b\n\n\nThis object was passed into my function. I need to strip off the 'emailChanged' property before saving it to the database. So I did this:\n\ndelete ctx.instance.emailChanged;\n\n\nThe delete returns 'true' which means the property doesn't exist.\n\nThe following statement after the delete yields false which also means it should be gone:\n\n'emailChanged' in ctx.instance\n\n\nYet, if I do a console.log(ctx.instance), the 'emailChanged' property is still there and it gets saved to the database.\n\nIf I check the property's properties, it says it is configurable. If I do a console.log(ctx.instance.emailChanged) after the delete statement, it says 'undefined'.\n\nWhy is it still there?\n\nI've searched all over the internet, tried tons of different things, and I can't find why this is occurring. This is happening within a Node environment.\n\nUPDATE:\nThe DB is Mongo. I'm using Loopback.js models and framework.\n\nThe data variable is the object submitted to the server from the client via a PUT. The data object was originally JSON but Loopback has made it a JavaScript object.\n\nThe code is within an operation hook so the save to the DB doesn't live within this function.\n\nThe 'delete' statement is the last statement within the function before I pass it back off to the framework.\n\nHere is the minimum code for the hook:\n\n module.exports = function( Member )\n {\n Member.observe( 'before save', upsertMember );\n\n function upsertMember( ctx, next )\n {\n // displays 'true' \n console.log( ctx.instance.hasOwnProperty( 'emailChanged' ) );\n\n // displays 'false'\n console.log( ctx.instance.emailChanged );\n var isDeleted = delete ctx.instance.emailChanged;\n\n // displays 'true'\n console.log( isDeleted );\n\n // displays 'false'\n console.log( 'emailChanged' in ctx.instance );\n\n // displays 'false' \n console.log( ctx.instance.hasOwnProperty( 'emailChanged' ) );\n\n // displays 'undefined'\n console.log( ctx.instance.emailChanged );\n // displays object properties including 'emailChanged'\n console.log( ctx.instance );\n // pass control back to loopback for upsert\n // 'emailChanged' gets into MongoDB record\n next();\n }\n }\n\n\nIf any of you know a JSFiddle type of environment that includes Loopback, I'll throw it in there.\n\nScreenshot of my debugger watch right after the delete statement:"
] | [
"javascript",
"node.js",
"loopbackjs"
] |
[
"Selecting certain columns in VBA after searching",
"I am trying to search for text on a sheet in column c then if found within the same row select column a and copy and paste to sheet two. i have started with this code \n\nSub Test()\nFor Each Cell In Sheets(\"Asset Capture\").Range(\"C35:C3000\")\nIf Cell.Value = \"MONITOR\" Then\nmatchRow = Cell.Row\nRows.Range(matchRow & \":\" & matchRow).Select\nSelection.Copy\nSheets(\"GRN Status Report\").Select\nlastRow = ActiveSheet.UsedRange.Rows.Count\nIf lastRow > 1 Then lastRow = lastRow + 1\nActiveSheet.Range(\"A\" & lastRow).Select\nActiveSheet.Paste\nSheets(\"Asset Capture\").Select\nEnd If\nNext\nEnd Sub\n\n\nbut it is selecting the whole row and i can not figure out how to change the code to select data from just the A column?"
] | [
"vba"
] |
[
"Best suitable JVM implementation for Realtime Applications of Telecom domain",
"Out of many implementations of JVM, which is most suitable for Realtime Applications like applications for Telecom domain?\n\nI am working on an application of Telecom domain, and wanted some advice regarding the choice of JVM.\n\nCurrently using HotSpot but read somewhere regarding JRockit and Azul.\n\nIf some one uses one of these JVMs and has seen some major improvements in performance please share."
] | [
"java",
"jvm"
] |
[
"How can I import all of sklearns regressors",
"I'm doing some predictive modeling and would like to benchmark different kinds of regressors in scikit-learn, just to see what's out there and how they perform on a given prediction task.\n\nI got inspired to do this by this kaggle kernel in which the author essentially manually imports a bunch of classifiers (about 10) and benchmarks them.\n\nI'm having trouble finding a comprehensive list of imports for the regressors in sklearn so I'm trying to automatize the import statements to automatically return me a list of classes that I can use.\n\nI tried to dynamically import the classes:\n\nfrom importlib import import_module\nimport sklearn\n\ndef all_regressors():\n regressors=[]\n for module in sklearn.__all__:\n try:\n regressors.extend([cls for cls in import_module(f'sklearn.{module}').__all__ if 'Regress' in cls ])\n except:\n pass\n regressors.append(sklearn.svm.SVR)\n return regressors\nprint(all_regressors())\n\n\nBut i only get back the names as strings, rather than the classes:\n\n['RandomForestRegressor', 'ExtraTreesRegressor', 'BaggingRegressor',\n'GradientBoostingRegressor', 'AdaBoostRegressor', \n'GaussianProcessRegressor', 'IsotonicRegression', 'ARDRegression', \n'HuberRegressor', 'LinearRegression', 'LogisticRegression', \n'LogisticRegressionCV', 'PassiveAggressiveRegressor', \n'RandomizedLogisticRegression', 'SGDRegressor', 'TheilSenRegressor', \n'RANSACRegressor', 'MultiOutputRegressor', 'KNeighborsRegressor', \n'RadiusNeighborsRegressor', 'MLPRegressor', 'DecisionTreeRegressor', \n'ExtraTreeRegressor', <class 'sklearn.svm.classes.SVR'>]\n\n\nHow can I get the actual classes?"
] | [
"python",
"scikit-learn",
"python-import"
] |
[
"ggplot scatter creating uniform points",
"I am trying to make a scatter plot with ggplot to show time watching TV on x axis and immigrant sentiment on y axis.\nThe code I am using is\nggplot(totalTV, \n aes(x = dfnew.TV.watching..total.time.on.average.weekday, \n y = dfnew.Immigrant.Sentiment)) + \n geom_point()\n\n\nI am getting this output\n\nMy table is so, with first variable being character, and subsequent two being numeric:\n\nAny idea on how to produce a representative scatter of the outcome?\nCheers"
] | [
"r",
"ggplot2"
] |
[
"Git command \"git svn rebase\" not working with XCode 4.3.1",
"I have cloned few SVN Project on my system, I used to do \"git svn rebase\" to sync them up with SVN Repositories. Now after updating XCode to version 4.3.1, this command stopped working. \n\nExecuting \"git svn rebase\" on my mac (v 10.7.3) gives me error \"git: 'svn' is not a git command\". \n\nI suspect, Apple is no longer installing git-svn with new XCode. Do anybody has any idea, how to fix this issue?\n\nThanks."
] | [
"xcode",
"macos",
"git",
"git-svn"
] |
[
"How to restore mysql backup using ActiveRecord",
"I'd like to know if it is possible (and preferable how to do it) to restore a mysql backup into the database. Right now I'm doing like this:\n\ndump_path = \"/tmp/backup.sql\"\nsystem \"mysql db_name < #{dump_path}\"\n\n\nI found out on Stack Overflow a way to do it, but it doesn't seem to work:\n\ndump_path = \"/tmp/backup.sql\"\nActiveRecord::Base.connection.execute IO.read(dump_path)\n\n\nThe error raised is:\n\nActiveRecord::StatementInvalid: Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\n/*!40101 SET @OLD_COL' at line 8\n\n\nI'd like to achieve interoperability between operating systems, and my current solution would only work on Unix-like systems.\n\nThanks."
] | [
"mysql",
"ruby-on-rails",
"activerecord"
] |
[
"How can I execute a __doPostBack function in puppeteer?",
"I am trying to scrape a web page that requires clicking on a page button through a __doPostBack function. I have tried the following code in the chrome console. \n\njavascript:__doPostBack('ctl00$siteContent$widgetLayout$rptWidgets$ctl03$widgetContainer$ctl00$pgrTable$pagingLinksRepeater$ctl02$pageSelector','')\n\n\nThis works and I am able to move to the next page. However I am having some difficulty in passing this command to puppeteer. I have tried the following with no success. \n\nawait page.evaluate(() => { javascript:__doPostBack('ctl00$siteContent$widgetLayout$rptWidgets$ctl03$widgetContainer$ctl00$pgrTable$pagingLinksRepeater$ctl02$pageSelector','');}) \n\n\nI have also tried to modify the aspnet form by resetting the __EVENTTARGET value to \n\n'ctl00$siteContent$widgetLayout$rptWidgets$ctl03$widgetContainer$ctl00$pgrTable$pagingLinksRepeater$ctl02$pageSelector' \n\n\nbut it does not seem to be sufficient. Grateful for any suggestions."
] | [
"javascript",
"node.js",
"web-scraping",
"puppeteer"
] |
[
"ValueError: invalid literal for int() with base 10: 'visits'",
"I'm going through udacity's CS253 and learning about cookies and hashing now. In this I have to get a cookie from the response and check whether it matches the one which is true. This is my code\n\n\nself.response.headers['Content-type'] = 'text/plain'\nvisits = 0\nvisit_cookie_str = self.request.cookies.get('visits')\n if visit_cookie_str:\n cookie_val = check_secure_val(visit_cookie_str)\n if cookie_val:\n visits = int(cookie_val)\n\n\nBut when I run this on the appserver I get the following error:\n\ninvalid literal for int() with base 10: 'visits'\n\n\nI looked up what that error means, I've gone through a lot of questions asked on the same error here but I have yet to understand why my code is showing this error because I have already declared visits as an int.\n\nThese are the functions that create and check the hashes\n\n\n\ndef hash_str(s):\n return hashlib.md5(s).hexdigest()\n\ndef make_secure_val(s):\n return \"%s|%s\" % (s, hash_str(s))\n\ndef check_secure_val(h):\n val = h.split('|')[0]\n if h == make_secure_val(val):\n return val\n\n\nI also checked whether the function check_secure_val is returning an string or not using \n\nprint check_secure_val(\"10|d3d9446802a44259755d38e6d163e820\").isdigit()\n\n\nThanks\n\nEDIT: The code that sets the cookie is \n\nnew_cookie_val = make_secure_val(str(visits))\nself.response.headers.add_header('Set-Cookie', 'visits=%s' % new_cookie_val)\n\n\nThe make_secure_val function returns a string in the form (string, HASH).\n\nAll in all the entire code for the get function is this\n\ndef get(self):\n self.response.headers['Content-type'] = 'text/plain'\n\n visits = 0\n\n visit_cookie_str = self.request.cookies.get('visits')\n if visit_cookie_str:\n cookie_val = check_secure_val(visit_cookie_str)\n if cookie_val:\n visits = int(cookie_val)\n visits += 1\n new_cookie_val = make_secure_val(str(visits))\n self.response.headers.add_header('Set-Cookie', 'visits=%s' % new_cookie_val)\n\n if visits > 100:\n self.write(\"You're the best ever !\")\n else:\n self.write(\"You've been here %s times\" % visits)"
] | [
"python",
"google-app-engine",
"cookies"
] |
[
"How can I make split(/\\t/, $STRING) detect empty values when $STRING ends with \"\\t\\t\"?",
"How can I make split(/\\t/, $STRING) detect empty items when $STRING ends with \"\\t\\t\"?\n\nUsing Perl script, I am trying to split strings based on as a separator between items then count and use these items. But, when the strings end with a combination s, the script doesn't count empty items.\n\nExample:\n\nstring=\"value1\\tvalue2\\t\\t\\t\\t\" (value1, value2 and 4 empty items)\n\nbut it counts 2 items (value1, value2):\n\n$STRING=\"value1\\tvalue2\\t\\t\\t\\t\";\nprint $STRING.\"\\n\";\nmy @F = split(/\\t/, $STRING);\nprint scalar(@F).\"\\n\";\n\n# The number of items must match the number of header name\nif( scalar(@F) == 6 )\n {\n print \"Done \\n\";\n }\n\n\nthe code prints:\n\nvalue1 value2 \n2\n\n\nwhile what is expected is:\n\nvalue1 value2 \n6"
] | [
"string",
"perl",
"whitespace",
"trailing"
] |
[
"QtDataVisualization \"meshing\" Q3Dscatter",
"I would like to be able to mesh a Q3DScatter (having it look like a Q3DSurface), or at least drawing lines between the points. \n\nI have not found anything like this in the docs or in the examples, is there a simple way to do it, or will I have to create my own visualization ?"
] | [
"c++",
"qt",
"qt5",
"data-visualization",
"point-clouds"
] |
[
"REGEX: GETTING VALUE OF href=\"\" EXCEPT FOR PATICULAR STRING",
"Here's my regex code:\n\n\\\\s*(?i)href\\\\s*=\\\\s*(\\\"(([^\\\"]*\\\")|'[^']*'|([^'\\\">\\\\s]+)))\n\n\nActually the real problem is like this. I want to change the value for each href that will match except for these two types <link href=\"foo.css\"> and <link href=\"boo.ico\">. I want to retain the value of these two Strings. \n\nPattern p = Pattern.compile(HTML_A_HREF);\nMatcher m = p.matcher(getLine()); \nsetNewLine(m.replaceAll((String.format(\"%-1s\", sp))+\"href=\\\"javascript:history.go(0)\\\"\" + (String.format(\"%-1s\", sp)))); \n\n\ngetLine() is the html file itself.\n\nString sp = \"\";"
] | [
"java",
"html",
"regex"
] |
[
"How not to display the .class in git",
"I don't want to display .class files when executing git status.\n\nI created a file named .gitignore and entered the .class in the file but nothing happened.\n\nWhat is the best way to prevent the .class file from being displayed when you execute git status command?"
] | [
"git",
"gitignore",
"git-status"
] |
[
"Python:: How to find out the subtuple of a tuple is in the tuple?",
"For instance, a tuple is (1,0,1,1,1,0)\nand subtuple is (1,0)\n\nin increasing order, how to find out this subtuple is in the tuple?\n\nIs it only way to compare one by one by using iteration?\n\nEx.\n(1,0,1,1,1,0) =\n(1,0, *, *, *, *)\nSo subtuple (1,0) is in the tuple!\n\nc.f. I don't need to know (1,0) is in (1,0,1,1,1,0) like this : \n\n(1,0,1,1,1,0) = ( *, *, *, *, 1,0) so (1,0) is in (1,0,1,1,1,0).. => wrong one."
] | [
"python",
"tuples"
] |
[
"FormsIdentity.Ticket.UserData and authentication ticket.UserData staying in sync",
"In my asp.net website. I am putting some data into the UserData portion of the forms authentication ticket. Later I am then able to access this data using\n\n(FormsIdentity)(HttpContext.Current.User.Identity).Ticket.UserData\n\n\nMy question is - as long as the authentication ticket is valid, will this data ALWAYS be available in the FormsIdentity.Ticket.UserData? Or will I eventually need to sync the FormsIdentity.Ticket.UserData and the UserData in the authentication ticket?"
] | [
"c#",
"asp.net",
"forms-authentication"
] |
[
"Permalink post thumbnail PHP inside If/Else statement for WordPress Page template?",
"I'm trying to hyperlink the WordPress blog post thumbnail image to link to its individual blog post (permalink). The text link in the code below does it, but the image part is inside an if/else statement.\n\nCode:\n\n<div class=\"carousel-inner\">\n <?php while( $query->have_posts() ) { $query->the_post(); $post_count++; ?>\n\n <div class=\"item <?php if( $post_count == 1 ) echo 'active'; ?>\">\n\n <?php \n if ( has_post_thumbnail() ) { \n //Permalink needed below\n the_post_thumbnail( 'slider', array( 'class' => 'img-fluid' ) ); \n }\n ?>\n <div class=\"carousel-caption\">\n <h6><a class=\"headline-links\" href=\"<?php echo get_permalink(); ?>\"><?php the_title() ?></a></h6>\n <p><?php echo excerpt( 15 ); ?></p>\n </div>\n </div>\n <?php } //wp_reset_postdata(); ?>\n </div>"
] | [
"php",
"wordpress",
"custom-wordpress-pages"
] |
[
"SELECT NOT IN two foreign keys from other table",
"I am trying to find a SELECT query that returns all of tableA.tba_id that are not exists on tableB (note that are two different foreign keys - tbb_tbAID1 and tbb_tbAID2 between data.\nYou can find DB Model here\n\nWhat I can do so far\nThis only tests one column\n\nSELECT tba_id FROM tableA \nWHERE tba_id NOT IN\n (SELECT tbb_tbAID1 FROM tableB\n WHERE tbb_date > '$date2')\n\n\nI get a MySQL error when trying to test on both foreign keys\n\n\n 1241 - Operand should contain 1 column(s)\n\n\nQuery:\n\nSELECT tba_id FROM tableA \nWHERE tba_id NOT IN\n (SELECT tbb_tbAID1,tbb_tbAID2 FROM tableB\n WHERE tbb_date > '$date2')\n\n\nTry 2:\n\nSELECT tba_id FROM tableA \nWHERE tba_id NOT EXISTS\n (SELECT 1 FROM tableB\n WHERE (tba_id = tbb_tbAID1 OR tba_id = tbb_tbAID2)\n AND tbb_date > '$date2')\n\n\nBut gets more results than the first try (that suggests that it's extremely wrongly done)\n\nTry3:\n\nSELECT tba_id FROM tableA JOIN tableB ON tba_id!=tbb_tbAID1 AND tba_is!=tbb_tbAID2 WHERE tbb_data > '$data'\n\n\nThis results on enormous set of data, far away from first method."
] | [
"mysql",
"database"
] |
[
"customError on web.config-originated Server Error",
"NOTE\n\nI've determined the the problem I'm describing below is specific to an error enountered loading DLL files specified in the web.config file. I would like to present a user-friendly error even in the case of web.config errors.\n\nEND NOTE\n\nWhen my ASP.Net application encounters a server error I would like it to present a custom error message to the user instead of the following default scary message.\n\nServer Error in '/' Application.\n\nRuntime Error\n\nDescription: An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine. \n\nDetails: To enable the details of this specific error message to be viewable on remote machines, please create a <customErrors> tag within a \"web.config\" configuration file located in the root directory of the current web application. This <customErrors> tag should then have its \"mode\" attribute set to \"Off\".\n\n\n<!-- Web.Config Configuration File -->\n\n<configuration>\n <system.web>\n <customErrors mode=\"Off\"/>\n </system.web>\n</configuration>\n\nNotes: The current error page you are seeing can be replaced by a custom error page by modifying the \"defaultRedirect\" attribute of the application's <customErrors> configuration tag to point to a custom error page URL.\n\n\n<!-- Web.Config Configuration File -->\n\n<configuration>\n <system.web>\n <customErrors mode=\"RemoteOnly\" defaultRedirect=\"mycustompage.htm\"/>\n </system.web>\n</configuration>\n\n\nI wrote a very simple HTML page and put it in the root of my application. It is called MaintenancePage.htm.\n\nI've set my web.config file to the following:\n\n<customErrors mode=\"RemoteOnly\" defaultRedirect=\"MaintenancePage.htm\">\n <error statusCode=\"404\" redirect=\"PageNotFound.aspx\" />\n</customErrors>\n\n\nI've also tried ~/MaintenancePage.htm and http://[mysite]/MaintenancePage.htm. None of those options seem to work.\n\nThe way I'm testing this is to rename a DLL my project depends upon and then loading up the site in a web browser. I would expect that since there is an error and a defaultRedirect set there should be no problem showing the error page, however, I'm obviously wrong.\n\nI've search around concerning this problem and it seem that most people are trying to redirect to an aspx page, and are encountering error with doing that. Many even report that they can't get the aspx page to load as a defaultRedirect, but they can get an html page to load.\n\nWhat could I be doing wrong here?\n\nI should note that I'm doing my testing from a different network outside the company firewall, so changing RemoteOnly to On is not the issue per the documentation. In testing changing RemoteOnly to On had no effect, as expected."
] | [
"asp.net",
"web-config"
] |
[
"Meaning of static and final fields of an interface",
"Stimulated by the question Interface vs Abstract Classes and the accepted answer, I would like to have a more detailed and clarified answer. In particular I cannot understand the statement \"a field in an interface is implicitly static and final\". Does it mean that a class A implementing an interface containing method foo() can invoke the method as A.foo()?\n\nWhat concerning final: As long as interfaces contain only methods, given an abstract class A which implements an interface with a method foo() and an ordinary class B which extends the abstract class A, cannot the class B override the foo method? As far as I am concerned, final methods are impossible to be overridden. What is true finally?"
] | [
"java",
"interface",
"static",
"final"
] |
[
"How to prevent from manually changing the date greater than max-date for uib-datepicker",
"I had a datepicker where I had set the max-date to today date..It is working..But the issue is can manually change the date greater than max date in the text field itself...How can we prevent this\n\nfiddle \n\n\nhttps://jsfiddle.net/cpu4euoj/58/\n\nEx:When I click on text field ,the date picker opens and I can select date greater than today..But manually I can change the date greater than today\n\ncan someone help.Thanks."
] | [
"javascript",
"angularjs",
"node.js",
"datepicker"
] |
[
"How to mix styles from different themes in Android?",
"I am new to Android themes, so this is probably a beginners question but I just can't figure it out.\n\n<style name=\"MyAppTheme\" parent=\"android:Theme.Material\">\n <item name=\"android:colorPrimary\">@color/primary</item>\n <item name=\"android:colorPrimaryDark\">@color/primary_dark</item>\n</style>\n\n\nI want to use the new Material theme, so I used Theme.Material with my own colorPrimary and primaryDark colors to get the action bar the way I want it. But for the context menu (the one that opens when you press the 3-dots icon in the top right corner) I want to use the Theme.Material.Light version. So I want the context menu with black text on a white background instead of white text on a gray background.\n\nHow can I do this?"
] | [
"android",
"material-design"
] |
[
"Scoping emmet expansion to round braces in VSCode?",
"I have quick suggestions and emmet enabled for javascript babel files.\nI'd like it so that when a quick suggestion is made e.g. when I type V in the context below for it to select View - not for emmet to expand it into a jsx tag e.g. <View />\n\nimport { View } from 'react-native'\n\n\nI would, however, like emmet to keep doing so for jsx tags that are scoped to a set of round braces e.g.\n\nreturn ( \n View // expands to: <View />\n)\n\n\nYou can currently do this in sublime text by using a package called Scope Selector which exposes meta values like: meta.group.braces.round.js given a selection. I can then use this value as a context for a keybinding.\n\nWhen I inspect the scope in VSCode however, there doesn't seem to be anything specific that I could use in the when clause of emmet's Expand Abbreviation keybinding:\n\n\n\nCan anyone shed some light on how I may go about doing this - if it's possible. Thanks."
] | [
"reactjs",
"react-native",
"visual-studio-code",
"jsx",
"emmet"
] |
[
"Unable to install jaspersoft studio in eclipse",
"while trying to install jasper studio in eclipse from eclipse marketplace, I got an the following error.\nHTTP Server 'Service Unavailable': http://jasperstudio.sourceforge.net/updates/content.xml\nHttpComponents connection error response code 503.\n\nVersion: Neon.3 Release (4.6.3)"
] | [
"jaspersoft-studio"
] |
[
"How to Display MySQL Database with PHP, and AJAX",
"Where is the error, console is spitting back ID is not defined, I want the \"url: id\" to select a button depending on its id to return a result and display it on a div on the index \n\n<script type=\"text/javascript\">\n jQuery(document).ready(function ($) {\n $('button').click(function() {\n $(this).attr(\"id\");\n switch(id) {\n case 1:\n id = 'Reportes/Empresas.php'\n break;\n case 2:\n id = 'Reportes/Departamento.php'\n break;\n case 3:\n id = 'Reportes/Empleados.php'\n break;\n }\n $.ajax({\n type: 'GET',\n url: id,\n data: '',\n datatype: 'html',\n cache: 'false',\n success: function(response) {\n $('div.results').append(response);\n alert('Load was performed.');\n },\n error: function(){\n alert('Nope');\n }\n });\n\n alert('Fail');\n }); // End onclick\n });\n</script>\n\n\nMy coworker says there are three errors, but cant help right now."
] | [
"php",
"jquery",
"mysql",
"ajax",
"html"
] |
[
"Xpath help to Find Unique value",
"I want to find the first tr tag with PONumber: text. I am not able to do that. Any help? I can find it using the //table/tbody/tr/td[contains(text(),'PONumber')] but it gives 2 objects. I want to find the first one only. \n\n<tr> \n<td class=\"clsLabel\" align=\"right\"> PONumber: </td>\n<td class=\"clsInput\"> PN659 </td>\n</tr> \n<tr> \n<td class=\"clsLabel\" align=\"right\"> PreviousPONumber: </td>\n<td class=\"clsInput\"/>\n</tr>"
] | [
"html",
"xpath"
] |
[
"Request/Response paradigm for Websocketsharp library with using Websocket.SendAsync() and OnMessage callback function",
"I am trying to implement request/response paradigm for Websocketsharp library exactly same it works for HttpClient's request/response async behavior. I am trying to achieve it using the async callback as given in below code. I tried to get SendAsync method's OnMessage callback event to wait until the server sends the response. I am able to get the response within the scope of the SendAsync method but as soon as we come out of SendAsync scope it clears out the value of the response. \n\nstring clientResponse = null;\n\n var response = Task.Run(() => objWSClient.SendAsync(stream, Convert.ToInt32(stream.Length), (async (completed) =>\n {\n if (completed)\n {\n clientResponse = await WSMessageSendSuccess(reqObject, callback);\n\n // Websocket response is flushed to the console window, but when it leaves the scope, it doesn't hold the response out of the SendAsync() scope.\n Console.WriteLine(clientResponse);\n }\n else\n {\n WSMessageSendFail(reqObject);\n clientResponse = \"Failure to send Message\";\n }\n })));\n\n\n while (response.Status != TaskStatus.RanToCompletion)\n {\n Task.Delay(10000).Wait();\n }\n response.Wait();\n\n // As soon as we leave scope of WebSocket.SendAsync() method, it clears the client response variable value.\n // variable name : clientResponse;, it also works same with static property/variable.\n return clientResponse;"
] | [
"c#-4.0",
".net-core",
"websocket-sharp"
] |
[
"MVC Editing Entities - Security implications",
"Probably a bit of a newbie question but Im going to ask it anyway.\nIm a webforms developer however I have been given an MVC app to look after and have found what I think may be a security hole, just want to check my thinking is right before I flag this up with my employer.\n\nBasically we have a view for editing an object (Call it a car)\nSo the object contains Make, Model, ManufactureYear, Color, RegistrationNumber\n\nThe view displays all of the above but only allows the Color to be edited.\n\nThe problem is that the other properties are written out to the HTML in hidden fields which are then posted back and used to populate a car object which is pushed through to the database.\n\nI saw this and thought, what happens if I change these hidden fields, and sure enough, I now have a car with a manufacture date 10 years in the future...\n\nThe original dev says that this is the way that MVC works... Im new (litterally have 2 hours MVC experience) so cant contest this at the moment.\n\nAny one have any thoughts? Can anyone advise how this should be done - im also told that my way of doing it (which would be to pull the car from the database and only update the field that the view can actually manipulate) is also wrong...\n\nId appreciate advice!\n\nCheers"
] | [
"asp.net-mvc",
"security"
] |
[
"amazon athena - select from multiples tables without join",
"I have three tables. Each table has common columns with the two other tables, with difference in some attributes. As I am interested in the common attribute, I would like to make one single request to get data from all three tables.\n\nI need to get the items from all three tables by UNION. Is it possible in AWS Athena?\n\nex:\n\ntable1 (att1, att2, att3)\ntable2 (att1, att2, att_3)\ntable3 (att1, att2, att3, att4)\n\n\nGoal: get items from table1, table2, table3 without join in the same request."
] | [
"sql",
"amazon-web-services",
"amazon-athena",
"presto"
] |
[
"Center A form HTML CSS",
"Hello I am having issues centering a form for a login page. I am not to good with CSS and it has been a while since I have played with HTML. What I want to do is, center the input boxes and align the text left on top of the input fields, as well as have an image centered as well, like in the picture. I have tried adding different div id and tags to the form but I can not seem to figure out the css part. I appreciate any help and sorry if the CSS is sloppy.\n\n\n\n\r\n\r\nbody {\r\n background-color:lightgray; \r\n font-family:Verdana, Arial, Helvetica, sans-serif; \r\n}\r\nh1 {\r\n color: black;\r\n}\r\np {\r\n color: black;\r\n}\r\n\r\nhtml {\r\n text-alight: center;\r\n}\r\n\r\n#login {\r\n text-align:center; \r\n}\r\n\r\ninput[type=text], input[type=date], input[type=password] {\r\n width: 30%;\r\n height: 50px;\r\n padding: 12px 20px;\r\n margin: 8px 0;\r\n box-sizing: border-box;\r\n}\r\n\r\ninput[type=submit] {\r\n width: 30%;\r\n height: 50px;\r\n background-color: #4CAF50;\r\n border: none;\r\n color: white;\r\n padding: 16px 32px;\r\n text-decoration: none;\r\n margin: 4px 2px;\r\n cursor: pointer;\r\n}\r\n\r\n#service_type, #series, #speaker, #users {\r\n width: 30%;\r\n height: 50px; \r\n}\r\n\r\n@media only screen and (max-device-width: 1024px){\r\n\r\ninput[type=text], input[type=date], input[type=password] {\r\n width: 100%;\r\n height: 50px;\r\n padding: 12px 20px;\r\n margin: 8px 0;\r\n box-sizing: border-box;\r\n}\r\n\r\ninput[type=submit] {\r\n width: 100%;\r\n height: 50px;\r\n background-color: #4CAF50;\r\n border: none;\r\n color: white;\r\n padding: 16px 32px;\r\n text-decoration: none;\r\n margin: 4px 2px;\r\n cursor: pointer;\r\n}\r\n\r\n#service_type, #series, #speaker, #users{\r\n width: 100%;\r\n height: 50px;\r\n}\r\n\r\n#keypad_users{\r\n width: 345px;\r\n height: 50px;\r\n vertical-align:middle; \r\n text-align:center;\r\n border:1px solid #000000; \r\n font-size:30px; \r\n font-weight:bold;\r\n}\r\n\r\n#keypad {margin:auto; margin-top:10px;}\r\n\r\n#keypad tr td {\r\n vertical-align:middle; \r\n text-align:center; \r\n border:1px solid #000000; \r\n font-size:18px; \r\n font-weight:bold; \r\n width:100px; \r\n height:80px; \r\n cursor:pointer; \r\n background-color:#666666; \r\n color:#CCCCCC;\r\n}\r\n\r\n#keypad tr td:hover {\r\nbackground-color:#999999; \r\ncolor:#FFFF00;\r\n}\r\n\r\n#display {\r\ntext-align:center; \r\n width:345px; \r\n margin:10px auto auto auto; \r\n background-color:#000000; \r\n color:#00FF00; \r\n font-size:48px; \r\n border:1px solid #999999;\r\n}\r\n#message {\r\n text-align:center; \r\n color:#009900; \r\n font-size:18px; \r\n font-weight:bold; \r\n display:none;\r\n}\r\n\r\n}\r\n<div id=\"login\">\r\n<form action = \"login.php\" id=\"login\" method =\"POST\">\r\nUsername <br />\r\n<input type=\"text\" name=\"username\" id=\"username\" required /><br /><br />\r\nPassword <br />\r\n<input type =\"password\" name=\"password\" id=\"password\" required /><br /><br />\r\n\r\n<input type=\"submit\" name=\"submit\" value=\"Log in\">\r\n\r\n</form> \r\n</div>"
] | [
"html",
"css"
] |
[
"How to give the absolute path for html img src?",
"I'm using Struts2 in my application. I have a HTML <img> tag, and for the src, I'm using Struts2 property value. Property's value is an image name (coming from database). I tried with this\n\n<s:iterator value=\"items\" var=\"items\"> \n <img onerror = \"this.style.display='none'\" \n src = 'D:/product_images/<s:property value=\"image\"/>' \n style = \"width: 290px; height: 260px\" \n />\n <s:label label=\"Imge path\" value='D:/product_images/%{image}'/>\n </s:iterator>\n\n\nMy Struts label shows a correct path. But when I declared in src as a property, the image isn't visible. How to give the path correctly to img tag src attribute?\n\nThanks in Advance!"
] | [
"java",
"image",
"jsp",
"dynamic",
"struts2"
] |
[
"Relation between memory paging and CPU cache lines",
"This is my understanding of Paging and CPU Cache lines:\nPaging is memory management scheme by which a computer stores and retrieves data from hard disk.\nPaging is not related to CPU load/store.\nCache line is the size in which data is stored and retrieved between memory and CPU registers.\nCache line is not related to hard disk load/store.\nMy questions are:\n1- Is my understanding mentioned above correct?\n2- When a Page fault occurs, how does the OS know where to look for in hard disk for the data to load? Say I need to load address 0x123 from memory but this address is not paged yet, where is 0x123 data located on disk?"
] | [
"caching",
"memory-management",
"paging"
] |
[
"How to get updated model values in a valueChangeListener method?",
"I am stuck with an issue on valueChangeListener. I am using JSF 1.2 on Weblogic 6.0.\n\nI have a page, where on top of the page there are 2 radio buttons with name as Name1 and Name2. When Name1 is clicked, the Name1 details(there are about 30 fields) is displayed below the radio buttons and when Name2 is clicked, Name2 details is displayed. Now the user can updated the clicked named details. e.g. the user clicks on Name1 and changes the address field and then clicks on Name2 and changes the age of Name2. When the user clicks back Name1, the address should be shown updated with the new value and again when the user clicks on Name2, the age should be updated.\n\nI have used valueChangeListener to tackle it because I need the old and new value of the changed event. The problem is, as the valueChangeListener is invoked at the end of the VALIDATION phase, I am not getting the updated address of the Name1 field in the valueChangeListener method. Can someone help me out to get any workaround ?"
] | [
"jsf",
"valuechangelistener"
] |
[
"Cache relation laravel with orderby",
"I would like to know how can I cache laravel relation with orderby in controller ?\n\nCurrently I have this in my controller :\n\n\n MyController.php\n\n\n$replies = $message->replies()->orderBy('position', 'asc')->get();\n\n\n\n MessageEntity.php\n\n\n/* Message has many Replies */\npublic function replies() {\n return \\Cache::remember('messages_' . $this->id . '_replies', $this->expiration, function () {\n return $this->hasMany('App\\Model\\Entities\\ReplyEntity', 'fk_message_id', 'id')->get();\n });\n}\n\n\nBut I have this error :\n\nBadMethodCallException\nMethod Illuminate\\Database\\Eloquent\\Collection::orderBy does not exist."
] | [
"php",
"laravel",
"eloquent"
] |
[
"Is it safe to use placement new on 'this' pointer",
"Current Implementation\n\nI have a class containing unique_ptr fields which depend on one other:\n\nclass ResourceManager {\n ResourceManager() {}\n\n ResourceManager(A* a_ptr) :\n b_ptr(new B(a)),\n c_ptr(new C(b_ptr.get())) {}\n\n ResourceManager& operator=(ResourceManager&& that) {\n // Call destructor, then construct a new instance on top\n ~ResourceManager();\n ResourceManager* new_this = new(this) ResourceManager();\n\n // Surely this must be the case, right?\n // Is there any reason to prefer using either?\n assert(new_this == this);\n\n new_this->b_ptr = that.b_ptr;\n new_this->c_ptr = that.c_ptr;\n\n return *new_this;\n }\n\n unique_ptr<B> b;\n unique_ptr<C> c;\n};\n\n\nUse case\n\nThe use case here is that I would like to reassign new values to the pointers, whilst keeping the ResourceManager as a stack-allocated variable, or as a non-pointer class member.\n\nWith my current setup I imagine using it something like this:\n\nA a, another_a;\nResourceManager r(&a);\n\n// Use r...\n\n// Destroy old ResourceManager and create the new one in place.\nr = ResourceManager(&another_a);\n\n\nThe reason this is even a problem is due to the fact that B and C are non-assignable (for e.g. file streams)\n\nUgly Alternative\n\nAn alternative uglier (and dangerous) method would be to explicitly reset the unique_ptr fields crucially in reverse order (remember that C depends on B, and hence must be destructed first), effectively mimicking the default destruction behaviour.\n\nResourceManager& operator=(ResourceManager&& that) {\n // Mimic destructor call (reverse-order destruction)\n c_ptr.reset();\n b_ptr.reset();\n\n b_ptr = that.b_ptr;\n c_ptr = that.c_ptr;\n\n return *this; \n}\n\n\nNote that a wrong implementation would be to simply use the default assignment operator for ResourceManager. This will assign the field in-order which implies in-order destruction of the unique_ptrs, whereas we require reverse-order destruction.\n\nQuestions\n\nIs this usage of this pointer with placement new and the explicit destructor call safe?\n\nMust I use the returned new_this pointer as opposed to the original this pointer (for example, if the this pointer technically becomes invalidated after calling the destructor)?\n\nAre there any better suggested ways to achieve this? If add more such unique_ptr fields to the class, I would have to make sure that I add a copy to the assignment operator. For instance, is it possible to call the move constructor instead, like so:\n\nResourceManager& operator=(ResourceManager&& that) {\n // Call destructor\n ~ResourceManager();\n\n // Move-construct a new instance on top\n ResourceManager* new_this = new(this) ResourceManager(that);\n return *new_this;\n}"
] | [
"c++",
"raii",
"placement-new",
"explicit-destructor-call"
] |
[
"PHP Login Form - MySQL Database - Invalid Password",
"I'm trying to login with this code, however I always get a negative when I try it ($errorMessage). I'm basicly trying to check the Username and Password to an existing database of vanilla forums. I got a User with only SELECT (read) access to the specific TABLE.\nI don't get what exactly this line does:\n\n\n prepare(\"SELECT * FROM GDN_User WHERE Email = :Email\")\n\n\nI have these ROWS in my Database:\n\n\n UserID, Email, Password, (Name) (and more unrelevant ones)\n\n\n<?php\n//username-, password-vars (etc.) removed for stackoverflow post\n//LOGIN START\nsession_start();\n$pdo = new PDO('mysql:host=localhost;dbname=vanilla_forums', $username2, $password);\nif(isset($_GET['Login'])) {\n $email = $_POST['Email'];\n $passwort = $_POST['Passwort'];\n\n $statement = $pdo->prepare(\"SELECT * FROM GDN_User WHERE Email = :Email\");\n $result = $statement->execute(array('Email' => $email));\n $user = $statement->fetch();\n\n //Überprüfung des Passworts\n if ($user !== false && password_verify($passwort, $user['Passwort'])) {\n $_SESSION['UserID'] = $user['UserID'];\n die('Login erfolgreich. Weiter zu <a href=\"access.php\">internen Bereich</a>');\n } else {\n $errorMessage = \"Password invalid.<br>\";\n }\n}\n\n//LOGIN END\n?>\n<!DOCTYPE html>\n<html>\n<head>\n <title>Login</title> \n</head>\n<body>\n\n<?php\nif(isset($errorMessage)) {\n echo $errorMessage;\n}\n?>\n\n<form action=\"?Login=1\" method=\"post\">\nE-Mail:<br>\n<input type=\"email\" size=\"40\" maxlength=\"250\" name=\"Email\"><br><br>\n\nDein Passwort:<br>\n<input type=\"password\" size=\"40\" maxlength=\"250\" name=\"Passwort\"><br>\n\n<input type=\"submit\" value=\"Abschicken\">\n</form>\n</body>\n</html>\n\n\nIt is possible that I simply did something wrong with Capped letters, however can't find the issue."
] | [
"php",
"mysql",
"sql",
"html",
"mariadb"
] |
[
"Getting error message while running this basic calculator",
"I'm new to Java (only been doing it for about 3 days in reality).. I have basic knowledge of Python, and decided to learn Java. I made my first calculator program in Java today, and used the same setup for the program as I have in a program in Python. The thing is, I'm getting an error message everytime i run it, though, specifically when it asks what sign i want to use on line 16. i know this is so basic, and im sure my problem is so stupid, but im only getting used to the syntax and stuff, so i'd like to know what im doing wrong. Here's the code:\n\n import java.util.Scanner;\n\n class Experiment {\n public static void main(String[] args){\n double num1, num2, ans = 0;\n String sign;\n Scanner num = new Scanner(System.in);\n\n System.out.print(\"Enter first number: \");\n num1 = num.nextDouble();\n\n System.out.print(\"+, -, x or /? \");\n sign = num.nextLine();\n\n System.out.print(\"Enter second number: \");\n num2 = num.nextDouble();\n\n if(sign == \"+\"){\n System.out.print(num1);\n System.out.print(\"+\");\n System.out.print(num2);\n System.out.print(\"=\");\n System.out.print(num1 + num2);\n }\n if(sign == \"-\"){\n System.out.print(num1);\n System.out.print(\"=\");\n System.out.print(num2);\n System.out.print(\"=\");\n System.out.print(num1 - num2);\n }\n if(sign == \"x\"){\n System.out.print(num1);\n System.out.print(\"x\");\n System.out.print(num2);\n System.out.print(\"=\");\n System.out.print(num1 * num2);\n }\n if(sign == \"/\"){\n System.out.print(num1);\n System.out.print(\"/\");\n System.out.print(num2);\n System.out.print(\"=\");\n System.out.print(num1 + num2);\n } else {\n System.out.print(\"That is not a valid input\");\n }\n\n } \n}"
] | [
"java",
"syntax",
"calculator"
] |
[
"LESS/Sass variable in Angular TypeScript component",
"Can I put some LESS/Sass variable in an Angular TypeScript component?\n\nFor example: \n\nanimations: [\n trigger('dialog', [\n state('*', style({\n transform: 'translate(unit(@var1, px), unit(@var2, px))',\n top: 'unit(@var3, px)',\n height: 'unit(@var4, px)'\n\n\nCurrent code:\n\n@Component({\n selector: 'animationDialog', \n templateUrl: './animationDialog.component.html',\n styleUrls: ['./modal.component.css'], \n animations: [\n trigger('dialog', [\n state('*', style({\n transform: 'translate(20px, 20px)',\n top: '20px',\n height: '20px'\n}))\n\n\nCase this is not possible: is there any other CSS preprocessing language for style?"
] | [
"angular",
"sass",
"less",
"css-preprocessor"
] |
[
"You cannot add or change a record because a related record is required vb.net",
"I know this question has been asked numerous times, but the situations people had were slightly different each time, or lacked enough detail, or the explanation for the problem lacked specific detail that I could understand the solution.\n\nSo here is my thing. I've got a combobox called \"StatesComboBox\" in a form that takes in customer data. This form is bound to a table called \"States\" in an ms access database file. So whatever states are in that table are reflected in the StatesComboBox.\n\nIn my access database file, I've got a table that stores the customer data called \"CustomerData\". One of the fields in it is called \"customerstate\", which stores the \"StatesComboBox\" selection made by the user. \n\nI have connected the \"States\" table to the \"CustomerData\" table with a relationship. It connects the States table to the \"customerstate\" field. This is a one-to-many relationship, and I have checked off on the enforce referential integrity, cascade add and cascade delete options.\n\nNow, when I enter data in the form and hit my register button, I get the message stated above - \"You cannot add or change a record because a related record is required in table 'States'\". But when I go back to access, delete the relationship between \"States\" and \"CustomerData\", the data gets stored just fine.\n\nBut I need to enforce limitations on the states selected... What am I doing wrong? What can I do to address this? Thank you."
] | [
"vb.net",
"ms-access",
"relationships"
] |
[
"variadic templates with template function names",
"following this question , I am trying to avoid copy-pasting some code related to calling all of the same-named methods of the mixins of the class BaseSensor.\n\nin sensor.hpp\n\nstruct EdgeSensor //a mixin\n{\n void update(){}\n void printStats() {}\n};\n\nstruct TrendSensor //another mixin\n{\n void update(){}\n void printStats() {}\n};\n\ntemplate<typename ... SensorType>\nclass BaseSensor : public SensorType ... //to my BaseSensor class\n{\n void update() /*{ what goes in here??? }*/\n void printStats() /*{ what goes in here??? }*/\n};\n\n\nin sensor.t.hpp\n\ntemplate<typename ... SensorType>\nvoid BaseSensor<SensorType...>::update()\n{\n int arr[] = { (SensorType::update(), 0)..., 0 };\n (void)arr;\n}\n\ntemplate<typename ... SensorType>\nvoid BaseSensor<SensorType...>::printStats()\n{\n int arr[] = { (SensorType::printStats(), 0)..., 0 };\n (void)arr;\n}\n\n\nin main.cpp\n\nint main(int , const char **) \n{\n {\n BaseSensor<EdgeSensor,TrendSensor> ets;\n ets.update();\n ets.printStats();\n }\n {\n BaseSensor<EdgeSensor> ets;\n ets.update();\n ets.printStats();\n }\n}\n\n\nThe above code executes the update() of all the mixins in turn, before going on to execute all the printStats() from all the mixins as well.\n\nI wonder if it is somehow possible to avoid duplicating the implementation of BaseSensor::update() and BaseSensor::printStats() and create a generic (template) function that accepts the name of the target function to execute across all the mixins:\n\nFor example, I could create a method runAll()\n\ntemplate<typename ... SensorType>\nclass BaseSensor : public SensorType ... //to my BaseSensor class\n{\n void update() /*{ what goes in here??? }*/\n void printStats() /*{ what goes in here??? }*/\n\n template<typename FnName>\n void runAll(FnName f)\n {\n int arr[] = { (SensorType::f(), 0)..., 0 };\n (void)arr;\n }\n};\n\n\nHow would I call it then from BaseSensor::update() and BaseSensor::printStats(). I have attempted to use\n\nvoid update() { runAll<update>(); }\nvoid printStats() { runAll<printStats>(); }\n\n\nbut this does not work (did not expect it to). The problem with passing function name as a function argument (which I see is many other questions such as here is that I do not know how to point to various ::update() functions from BaseSensor::update(). for example\n\nvoid update() { runAll<update>( update() ); }\n\n\nis also not correct. \n\nIs it possible to avoid copying in this case? How would the template parameters look like if I where to move a working runAll() into file \"sensor.t.hpp\" ?\n\nThank you"
] | [
"c++",
"templates",
"variadic-templates"
] |
[
"What is the difference between the respective toString methods for POJO and POGO after mixing a groovy class",
"class A { String methodFromA() { 'A' } }\nclass B { String methodFromB() { 'B' } }\nA.metaClass.mixin B\ndef o = new A()\nassert o.methodFromA() == 'A'\nassert o.methodFromB() == 'B'\nassert o instanceof A\nassert !(o instanceof B)\n\nprintln A\nprintln A.toString()\n\n\nJavaPojo.metaClass.mixin( B)\ndef javaPojo=new JavaPojo()\nprintln javaPojo\nprintln javaPojo.toString()\n\n\nresult:\n\nclass com.xxx.A\nclass com.xxx.B\ntoString from Java\ncom.xxx.B@5c1a1ff9\n\n\nwhy line3 is from java?\nwhy line4 is a intance toString (end with hashcode)\n\nhere is my env\n\n➜ ~ groovy --version\nGroovy Version: 2.4.7 JVM: 1.7.0_25 Vendor: Oracle Corporation OS: Mac OS X\n\n➜ ~ java -version\njava version \"1.7.0_25\"\nJava(TM) SE Runtime Environment (build 1.7.0_25-b15)\nJava HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode)"
] | [
"java",
"groovy",
"pojo",
"pogo"
] |
[
"Table layout to bitmap",
"I have a form in a TableLayout where the form is filled from my database, I want to send the table output via email.But I have problem with converting the tablelayout to Bitmap. Here is the final activity I am working on\n\npublic class SendEmail extends Activity {\n\n\n Button buttonSend;\n TableLayout tableMessage;\n Intent emailFinal;\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.sendemail);\n\n String Orderdate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());\n\n String email = pdatabase.getPEmail();\n emailFinal = new Intent(Intent.ACTION_SEND); \n emailFinal.putExtra(Intent.EXTRA_EMAIL, new String[]{ email});\n\n\nbuttonSend =(Button) findViewById(R.id.sendEmail);\n\ntableMessage = (TableLayout) findViewById(R.id.tableLayout1); \n\n buttonSend.setOnClickListener(new OnClickListener() {\n\n @Override\n public void onClick(View v) {\n Bitmap b = Bitmap.createBitmap( tableMessage.getWidth(),\n tableMessage.getHeight(),\n Bitmap.Config.ARGB_8888);\n Canvas c = new Canvas(b);\n tableMessage.draw(c);\n BitmapDrawable d = new BitmapDrawable(getResources(), b) \n emailFinal.putExtra(Intent.EXTRA_TEXT, b); \n emailFinal.setType(\"message/rfc822\");\n startActivity(Intent.createChooser(emailFinal, \"Choose an Email client :\"));\n }"
] | [
"android",
"tablelayout"
] |
[
"Creating a nested UL from flat array in PHP",
"This is an array that was built from a JSON file. What I want to do is create a unordered nested list. I have seen a lot of tutorials out there but they usually only work for a simple (id, parent id, name) layout. This array is more complicated than that which is why my attempts don't seem to work. \n\nThis is the desired outcome:\n\n\nStandard I: Curriculum, Planning, and Assessment\n\nIndicator I-A. Curriculum & Planning\n\nI-A-1. Child and Adolescent Development\n\ncontent will go in here\n\nI-A-2. Child and Adolescent Development\n\ncontent will go in here\n\n\nMore indicators here that are related to Standard I\n\nStandard II: .... \n\n\nThere are multiple parents, and their IDs are separated by the *_id field. I included duplicate fields, with different names, to allow a comparison based off the examples I saw online that could do something like $parentID == $id. I was looking into ways of converting this to a tree array to make reading it easier, but ran into similar complications there too. \n\nSo to understand the structure below, here is a key:\n\n[top_id] = [standard]'s ID and is the same as [top] for comparison reasons\n\n[parent_id] = [indicators]'s ID and is the same as [parent] for comparison reasons\n\n[child_id] = [element]'s ID and is the same as [parent] for comparison reasons\n\nThe others are content associated to the [element] which I can get to show up once I get my list created successfully.\n\n Array\n (\n [0] => Array\n (\n [top_id] => 1\n [top] => 1\n [parent_id] => 2\n [parent] => 2\n [child_id] => 5\n [child] => 5\n [standard] => Standard I: Curriculum, Planning, and Assessment\n [indicator] => Indicator I-A. Curriculum & Planning\n [element] => I-A-1. Child and Adolescent Development\n [Connections] => some content here\n [Effective Practice] => some content here\n [Proficient] => some content here\n [Suggested Artifacts] => some content here\n )\n\n [1] => Array\n (\n [top_id] => 1\n [top] => 1\n [parent_id] => 2\n [parent] => 2\n [child_id] => 6\n [child] => 6\n [standard] => Standard I: Curriculum, Planning, and Assessment\n [indicator] => Indicator I-A. Curriculum & Planning\n [element] => I-A-2. Child and Adolescent Development\n [Connections] => some content here\n [Effective Practice] => some content here\n [Proficient] => some content here\n [Suggested Artifacts] => some content here\n )\n\n )\n\n\n-- UPDATE WITH ATTEMPT EXAMPLES --\n\nforeach ($nodes as $node => $v) { \n\n // id's\n $topID = $v['top_id'];\n $parentID = $v['parent_id'];\n $childID = $v['child_id'];\n $top = $v['top'];\n $parent = $v['parent'];\n $child = $v['child'];;\n\n // name values\n $standard = $v['standard'];\n $indicator= $v['indicator'];\n $element = $v['element'];\n $connections = $v['Connections'];\n $practice = $v['Effective Practice'];\n $proficient = $v['Proficient'];\n $artifacts = $v['Suggested Artifacts'];\n\n echo \"<ul>\";\n\n foreach($standard as $value){\n echo \"<li>\";\n print $value;\n echo \"<ul>\";\n\n foreach($indicator as $v){\n echo \"<li>\";\n print $v;\n echo \"</li>\";\n }\n echo \"</ul>\";\n echo \"</li>\";\n }\n echo '</ul>';\n}\n\n\nAlso\n\n if ($node[$top][] == $topID[]){\n echo \"<li>\";\n print $standard;\n echo \"<ul>\";\n if ($node[$parent][] == $parentID[]){\n echo \"<li>\";\n print $indicator;\n echo \"</li>\";\n }\n echo \"</ul>\"; \n echo \"</li>\";\n }"
] | [
"php",
"arrays",
"nested-lists"
] |
[
"Grunt compiling Jade files",
"I'm trying to configure my Gruntfile to compile all of my Jade files to individual HTML files. For example, if I have the following source folder:\n\nsource\n└── templates\n ├── first.jade\n ├── second.jade\n └── third.jade\n\n\nThen I would expect grunt jade to output:\n\nbuild\n└── templates\n ├── first.html\n ├── second.html\n └── third.html\n\n\nHere's my Gruntfile using grunt-contrib-jade:\n\nmodule.exports = function(grunt) {\n grunt.initConfig({\n\n jade: {\n compile: {\n options: {\n client: false,\n pretty: true\n },\n files: [ {\n src: \"*.jade\",\n dest: \"build/templates/\",\n ext: \"html\",\n cwd: \"source/templates/\"\n } ]\n }\n },\n });\n\n grunt.loadNpmTasks(\"grunt-contrib-jade\");\n};\n\n\nHowever, when I run the jade command I get the following errors:\n\nRunning \"jade:compile\" (jade) task\n>> Source file \"first.jade\" not found.\n>> Source file \"second.jade\" not found.\n>> Source file \"third.jade\" not found.\n\n\nWhat am I doing wrong?"
] | [
"javascript",
"node.js",
"gruntjs"
] |
[
"VB.net Passing parameter to function with a stored procedure",
"I am trying to call a function that populate a datatable, but it is not working and I am lost. I am getting a function error. Function doesn't return a value on all code paths. Here's is my code please help thank you.\n\nProtected Sub Search_Click(sender As Object, e As EventArgs) Handles Search.Click\n strPartNumber = txtPartNumber.Text\n\n Dim CT As DataTable = Me.GetCompanyInfo(strPartNumber, \"None\")\n dvCommon.DataSource = CT\n dvCommon.DataBind()\n End Sub\n\nPrivate Function GetCompanyInfo(ByRef PartNumber As String, ByRef Version As String) As DataTable\n Dim constr As String = ConfigurationManager.ConnectionStrings(\"DefaultConnection\").ConnectionString\n Using con As New SqlConnection(constr)\n Using cmd As New SqlCommand(\"spCommonInfo\")\n cmd.Connection = con\n cmd.CommandType = CommandType.StoredProcedure\n cmd.Parameters.AddWithValue(\"@PartNumber\", PartNumber)\n cmd.Parameters.AddWithValue(\"@Version\", Version)\n Using sda As New SqlDataAdapter(cmd)\n Dim CT As New DataTable()\n sda.Fill(CT)\n End Using\n End Using\n End Using\n End Function"
] | [
"sql",
"vb.net",
"function"
] |
[
"hibernate 4.x with second level Ehcache not working as expected",
"Here's my config:\n\npom.xml:\nUsing hibernate and hibernate-ehcache 4.2.8.Final version\n\nspring config: i have the following hibernate properties\n\n<prop key=\"hibernate.cache.region.factory_class\">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>\n<prop key=\"hibernate.cache.use_second_level_cache\">true</prop>\n\n\nehcache.xml\n\n<ehcache>\n\n <diskStore path=\"java.io.tmpdir\"/>\n\n <!-- cache setting for com.cisco.locker.entity.SystemConfig entity -->\n <cache name=\"com.cisco.locker.entity.SystemConfig\"\n maxElementsInMemory=\"100\"\n eternal=\"false\"\n timeToIdleSeconds=\"600\"\n timeToLiveSeconds=\"600\"\n overflowToDisk=\"false\"\n statistics=\"true\"\n />\n\n</ehcache>\n\n\nentity - com.cisco.locker.entity.SystemConfig.java \n\n@Entity\n@Table(name = \"system_config\")\n@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)\npublic class SystemConfig implements Serializable {\n...\n}\n\n\nlogs:\n\nFirst call: http://localhost:8080/test/getSystemConfigs\n{\n \"statusCode\": \"200\",\n \"statusMessage\": \"SUCCESS\",\n \"response\": {\n \"admin.lcu_status_polling_timer\": \"120\",\n \"admin.site_status_polling_interval\": \"15\"\n }\n}\n\nHibernate: select systemconf0_.ID as ID1_12_, systemconf0_.description as descript2_12_, systemconf0_.property as property3_12_, systemconf0_.value as value4_12_ from system_config systemconf0_ where systemconf0_.property like ?\n2014-05-13 00:53:40,553 DEBUG net.sf.ehcache.Cache [http-bio-8080-exec-1]: com.cisco.locker.entity.SystemConfig cache - Miss\n2014-05-13 00:53:40,561 DEBUG net.sf.ehcache.Cache [http-bio-8080-exec-1]: com.cisco.locker.entity.SystemConfig cache - Miss\n\nSecond call: http://localhost:8080/test/getSystemConfigs\n{\n \"statusCode\": \"200\",\n \"statusMessage\": \"SUCCESS\",\n \"response\": {\n \"admin.lcu_status_polling_timer\": \"120\",\n \"admin.site_status_polling_interval\": \"15\"\n }\n}\n\nHibernate: select systemconf0_.ID as ID1_12_, systemconf0_.description as descript2_12_, systemconf0_.property as property3_12_, systemconf0_.value as value4_12_ from system_config systemconf0_ where systemconf0_.property like ?\n2014-05-13 00:53:48,037 DEBUG net.sf.ehcache.Cache [http-bio-8080-exec-2]: com.cisco.locker.entity.SystemConfigCache: com.cisco.locker.entity.SystemConfig store hit for com.cisco.locker.entity.SystemConfig#11\n2014-05-13 00:53:48,037 DEBUG net.sf.ehcache.Cache [http-bio-8080-exec-2]: com.cisco.locker.entity.SystemConfigCache: com.cisco.locker.entity.SystemConfig store hit for com.cisco.locker.entity.SystemConfig#12\n\n\nThird call – After manually changing value in DB \"admin.site_status_polling_interval\" from 15 to 10: http://localhost:8080/test/getSystemConfigs\n{\n \"statusCode\": \"200\",\n \"statusMessage\": \"SUCCESS\",\n \"response\": {\n \"admin.lcu_status_polling_timer\": \"120\",\n \"admin.site_status_polling_interval\": \"10\"\n }\n}\n\nHibernate: select systemconf0_.ID as ID1_12_, systemconf0_.description as descript2_12_, systemconf0_.property as property3_12_, systemconf0_.value as value4_12_ from system_config systemconf0_ where systemconf0_.property like ?\n2014-05-13 00:54:08,738 DEBUG net.sf.ehcache.Cache [http-bio-8080-exec-4]: com.cisco.locker.entity.SystemConfigCache: com.cisco.locker.entity.SystemConfig store hit for com.cisco.locker.entity.SystemConfig#11\n2014-05-13 00:54:08,738 DEBUG net.sf.ehcache.Cache [http-bio-8080-exec-4]: com.cisco.locker.entity.SystemConfigCache: com.cisco.locker.entity.SystemConfig store hit for com.cisco.locker.entity.SystemConfig#12\n\n\nI dont seem to understand how the cache picked up the latest values when i ended up doing a manual DB change. The logs suggest it is picking these changed values also from the cache.\n\nDoes the second level cache pick up manual DB changes i.e. DB changes not going through hibernate as the above logs suggest? or is there something wrong that i am doing?"
] | [
"java",
"spring",
"hibernate",
"ehcache"
] |
[
"How to efficiently replace elements in an unordered_set while iterating over it?",
"Suppose you have an\n\nstd::unordered_set<std::shared_ptr<A>> as;\n// (there is an std::hash<std::shared_ptr<A>> specialisation)\n\n\nand you want to replace some of its elements while iterating over it:\n\nfor (auto it = as.begin(); it != as.end(); ++it) {\n if ((*it)->condition()) {\n as.erase(it);\n as.insert(std::make_shared<A>(**it));\n }\n}\n\n\nThis could invalidate the iterator at erase and insert (if rehashing takes place), so this loop will exhibit undefined behaviour and will most likely crash horribly.\n\nThe one solution I can think of is using two separate vectors to buffer the insert and erase operations and later use the overloads that take iterator pairs for erasing and inserting (this is presumably more rehashing-friendly).\n\nEven if I use the buffer approach, this still seems bloated code and could result in two rehashes that might possibly both be unnecessary.\n\nSo, is there a better way to do it?"
] | [
"c++",
"iterator",
"replace",
"unordered-set"
] |
[
"Difference between Eclipse CDT ast and model packages",
"I use Eclipse CDT to analyse C/C++ source code as part of a research project. I noticed that CDT's API has two packages of \"accessible\" interfaces:\n\n(1) Package org.eclipse.cdt.core.dom.ast\n\n(2) Package org.eclipse.cdt.core.model\n\nI assume that (1) is for AST traversal, but what is the purpose of (2)?"
] | [
"c++",
"c",
"eclipse",
"eclipse-cdt"
] |
[
"Adding Gizeh gif with transparent background to existing movie with moviepy",
"Hello Im new to moviepy and gizeh.\nI want to create a gif with transparent background and add this gif to left-top of movie. For creating gif I used Gizeh.\nMy code snipped like that:\nimport gizeh as gz\nimport numpy as np\nfrom moviepy.editor import *\n\nvideoclip = VideoFileClip("movie.MOV")\n\nW = H = 150\nD = 2 #Duration\nnballs = 60\n\nradii = np.random.randint(.1*W, .2*W, nballs)\ncolors = np.random.rand(nballs,3)\ncenters = np.random.randint(0,W,(nballs,2))\n\ndef make_frame(t):\n surface = gz.Surface(W,H)\n for r,color, center in zip(radii, colors, centers):\n angle = 2*np.pi*(t/D*np.sign(color[0]-.5)+color[1])\n xy = center+gz.polar2cart(W/5,angle) # center of the ball\n gradient = gz.ColorGradient(type="radial",\n stops_colors = [(0,color),(1,color/10)],\n xy1=[0.3,-0.3], xy2=[0,0], xy3 = [0,1.4])\n ball = gz.circle(r=1, fill=gradient).scale(r).translate(xy)\n ball.draw(surface)\n return surface.get_npimage(transparent=True)\n\ngraphics_clip_mask = VideoClip(lambda t: make_frame[t][3] / 255.0, is_mask=True) =====>>>> Error\n\n\nBut I try to run this snipped I get an error like that:\n1 graphics_clip_mask = VideoClip(lambda t: make_frame[t][3] / 255.0, is_mask=True)\n\nTypeError: __init__() got an unexpected keyword argument 'is_mask'\n\nI tried to solve this problem with several solutions but I cannot solve it. How can I add this gif with transparent background to existing movie."
] | [
"python",
"python-3.x",
"cairo",
"moviepy",
"pycairo"
] |
[
"Only push specific substring to array in Ruby",
"I have an array that I am looping through and pushing specific values to a separate array. EX:\n\nfirst_array = [\"Promoter: 8\", \"Passive: 7\"]\n\n\nI want to push every value that is an integer to a separate array, that would look like this in the end:\n\nfinal_array = [8,7]\n\n\nIt would be nice for the values in the new array to be integers. I can't think of a way to push all numeric values within a string to a new array, but what would be the best option to do what I am wanting?"
] | [
"ruby",
"arrays"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.