texts
sequence
tags
sequence
[ "Changing text after an input field", "How do I change the \"2 Year Subscription\" to \"2 year:\" without losing the input field\n\n<div class=\"radioOption subscription1Col3\">\n<input class=\"buyNow\" type=\"radio\" name=\"product2\" value=\"6_0\" checked=\"\">2 Year Subscription</div>" ]
[ "jquery", "jquery-selectors" ]
[ "Generate random coordinates outside and within a given radius from origin", "I need to generate a spec for my search engine to test that, when I specify an origin point and a radius, results beyond results of my source origin are not included in the response, while radius within the given radius in kilometers are included.\n\nGiven the origin and the radius, I want to test two \"extreme\" cases where I create two test data points, \n\n\none within: on the exact radius minus an epsilon (radius - e away from the origin)\none outside: on the exact radius plus an epsilon (radius + e away from origin)\n\n\nFor instance if my radius is 10km, I'd like to generate a point 10.1km away and 9.9 km away from the source. \n\nThen, I want to run many tests where I pick random points on earth (either within or outside the radius) to check that all corner cases are handled well by my search engine\n\nI am checking the code actually works with Geocoder.distance_between\n\nbefore do\n # Ensure our example is correct\n expect(\n Geocoder::Calculations.distance_between(origin, point_outside_radius_of_origin)\n ).to be > radius_in_km\n\n expect(\n Geocoder::Calculations.distance_between(origin, point_within_radius_of_origin)\n ).to be < radius_in_km\nend\n\n\nFor instance the following fixed example passes\n\nUsing a fixed example of Paris\n\nlet(:origin) { [48.856614, 2.3522219] } # Geocoder.coordinates('Paris')\nlet(:radius_in_km) { 10 }\nlet(:point_within_radius_of_origin) { [48.801148, 2.429443] } # Geocoder.coordinates('Maisons-Alfort')\nlet(:point_outside_radius_of_origin) { [48.790367, 2.455572] } # Geocoder.coordinates('Créteil')\n\n\n\n\nSo I'm trying to implement function to generate random points from an origin. \n\nFrom https://stackoverflow.com/a/43202522/2832282 I was somehow able to generate a point within the given radius : (this function seems to work perfectly)\n\n# Thanks to https://stackoverflow.com/a/43202522/2832282\n#\n# @param lon [Float]\n# @param lat [Float]\n# @param max_radius [FLoat] in km\n#\n# @return [Pair<Float>] [Lng, lat]\ndef random_point_within_radius_of_origin(lng:, lat:, max_radius:)\n dx, dy = Utility.random_point_in_disk(max_radius)\n random_lat = lat + dy / OneDegree\n random_lng = lng + dx / ( OneDegree * Math::cos(lat * Math::PI / 180) )\n [random_lng, random_lat]\nend\n# @param max_radius [Float] Distance in km\n#\n# @return [Pair<Float>]\ndef random_point_in_disk(max_radius)\n r = max_radius * rand**0.5\n theta = rand * 2 * Math::PI\n [r * Math.cos(theta), r * Math.sin(theta)]\nend\n\n\nI need to implement the function below to generate a random point outside the radius from the origin (I don't really care whether uniformly distributed or not) outside the given disk. I guess I could generate a fake point and retry until I hit the goal off.\n\nNote that if you have some code that works without specifying a max_radius this is even better (I basically just want to exclude the coordinates generated by the aforementionned function) \n\n# @param lon [Float] Longitude of origin\n# @param lat [Float] Latitude of origin\n# @param max_radius [FLoat] Max radius from origin in km\n# @param min_radius [FLoat] Min radius from origin in km\n#\n# @return [Pair<Float>] [Lng, lat] of some random point between min_radius and max_radius of origin\ndef random_point_within_radius_band_of_origin(lng:, lat:, max_radius:, min_radius:)\n # What this SO Question is about\nend" ]
[ "ruby", "random", "coordinates", "polar-coordinates" ]
[ "Menu doesn't collapse after clicking, Storefront theme wordpress", "I'm using the Storefront theme in wordpress and I have a problem with the menu on the mobile site. \nAfter clicking a menu item, the menu should collapse. I've looked online, but there is a lot of Javacode for the Bootstrap plugin, and I cannot get this working with the Storefront theme. \n\nWebsite\n\nBootstrap close responsive menu "on click"" ]
[ "javascript", "jquery", "css", "wordpress", "storefront" ]
[ "Find overlapping modularity in two graphs - iGraph in Python", "I have two related graphs created in iGraph, A and G. I find community in structure in G using either infomap or label_propagation methods (because they are two that allow for weighted, directional links). From this, I can see the modularity of this community for the G graph. However, I need to see what modularity this will provide for the A graph. How can I do this?" ]
[ "python", "graph", "igraph" ]
[ "Using .onresize to control text on responsive video player", "I'm trying to control the size of the text used to show elapsed and total time of a video player. I am currently controlling the play/pause/sound and full screen icons, but can't access the time display. Below is the javascript used to resize the controls on window resize:\n\nwindow.onload = function() {\nresize();\n}\n\nwindow.onresize = function() {\nresize();\n}\n\nfunction resize() {\n document.getElementsByClassName('play')[0].style.width = (document.getElementsByClassName('timeline')[0].offsetHeight * .25) + 'px';\n document.getElementsByClassName('fullscreen')[0].style.width = (document.getElementsByClassName('timeline')[0].offsetHeight * .25) + 'px';\n document.getElementsByClassName('mute')[0].style.width = (document.getElementsByClassName('timeline')[0].offsetHeight * .25) + 'px';\n document.getElementsByClassName('time-played')[0].style.width = (document.getElementsByClassName('timeline')[0].offsetHeight * .25) + 'px';\n}\n\n\nAlso trying to figure out the best way to minimize and simplify this using jQuery(to consolidate all of the classes into one array, similar to:\n\n$('.play .fullscreen .mute .time-played')\n\n\nMy current implementation: jsfiddle" ]
[ "javascript", "jquery", "onresize" ]
[ "Mapping over observable", "I'm having a hard time wrapping my head around filtering an observable.\n\nI have a widget \n\n{name: string, description: string}\n\n\nI have an observable of widgets \n\n[{},{},{}]\n\n\nI want to loop over my widgets observable but widgets.map() doesn't loop over each individual widget in the observable but the entire observable. \n\nwidgets.map((widget) => {console.log(widget.name)}) is always undefined.\n\n\nWhat am I not understanding?" ]
[ "angular", "mapping", "observable" ]
[ "Writing a netcdf4 file is 6-times slower than writing a netcdf3_classic file and the file is 8-times as big?", "I am using the netCDF4 library in python and just came across the issue stated in the title. At first I was blaming groups for this, but it turns out that it is a difference between the NETCDF4 and NETCDF3_CLASSIC formats (edit: and it appears related to our Linux installation of the netcdf libraries).\n\nIn the program below, I am creating a simple time series netcdf file of the same data in 2 different ways: 1) as NETCDF3_CLASSIC file, 2) as NETCDF4 flat file (creating groups in the netcdf4 file doesn't make much of a difference). What I find with a simple timing and the ls command is:\n\n1) NETCDF3 1.3483 seconds 1922704 bytes\n2) NETCDF4 flat 8.5920 seconds 15178689 bytes\n\n\nIt's exactly the same routine which creates 1) and 2), the only difference is the format argument in the netCDF4.Dataset method. Is this a bug or a feature?\n\nThanks, Martin\n\nEdit: I have now found that this must have something to do with our local installation of the netcdf library on a Linux computer. When I use the program version below (trimmed down to the essentials) on my Windows laptop, I get similar file sizes, and netcdf4 is actually almost 2-times as fast as netcdf3! When I run the same program on our linux system, I can reproduce the old results. Thus, this question is apparently not related to python.\n\nSorry for the confusion.\n\nNew code:\n\nimport datetime as dt\nimport numpy as np\nimport netCDF4 as nc\n\n\ndef write_to_netcdf_single(filename, data, series_info, format='NETCDF4'):\n vname = 'testvar'\n t0 = dt.datetime.now()\n with nc.Dataset(filename, \"w\", format=format) as f:\n # define dimensions and variables\n dim = f.createDimension('time', None)\n time = f.createVariable('time', 'f8', ('time',))\n time.units = \"days since 1900-01-01 00:00:00\"\n time.calendar = \"gregorian\"\n param = f.createVariable(vname, 'f4', ('time',))\n param.units = \"kg\"\n # define global attributes\n for k, v in sorted(series_info.items()):\n setattr(f, k, v)\n # store data values\n time[:] = nc.date2num(data.time, units=time.units, calendar=time.calendar)\n param[:] = data.value\n t1 = dt.datetime.now()\n print \"Writing file %s took %10.4f seconds.\" % (filename, (t1-t0).total_seconds())\n\n\nif __name__ == \"__main__\":\n # create an array with 1 mio values and datetime instances\n time = np.array([dt.datetime(2000,1,1)+dt.timedelta(hours=v) for v in range(1000000)])\n values = np.arange(0., 1000000.)\n data = np.array(zip(time, values), dtype=[('time', dt.datetime), ('value', 'f4')]) \n data = data.view(np.recarray)\n series_info = {'attr1':'dummy', 'attr2':'dummy2'}\n filename = \"testnc4.nc\"\n write_to_netcdf_single(filename, data, series_info)\n filename = \"testnc3.nc\"\n write_to_netcdf_single(filename, data, series_info, format='NETCDF3_CLASSIC')\n\n\n[old code deleted because it had too much unnecessary stuff]" ]
[ "file-io", "netcdf" ]
[ "RCPP_MODULE for inheritance class", "I got a problem when I try module with inheritance class. Basiclly, I can't compile this part.\n\nRCPP_MODULE(PACE){\n using namespace Rcpp;\n class_<FPCAreg>(\"FPCAreg\")\n .constructor<List, List, double, double, int, bool, bool>()\n .field(\"n\", &FPCAreg::n)\n ;\n}\n\n\nHere FPCAreg is a inheritance class based on FPCA class, and \"n\" is defined in FPCA. No matter I use \".field(\"n\", &FPCAreg::n)\" or \".field(\"n\", &FPCA::n)\". When I use \".field(\"n\", &FPCAreg::n)\", the error message is \"no matching function for call to blablabla\", and for \".field(\"n\", &FPCA::n)\", that's same but different class name. Is there any suggestion? Thanks." ]
[ "r", "rcpp" ]
[ "Why Linux doesn't redirect Samba port on Alfresco JLAN?", "I'm trying an SMB/CIFS Java implementation from Alfresco, named Alfresco JLan.\n\nMy server has stand up correctly, but I'm using non-privileged ports for SMB (1445, 1139, 1138, 1137).\n\nI've used that shell code:\n\necho 1 > /proc/sys/net/ipv4/ip_forward\nmodprobe iptable_nat\niptables -F\niptables -t nat -F\niptables -P INPUT ACCEPT\niptables -P FORWARD ACCEPT\niptables -P OUTPUT ACCEPT\niptables -t nat -A PREROUTING -p tcp --dport 445 -j REDIRECT --to-ports 1445\niptables -t nat -A PREROUTING -p tcp --dport 139 -j REDIRECT --to-ports 1139\niptables -t nat -A PREROUTING -p udp --dport 137 -j REDIRECT --to-ports 1137\niptables -t nat -A PREROUTING -p udp --dport 138 -j REDIRECT --to-ports 1138\n\n\nIf I try:\n\ntelnet localhost 1445\n\n\neverything goes OK.\n\nBut, when I try with:\n\ntelnet localhost 445\n\n\nI receive: \n\nTrying 127.0.0.1...\ntelnet: Unable to connect to remote host: Connection refused\n\n\nDoes anyone know what is wrong? I'm using Ubuntu 12.04." ]
[ "alfresco", "samba", "smb", "cifs" ]
[ "Internet Explorer 10 not reading jQuery function", "I have a jQuery load function to create and add a after images using the alt tag data. It works in every browser and IE9, just not IE10 and I can't figure out why.\n\nHere's the jQuery code:\n\n$(\"img.caption\").load(function () {\n var imageCaption = $(this).attr(\"alt\"); \n if (imageCaption != '') {\n var imgWidth = $(this).width();\n $(\"<figcaption class='img-caption'><em>\" + imageCaption + \"</em></figcaption>\").css({ \"position\": \"relative\", \"bottom\": 0, \"left\": 0, \"width\": imgWidth + \"px\" }).insertAfter(this);\n }\n var figcaptionHeight = $('.img-caption').outerHeight();\n $('.img-caption').css('margin-top', -(figcaptionHeight + 2));\n});\n\n\nI've even tried using other tags like but there's no response at all.\n\nThis is the HTML markup:\n\n<figure>\n <img class=\"caption\" alt=\"caption text\" /> \n</figure>" ]
[ "jquery", "html", "internet-explorer-10" ]
[ "Copy / migrate users from Firebase Auth to Google Identity Platform", "I've been using Firebase auth to handle sign-in / sign up in my application (react/express js) which contains now +2000 users.\nWe are going to migrate to use a new project in Identity Platform (to benefit from SAML etc) which uses the same SDK of the firebase. So now we have 2 separate projects, is there a way to copy all users in that Identity Platform new project? or can I combine them and use them simultaneously?\nThanks" ]
[ "node.js", "reactjs", "firebase", "firebase-authentication", "google-identity" ]
[ "Open a file and replace strings in C#", "I'm trying to figure out the best way to open an existing file and replace all strings that match a declared string with a new string, save it then close.\n\nSuggestions ?" ]
[ "c#", "string", "file" ]
[ "Getting CORS error while calling Dynamics 365 Operations JSON-Based custom service using Javascript", "I am developing a simple SPA application and trying to access a Dynamics 365 for Operations JSON-Based custom service. I am using ADAL.js library for authentication. The way for authentication I am following from This Dynamics Community thread.\n\nBut opportunity, after successfully getting the valid token, and calling my target api with acquired token, I am unable to call the API and getting CORS error. \n\nPSB screenshot for the same\n\n\n\nBelow is my code sample:\n\n var req = new XMLHttpRequest()\n req.open(\"POST\", organizationURI + \"/api/services/ServiceGroup/Service/Operaton\", true);\n\n //Set Bearer token\n req.setRequestHeader(\"Authorization\", \"Bearer \" + token);\n req.setRequestHeader(\"Accept\", \"application/json\");\n req.setRequestHeader(\"Content-Type\", \"application/json\");\n\n req.onreadystatechange = function () {\n if (this.readyState == 4 /* complete */) {\n req.onreadystatechange = null;\n if (this.status == 200) {\n var empData = JSON.parse(this.response).value;\n console.log(empData);\n }\n else {\n var error = JSON.parse(this.response).error;\n console.log(error.message);\n errorMessage.textContent = error.message;\n }\n }\n };\n req.send();" ]
[ "office365", "axapta", "dynamics-365", "dynamics-365-operations", "microsoft-dynamics-webapi" ]
[ "How to return a strongly-typed object from a SubSonic SPROC call with SPROC parameters?", "I have a data caller method that returns a SubSonic collection of type ItemDatumCollection.\n\nThe sproc is executed as follows:\n\nitemDatumCollection.LoadAndCloseReader(sp.GetReader());\n\n\nHowever, I am unable to access the output parameters of the sproc in this fashion, as I am able to do when calling sp.GetDataSet() as follows:\n\n itemsDataSet = sp.GetDataSet();\n\n actualNumberOfResults = ((Int64)sp.OutputValues[1]);\n numberOfResultsReturned = ((Int64)sp.OutputValues[2]);\n\n\nIs there a way to access the sproc's output parameters with the first method - returning a SubSonic strongly-typed collection from my sproc call?\n\nThanks." ]
[ "c#", "sql-server-2008", "stored-procedures", "subsonic", "strongly-typed-dataset" ]
[ "iOS programmatically aspect ratio constraint gets broken in UITableviewcell", "I am trying to set an aspect ratio to an image inside a tableviewcell and it is getting broken because iOS can't accomplish accomplish constraints for width or height with decimals that are different from .5 or .0.\n\nThere is anyway to make that a constraint doesn't fail/break if it is close to its value, or it gets rounded to a value erasing the decimal? \n\nI know that the problem is because of the decimal after many tries, I will show you with the following example:\n\nWith the following code\n\npostImage.heightAnchor.constraint(equalToConstant: 88.9).isActive = true\n\n\nI get the following error:\n\n Will attempt to recover by breaking constraint \n<NSLayoutConstraint:0x6000036067b0 UIImageView:0x7fb76fe397e0.height == 88.9 (active)>\n\n\nAnd the view view hierarchy the size of the image is 89\n\n\n\nIt happens to me when I set a height that is different from .5 or .0 it gets rounded to the nearest value .5 or .0 (If I set 88.6 it gets rounded to 88.5 throwing the error), but If I set any value that ends in .0 or .5 it works smooth!\n\n(I know I can do it setting a lower priority but it can give me more unexpected behaviors) \n\n(I am doing it programmatically, doing it through a Xib is not an option :) )\n\nEDIT: Whole log:\n\n (\n \"<NSLayoutConstraint:0x600000facd20 UIImageView:0x7fc98362fe80.height == 86.9 (active)>\",\n \"<NSLayoutConstraint:0x600000facd70 V:|-(0)-[UIImageView:0x7fc98362fe80] (active, names: '|':UITableViewCellContentView:0x7fc98362f940 )>\",\n \"<NSLayoutConstraint:0x600000face10 UIImageView:0x7fc98362fe80.bottom == UITableViewCellContentView:0x7fc98362f940.bottom - 8 (active)>\",\n \"<NSLayoutConstraint:0x600000fad680 'UIView-Encapsulated-Layout-Height' UITableViewCellContentView:0x7fc98362f940.height == 95 (active)>\"\n )\n\nWill attempt to recover by breaking constraint \n<NSLayoutConstraint:0x600000facd20 UIImageView:0x7fc98362fe80.height == 86.9 (active)>" ]
[ "ios", "swift", "xcode", "autolayout" ]
[ "Rails Thread.current[] & thread safety", "So there I was, right. Just looking through some code, studying bits and pieces when all of a sudden, my ocular receptors were assaulted by the unfamiliar. I was like: \n\n\n What!!! What's that all about!\n\n\nAnyway, what I saw was (source):\n\ndef authenticate_user!\n if doorkeeper_token\n Thread.current[:current_user] = User.find(doorkeeper_token.resource_owner_id)\n end\n\n # ...\nend\n\n\nSo after looking at it for a while, thinking:\n\n\n Wtf is this Thread.current[] insanity? Is this even necessary? What's it even trying to do?\n\n\nIt seemed to me it was kind of like wearing a baseball cap backwards: You may look pretty f'ing cool but that sun glare is winning. I then decided to Google around, read some articles and some SO.\n\nNone seemed to concisely answer my question: Given the context of the code, would it not be the same as:\n\ndef authenticate_user!\n if doorkeeper_token\n @current_user = User.find(doorkeeper_token.resource_owner_id)\n end\n\n # ...\nend\n\n\nIf not, what situation/scenario is it useful/protecting against?\n\nI hope you enjoyed my story and want to contribute an awesome ending." ]
[ "ruby-on-rails", "ruby", "thread-safety" ]
[ "How do I change the home page of an app service after deploying an application into web apps", "I have deployed an application into webapps in azure but was not able to see my home page of my application . Instead it shows the default page of microsoft .How do i change the home page of the application app service" ]
[ "azure", "azure-app-service-envrmnt" ]
[ "String begins with a number return different result after query", "Suppose I have a table A like this:\n+----+---------+--+\n| Id | Email | |\n+----+---------+--+\n| 1 | [email protected] | |\n| 2 | [email protected] | |\n| 3 | [email protected] | |\n| 4 | [email protected] | |\n| 5 | [email protected] | |\n+----+---------+--+\n\nand my sql query is:\nselect Email\n , case when @record=Email \n then @cnt:=@cnt+1 \n when @record:=Email \n then @cnt:=1 \n end as n \n from A\n , (select @cnt:=0, @record:='') r \n order \n by Id;\n\nThe purpose of this query is to find the consecutive number with same Email order by Id.\nit will return\n+---------+------+\n| Email | n |\n+---------+------+\n| [email protected] | NULL |\n| [email protected] | NULL |\n| [email protected] | NULL |\n| [email protected] | 1 |\n| [email protected] | 2 |\n+---------+------+\n\nWhy the n column has the null result, that's not what I expected.\nBut if I change the value of Email field in table A:\n+------+----------+\n| Id | Email |\n+------+----------+\n| 1 | [email protected] |\n| 2 | [email protected] |\n| 3 | [email protected] |\n| 4 | [email protected] |\n| 5 | [email protected] |\n+------+----------+\n\nit returns:\n+----------+------+\n| Email | n |\n+----------+------+\n| [email protected] | 1 |\n| [email protected] | 1 |\n| [email protected] | 1 |\n| [email protected] | 2 |\n| [email protected] | 3 |\n+----------+------+\n\nI think this is the right result, but why?\nI am a little confused, can anyone help me?" ]
[ "mysql" ]
[ "Trying to use enum as index works but gives warning in pycharm", "I have this enum class:\nclass MtuType(IntEnum):\n GENERATED = 0\n CONSUMED = 1\n NET = 2\n PEAK_GENERATED = 3\n PEAK_CONSUMED = 4\n OFF_PEAK_GENERATED = 5\n OFF_PEAK_CONSUMED = 6\n PEAK_NET = 7\n OFF_PEAK_NET = 8\n\nAnd later on, I am trying to use it like this:\n.\n.\n.\n powers = [None] * 9\n if generated is not None:\n powers[History.MtuType.GENERATED] = generated * sample_interval\n if consumed is not None:\n powers[History.MtuType.CONSUMED] = consumed * sample_interval\n if net is not None:\n powers[History.MtuType.NET] = net * sample_interval\n if peak_consumed > 0:\n powers[History.MtuType.PEAK_CONSUMED] = peak_consumed * sample_interval\n if peak_generated > 0:\n powers[History.MtuType.PEAK_GENERATED] = peak_generated * sample_interval\n if off_peak_consumed > 0:\n powers[History.MtuType.OFF_PEAK_CONSUMED] = off_peak_consumed * sample_interval\n if off_peak_generated > 0:\n powers[History.MtuType.OFF_PEAK_GENERATED] = off_peak_generated * sample_interval\n\nIt works fine, but PyCharm is complaining about these lines (only):\n powers[History.MtuType.PEAK_CONSUMED] = peak_consumed * sample_interval\n powers[History.MtuType.PEAK_GENERATED] = peak_generated * sample_interval\n powers[History.MtuType.OFF_PEAK_CONSUMED] = off_peak_consumed * sample_interval\n powers[History.MtuType.OFF_PEAK_GENERATED] = off_peak_generated * sample_interval\n\nwith the following warning:\nUnexpected type(s): (MtuType, float) Possible type(s): (int, None) (slice, Iterable[None]) \n\nI have tried to add .value:\n powers[History.MtuType.PEAK_CONSUMED.value] = peak_consumed * sample_interval\n\nbut I get the same error. I have even tried casting to an int:\n powers[int(History.MtuType.PEAK_CONSUMED.value)] = peak_consumed * sample_interval\n\nAny suggestions would be most welcome!" ]
[ "python", "enums", "pycharm" ]
[ "Cache response of spring rest api controller", "Is there anyway to cache the response of spring REST API by method parameter? For example, in below code, return the same response (the json serialized data) from cache if the country is already retrieved once.\n\n@Controller\npublic class DataController {\n\n // Can we cache here by country?\n @RequestMapping(value = \"/api/info/{country}\", method = RequestMethod.GET)\n public CountryInfo getCountryInfo(@PathVariable(\"country\")String country){\n return service.getCountryInfo(country);\n }\n}" ]
[ "java", "spring-mvc", "caching" ]
[ "How do you draw a sector in matplotlib?", "I would like just a pure sector line, not a wedge. I am trying to use it to represent the uncertainty of a vector's direction, at the tip of the vector arrow. I am using plt.arrow to plot the arrow over a basemap in matplotlib. \n\nI haven't been able to find any way to express this uncertainty other than with a wedge. I was wondering if it is possible to plot just a sector line at the tip of the arrow." ]
[ "python", "matplotlib", "sector" ]
[ "Codeception Actor Actor vs Helper?", "In Codeception, the documentation suggests I add actions to Helper\\Acceptance class which are then included in the AcceptanceTester class. The AcceptanceTester class also says this:\n\nclass AcceptanceTester extends \\Codeception\\Actor\n{\n use _generated\\AcceptanceTesterActions;\n\n /**\n * Define custom actions here\n */\n}\n\n\nSo I can add my actions to the AcceptanceTester which is more straightforward for both a developer and his IDE than the auto-generated trait.\n\nIs there any difference and why the documentation suggests the less straightforward way?" ]
[ "php", "testing", "codeception" ]
[ "Java Object Initialization many times in a Class or just once?", "I want to know whats the best practice when it comes to Class Initialization,\n\nI mean should I initialize a Class once Customer c = new Customer(); in the top level, and use it everywhere in the class:\n\nTools tools = new Tools();\n public boolean doCIdCheck(int cId) {\n final Iterator<Customer> cursor = tools.Customers.iterator();\n while (cursor.hasNext()) {\n if (cursor.next().getCIdCheck(cId)) {\n return true;\n }\n }\n return false;\n }\n\n\nor should I just use new Customer().checkCId(); where ever I need it:\n\n public boolean doCIdCheck(int cId) {\n final Iterator<Customer> cursor = new Tools().Customers.iterator();\n while (cursor.hasNext()) {\n if (cursor.next().getCIdCheck(cId)) {\n return true;\n }\n }\n return false;\n }\n\n\nOr best to have each function/method have its own instance of a class:\n\n public boolean doCIdCheck(int cId) {\n Tools tools = new Tools();\n final Iterator<Customer> cursor = tools.Customers.iterator();\n while (cursor.hasNext()) {\n if (cursor.next().getCIdCheck(cId)) {\n return true;\n }\n }\n return false;\n }" ]
[ "java", "class", "instance" ]
[ "Why session_destroy cannot unset the current session value php", "session_start();\n$_SESSION['name'] = 'Sam';\necho $_SESSION['name'];//Sam\nsession_destroy();\necho $_SESSION['name'];//Sam\n\nI know that using unset() or $_SESSION = array() can unset $_SESSION value\nBut I am still wondering why session_destroy() cannot unset the $_SESSION value, what exactly did session_destroy() do?\nWhen is it appropriate to use session_destroy()?\nDo I need to call session_destroy() after using unset()?" ]
[ "php", "session" ]
[ "How to get Android Maps app (version 5.0.1) source code?", "I am an Android developer, I need to see the Android Maps app source code. If someone has it, I would like to know where it is.. Actually, I wish to have a look the part of getting \"Starred Place\" list from Google server. So, the source should have it. Probably, version 5.0.1 has it.\n\nThanks in advance." ]
[ "android", "google-maps" ]
[ "Modify Column vs Drop and Add Column Mysql", "table structure - \n\n| Field | Type | Null | Key | Default | Extra |\n+----------------+--------------+------+-----+---------+----------------+\n| id | bigint(20) | NO | PRI | NULL | auto_increment |\n| candidateId | bigint(20) | NO | | NULL | |\n| profileId | bigint(20) | NO | MUL | NULL | |\n| clientId | bigint(20) | NO | | NULL | |\n| email | varchar(128) | NO | | NULL | |\n| verified | tinyint(1) | YES | | 0 | |\n| isPrimary | tinyint(1) | YES | | 0 | |\n| createdOn | datetime | NO | | NULL | |\n| createdBy | bigint(20) | NO | | NULL | |\n| encryptedEmail | varchar(255) | NO | | NULL | |\n+----------------+--------------+------+-----+---------+---------\n\n\nCurrently, there is no data in encryptedemail.\n\nI wanted to create a unique key - (clientId, profileId, encryptedEmail) \n\nSo I tried converting encrypted email to default null as there were records where \n\nclientId and profileId were duplicate.\n\n\nQuery I used - \n\n ALTER TABLE AlternateEmails MODIFY encryptedEmail varchar(255) NULL, \n add constraint `profileId_3` \n unique(`encryptedEmail`,`clientId`,`profileId`);\n\n\nIt was still showing duplicate record error.\n\nThen I used -\n\n alter table AlternateEmails drop column encryptedEmail,\n add column encryptedEmail varchar(255) default NULL, add constraint \n `profileId_3` unique(`encryptedEmail`,`clientId`,`profileId`);\n\n\nIt worked fine. Can Anyone explain why simply modifying column did not work?" ]
[ "mysql", "sql", "database", "rdbms" ]
[ "Can not see “SQL Server Reporting Services” in PowerBI desktop save as menu", "When I get data from SQL Server Analysis Services database and finished designing report in Power BI desktop, in \"Save As\" menu, I can not see “SQL Server Reporting Services”.\n\nCan you help me activate this important option?\n\nI use the last version of Power BI desktop.\n\nThank you" ]
[ "powerbi-desktop" ]
[ "How does CloudFlare or CDNs in general work and can I force them to get my updated static content?", "I would like to turn CloudFlare on for my WordPress server, but I'm still making changes very frequently. CloudFlare says that it caches static files (javascript, css, images, etc), so I'm assuming that if I made changes to these files and saved them on my servers, they would not show up changed on theirs (at least for a while).\n\nIf I make changes to these files, will they eventually propagate to their servers? How long does that take?\n\nI've been doing the little trick of changing the src of my css files from \"my.css\" to \"my.css?v=1.1\" and \"my.css?v=1.2\" etc when I make changes so it forces your browser to get the newer version of the file because it is tricking it into thinking it's a new file. Will this also work with CloudFlare, or does it bypass this?\n\nThank you." ]
[ "html", "static", "cdn", "cloudflare" ]
[ "how to fetch value of all source url in array from given string", "{\n data = (\n {\n \"created_time\" = \"2011-09-28T07:29:37+0000\";\n from = {\n id = 100002944043966;\n name = \"alok sinha\";\n };\n height = 500;\n icon = \"https://s-static.ak.facebook.com/rsrc.php/v2/yz/r/StEh3RhPvjk.gif\";\n id = 114750595299741;\n images = (\n {\n height = 2048;\n source = \"https://fbcdn-sphotos-a.akamaihd.net/hphotos-ak-ash4/s2048x2048/300035_114750595299741_1543248164_n.jpg\";\n width = 2048;\n },\n {\n height = 500;\n source = \"https://fbcdn-sphotos-a.akamaihd.net/hphotos-ak-ash4/300035_114750595299741_1543248164_n.jpg\";\n width = 500;\n },\n {\n height = 500;\n source = \"https://fbcdn-sphotos-a.akamaihd.net/hphotos-ak-ash4/300035_114750595299741_1543248164_n.jpg\";\n width = 500;\n },\n {\n height = 480;\n source = \"https://fbcdn-sphotos-a.akamaihd.net/hphotos-ak-ash4/s480x480/300035_114750595299741_1543248164_n.jpg\";\n width = 480;\n },\n {\n height = 320;\n source = \"https://fbcdn-sphotos-a.akamaihd.net/hphotos-ak-ash4/s320x320/300035_114750595299741_1543248164_n.jpg\";\n width = 320;\n },\n {\n height = 180;\n source = \"https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/300035_114750595299741_1543248164_a.jpg\";\n width = 180;\n },\n {\n height = 130;\n source = \"https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/300035_114750595299741_1543248164_s.jpg\";\n width = 130;\n },\n {\n height = 130;\n source = \"https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/s75x225/300035_114750595299741_1543248164_s.jpg\";\n width = 130;\n }\n );\n link = \"https://www.facebook.com/photo.php?fbid=114750595299741&set=a.114750591966408.20279.100002944043966&type=1\";\n picture = \"https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/300035_114750595299741_1543248164_s.jpg\";\n position = 1;\n source = \"https://fbcdn-sphotos-a.akamaihd.net/hphotos-ak-ash4/300035_114750595299741_1543248164_n.jpg\";\n \"updated_time\" = \"2011-09-28T07:29:38+0000\";\n width = 500;\n }\n );\n paging = {\n next = \"https://graph.facebook.com/114750591966408/photos?value=1&redirect=1&limit=25&after=MTE0NzUwNTk1Mjk5NzQx\";\n };\n}" ]
[ "iphone", "objective-c", "ios" ]
[ "How to test if Canvas.toBlob() failed", "Using canvas.toBlob(callback, ...), I am converting several large canvas elements (2048x2048 pixels) to png.\n\nHowever, at least in Chrome, the callback is not always called. There are no errors generated in Chrome Devtools.\n\nMy Questions:\n\n\nIs there are way to check if toBlob() failed, aside from timing out after x seconds?\nUnder which conditions does toBlob() fail? How do I know which condition was not met / How do I get an error message?\n\n\n\n\nThe code I am using:\n\nfunction trigger_browser_download(blob, fileName) { \"use strict\";\n var url = window.URL.createObjectURL(blob);\n a.href = url;\n a.download = fileName;\n a.click();\n window.URL.revokeObjectURL(url);\n};\n\nfunction download_canvas(canvas, filename) { \"use strict\";\n canvas.toBlob(function(blob) {\n debugger; // not always reached\n if(blob instanceof Blob) {\n trigger_browser_download(blob, filename);\n } else {\n console.error(\"error generating blob\");\n }\n }, 'application/octet-binary'); \n}\n\nfor(var i = 0; i < 10; ++i) {\n var canvas = document.createElement('canvas');\n canvas.height = 2048;\n canvas.width = 2048;\n download_canvas(canvas, i + \".png\");\n\n}" ]
[ "javascript", "canvas", "html5-canvas" ]
[ "Bigquery Dataset/Table's metadata", "Is there a way to programmatically (Java API) get Bigquery's table and dataset metadata? \n\nI was trying to create a report on the size, creator, creation time of each tables/datasets and want to avoid doing it manually. We have a lot of tables." ]
[ "google-bigquery" ]
[ "How to find associated rows when I only know the primary key?", "I am trying to find all rows which contain the same value in one column, but I only know the primary key. I have read through the SQL tutorial at W3Schools, but I still can't figure it out. \n\nID First Last\n111 Bob Smith\n222 Tom Smith\n333 Alex Jones\n444 Peter Williams\n\n\nFor example if I only know the ID 111, how do I query with that and find everyone who shares the same last name? Meaning I would want the following two records returned:\n\nID First Last\n111 Bob Smith\n222 Tom Smith" ]
[ "sql" ]
[ "Data Manipulation - shifting rows manipulation", "I have a Pandas DataFrame and I want to loop through the column 1 and if the column value is vergleich I shift the row cells once to the right. \n\nHere is my attempt:\n\nfor i,j in df.iterrows():\n if j[1]== \"stringobject\":\n df.shift(periods=1,axis=1)\nprint(df)\n\n\nWhen I print df, I do not see any changes. Kindly advise how to go about this" ]
[ "python", "pandas", "dataframe", "data-manipulation", "shift" ]
[ "Looping up inheritance to get overridden properties", "Consider the following classes\n\npublic class Super\n{\n public abstract string Foo { get; }\n}\n\npublic class Base : Super\n{\n public override string Foo { get { return \"Foo\"; } }\n}\n\npublic class Sub : Base\n{\n public override string Foo { get { return \"Bar\"; } }\n}\n\n\nHow can I, knowing the Type of Sub and with the PropertyInfo of Foo, loop through both declarations of Foo to invoke PropertInfo.GetValue(this) and therefore get both unique strings" ]
[ "c#", "generics", "inheritance", "properties" ]
[ "XCode: Different UI for different device sizes", "I would like to apply design A for iPhone3.5in, and design B for all other iPhones. In XCode storyboard, I thought changing the size constraints was there for this purpose but they don't seem to have any effect. More specifically, I want to apply the first design below for iPhone3.5in, and the second one for all the other iphone devices. Someone suggested that there is no way to do it in XCode and I should do it programmatically but I believe there must be a way. Thank you so much for your help in advance!" ]
[ "ios", "iphone", "xcode" ]
[ "Can scala's type generics figure out match/cases?", "I have some code that is similar to the following: \n\nclass testClass {\n class A(val next:Option[A]){\n def printA=println(\"A called\")\n\n }\n\n class B(val someValue:Int){\n def printB=println(\"B called with value \"+someValue)\n }\n\n def printStuff[T](obj:T):Any={\n obj match{\n case a:A=>{ a.printA\n return new A(Some(a))\n }\n case b:B=>{ b.printB\n return if (b.someValue==0) new B(0) else\n printStuff(new B(b.someValue-1))\n }\n }\n }\n\n\nHere, I'd like for my method printStuff to return an object with the same type as the input. However, when trying to compile this, I get the following error :\n\nerror: type mismatch;\nfound : a.type (with underlying type testClass.this.A)\nrequired: T\nreturn a\n\n\nwith a similar error for return b . I realise that I could set the return type to Any,but in my \"real\" code, I am applying the function in a recursive descent manner, so it would force me to add quite a few asInstanceOfs, something which I'd like to avoid. \n\nIs it possible to get Scala's type system to figure out what I'm trying to write, without having to completely rewrite the function? \n\nEDIT: I've tried to edit my example to bring out things that might be important in my real code :\n\n\nthe fact that it's recursive\nthe fact that its return type depends on one of the arguments." ]
[ "scala", "types" ]
[ "C++ polymorphism function taking void * and other pointer type as argument: is it considered ambiguous?", "C++ polymorphism functions taking void * and other pointer type as their arguments: is it considered ambiguous?\n\nI am worried that since any pointer can be cast to void*, will the 2nd call of bar below executes void bar(void*) instead of my expected void bar(int*), in the program below?\n\nI tested on my g++, and it runs as expected (i.e. int* won't be cast to void*). But can anyone comment/answer on/to this question in the respect of C++ language specifications?\n\nfoo.h:\n\nclass Foo {\npublic:\n void bar(void *);\n void bar(int *);\n};\n\n\nmain.cpp:\n\n...\nstruct A *p1;\nint *p2;\nFoo foo;\n...\nfoo.bar(p1);\nfoo.bar(p2);\n\n\nFurthermore, say, bar are now virtual polymorphism functions, taking void* argument as the 1st form, and base abstract class pointer argument as the 2nd form. Will a call with a derived class pointer as the argument execute the 1st form or the 2nd form? i.e. Will the derived class pointer been cast to its base abstract class pointer (and thus the 2nd form will be in action), or will it be cast to void * (and thus the 1st form will be in action) before calling bar()?" ]
[ "c++", "overloading", "implicit-conversion", "void-pointers", "pointer-conversion" ]
[ "Replace stock clipboard on Android", "Os there a way to replace the system clipboard in Android? I'd like to build a custom open source clipboard that once a user copies some text then this text should be translated by the clipboard." ]
[ "android", "clipboard", "translate" ]
[ "Laravel elFinder Image upload issue", "I used this package on my app to upload images and files, in local it worked just fine but since i moved my app to server i'm getting this error:\n\n\n Call to a member function hasPermissionTo() on null\n in AdminMiddleware.php (line 22)\n\n\nI'm using TinyMCE 4 with Laravel 5.4\n\nHere is my AdminMiddleware\n\n<?php\n\nnamespace App\\Http\\Middleware;\n\nuse Closure;\nuse Illuminate\\Support\\Facades\\Auth;\nuse App\\User;\n\nclass AdminMiddleware\n{\n /**\n * Handle an incoming request.\n *\n * @param \\Illuminate\\Http\\Request $request\n * @param \\Closure $next\n * @return mixed\n */\n public function handle($request, Closure $next)\n {\n $user = User::all()->count();\n if (!($user == 1)) {\n if (!Auth::user()->hasPermissionTo('Administer roles & permissions')) //If user does //not have this permission\n {\n abort('401');\n }\n }\n\n return $next($request);\n }\n}\n\n\nand here is my script on post create page\n\n@section('scripts')\n<script type=\"text/javascript\" src=\"{{asset('js/select2.min.js')}}\"></script>\n<script>\n var editor_config = {\n path_absolute : \"/\",\n selector: \"textarea.my-editor\",\n plugins: [\n \"advlist autolink lists link image charmap print preview hr anchor pagebreak\",\n \"searchreplace wordcount visualblocks visualchars code fullscreen\",\n \"insertdatetime media nonbreaking save table contextmenu directionality\",\n \"emoticons template paste textcolor colorpicker textpattern codesample\"\n ],\n toolbar: \"insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media | emoticons charmap | code codesample | forecolor backcolor\",\n relative_urls: false,\n remove_script_host: false,\n file_browser_callback : function(field_name, url, type, win) {\n var x = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth;\n var y = window.innerHeight|| document.documentElement.clientHeight|| document.getElementsByTagName('body')[0].clientHeight;\n\n var cmsURL = editor_config.path_absolute + 'laravel-filemanager?field_name=' + field_name;\n if (type == 'image') {\n cmsURL = cmsURL + \"&type=Images\";\n } else {\n cmsURL = cmsURL + \"&type=Files\";\n }\n\n tinymce.activeEditor.windowManager.open({\n file: '<?= route('elfinder.tinymce4') ?>',// use an absolute path!\n title: 'File Manager',\n width: 900,\n height: 450,\n resizable: 'yes'\n }, {\n setUrl: function (url) {\n win.document.getElementById(field_name).value = url;\n }\n });\n }\n };\n\n tinymce.init(editor_config);\n</script>\n<script>\n {!! \\File::get(base_path('vendor/barryvdh/laravel-elfinder/resources/assets/js/standalonepopup.js')) !!}\n</script>\n@endsection\n\n\nDoes anyone know why I have this issue and how to fix it?" ]
[ "php", "laravel" ]
[ "How to add points with manual colour to a plot in R", "I have created a complex plot g with ggplot with a number of series with different colors. Now, I'd like to add a few points with a manual color, without bothering about the colors of all the pre-existing series.\n\nFor example, if I do this\n\ng + geom_point(data = dd, aes_string(x = xseries, y = yseries, color = \"red\" ) )\n\n\nit doesn't work, obviously, because it's expecting a factor variable because it wants to associate colors to values of a variable in the data frame dd.\nAnother trial was to assign a variable to those points (say redpoint, so the data frame ddwould contain columns \"xseries\", \"yseries\" and \"redpoint\") like this:\n\ng + geom_point(data = dd, aes_string(x = xseries, y = yseries, color = \"redpoint\" ) )\n\n\nNow, people advice to use scale_color_manual to manually define colors. However, if I do that I should explicitly state all the colors of the data series that are in g, which is quite problematic as they are several tens and it took me a while to assign them the colors I want.\nSo, is there a method to add points with a manual color without specifying all the colors of the pre-existing plot?" ]
[ "r", "ggplot2" ]
[ "Symfony on Apache permission issues", "I have made a lot of Symfony apps that work in production, but recently tried deploying one to Ubuntu 16 for the first time. var/logs/prod.log shows errors about not being able to find classes, so of course the app won't run.\n\nI can \"fix\" this with chmod 777 /var/www/ -R, and everything starts working. Surely that's not safe... How can I fix this the right way?\n\nNote: I am currently not logged in as a user but as root.\n\n*EDIT\nThe app will not run after chmod 777 /var/www/var -R to change permissions for chache and logs, but only if I change the permissions for all the folders of the entire app." ]
[ "php", "apache", "symfony", "ubuntu", "permissions" ]
[ "PowerShell zip file extraction catching exceptons", "I am having the following code in Power Shell ( windows Server 2016 TP3 )\n\n$zipFrom = Get-Item($zipfilepath);\n$destTo=Get-Item($destination)\n[System.IO.Compression.ZipFile]::ExtractToDirectory($zipfrom,$destTo)\n\n\nThe problem is that I get the dreaded 260 character file limit error . The question is how do i ignore error and continue with the extraction ?" ]
[ ".net", "windows", "powershell" ]
[ "Retrieving the name of the Submit Button with Flask", "I have a front end page which has a a set of submit buttons and the snippet is:\n\n<div class=\"table-outer\">\n<div class=\"table-inner\">\n<table>\n<form action=\"addtocart\" method=\"post\" > \n<tr><td>IIT Jee Prep Combo pack</td><td><input type=\"submit\" name=\"IIT Jee Prep Combo pack \" value=\"Add to Cart\"></td></tr>\n</form>\n<form action=\"addtocart\" method=\"post\"> \n<tr><td>GRE Prep Combo Pack</td><td><input type=\"submit\" name=\"GRE Prep Combo Pack\" value=\"Add to Cart\"></td></tr>\n</form>\n<form action=\"addtocart\" method=\"post\"> \n<tr><td>GATE Prep Combo Pack </td><td><input type=\"submit\" name=\"GATE Prep Combo Pack\" value=\"Add to Cart\" ></td></tr>\n</form>\n<form action=\"addtocart\" method=\"post\"> \n<tr><td>CAT Prep Combo Pack</td><td><input type=\"submit\" name\"CAT Prep Combo Pack\" value=\"Add to Cart\"></td></tr>\n</form>\n<form action=\"addtocart\" method=\"post\">\n<tr><td>Civil Services Prep Combo Pack</td><td><input type=\"submit\" name=\"Civil Services Prep Combo Pack\" value=\"Add to Cart\"></td></tr>\n</form> \n</table>\n</div>\n</div>\n\n\nI have a Flask server handling all the requests. Now, I want to store the name of the\n book in a file when the user clicks. The name of the book is stored in the name attribute of the form tag. How can I perform this. If it were a text box, I did it with request.form['name']. How can the same be performed in case of a submit button" ]
[ "python", "html", "flask" ]
[ "HiveServer2 - Not starting / working", "I've installed Hadoop 2.7.2 and Hive 2.0.1 on local Ubuntu local VM. Hive is working fine on the shell and able to create tables & load data. The problem is with the hiveserver which I want to retrieve data from clients as well as load data from Java program.\n\nWhen I try to start HiveServer2 nothing is happening as following.\n\nhadoop_user@ubuntu:~$ $HIVE_HOME/bin/hive --service hiveserver2\n\nI checked in hive-site.xml and all configurations seem to be fine.\n\nAny idea what is going on? Appreciate your help.\n\nThanks in advance." ]
[ "hadoop", "hive", "hiveql", "hadoop2" ]
[ "Fatal error: openssl_random_pseudo_bytes", "I am building a web page with login feature and I came up with this error:\n\n\n Fatal error: Call to undefined function openssl_random_pseudo_bytes() in ...Users_model.php\n\n\nThis is a snippet of source code where it leads(line 2):\n\nif(password_verify($password, $row->password)) {\n $token = bin2hex(openssl_random_pseudo_bytes(21));\n $this->insert_token_user($row->id, $token);\n $res = [\n 'id' => $row->id,\n 'first_name' => $row->first_name,\n 'last_name' => $row->last_name,\n 'email' => $row->email,\n 'token' => $token\n ];\n\n\nAnd this is the code where it happens in debug (line 3):\n\njQuery.ajax({\n beforeSend: function(xhr) {\n xhr.setRequestHeader(\"Authorization\", \"Basic \" + btoa(email + \":\" + password));\n },\n url: URL + 'user/login',\n contentType: 'application/json',\n type: 'GET',\n success: function(data, status, response) {\n },\n error: function(xhr, status, error) {\n var err = JSON.parse(xhr.responseText);\n responseHandling(err);\n }\n\n\nThe screenshots of errors from debugger:\n\n...\n\n\n\nI am running Windows 10 x64 and MAMP 3.2.2 as localhost.\nMAMP settings: php 5.6.24 , cache off.\n\nThis is what I did to try to solve the problem:\n\n\nremoved semicolon in extension=php_openssl.dll \nin this folder C:\\MAMP\\conf\\php5.6.24\\php.ini\nand here C:\\MAMP\\conf\\php5.6.0\\php.ini\nmoved both php.ini to C:\\MAMP\\bin\\php\\php5.6.0 and C:\\MAMP\\bin\\php\\php5.6.24 folders \n\n\nThe reason for doing this in these two places is because Chrome extension \"Wappalyzer\" shows this page as PHP version 5.6.0. \n\nerror I get when I restart my PC with semicolons removed" ]
[ "php", "ajax" ]
[ "Logging logic and data errors in MVC3 with Elmah", "I have a Service layer in my MVC3 app, which plays the role of a Repository among other things, as a layer between my Data layer and the actual web application. I have coded all my GetById methods to be robust, using FirstOrDefault and not just First, because the Id is passed in a URL and cannot be guaranteed to be a valid Id.\n\nI now find myself where I'm doing a FirstOrDefault, then only proceeding if the result is not null. I would like to log the event when it is null, and then proceed to do nothing etc. Now, I am already using Elmah to log unhandled exceptions, and I have very little experience with exception handling etc. in MVC3, but it occurs to me that it might be better for me to use a simple First, with Elmah logging the exception if no entity is found.\n\nHow should I approach this scenario, where an invalid Id is quite definitely an logic exception, but not a low level CLR exception? This is not like when somebody is asked to enter an Id and no entity is found for their search term, which is a normal logic result." ]
[ "entity-framework", "asp.net-mvc-3", "exception-handling", "elmah" ]
[ "Can Java GC local variables that are in scope but no longer used?", "In the following code:\n\nvoid method() {\n HeavyObject heavy = new HeavyObject();\n doStuffWith(heavy);\n doOtherStuff();\n}\n\n\n...can heavy be garbage collected before or during doOtherStuff()? JLS references preferred, though actual experiments would be cool too.\n\nMy goal is to determine whether or not heavy = null is strictly useless, or might conceivably have some benefit." ]
[ "java", "garbage-collection" ]
[ "undefined behaviour error but code works fine", "Output -\n\nsuper customer for product1\n\ngood customer for product2\n\npotential customer for product3\n\nundefined\n\nQuestion - Why am I getting that undefined at the end?\n\nvar customer = {\n firstname: \"\",\n lastname: \"\",\n moneySpent: [],\n getTotal: function(){\n var sum = 0;\n for(let i = 0; i < 3; i++){\n sum += this.moneySpent[i];\n }\n return sum;\n },\n getLevel: function(){\n var level = \"\";\n for(let i = 0; i < 3; i++){\n if(this.moneySpent[i] >= 1000){\n level = \"super\";\n }else if(this.moneySpent[i] >= 500 && this.moneySpent[i] < 1000){\n level = \"good\";\n }else{\n level = \"potential\";\n }\n console.log(level + \" customer for \" + \"product\" + (i+1));\n }\n }\n};\n\n\n\nvar customer1 = Object.create(customer);\ncustomer1.firstname = \"First1\";\ncustomer1.lastname = \"Last1\";\ncustomer1.moneySpent = [1080.89, 783.23, 68.09];\n\nconsole.log(customer1.getLevel());" ]
[ "javascript" ]
[ "JDBC Pagination: vendor specific sql versus result set fetchSize", "There are a lot of different tutorials across the internet about pagination with JDBC/iterating over huge result set. \nSo, basically there are a number of approaches I've found so far:\n\n\nVendor specific sql\nScrollable result set (?)\nHolding plain result set in a memory and map the rows only when necessary (using fetchSize)\n\n\n The result set fetch size, either set explicitly, or by default equal\n to the statement fetch size that was passed to it, determines the\n number of rows that are retrieved in any subsequent trips to the\n database for that result set. This includes any trips that are still\n required to complete the original query, as well as any refetching of\n data into the result set. Data can be refetched, either explicitly or\n implicitly, to update a scroll-sensitive or\n scroll-insensitive/updatable result set.\n\nCursor (?)\nCustom seek method paging implemented by jooq\n\n\nSorry for messing all these but I need someone to clear that out for me.\nI have a simple task where service consumer asks for results with a pageNumber and pageSize. Looks like I have two options: \n\n\nUse vendor specific sql\nHold the connection/statement/result set in the memory and rely on jdbc fetchSize\n\n\nIn the latter case I use rxJava-jdbc and if you look at producer implementation it holds the result set, then all you do is calling request(long n) and another n rows are processed. Of course everything is hidden under Observable suggar of rxJava. What I don't like about this approach is that you have to hold the resultSet between different service calls and have to clear that resultSet if client forgets to exhaust or close it. (Note: resultSet here is java ResultSet class, not the actual data)\n\nSo, what is recommended way of doing pagination? Is vendor specific sql considered slow compared to holding the connection?\n\nI am using oracle, ScrollableResultSet is not recommended to be used with huge result sets as it caches the whole result set data on the client side. proof" ]
[ "java", "oracle", "jdbc", "pagination" ]
[ "How to parse individual likes from FQL query response?", "I am using FQL to find the likes of a user. It is returning all the likes as CSV. For example, this the response for my likes:\n\nArray ( [0] => Array ( [uid] => XXXXXXX [name] => XXXXXXX [movies] => Pi, 12 Angry Men, The Shining, Lock, Stock and Two Smoking Barrels ) )\n\n\nI tried using php's explode at comma to parse the individual movie names but that leads to an error.\nOver here, the last movie I like is \"Lock, Stock and Two Smoking Barrels\" which has a comma in its name. So, how do I parse this movie name? I can't split at comma, because then I will get two movies - \"Lock\" ; \"Stock and Two Smoking Barrels\"." ]
[ "php", "facebook", "facebook-fql", "facebook-php-sdk" ]
[ "How to connect ethereum smart contract with iOS app", "I want to connect smart contract with iOS app using webView. I researched so many but didn't get any thing. How to call smart contract from the iOS using swift." ]
[ "swift", "ethereum", "solidity" ]
[ "i cant access my files in media file system in ubuntu", "enter image description here cant access the directories in media file system on my mobile via my Ubuntu 14.04 \ncan anyone help me?" ]
[ "ubuntu-14.04", "user-permissions" ]
[ "How to migrate IDs from JOIN table into foreign key column in MySQL", "I have the following tables in my MySQL database:\n\nCREATE TABLE `User` (\n `id` char(25) CHARACTER SET utf8 NOT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `email_UNIQUE` (`email`(191))\n);\n\nCREATE TABLE `Post` (\n `id` char(25) NOT NULL,\n `authorId` char(25) DEFAULT NULL,\n PRIMARY KEY (`id`),\n KEY `authorId` (`authorId`),\n CONSTRAINT `Post_ibfk_1` FOREIGN KEY (`authorId`) REFERENCES `User` (`id`)\n);\n\nCREATE TABLE `_PostToUser` (\n `A` char(25) CHARACTER SET utf8 NOT NULL,\n `B` char(25) CHARACTER SET utf8 NOT NULL,\n UNIQUE KEY `PostToUser_AB_unique` (`A`,`B`),\n KEY `B` (`B`),\n CONSTRAINT `_PostToUser_ibfk_1` FOREIGN KEY (`A`) REFERENCES `Post` (`id`) ON DELETE CASCADE,\n CONSTRAINT `_PostToUser_ibfk_2` FOREIGN KEY (`B`) REFERENCES `User` (`id`) ON DELETE CASCADE\n);\n\n\nThe relationship between User and Post right now is managed via the _PostToUser JOIN table.\n\nHowever, I want to get rid of this extra JOIN table and simply have a foreign key reference from Post to User, so I ran this query to create the foreign key:\n\nALTER TABLE `Post` ADD COLUMN `authorId` char(25);\nALTER TABLE `Post` ADD FOREIGN KEY (`authorId`) REFERENCES `User` (`id`);\n\n\nNow, I'm wondering what SQL query I need to run in order to migrate the data from the JOIN table to the new authorId column? If I understand correctly, I need a query that reads all the rows from the _PostToUser relation table and for each row:\n\n\nFinds the respective Post record by looking up the value from column A\nInserts the value from column B as the value for authorId into that Post record\n\n\nNote that I am aware that this changes the relationship from m-n and restricts it to 1-n: One post can at most have one author. One author/user can write many posts.\n\n\n\nI'm basically looking for the equivalent of this PostgreSQL statement:\n\nUPDATE \"Post\" post\nSET \"authorId\" = post_to_user.\"B\"\nFROM \"_PostToUser\" post_to_user \nWHERE post_to_user.\"A\" = post.\"id\";" ]
[ "mysql", "sql" ]
[ "How to efficiently use a numpy function in a cython loop?", "I would to know if their is a way to call a numpy function efficiently in a cython code ? It seems that the communication with python can be very costly in a loop.\n\nExemple: \n\nimport numpy as np\n\ncimport numpy as np\n\n\ncimport cython \nDTYPE = np.float\nITYPE = np.int\nctypedef np.float_t DTYPE_t\nctypedef np.int_t ITYPE_t\n\n\ndef func(A,B):\n return func_c(A,B)\n\n\[email protected](True) \[email protected](False)\[email protected](False)\n\ncdef np.ndarray[DTYPE_t,ndim=2] func_c(np.ndarray[DTYPE_t,ndim=2] A,np.ndarray[DTYPE_t,ndim=2] B):\n\n\n cdef np.ndarray[DTYPE_t,ndim=2] P1=np.matrix(np.zeros((3,3)))\n\n for t in range(10):\n\n P1=np.linalg.inv(A) \n P2=np.dot(P1,B)\n\n return P2" ]
[ "numpy", "loops", "cython" ]
[ "Adding JScrollPane on a JList without using JPanel", "I need help on my program. I need to have a JScrollPane on a JList without putting JList on a JPanel.\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport java.util.*;\nimport javax.swing.*;\n\npublic class refurbished extends JFrame implements ActionListener {\n ArrayList<String> names;\n JButton add;\n JTextField inputName;\n JScrollPane scrollName;\n JList nameList;\n\npublic refurbished() {\n setSize(700,500);\n setLayout(null);\n\n names = new ArrayList<String>();\n\n add = new JButton(\"Add\");\n add.setBounds(25,200,90,30);\n add.setBackground(Color.WHITE);\n add.addActionListener(this);\n\n inputName = new JTextField();\n inputName.setBounds(150,350,150,30);\n\n nameList = new JList(names.toArray());\n\n scrollName = new JScrollPane(nameList);\n scrollName.setBounds(150,75,150,200);\n\n getContentPane().add(add);\n getContentPane().add(inputName);\n getContentPane().add(scrollName);\n\n setVisible(true);\n}\n\npublic void actionPerformed (ActionEvent buttonclick) {\n if (buttonclick.getSource() == add) {\n names.add(inputName.getText().toLowerCase());\n nameList = new JList(names.toArray());\n scrollName = new JScrollPane(nameList);\n scrollName.setBounds(150,75,150,200);\n}\n}\n\npublic static void main (String[] args) {\n refurbished r = new refurbished();\n}\n\n\n}\n\nCan you help me? I really need your help because this is the only missing feature in my code.\n\nYour help is really appreciated." ]
[ "java", "swing", "jpanel", "jscrollpane", "jlist" ]
[ "c# about GC.Collect() Test", "Firstly,\n\nthanks someone can help me answer this question, really in my heart~ thanks\n\ncurrently I am learn something about Gc in c#, do some test\n\ncode there\n\nusing System;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n Person p = new Person();\n Person p1 = new Person();\n Person p2 = new Person();\n Person p3 = new Person();\n GC.Collect();\n }\n\n }\n\n public class Person\n {\n ~Person()\n {\n MessageBox.Show(\"destructor has call...\");\n }\n\n }\n}\n\n\nscenario one\n\nwhen I press button1 to new some object, then call Gc.Collect();\nbut nothing happen(I expect MessageBox will show 4 times)\n\nwhen I press button2 secondly ,MessageBox show...(I am confused)\n\ndo some one can explain it? (thanks)\n\nscenario two\n\ncode here\n\nusing System;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n public partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n Person p = new Person();\n Person p1 = new Person();\n Person p2 = new Person();\n Person p3 = new Person();\n }\n\n private void button2_Click(object sender, EventArgs e)\n {\n GC.Collect();\n }\n }\n\n public class Person\n {\n ~Person()\n {\n MessageBox.Show(\"destructor has call...\");\n }\n\n }\n}\n\n\nwhen I press button1 then press button2 \nthe MessageBox show....." ]
[ "c#", "garbage-collection" ]
[ "Can't figure out how to stop returning list inside of list (leetcode problem)", "Returning list inside of list (not desired)\nI keep returning a list inside of a list for the following LeetCode Problem 257. Binary Tree Paths, which is not what the problem wants. I always seem to run into this issue while solving traversal problems.\nHere is my current solution along with it's output.\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\n\nclass Solution:\n def binaryTreePaths(self, root: TreeNode, val: str="") -> List[str]:\n if not root:\n return ""\n val += str(root.val) + "->"\n if not root.left and not root.right:\n return val[:-2]\n return [path for path in [self.binaryTreePaths(root.left, val), self.binaryTreePaths(root.right, val)] if path]\n\nInput: [1,2,3,null,5]\nOutput: [["1->2->5"],"1->3"]\nExpected: ["1->2->5","1->3"]\nThings I've tried\n\nCreating a res variable and using res.extend()\n\nres = []\nres.extend(path for path in [self.binaryTreePaths(root.left, val), self.binaryTreePaths(root.right, val)] if path)\n\n\nUsing append instead of extend along with conditionals to try and filter out unwanted elements.\n\nI constantly run into this problem while solving traversal problems so if anyone here has a solution along with some general advice on how to develop an intuition on what's going wrong here and how to solve it in the future, I'd be extremely grateful for your help.\nEdit\nWell I kept working at trying to fix my solution and after about ~20 minutes, I came up with the following abomination.\nclass Solution:\n def binaryTreePaths(self, root: TreeNode, val: str="") -> List[str]:\n if not root:\n return ""\n val += str(root.val) + "->"\n if not root.left and not root.right:\n return val[:-2]\n r1 = self.binaryTreePaths(root.left, val)\n r2 = self.binaryTreePaths(root.right, val)\n if isinstance(r1, str):\n r1 = [r1]\n if isinstance(r2, str):\n r2 = [r2]\n for i in r1:\n if i == "":\n r1.pop(r1.index(i))\n for i in r2:\n if i == "":\n r2.pop(r2.index(i))\n return r1 + r2\n\nI'm by no means satisfied with my solution as is so if you know of a cleaner fix please continue to post your fix/advice." ]
[ "python", "python-3.x", "list", "return" ]
[ "How to delete strings that matches a word within the same file?", "I am seeking for a function or script that reads every line and seek for a duplicate or match in the same file to then delete it.\n\nThe uniq -u function does half the job. I was trying to use a while read with a grep. Some how it works but for some reason it's outputing twice the strings that it's looking for.\n\nThis is the code I have for now to identify the matching word. I did not come up yet with the code to then delete the matching word, but I would have used most likely sed\n\nfilename=$1\nwhile read line; do\n grep \"$line\" $filename\ndone < $filename\n\n\nand this is the file I have\n\nJonasB/JB\nAZ\nLeylaS/LS\nJB\nAmeliaZ/AZ\n\n\nThe expected result should be:\n\nJonasB/\"JB\"\n\"AZ\"\nLeylaS/LS\n\"JB\"\nAmeliaZ/\"AZ\"\n\n\nBut the result I have is this:\n\nJonasB/\"JB\"\n\"AZ\"\nAmeliaZ/\"AZ\"\n\"LeylaS/LS\"\nJonasB/\"JB\"\n\"JB\"\n\"AmeliaZ/AZ\"\n\n\nThe outcome I would like for this script would be:\n\nLeylaS/LS\n\nClarification\n\nThe previous example brought some confusion and I apologise for it.\n\nThis is other example:\n\necar/ElectricCar/EV\nElectricCar\nEV/ecar\nCar/ICE\nVan\nHybrid\nTruck/Van/MiniVan/BigCar\nElectricVan/ElectricTruck\n\n\nSo the FS would be /.\n\nThe lines 2 and 3 should be deleted, because they match line 1 fields\n\nLine 5 should be deleted with line 7, because it matches the second field\n\nThe output I expect to have is:\n\nCar/ICE\nHybrid\nElectricVan/ElectricTruck\n\n\nHope this clarifies better the issue." ]
[ "bash", "shell", "awk", "sed", "grep" ]
[ "Passing metadata when slicing subclass of DataFrame", "I've created a class which inherits from pandas.DataFrame. In this class metadata is added (not to columns, but to the class instance):\n\nclass MeasurementPoint(pandas.DataFrame):\n\n def __init__(self, data, metadata):\n super(MeasurementPoint, self).__init__(data)\n self.metadata = metadata\n\n # in order to return MeasurementPoint instead of DataFrame, define _constructor\n def _constructor(self):\n return MeasurementPoint\n\n\nIf I slice the class, I get a TypeError since __init__ is missing the required argument metadata. \nI've tried to modify _constructor to pass the metadata, but without succes.\nI've also tried to add the metadata to the class as an additional property (_metadata' = ['metadata']) as described here: http://pandas.pydata.org/pandas-docs/stable/internals.html, but to no avail.\n\nHow can I get the class MeasurementPoint to retain the metadata when it's being sliced?" ]
[ "python", "pandas" ]
[ "How to listen continuously to a socket for data in python?", "I open a socket which sends and receives data on a socket.\nI have the following code shown below to open a socket and then send information.\n\n# Socket Information\nhost = \"localhost\"\nport = 6800\n\n# Initailize the socket\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nsock.connect((host, port))\n\n\n# Method to send the data on the socket\n# This method is called periodically every 5 seconds to send the data\n\ndef send_data():\n sock.send((request_string).encode(\"utf-8\"))\n\n\nThe issue that I am currently facing. I want to be able to continuously listen for data and I am unsure on how to do it. I dont want to be blocking the other parts of my code as I am listening on the port. Do I need to do the listen on another thread? Is it just a simple while(1) loop which listens on the same port 6800.\n\nAny help for the implementation of the listen method would be appreciated." ]
[ "python", "sockets" ]
[ "Python Pyomo gets error: Constant objective detected, replacing with a placeholder to prevent solver failure", "I am trying to solve a mathematical programming problem with Pyomo\nHere is my code:\nmodel = AbstractModel()\n\n*####communities*\n\nmodel.I = set()\n\n*####suppliers*\n\nmodel.J = set()\n\nmodel.c = Param(model.J) \n\nmodel.p = Param(model.I) \n\nmodel.s = Param(model.J) \n\nmodel.e = Param(model.J) \n\nmodel.b = Param(model.I) \n\n\nDecision variables totally there are 19*6 = 114\nmodel.q = Var(model.I,model.J,domain = NonNegativeReals) #bought quantity \n\ndefinition of the objective function\ndef obj_expression(model): \n return sum(model.c[j]*sum(model.q[i,j] for i in model.I) for j in model.J) \n \n \nmodel.OBJ = Objective(rule=obj_expression)\n\n####q11+q12+q13...q1j >= pi\n\ndef cons_1(model, i): \n return sum(model.q[i,j] for j in model.J) >= model.p[i]\nmodel.vaccine_quantity = Constraint(model.I, rule = cons_1)\n\n\ntotal quantity of vaccine j smaller than the supply j\ndef cons_2(model,j):\n return sum(model.q[i,j] for i in model.I) <= model.s[j]\nmodel.supply = Constraint(model.J, rule = cons_2)\n\nbudget\ndef cons_3(model, i):\n return sum(model.q[i,j] for j in model.J) <= model.b[i]\n\nMy data:\nparam J : c s e :=\n\n"China 1" 10 1000 0.6\n\n"Russian" 10 700 0.92\n\n"UK" 3 2000 0.76\n\n;\n\nparam I : p b := \n"Andalucia" 845 40000\n\n"Aragón" 132 35000\n\n"Principado de Asturias" 275 10000\n\n"Comunitat Valenciana" 500 40000\n;\n\nI have reviewed several times, but I don't know where is the problem.\nThe warning is:\nWARNING: Constant objective detected, replacing with a placeholder to prevent\n solver failure.\nWARNING: Empty constraint block written in LP format - solver may error\n[ 0.05] Processing results\n Number of solutions: 1\n Solution Information\n Gap: 0.0\n Status: feasible\n Function Value: 0.0\n]" ]
[ "python", "mathematical-optimization", "pyomo" ]
[ "Dot file viewer for live updates from python (Through GraphViz)", "I'm trying to find a way to visualize a directed graph of nodes in a way such that I can run a script in Python that modifies the graph, and in turn, outputs a new graph. The goal is really to be able to programmatically add and remove edges from the graph in real time. \n\nMy current implementation is using GraphViz and Python 3.6 on a Windows box, and outputting it into a .dot file. I found a viewer online under a Github project by the name of \"gvuv\", but it doesn't support Python 3.6. \n\nMy graph is currently defined by a dictionary of sets, where each key in the dictionary is a node, and each value is a set containing all nodes with a directed edge. If anyone has a different way of viewing this information, please let me know as well.\n\nExample graph:\n\ngraph = { \"a\" : set(\"c\"),\n \"b\" : set(\"c\", \"e\"),\n \"c\" : set(\"a\", \"b\", \"d\", \"e\"),\n \"d\" : set(\"c\"),\n \"e\" : set(\"c\", \"b\"),\n \"f\" : set()\n }" ]
[ "python", "python-3.x", "graph", "graphviz", "dot" ]
[ "Error 403 on simple request with CURL / PHP", "this is my code, is a simple request using cURL:\n\n<?php\n$ch = curl_init();\n$url = \"http://pt.fakenamegenerator.com/gen-random-br-br.php\";\ncurl_setopt_array($ch, array(\n CURLOPT_URL => $url\n));\n\necho curl_exec($ch);\n\n\nWhen you run it, the following error appears:\n\nForbidden\n\nYou do not have permission to access / gen-random-en-br.php on this server.\n\nApache/2.2.15 (CentOS) Server at Port 80 pt.fakenamegenerator.com\n1\n\n\nHow do I solve my problem?\nThanks!" ]
[ "php", "curl" ]
[ "Error compiling basic java code", "New to java. Practicing coding by following a book.\n\nHeres my code:\n\nclass Motorcycle {\n\n\n //Three instance variables - make and color are strings. while a boolean refers to TRUE OR FLASE(in this case off or on)\n String make;\n String color;\n boolean engineState;\n\n void startEngine() {\n if (engineState == true)\n System.out.print(\"The engine is already on.\");\n else {\n engineState = true;\n System.out.print(\"The engine is now on.\");\n\n }\n\n void showAtts() {\n System.out.print(\"This motorcycle is a \" + color + \" \" + make);\n if (engineState ==true)\n System.out.print(\"The engine is on.\");\n else System.out.print(\"The engine is off.\");\n\n }\n}\n}\n\n\nWhen I compile I get 2 errors:\n\n1) illegal start of expression\n2) ; expected\n\nI can't pin point the problem. If anyone can direct me or hint me please do." ]
[ "java", "compiler-errors", "cmd" ]
[ "Is Array[String] not a subclass of Seq[String] in Scala?", "I wrote a method that accepts objects of all subclasses of Seq[String]. Unfortunately it won't accept an object of the type Array[String]. Is Array[String] not a subclass of Seq[String]?\n\nscala> def test[T <: Seq[String]](x: T) = {}\ntest: [T <: Seq[String]](x: T)Unit\n\nscala> val data = \"This is a test string\"\ndata: java.lang.String = This is a test string\n\nscala> test(data.split(\" \"))\n<console>:10: error: inferred type arguments [Array[java.lang.String]] do not conform to method test's type parameter bounds [T <: Seq[String]]\n test(data.split(\" \"))" ]
[ "arrays", "scala", "scala-collections", "seq" ]
[ "How to load data with ajax and jquery from external db with no page refresh", "I have got a problem with this small script. I would like to query db Content on a simple html page with no page refresh. \n\n <form method=\"get\" name=\"formrrv\" id=\"formrrv\">\n <input type=\"hidden\" name=\"calculate\" value=\"1\">\n <input type=\"hidden\" name=\"func\" value=\"rrvform\"> \n <div class=\"searchbox\"> \n <input type=\"checkbox\" value=\"0\" name=\"sb\"> no<br>\n <input type=\"checkbox\" value=\"1\" name=\"sb\"> yes<br> \n <script>\n $('input[type=\"checkbox\"][name=\"sb\"]').on('change', function() {\n $('input[type=\"checkbox\"][name=\"sb\"]').not(this).prop('checked', ! this.checked);\n });\n </script>\n\n <input type=\"checkbox\" value=\"1\" name=\"status\"> Single<br>\n <input type=\"checkbox\" value=\"2\" name=\"status\"> family<br>\n <script>\n $('input[type=\"checkbox\"][name=\"status\"]').on('change', function() {\n $('input[type=\"checkbox\"][name=\"status\"]').not(this).prop('checked', ! this.checked);\n });\n </script> \n<input id=\"maxage\" name=\"maxage\" value=\"\"> \n <input name=\"price\" id=\"price\" name=\"price\" value=\"\"> EUR\n <br>\n <button class=\"submit\" name=\"submit\" onclick=\"getPage();\">search</button> \n <br>\n </div>\n </form>\n <div id=\"output\">werwerwerwewerwer</div> \n <script> \n function getPage() {\n $('#output').html('Hole Daten');\n jQuery.ajax({ \n url: \"rrv2.php\", \n data: {\n calculate:'1', \n func:'rrvform', \n sb:sb, \n status:status, \n maxage:maxage, \n price:price\n }, \n type: \"get\",\n success:function(data){$('#output').html(data);}\n }); \n }\n </script>\n\n\nSo rrv2.php is defintely working if vars are transfered per get. Can someone please help?" ]
[ "javascript", "jquery", "ajax" ]
[ "Get the key of an array \"value\" for use in a function", "I have an array defined:\n\n$flatdata[\"body_font-family\"] = \"Arial\";\n\n\nI want to use that array value in a function:\n\nfunction display_name($input) {\n showmethekeyofthearrayvalue($input); // how can I get the key name here?\n}\n\necho display_name($flatdata[\"body_font-family\"]);\n\n\nSo that the output is:\n\nbody_font-family" ]
[ "php", "arrays" ]
[ "d3.js Error data.map is not a function", "I'm new with d3.js and I'm trying to build a bar chart with a json file. Here is my code :\n\n// scale to ordinal because x axis is not numerical\nvar x = d3.scaleBand().rangeRound([0, width]);\n\n//scale to numerical value by height\nvar y = d3.scaleLinear().range([height, 0]);\n\nvar chart = d3.select(\"#chart\")\n .append(\"svg\") //append svg element inside #chart\n .attr(\"width\", width + (2 * margin.left) + margin.right) //set width\n .attr(\"height\", height + margin.top + margin.bottom); //set height\nvar xAxis = d3.axisBottom(); //orient bottom because x-axis will appear below the bars\n\nvar yAxis = d3.axisLeft();\n\nd3.json(\"coucou.json\", function (error, data) {\n x.domain(data.map(function (d) {\n return d.time\n }));\n y.domain([0, d3.max(data, function (d) {\n return d.value\n })]);\n\n var bar = chart.selectAll(\"g\")\n .data(data)\n .enter()\n .append(\"g\")\n .attr(\"transform\", function (d, i) {\n return \"translate(\" + x(d.receive_date) + \", 0)\";\n });\n\n bar.append(\"rect\")\n .attr(\"y\", function (d) {\n return y(d.responses);\n })\n .attr(\"x\", function (d, i) {\n return x.rangeBand() + (margin.left / 2);\n })\n .attr(\"height\", function (d) {\n return height - y(d.responses);\n })\n .attr(\"width\", x.rangeBand()); //set width base on range on ordinal data\n\n bar.append(\"text\")\n .attr(\"x\", x.rangeBand() + margin.left)\n .attr(\"y\", function (d) {\n return y(d.responses) - 10;\n })\n .attr(\"dy\", \".75em\")\n .text(function (d) {\n return d.responses;\n });\n\n chart.append(\"g\")\n .attr(\"class\", \"x axis\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + height + \")\")\n .call(xAxis);\n\n chart.append(\"g\")\n .attr(\"class\", \"y axis\")\n .attr(\"transform\", \"translate(\" + margin.left + \",0)\")\n .call(yAxis)\n .append(\"text\")\n .attr(\"transform\", \"rotate(-90)\")\n .attr(\"y\", 6)\n .attr(\"dy\", \".71em\")\n .style(\"text-anchor\", \"end\")\n .text(\"responses\");\n});\n\n\nAnd my json file:\n\n[{\n \"data\": [{\n \"time\": \"11:30:00\",\n \"value\": 121863\n },\n {\n \"time\": \"11:35:00\",\n \"value\": 121822\n },\n {\n \"time\": \"11:40:00\",\n \"value\": 121528\n },\n {\n \"time\": \"11:45:00\",\n \"value\": 121288\n }\n ]\n}]\n\n\nWhen I load my html page, I have this error : TypeError: data.map is not a function on this line :\n\n x.domain(data.map(function (d) {\n return d.time\n }));\n\n\nI don't understand why. Did the syntax has changed with a new version ? But I don't find the way to write it...\n\nThanks for your help :)" ]
[ "javascript", "d3.js" ]
[ "Read one line at a time using shell", "I'm trying to create a shell script. It will read one line at a time, assign the values to macros, then run a query with macros. After query is done, it will read the second line, create macros, run queries...\nI developed the code below, but it will read all lines together then run the query. Should I use do i=1 to n ?\n\n#!/bin/sh\n$HOME/.profile\nfile=$1\n\nOutputTable=$2\n\nfile=rule_flg.txt\n\ncat $file|(\n read flg table_num rule_num\n\n while test \"$flg\" != \"\"\n do\n echo table_num is $table_num and rule_num is $rule_num \n echo time is `date`\n\n (here are some parameters of database)... -v flg=$flg -v table_num=$table_num -v rule_num=$rule_num -f query_1.sql &> query_1.log\n\n read flg table_num rule_num\n done\n )\n\n echo run finished!\nexit 0" ]
[ "sql", "shell" ]
[ "Converting Javascript Date getTime()", "I have a problem,which I can't find a solution.I have a MVC Project,where I work only in locale date ( Bulgarian Time GMT +2 ).I transfer my date in seconds and then in my javascript code I translate it in the seconds.Then I want to translate it again but I get 3 hours less.\n\nvar date = new Date(1970,0,1); \ndate.setSeconds(1476086900); // 10.10.2016 8:20 a.m\n\n\nThen when i transfer it with getTime(function) and divide it to 1000 to get seconds again I get aproximetly 10k seconds less - > 5 a.m.\n\nvar apprSeconds = date.getTime() / 1000 ;\n\n\napprSeconds is 1476076100.\n\nThe problem is that I get different values:\n\n1476086900\n1476076100\n\nThank you for your help." ]
[ "javascript", "asp.net-mvc", "date" ]
[ "jboss war deployed listener", "Is there a single listener one could implement to get a \"war deployed\" event?\n\nI know there is the ContextServletListener. \nBut it has to be 'attached' for each component (several web.xml files).\n\nAs a fallback, if I use ContextServletListener, how can I tell that the last component has been deployed?\n\nAs a side note: I need to be aware of a hot deploy when it finishes." ]
[ "jboss", "hotdeploy" ]
[ "How to print the sum of the first and last element, second and second last and so on.., of an array after you input the elements using pointers?", "I got to this point which does what i intended it to but i need to incorporate pointers, which is what i need help with.\n#include <iostream>\nusing namespace std;\nint main()\n{\n int a[50],n,i,j;\n {\n cout<<"Input number of elements: "<<endl;\n cin>>n;\n}\ncout<<"Input elements: ";\nfor(i=0; i<n; i++)\n cin>>a[i];\ncout<<"Array is:"<<endl;\nfor(i=0; i<n; i++)\n cout<<a[i]<<endl;\n\n for(i=0,j=n-1;i<j;i++,j--)\n {\n a[i]=a[i]+a[j];\n }\n for(i=0;i<n/2;i++)\n\n cout<<a[i]<<",";\n return 0;\n}\n\nThis prints:\nExample 1,2,3,4,5,6 -----> 7 7 7" ]
[ "c++", "arrays", "sum" ]
[ "Nuxt Failed to execute ‘appendChild’ on ‘Node’ when trying to get window size", "The problem is that the project must be transferred to Nuxt and some of the code does not work. Namely, the size of the screen must perform actions with the text. Since Nuxt is an SSR, the code cannot be executed on the server side because it does not know the size of the window.\n\nCan I somehow fulfill this idea so that everything works?\nI have a project with nuxt and i18n\n\n[nuxt] Error while initializing app DOMException: Failed to execute 'appendChild' on 'Node': This node type does not support this method.\n at Object.Je [as appendChild] \n\n\nthis my component vue\nThis code is an example of what causes an error.\n\n<template>\n <section>\n <div> \n <h2 class=\"subtitle\" v-html=\"filterHeadSlogan\"></h2> \n </div>\n </section>\n</template>\n<script>\n export default {\n name: 'testapp',\n data() {\n return {\n filterHeadSlogan: '',\n windowWidth: 0\n }\n },\n methods: {\n getWindowWidth(event) {\n this.windowWidth = document.documentElement.clientWidth\n var str = \"<i>HELLO WORLD</i>\"\n if (this.windowWidth >= 960) {\n this.filterHeadSlogan = str\n } else {\n this.filterHeadSlogan = str.replace(/<\\/?[^>]+(>|$)/g, '')\n }\n }\n },\n mounted() {\n this.$nextTick(function () {\n window.addEventListener('resize', this.getWindowWidth);\n //Init\n this.getWindowWidth()\n })\n }\n\n }\n</script>" ]
[ "vuejs2", "nuxt.js" ]
[ "[Firebase Analytics - Selective tracking of screens", "I have a react native app for ios and android. \nIs it possible disable auto tracking of certain activities and viewcontrollers? \n\nLike for example in my android app, I have 4 activities there and I want to track 2 only." ]
[ "android", "firebase", "react-native" ]
[ "How to do a \"join\" with an anonymous scope in ruby", "Hey guys (and girls ^^) !!!\n\nDoes sommebody knows how to do a \"join\" with an anonymous scope in ruby ???\nWith a named scope you just have to add \":joins =>.....\" but i can't really find the way to do it with anonymous ones ... .\n\nThx in advance for the help ;)" ]
[ "ruby-on-rails", "ruby", "named-scope" ]
[ "Clear button only makes counter JLabel blank but does not reset it.", "I have made this application: \n\n\n\nFor example when I click on the clear button when the counter JLabel (pointsAvailable) is 19 then the counter JLabel goes blank as expected, however when I start adding points again it starts from 19 not 40 as set on the start. I would like to make it to reset back to 40 instead of just making it blank\n\nCode for the clear button\n\nprivate void JButtonActionPerformed(java.awt.event.ActionEvent evt) { \n speedPoints.setText(\"\");\n attackPoints.setText(\"\");\n defencePoints.setText(\"\");\n powerPoints.setText(\"\");\n agilityPoints.setText(\"\");\n focusPoints.setText(\"\");\n availablePoints.setText(\"\");\n} \n\n\nCode for Jlabel counter \n\n public class addingPointsUI extends javax.swing.JFrame {\nint pointsAvailable=40;\n int speed=0;\n int power=0;\n int focus=0;\n int agility=0;\n int defence=0;\n int attack=0;\n\n\nCode for buttons +/-: to allow me to add or decrease value \"example power - button\"\n\nprivate void powerMinusActionPerformed(java.awt.event.ActionEvent evt) { \n if (power > 0 ){\n if (pointsAvailable <= 0) {\n JOptionPane.showMessageDialog(null, \"You are out of available points\");\n return;\n }\n power = power - 1;\n\n pointsAvailable = pointsAvailable +1;\n\n availablePoints.setText(String.valueOf(pointsAvailable));\n\n powerPoints.setText(String.valueOf(power));\n\n }else {\n\n JOptionPane.showMessageDialog(null,\"You cannot take anymore points from Power\");\n }\n}\n\n\nThank your for your kind replies." ]
[ "java", "swing", "counter", "jlabel" ]
[ "height of page on scrolling", "How do I get the height of the page on scroll?\n\nIs it possible to determine how much the user has scrolled the page and determine the position of length that it covered.\n\nI have tried:\n\nvar scroll=$wnd.scrollTop \n\n\nin JavaScript but it is giving result undefined?\n\nAm I doing it wrong?" ]
[ "javascript", "gwt", "scrollbar" ]
[ "How to do insertion with JPA OneToOne relationship using ORACLE database?", "I'm having a problem with JPA OneToOne relationship, and I spent 4 days trynig to resolve it but with no success.\nFirst of all, seeing that oracle does not support Generate.Auto for primary key, we have to create trigger before insertion using a sequence.\nAnd here is my 2 tables:\n\nCREATE TABLE address (\n ID INTEGER PRIMARY KEY,\n CITY varchar(50) DEFAULT NULL,\n COUNTRY varchar(50) DEFAULT NULL,\n STREET varchar(50) DEFAULT NULL,\n SUBURB varchar(50) DEFAULT NULL\n)\n\nCREATE TABLE utilisateur (\n ID INTEGER PRIMARY KEY,\n EMAIL varchar(50) DEFAULT NULL,\n FIRSTNAME varchar(50) DEFAULT NULL,\n LASTNAME varchar(50) DEFAULT NULL,\n PASSWORD varchar(64) DEFAULT NULL,\n USERNAME varchar(50) NOT NULL,\n ADDRESS_ID INTEGER DEFAULT NULL,\n CONSTRAINT FK_USER_ADDRESS_ID FOREIGN KEY (ADDRESS_ID) REFERENCES address (ID)\n) \n\n\nand the triggers for the instertions:\n\ncreate SEQUENCE address_seq;\n\nCREATE OR REPLACE TRIGGER address_trig\n BEFORE INSERT ON address\n FOR EACH ROW\nBEGIN\n :new.id := address_seq.nextval;\nEND\n\ncreate SEQUENCE user_seq\n/\n\n\n\n\nCREATE OR REPLACE TRIGGER user_trig\n BEFORE INSERT ON utilisateur\n FOR EACH ROW\nBEGIN\n :new.id := user_seq.nextval;\nEND;\n/\n\n\nthe entities : \n\n@Entity\n@Table(name = \"UTILISATEUR\")\npublic class User implements Serializable {\n\n @Id\n @SequenceGenerator(name = \"USER_SEQ\", sequenceName = \"USER_SEQ\", allocationSize = 1)\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"USER_SEQ\")\n @Column(name = \"id\", nullable = false)\n private Integer id;\n\n @Column(nullable = false, length = 50)\n private String username;\n\n @JoinColumn(name = \"ADDRESS_ID\")\n @OneToOne(cascade = {CascadeType.ALL})\n private Address address;\n\n @ManyToMany\n @JoinTable(name = \"user_roles\", joinColumns = {\n @JoinColumn(name = \"User_userid\")}, inverseJoinColumns = {\n @JoinColumn(name = \"Role_roleid\")})\n private List<Role> roles;\n\n public User() {\n roles = new ArrayList<Role>();\n address = new Address();\n }\n\n@Entity\npublic class Address implements Serializable {\n\n @Id\n @SequenceGenerator(name = \"USER_SEQ\", sequenceName = \"USER_SEQ\", allocationSize = 1)\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"USER_SEQ\")\n @Column(name = \"id\", nullable = false)\n private Integer id;\n.....\n\n\nthe creation methode: \n\npublic void create(T t) {\n this.em.persist(t);\n this.em.merge(t);\n }\n\n\nin order to create a new user this methode is called: \n\n public void doCreateUser() {\n try {\n addressService.create(address);\n newUser.setAddress(address);\n userService.create(newUser);\n FacesMessage message = new FacesMessage(\"utilisateur ajouté avec succès\");\n FacesContext.getCurrentInstance().addMessage(null, message);\n } catch (Exception e) {\n ....}\n\n\nThe insertion is successful using MySQL, but when I configurate the pool to use ORACLE I get an error which means that the foreign key is violated, knowing that while debugging I see the object address created and inserted into the user, but at the end of the methode I get this error:\n\nException [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException\nInternal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-02291: integrity constraint (FK_USER_ADDRESS_ID) violated - parent key not found\nError Code: 2291\nCall: INSERT INTO UTILISATEUR (id, EMAIL, FIRSTNAME, LASTNAME, PASSWORD, USERNAME, ADDRESS_ID) VALUES (?, ?, ?, ?, ?, ?, ?)\n bind => [7 parameters bound]\n\n\nThank you for any help about it.\nBest regards." ]
[ "oracle", "jpa", "one-to-one" ]
[ "graphql-java cyclic types dependencies", "i've hit a brick wall while trying to construct types that depend on each other, here is the code:\n\nimport graphql.schema.GraphQLObjectType;\nimport static graphql.schema.GraphQLObjectType.newObject;\n\nimport static graphql.Scalars.*;\nimport graphql.schema.GraphQLFieldDefinition;\nimport graphql.schema.GraphQLList;\n\nimport static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;\n\npublic class GraphQLTypes {\n\n private GraphQLObjectType studentType;\n private GraphQLObjectType classType;\n\n public GraphQLTypes() {\n\n createStudentType();\n createClassType();\n }\n\n void createStudentType() {\n studentType = newObject().name(\"Student\")\n .field(newFieldDefinition().name(\"name\").type(GraphQLString).build())\n .field(newFieldDefinition().name(\"currentClass\").type(classType).build())\n .build();\n }\n\n void createClassType() {\n classType = newObject().name(\"Class\")\n .field(newFieldDefinition().name(\"name\").type(GraphQLString).build())\n .field(newFieldDefinition().name(\"students\").type(new GraphQLList(studentType)).build())\n .build();\n }\n\n}\n\n\nits impossible to intantiate this class, as i get this exception\n\nCaused by: graphql.AssertException: type can't be null\nat graphql.Assert.assertNotNull(Assert.java:10)\nat graphql.schema.GraphQLFieldDefinition.<init>(GraphQLFieldDefinition.java:23)\nat graphql.schema.GraphQLFieldDefinition$Builder.build(GraphQLFieldDefinition.java:152)\nat graphql_types.GraphQLTypes.createStudentType(GraphQLTypes.java:26)\nat graphql_types.GraphQLTypes.<init>(GraphQLTypes.java:19)\n\n\nobviously classType is not yet intantiated at the point createStudentType() is referencing it. How to i get around this problem?" ]
[ "java", "graphql", "graphql-java" ]
[ "Joining on long text field", "I am building a database and have run into an issue where two tables need to be joined via an error message field, currently set to varchar(255). This (obviously) causes performance and locking issues when the join is performed. My initial statement was hanging on any update larger than 1000 rows. Here is the code:\n\n UPDATE Integration_Detail D\n JOIN Integration_Error_Descriptor E\n ON D.Error_Message = E.Error_Message\n SET D.Error_Key = E.Error_Key\n WHERE D.Error_Key is null;\n\n\nI decided to change to a stored procedure in order to break the UPDATE statement down into smaller pieces. This works, but is not ideal in terms of performance since I am using a while loop and updating in batches of 200. The procedure code looks like this:\n\nCREATE PROCEDURE update_detail_table()\n\nBEGIN\n\ndeclare rowsToProcess int default 0;\n\nset rowsToProcess = \n (select count(*)\n from Integration_Report.Integration_Detail\n where Error_Key is null);\n\nCREATE TABLE Integration_Report.temp_error_processing (\n Detail_Key bigint DEFAULT null,\n Error_Key bigint DEFAULT null\n ) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n\nwhile rowsToProcess > 0 DO\n\n INSERT INTO Integration_Report.temp_error_processing\n (SELECT D.Detail_Key, E.Error_Key\n FROM Integration_Report.Integration_Detail D\n JOIN Integration_Report.Integration_Error_Descriptor E\n ON D.Error_Message = E.Error_Message\n WHERE D.Error_Key is null\n ORDER BY D.Insert_Datetime desc\n LIMIT 200);\n\n UPDATE Integration_Report.Integration_Detail D\n JOIN Integration_Report.temp_error_processing T\n ON D.Detail_Key = T.Detail_Key\n SET D.Error_Key = T.Error_Key;\n\n TRUNCATE TABLE Integration_Report.temp_error_processing;\n\n set rowsToProcess = \n (select count(*)\n from Integration_Report.Integration_Detail\n where Error_Key is null);\n\nend while;\n\ndrop table Integration_Report.temp_error_processing;\n\nEND;\n\n\nIs there a way to accomplish this that is faster and uses less memory? I have not written many procedures before so please let me know if my code is ugly as well.\n\nThank you for your help." ]
[ "mysql", "performance", "join", "stored-procedures" ]
[ "SharedPreferences in FirebaseMessaging Service (Background Service)", "Good Day,\n\nmy problem is that the data I get from FCM doesn't get saved in the SharedPreferences, if I receive a Notification when the application is closed.\n\nThe Code:\n\npublic class SomeService extends FirebaseMessagingService\n{\n\nSharedPreferences prefs;\nSharedPreferences.Editor prefsEditor;\n\n@Override\npublic void onMessageReceived(RemoteMessage remoteMessage) {\n super.onMessageReceived(remoteMessage);\n\n prefs = this.getSharedPreferences(\"prefs\", MODE_PRIVATE);\n prefsEditor = prefs.edit();\n\n Map<String,String> data = remoteMessage.getData();\n\n prefsEditor.putBoolean(Keys.text, Boolean.parseBoolean(data.get(\"text\")));\n\n prefsEditor.apply();\n}\n\n}" ]
[ "android", "firebase", "android-studio", "sharedpreferences", "background-process" ]
[ "C++ creating a scope at the file level", "Everybody knows that writing a \"using\" statement inside a .h is a terrible terrible thing. \n\nNow, I'm using a tool to generate an UI (for those who know Juce, it's the Jucer) , which requires this kind of using statement in the .h . \n\nTo avoid this, I edited the template files to enclose this using into namespaces but that's not enough protection as those very namespaces are used elsewhere.\n\nTherefore I tried to enclose this using directive into an unnamed scope like this :\n\nnamespace Gui \n{\n { \n using namespace juce;\n\n <generated code>\n }\n}\n\n\nThis seemed fine to me but Visual studio generates an error : \n\n\n '{' : missing function header (old-style formal list?)\n The compiler encountered an unexpected open brace at global scope. In most cases, this is caused by a badly-formed function header, a misplaced declaration, or a stray semi-colon. To resolve this issue, verify that the open brace follows a correctly-formed function header, and is not preceded by a declaration or a stray semi-colon.\n This error can also be caused by an old-style C-language formal argument list. To resolve this issue, refactor the argument list to use modern style—that is, enclosed in parentheses.\n\n\nDo you know another way to achieve that - except enclosing that in yet another namespace, which would change tons of legacy code ?\n\nEDIT : I ended up modifying the generator tool. If someone needs it, contact me." ]
[ "c++", "scope", "header" ]
[ "Producer–consumer pattern: wakeup UI thread", "How to implement producer–consumer pattern with background thread(s) as producer(s) and UI thread as consumer? In good old C++ I would use a mutex, a conditional variable and a flag and maybe some sort of concurrent queue. Producer thread(s) would put data into the queue, lock the mutex, set the flag, unlock the mutex and then signal the conditional variable.\n\nHow do I implement similar pattern with UI thread? Thank you." ]
[ "android", "ios" ]
[ "How to map TypeScript ES6 default imports to return values of AMD modules?", "For example, I have an AMD module in vanilla JS (not touched by tsc):\n\n// Foo.js\ndefine([], function() {\n return class Foo {}\n})\n\n\nwith accompanying declaration file:\n\n// Foo.d.ts\ndeclare class Foo {\n // ...\n}\n\nexport default Foo\n\n\nthen I have a typescript module:\n\n// app.ts\nimport Foo from './Foo'\nnew Foo // Uncaught TypeError: Foo_1.default is not a constructor\n\n\nWhen I compile my typescript module to AMD format with tsc and run it in my RequireJS environment, there's an error that default is undefined because typescript compiles to:\n\ndefine(\"app\", [\"require\", \"exports\", \"Foo\"], function (require, exports, Foo_1) {\n \"use strict\";\n console.log(Foo_1[\"default\"]);\n});\n\n\nI don't want it to grab the default property. I want it to treat a default import like it is simply grabbing the returned value of my define module. Every single module in my project is a define() module, or a typescript module compiled to define() (AMD). I'd simply like to get that return object.\n\nIs there a way to do (configure) this?\n\nEDIT:\n\nI know I can import * as Foo from './Foo', but that is sort of hacky, and it generates errors because the declared module doesn't have named exports. I would like a non-error way to do it, if possible.\n\nEDIT: I learned I can just do \n\n// app.ts\nimport Foo = require('./Foo')\nnew Foo // no error\n\n\nto achieve the result. The only problem with that is it is not ES6-compatible. This means that if we tell typescript to leave ES6 import statements as-is, then other tools won't understand typescript-specific import/export statements. I need a way to use only official ES6 module syntax in a reasonable way.\n\nI'm think that my solution might be to just do a post-tsc-compile transform step to convert default import access points." ]
[ "javascript", "typescript", "amd" ]
[ "emulator only shows one marker", "i am trying to put a new marker everytime the user touches the screen.\nthe following is my code, my problem is that the new marker doesn't appear at all \n\npackage com.org;\n\nimport java.io.IOException;\nimport java.util.List;\nimport java.util.Locale;\n\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Point;\nimport android.location.Address;\nimport android.location.Geocoder;\nimport android.os.Bundle;\nimport android.view.MotionEvent;\nimport android.view.View;\nimport android.widget.LinearLayout;\nimport android.widget.Toast;\n\nimport com.google.android.maps.GeoPoint;\nimport com.google.android.maps.MapActivity;\nimport com.google.android.maps.MapController;\nimport com.google.android.maps.MapView;\nimport com.google.android.maps.MyLocationOverlay;\nimport com.google.android.maps.MapView.LayoutParams;\nimport com.google.android.maps.Overlay;\n\npublic class MapExampleActivity extends MapActivity {\nMapView mapView;\nMapController mc;\nGeoPoint p;\nMapOverlay mapOverlay = new MapOverlay();\nprivate MyLocationOverlay myLocOverlay;\n\nclass MapOverlay extends com.google.android.maps.Overlay {\n @Override\n public boolean draw(Canvas canvas, MapView mapView, boolean shadow,\n long when) {\n super.draw(canvas, mapView, shadow);\n\n // ---translate the GeoPoint to screen pixels---\n Point screenPts = new Point();\n mapView.getProjection().toPixels(p, screenPts);\n\n // ---add the marker---\n Bitmap bmp = BitmapFactory.decodeResource(getResources(),\n R.drawable.marker);\n canvas.drawBitmap(bmp, screenPts.x + 25, screenPts.y - 50,null);\n return true;\n }\n}\n\n\n@SuppressWarnings(\"deprecation\")\n@Override\npublic void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.main);\n\n\n mapView = (MapView) findViewById(R.id.mymap);\n LinearLayout zoomLayout = (LinearLayout)findViewById (R.id.myzoom); \n View zoomView = mapView.getZoomControls(); \n\n zoomLayout.addView(zoomView, \n new LinearLayout.LayoutParams(\n LayoutParams.WRAP_CONTENT, \n LayoutParams.WRAP_CONTENT)); \n mapView.displayZoomControls(true);\n\n mc = mapView.getController();\n String coordinates[] = {\"1.352566007\", \"103.78921587\"};\n double lat = Double.parseDouble(coordinates[0]);\n double lng = Double.parseDouble(coordinates[1]);\n\n p = new GeoPoint(\n (int) (lat * 1E6), \n (int) (lng * 1E6));\n\n mc.animateTo(p);\n mc.setZoom(17); \n\n\n // ---Add a location marker---\n MapOverlay mapOverlay = new MapOverlay();\n List<Overlay> listOfOverlays = mapView.getOverlays();\n listOfOverlays.clear();\n listOfOverlays.add(mapOverlay);\n\n mapView.invalidate();\n\n}\n\n\n@Override\nprotected boolean isRouteDisplayed() {\n // TODO Auto-generated method stub\n return false;\n}\npublic boolean onTouchEvent(MotionEvent event, MapView mapView) \n { \n //---when user lifts his finger---\n if (event.getAction() == 1) { \n GeoPoint p1 = mapView.getProjection().fromPixels(\n (int) event.getX(),\n (int) event.getY());\n\n\n mc.animateTo(p1);\n mc.setCenter(p1);\n return true;\n } \n else \n return false;\n } \n\n\n }" ]
[ "android", "map", "markers" ]
[ "Draw GoogleMap path with 9patch", "I'm currently trying to draw a fairly stylised path onto a map.\n\nMethod as it stands\n\npublic ArrayList<Polyline> renderNeonPolyline(Context context,\n ArrayList<LatLng> routeCoordinates,\n GoogleMap googleMap) {\n ArrayList<Polyline> polylines = new ArrayList<>();\n for (int i = 0; i < 6; i++) {\n PolylineOptions polylineOptions = new PolylineOptions();\n polylineOptions.width(48 - (i * 8));\n if (i == 0) {\n polylineOptions.color(ContextCompat.getColor(context, R.color.apple_25));\n } else if (i == 1) {\n polylineOptions.color(ContextCompat.getColor(context, R.color.apple_50));\n } else if (i == 2) {\n polylineOptions.color(ContextCompat.getColor(context, R.color.apple_75));\n } else if (i == 3) {\n polylineOptions.color(ContextCompat.getColor(context, R.color.apple));\n } else if (i == 4) {\n polylineOptions.color(ContextCompat.getColor(context, R.color.white_75));\n } else if (i == 5) {\n polylineOptions.color(ContextCompat.getColor(context, R.color.white));\n }\n polylineOptions.addAll(routeCoordinates);\n Polyline polyline = googleMap.addPolyline(polylineOptions);\n polylines.add(polyline);\n }\n\n return polylines;\n}\n\n\nSo this is working. It draws a nice line with a neon-y kind of effect... most of the time. For some reason there are certain circumstances where only the first apple_25 line gets rendered. (I think this has something to do with the fact that we're trying to zoom and pan the map at the same time, but haven't looked into it) Also, the ends look pretty rough.\n\nWhat I was really hoping to do was draw a single line with a 9patch image.\n\nAny ideas?\n\nThanks" ]
[ "android", "google-maps" ]
[ "remove users and groups from multiple groups using Remove-ADGroupMember", "Hoping someone can point me in the right direction. Also I freely admit that there are probably better more efficient ways to do what I'm doing here but my goal is to get this working and understand what I'm doing wrong so I'd appreciate corrections on my code instead of writing something from scratch if at all possible.\n\nSo here's my goal: I've got a list of groups in AD that all have similar name formats. I'm trying to create an array of those groups and remove any users who are not members of a specific group and any groups that are not members of a specific group. \n\nFor Example WAS-MyAdmins and NYC-MyAdmins are two group names. They have some users that should stay and may also have some groups that should stay. They also have users and groups that need to be removed. I swear I had this partially working earlier but I've tried a couple things and can't get back to that point. \n\nWhen I run this it just deletes all the users and groups. \n\n$Groups = Get-ADGroup -Filter 'Name -like \"*-MyAdmins\"' | Foreach-Object{ \n$Members1 = Get-ADGroupMember -Identity $_ | Where {$_.ObjectClass -eq 'user'} | Get-ADUser -Properties * | Where {$members1.memberof -ne \"CN=Tech_IDs,OU=Groups,DC=contoso,DC=com\"}\nRemove-ADGroupMember -Identity $_ -Members $Members1 -Confirm:$true}\n$Members2 = Get-ADGroupMember -Identity $_ | Where {$_.ObjectClass -eq 'Group'}| Get-ADGroup -Properties * | where {$Members2.memberof -ne \"CN=Tech_Group,OU=Groups,DC=contoso,DC=com\"}\nRemove-ADGroupMember -Identity $_ -Members $Members1 -Confirm:$true\n\n\nUPDATED CODE\n\n$Groups = Get-ADGroup -Filter 'Name -like \"*-MyAdmins\"' | Foreach-Object{ \n$Members1 = Get-ADGroupMember -Identity $_ | Where {$_.ObjectClass -eq 'user'} | Get-ADUser -Properties * | Where {$_.memberof -notcontains \"CN=Tech_IDs,OU=Groups,DC=contoso,DC=com\"}\nRemove-ADGroupMember -Identity $_ -Members $Members1 -Confirm:$true\n$Members2 = Get-ADGroupMember -Identity $_ | Where {$_.ObjectClass -eq 'Group'}| Get-ADGroup -Properties * | where {$_.memberof -notcontains \"CN=Tech_Group,OU=Groups,DC=contoso,DC=com\"}\nRemove-ADGroupMember -Identity $_ -Members $Members1 -Confirm:$true}" ]
[ "powershell" ]
[ "Should I leave non-function values in modules or bring them to the main program file?", "This is a question about how I should organize my F# code. I hope it is not in violation of SO rules. \n\nI have dozens of source files (names terminating in .fs) in my project. Each file contains a module. In some of these files/modules I define only functions. In others I define functions and other values (not functions). \n\nThe last file in the Solution Explorer (Visual Studio) is Program.fs which actually contains very little code. Most calculations have been done \"above\" it.\n\nI am considering moving the non-function values declared in the other modules to Program.fs. These are the advantages and disadvantages I see from this change:\n\nAdvantages:\n\n1) A better view of program flow.\n\n2) Easier to select all code above a certain line and send it for execution in FSI.\n\n3) Slightly easier to search for those values in the editor.\n\n4) Possibly easier to debug by putting breakpoints on the lines where values are declared.\n\nDisadvantages:\n\n1) Program.fs could become large and unwieldy.\n\n2) Loss of modularity.\n\n3) After implementing the changes, if the calculation of value y in module B depends on value x in module A \"above\" it then I can no longer have y as a value, it must be declared as a function of x. Similarly if a function declaration in module B depends on a value in module A I must add a parameter to the function definition.\n\nBelow are two examples of the same small program created under the two alternative methods. Which of the two is better in general?\n\n// ///////////////// Values in modules \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\n// File A.fs\n\nmodule A\n\nlet i = 1\nlet add x y : float = x + y\n\n// File B.fs\n\nmodule B\n\nlet sqr z = z * z + float i\nlet x = sqr 99.9\n\n// File Program.fs\n\nopen A\nopen B\n\nlet y =\n add (float i) x \n |> sqr\n\nprintfn \"%f\" y\n\n[<EntryPoint>]\nlet main argv = \n printfn \"%A\" argv\n 0 // return an integer exit code\n\n// This is the calculated value for y: 99640524.640100\n\n// ///////////////// Values in Program.fs \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\n\n// File A.fs\n\nmodule A\n\nlet add x y : float = x + y\n\n// File B.fs\n\nmodule B\n\nopen A\n\nlet sqr i z = z * z + float i // notice the additional parameter\n\n//File Program.fs\n\nopen A\nopen B\n\nlet i = 1\nlet x = sqr i 99.9\n\nlet y =\n add (float i) x \n |> sqr i\n\nprintfn \"%f\" y\n\n[<EntryPoint>]\nlet main argv = \n printfn \"%A\" argv\n 0 // return an integer exit code\n\n// This is the calculated value for y: 99640524.640100" ]
[ "module", "f#" ]
[ "How to delete past working directories in Octave GUI?", "Does anyone know how to delete those past working directories in Octave GUI? They are very annoying and useless." ]
[ "octave", "octave-gui" ]
[ "Facebook Graph API Explorer Read Page Messages", "I want to create an app that reads the messages sent to a page so I'm playing with Graph API Explorer to see what's possible.\n\nI retrieved an access token with read_page_mailboxes and when I send a GET to /v2.5/my_page_name/conversations in explorer, I get:\n\n{\n \"error\": {\n \"message\": \"(#298) Requires extended permission: read_mailbox\",\n \"type\": \"OAuthException\",\n \"code\": 298,\n \"fbtrace_id\": \"GV+BcPhVkWw\"\n }\n}" ]
[ "facebook-graph-api" ]
[ "How to reverse mv to file - Unix", "I accidentaly ran a find and mv command as per below to move some files with specific extensions to a directory. Unfortunately it was early and I was tired and I didn't put and slash on the end and all the .ext files are gone and I am left with a file called 'file' with no extension.\n\n find /folder -iname \"*.zip\" -exec mv {} /home/zip \\;\n\n\nQuestion is : How can I reverse or extract my .zip files from this 'file'\n\nI have tried to open with archiver, cat, tail, head and it's just abinary output and archiver can't extract\n\nNote: I am on a Imac" ]
[ "linux", "macos", "bash", "unix" ]
[ "d3 trigger mouseover on path underlying other path?", "I have this chart.\n\nAs you can see i inserted two paths.\n\nThere is am mouseover listener on the circles.\n\nNow the problem is, that one path is overlaying the other and the circles belonging to it, and the event is not triggered when hovering an underlying circle.\n\nHere the circle I mean:\n\n\n\nI draw the lines and circles like this:\n\n//draw line\nlet valueline = d3.line()\n .x(function(d) { return x(d.date); })\n .y(function(d) { return ys[count](d.val); });\n\nlet chart = chartBody.append(\"g\")\n .attr(\"class\", `charts chart-${count}`)\n .append(\"path\")\n .attr(\"class\", `line-${count} line`)\n .attr(\"d\", valueline(data.samples));\n\n//get dots for circle values\nlet node = chartBody.selectAll(\"dot\")\n .data(data.samples)\n .enter()\n .append(\"g\");\n\n//add circle\nnode.append(\"circle\")\n .attr(\"class\", `circle-${count}`)\n .attr(\"cx\", function(d) {return x(d.date); })\n .attr(\"cy\", function(d) { return ys[count](d.val); })\n .attr(\"r\", 8)\n .on(\"mouseover\", showHideDetails)\n .on(\"mouseout\", showHideDetails);\n\n\nIs there a way to trigger the event on the underlying circle or do i have to use something else than the path tag?\n\nHelp would be greatly appreciated." ]
[ "javascript", "d3.js", "mouseover", "svg-path" ]
[ "laravel \"Undefined variable: categories \"", "I am trying to display my categories in the welcome.blade.php, however it gives me an error.\n\nMy welcome.blade.php:\n\n<div class=\"links\">\n @foreach($categories as $category)\n <a href=\"{{ url('/receitas/'.$category->id)}}\">{{ $category->name }}</a>\n @endforeach\n</div>\n\n\nMy WelcomeController.php:\n\n<?php\n\n namespace App\\Http\\Controllers;\n use App\\Category;\n use Illuminate\\Http\\Request;\n use App\\Welcome;\n\nclass WelcomeController extends Controller\n{\n\n public function index()\n {\n return view('welcome');\n }\n\n public function show()\n {\n $categories = Category::all();\n\n return view('welcome', compact([ 'categories' => $categories]));\n }\n}\n\n\nAnd my web.php:\n\n<?php\n\nRoute::get('/', 'WelcomeController@index')->name('entrada');\n\nRoute::get('/teste/teste', 'UserController@index');\n\nAuth::routes();\n\nRoute::get('/home', 'HomeController@index')->name('home');\n\nRoute::get('/receitas', 'ReceitasController@index')->name('receitas');\n\nRoute::get('/clientes', 'HomeController@clientes');\n\nRoute::get('/category', 'CategoryController@index');\n\n\nI have already tried to use a @if condition to verify if the variable $categories is empty and it seem it is.\n\n<div class=\"links\">\n @if(empty($categories))\n Alert: the variable is empty!!\n @else\n @foreach($categories as $category)\n <a href=\"{{ url('/receitas/'.$category->id)}}\">{{ $category->name }}</a>\n @endforeach\n @endif\n </div>\n\n\nHowever in my database I have records of categories.\n\nPrintscreen of my category table\n\nCan you help me please!" ]
[ "laravel" ]
[ "php putenv() return inconsistent value", "I have a PHP that connect to an Oracle database, and I need to set the NLS_LANG variable. In my PHP I set it with:\nputenv("NLS_LANG=American_America.UTF8");\n$oracle = $this->load->database('oracle', TRUE);\n\n//do some query after this\n\nBut the value returned is inconsistent. One time it return\narray(1) { [0]=> object(stdClass)#17 (1) { ["USERENV('LANG')"]=> string(2) "US" } } //this is correct\n\nAnd a few refresh later it return\narray(1) { [0]=> object(stdClass)#17 (1) { ["USERENV('LANG')"]=> string(2) "GB" } } //this is from my PC language setting\n\nThe query I use to check the LANG is :\nSELECT userenv('LANG') FROM DUAL;\n\nIs there any way to make it work without changing my PC language?\nMy configuration is :\n\nPHP 7.4 (XAMPP)\nOCI8 2.2.0\nWin 7\nCodeIgniter 3.1.11\n\nNote : I also have tried using the $_ENV but the result also inconsistent." ]
[ "php", "oracle", "oci8" ]
[ "PhpStorm didn't display any information of Xdebug", "I am new at Xdebug and trying to configure Xdebug with PhpStorm. The problem is, i can't get any information in phpstorm debug console even i hit a breakpoint. You can see the below picture phpstorm console when i hit a breakpoint \n\n\n\nHere is my configurations\n\n1.Xdebug.ini Configurations\n\nzend_extension=xdebug.so\nxdebug.remote_autostart=0\nxdebug.remote_enable=1\nxdebug.remote_port=9000\nxdebug.remote_connect_back=1\nxdebug.remote_host=192.168.0.161\n\n\n2.Xdebug Verification\n\n\n3.1.PHPStorm Setting\n\n\n3.2\n\n\n3.3" ]
[ "docker", "phpstorm", "xdebug" ]
[ "How to connect and download file from FTP server in Flutter", "Im already try SSH plugin, in debug mode app is running without error but when i try in release mode error is throw java.lang.ClassNotFoundException: com.jcraft.jsch.jce.Random, anyone know how to fix this problem or different way to connect SFTP?" ]
[ "flutter", "sftp" ]
[ "How to pass query string data to all pages of my website?", "I am trying to pass the UTM parameters from my facebook ads to all pages on my website.\n\nexample query string: www.mysite.com/?utm__source=facebook&utm_medium=psocial&utm_campaign=summer&utm_content=pool&fbclid=1234Jfshio\n\nTypically the utm parameters will exist on the first page the user visits, but once they navigate to a new page the query string is lost.\n\nI want the query string to be appended to the end of the URL on all of the pages my user navigates to during their session.\n\nI have to do this so they when they open a chat with our LiveChat service, the start URL that is captured by our service contains the utm parameters from the ad they clicked.\n\nHere is the code I am currently using - but it is not working as intended:\n\n\r\n\r\n<script type=\"text/javascript\">\r\n (function() {\r\n var utmInheritingDomain = \"brilliance.com\", // REPLACE THIS DOMAIN \r\n utmRegExp = /(\\&|\\?)utm_[A-Za-z]+=[A-Za-z0-9]+/gi,\r\n links = document.getElementsByTagName(\"a\"),\r\n utms = [\r\n \"utm_source={{url - utm_source}}\", // IN GTM, CREATE A URL VARIABLE utm_source\r\n \"utm_medium={{url - utm_medium}}\", // IN GTM, CREATE A URL VARIABLE utm_medium\r\n \"fbclid={{url - fbclid}}\" // IN GTM, CREATE A URL VARIABLE fbclid\r\n ];\r\n \r\n for (var index = 0; index < links.length; index += 1) {\r\n var tempLink = links[index].href,\r\n tempParts;\r\n\r\n if (tempLink.indexOf(utmInheritingDomain) > 0) { // The script is looking for all links with the utmInheritingDomain\r\n tempLink = tempLink.replace(utmRegExp, \"\");\r\n\r\n tempParts = tempLink.split(\"#\");\r\n\r\n if (tempParts[0].indexOf(\"?\") < 0 ) {\r\n tempParts[0] += \"?\" + utms.join(\"&\"); // The script adds UTM parameters to all links with the domain you've defined\r\n } else {\r\n tempParts[0] += \"&\" + utms.join(\"&\");\r\n }\r\n\r\n tempLink = tempParts.join(\"#\");\r\n }\r\n\r\n links[index].href = tempLink;\r\n }\r\n }());\r\n</script>" ]
[ "javascript", "google-tag-manager" ]
[ "Stata drops variables that \"predicts failure perfeclty\" even though the correlation between the variables isn't 1 or -1?", "I am running a logit regression on some data. My dependent variable is binary as are all but one of my independent variables.\nWhen I run my regression, stata drops many of my independent variables and gives the error:\n\n\n \"variable name\" != 0 predicts failure perfectly\n \"variable name\" dropped and \"a number\" obs not used\n\n\nI know for a fact that some of the variables dropped don't predict failure perfectly. In other words, the dependent variables can take on the value 1 for either the value 1 or 0 of the independent variable. \n\nWhy is this happening and how can I resolve it?" ]
[ "regression", "stata", "logistic-regression" ]
[ "Sorting TableView column in qml", "I need to sort my column number 1 in TableView. I followed this link but I get some errors and I'm not really sure why it doesnt work.\n\nIn my TableView model qml file I have this:\n\nTableView\n{\n ...\n onSortIndicatorColumnChanged: model.sort(1, sortIndicatorOrder)\n...\n\n\nand in cpp file:\n\n Q_INVOKABLE virtual void sort(int column, Qt::SortOrder order=Qt::AscendingOrder)\n {\n proxyModel=new QSortFilterProxyModel;\n qDebug(\"Sorting by column %d\", column);\n proxyModel->sort(column, order);\n }" ]
[ "c++", "qt", "qml" ]
[ "StackOverflow when filtering datoms", "I'm trying to filter through a database, based on the keyword patter match. \n\nTo do this, I wrote ->\n\n(defn find-users\n [db keyword]\n (if (>= (count keyword) 3)\n (let [login-pattern (login-pattern keyword)]\n (->> (d/datoms db :aevt :user/name)\n (filter #(re-matches login-pattern (:v %)))\n (map #(d/entity db (:e %)))))\n []))\n\n\nBut, I'm getting a StackOverflow error.\n\nI think it's because of (map #(d/entity db (:e %)))\n\nWhen I plainly do (map :e), the function works. \n\nI'm a bit confused as to why the Stackoverflow would happen though, the queries I'm performing with map :v are returning only a few entities. \n\nWhat's happening here?" ]
[ "clojure", "datomic" ]