texts
sequence | tags
sequence |
---|---|
[
"Rail's cancancan deep has_many through",
"I have a problem while defining abilities when the association goes deep, between User and ClassD.\n\nUser < ActiveRecord::Base \n has_many :classB\n has_many :classC, through classB\n has_many :classD, through classB\nend\nClassB < ActiveRecord::Base\n belongs_to :User\n has_many :classC\n has_many :classD, through classC\nend \nClassC < ActiveRecord::Base\n belongs_to ClassC\n has_many :ClassD\nend\nClassD < ACtiveRecord::Base\n belongs_to Class C\nend\n\n\nHow can I define an ability with cancancan, something like:\n\nclass Ability\n include CanCan::Ability\n\n def initialize(user) \n user ||= User.new \n can :manage, ClassD do |cd|\n cd.user_id: user.id\n end\n\n end\nend"
] | [
"ruby-on-rails",
"cancancan"
] |
[
"How to add TextView into ScrollView in different way at any screen size?",
"I am adding TextView into ScrollView. \n\nSpace between text views should be scalable. \n\nI mean that if device is small then space should be smaller that if device is bigger.\n\nMaybe i should look at ScrollView size ant scale TextView depending on it ? \n\nOr there are some way how this is doing ? I am creating my TextView programmically.\n\nThanks."
] | [
"android"
] |
[
"A card inside a dialog occupies full screen",
"I am using a card inside a dialog. It occupies full screen even though the child of the card has a container widget of fixed width and height. \nI am using the below code: \n\nshowDialog(context: context, builder: (context)\n{\n return Card(\n clipBehavior: Clip.antiAlias,\n shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8.0)),\n elevation: 8.0,\n child: Container(\n width: MediaQuery.of(context).size.width * 0.80,\n height: 300,\n color: const Color(0xFF465A63)\n ),\n );\n});"
] | [
"flutter"
] |
[
"Rails LinkedIn API gem",
"I am using the Rails LinkedIn API gem. https://github.com/pengwynn/linkedin/issues/141\n\nI am trying to search linked in users by first and last name and so far I've come up with this:\n\n@profiles = linkedin_client.search(:first_name => fname, :last_name => lname, :sort => \"connections\", :fields => %w(id first-name last-name headline industry location api-standard-profile-request picture_url public_profile_url summary));\n\n\nOne question I have is, will \":first_name\" work as the parameter \"first-name\"? What I mean is will the underscore be a good substitute for the dash \"-\"? \n\nI'm hoping these results would be organized by connection, as I've tried to do above with :sort => \"connections\" \n\nThe problem is that it will not return any results, even when I know the user's name exists. Thanks for the help!"
] | [
"ruby-on-rails",
"ruby",
"linkedin"
] |
[
"Geolocation and IP address targeting for ads",
"I'm trying to create a Ad campaign with either or both Google Adwords and Google Analytics. The key point for the campaign is to target a specific geographic location and a specific range of class 4 IP addresses and no one else. \n\nI would like the ability to rotate between ads once a specific IP address has already seen an ad in the Ad group. \n\nI've seen something like this done by a company called We-Care-Software and when you click on the image in the email they send it takes you to a landing page for a Time Warner Cable or Verizon Wireless promotion.\n\nI'd like to do something similar to that but targeting IP address ranges. I want to know if this is possible with Google Adsense, DoubleClick for Publishers or Adwords even because with the research I've been doing I haven't come across anything so specific with their services, only geographic targeting, but I need to go deeper than that. Maybe there is an alternative web app that does this?\n\nAny help appreciated.\nThanks in advance."
] | [
"geolocation",
"ip",
"adsense",
"google-ads-api",
"geotargetting"
] |
[
"Forking and pipes: does this C program contain a race condition?",
"I'm learning about interprocess communication and came across the below example program.\n\nI don't understand what's to prevent the parent process from attempting the read (as part of the else condition at the bottom of the program) before the child process has completed the write.\n\nWhat (if anything) constrains the parent process from attempting the read from standard input before the child process has written to standard output?\n\nint main(void)\n{\n int fd[2], nbytes;\n pid_t childpid;\n char string[] = \"Hello, world!\\n\";\n char readbuffer[80];\n\n pipe(fd);\n\n if((childpid = fork()) == -1)\n {\n perror(\"fork\");\n exit(1);\n }\n\n if(childpid == 0)\n {\n /* Child process closes up input side of pipe */\n close(fd[0]);\n\n /* Send \"string\" through the output side of pipe */\n write(fd[1], string, (strlen(string)+1));\n exit(0);\n }\n else\n {\n /* Parent process closes up output side of pipe */\n close(fd[1]);\n\n /* Read in a string from the pipe */\n nbytes = read(fd[0], readbuffer, sizeof(readbuffer));\n printf(\"Received string: %s\", readbuffer);\n }\n\n return(0);\n}"
] | [
"c",
"process",
"pipe",
"fork",
"parent-child"
] |
[
"Get orders by status Firebase",
"Commerce using React and Firebase\n\nI need to get all the orders with the status 'on-hold', so I did the following: \n\nJS\n\n const ordersRef = firebase.database().ref('/orders');\n\n let orders = [];\n\n ordersRef.on('child_added', snap => {\n if (snap.val().status.state === 'on-hold') {\n orders = [\n {\n ...snap.val(),\n id: snap.key\n }, \n ...orders\n ];\n this.setState({loading:false, orders: orders});\n }\n })\n\n\nThis is working, the only problem is that if there's no orders 'on-hold' the 'loading' state would never change.\n\nThe firebase db looks something like:\n\norders: {\n ...\n id: {\n ...\n status: {\n ...\n state: 'on-hold'\n }\n }\n}"
] | [
"javascript",
"reactjs",
"firebase",
"firebase-realtime-database"
] |
[
"javascript onsubmit returns two different values in the same call",
"the validation function\n\n function validateForm(){\n var els;\n els = document.getElementById('name');\n if(els.value == ''){\n console.log(0);\n alert('Ai uitat sa completezi numele');\n return false;\n }\n els = document.getElementsByClassName('education');\n [].forEach.call(els, function (el){\n if(el.value == ''){\n alert('Ai uitat unul sau mai multe campuri la educatie');\n console.log(1);\n return false;\n }\n });\n console.log(2)\n return false;\n }\n\n\nthe form \n\n<form onsubmit=\"return validateForm()\" class=\"form-horizontal\" action=\"{{ URL::to('/admin/people/') }}\" method=\"POST\" id=\"myForm\">\n\n\nI have dynamic html generated, so im doing a javascript validation besides the server side validation so the user won't lose that dynamic generated html when the page reloads.\nThe problem here is that it outputs both 1 and 2 (submitting the form if i change the third return to true), which is extremely strange...\nThere are no errors displayed in the console too\n\nIf it enters the first if, it only outputs 0 there,so i'm guessing it's something caused by the loop?"
] | [
"javascript",
"html",
"validation"
] |
[
"Rails activeRecord version for to_tsvector() function of Postgresql",
"I have a TSVECTOR column in my database and I want to update this column via Rails callback rather than a trigger. I want to know if there's an ActiveRecord code to achieve this. So far I'm doing this by manually executing a raw SQL and it doesn't look nice. \n\nActiveRecord::Base.connection.execute(\"update my_table set tsvector_document = to_tsvector('english', #{string_tokens}) where id = #{id}\")\n\n\nI'm wondering if there's a better approach to do this without using a raw SQL.\n\nThanks in advance."
] | [
"postgresql",
"ruby-on-rails-5",
"tsvector"
] |
[
"Retrieval of String with Regex undefined",
"I am attempting to retrieve a string between to words using Regex, however, the result comes up with undefined and upon investigation, it seems I cannot look back with regex which makes me a little confused how to attempt the extraction.\n\nRegex : (?<=1 x )(.*)(?= for)\n\nString : 1 x String Name for x\n\n\nTo confirm I am trying to retrieve the string 'String Name' from the above string.\n\nEdit: Possible that (?<=1 x ) is unsupported?"
] | [
"javascript",
"regex"
] |
[
"Angular5: show hidden rows in ag-grid",
"Below is my service response, as soon as the page loads the grid shows only those rows whose result is yes. Now, my page also has a show all check box, so as soon as the checkbox is checked all the hidden rows should also be visible and as as soon as I un-check the check-box only rows with result = yes should be visible. How can I achieved this show/hide rows functionality? Please guide. Below is my code so far, I did used refreshCells but it is not giving me expected results.\n\n data = {\n name: \"A\",\n result: \"no\"\n },\n {\n name: \"B\",\n result: \"no\"\n },\n {\n name: \"C\",\n result: \"yes\"\n },\n {\n name: \"D\",\n result: \"yes\"\n }\n\n private gridApi;\n private dataCopy;\n\n constructor() {\n this.dataCopy = data;\n }\n\n this.gridOptions = {\n isExternalFilterPresent: function() { \n return true; \n },\n\n doesExternalFilterPass: function(rowNode) { \n return rowNode.data.result = \"yes\"; \n }\n };\n\n onGridReady(params) {\n this.gridApi = params.api;\n }\n\n //function call on checkbox click\n showAll(event) {\n if(event.target.checked) {\n this.gridApi.refreshCells(this.dataCopy); \n }\n }\n\n //HTML\n <input type=\"checkbox\" (change)=showAll($event)"
] | [
"angular",
"ag-grid",
"ag-grid-angular"
] |
[
"Facing issue installing openCV 2.4.9 on ubuntu 18.04",
"I am trying to install openCv on ubuntu 18.0\nI have followed steps of this blog\n\nBut when I run this command\n\n\n make\n\n\nit throws the following error\n\n[ 57%] Built target opencv_perf_ocl\n[ 57%] Built target opencv_nonfree\n[ 57%] Built target opencv_perf_nonfree\n[ 58%] Built target opencv_test_nonfree\n[ 58%] Building CXX object modules/contrib/CMakeFiles/opencv_contrib.dir/src/chamfermatching.cpp.o\n/home/knoldus/opencv-2.4.9/modules/contrib/src/chamfermatching.cpp: In member function ‘void cv::ChamferMatcher::Matching::computeDistanceTransform(cv::Mat&, cv::Mat&, cv::Mat&, float, float, float)’:\n/home/knoldus/opencv-2.4.9/modules/contrib/src/chamfermatching.cpp:969:30: error: the compiler can assume that the address of ‘annotate_img’ will never be NULL [-Werror=address]\n if (&annotate_img!=NULL) {\n ^\n/home/knoldus/opencv-2.4.9/modules/contrib/src/chamfermatching.cpp:1016:34: error: the compiler can assume that the address of ‘annotate_img’ will never be NULL [-Werror=address]\n if (&annotate_img!=NULL) {\n ^\n/home/knoldus/opencv-2.4.9/modules/contrib/src/chamfermatching.cpp: In member function ‘cv::ChamferMatcher::Match* cv::ChamferMatcher::Matching::localChamferDistance(cv::Point, cv::Mat&, cv::Mat&, cv::ChamferMatcher::Template*, float)’:\n/home/knoldus/opencv-2.4.9/modules/contrib/src/chamfermatching.cpp:1111:25: error: the compiler can assume that the address of ‘orientation_img’ will never be NULL [-Werror=address]\n if (&orientation_img!=NULL) {\n ^\n/home/knoldus/opencv-2.4.9/modules/contrib/src/chamfermatching.cpp:1111:5: warning: nonnull argument ‘orientation_img’ compared to NULL [-Wnonnull-compare]\n if (&orientation_img!=NULL) {\n ^~\n/home/knoldus/opencv-2.4.9/modules/contrib/src/chamfermatching.cpp: In member function ‘void cv::ChamferMatcher::Matching::computeDistanceTransform(cv::Mat&, cv::Mat&, cv::Mat&, float, float, float)’:\n/home/knoldus/opencv-2.4.9/modules/contrib/src/chamfermatching.cpp:1016:17: warning: nonnull argument ‘annotate_img’ compared to NULL [-Wnonnull-compare]\n if (&annotate_img!=NULL) {\n ^~\n/home/knoldus/opencv-2.4.9/modules/contrib/src/chamfermatching.cpp:969:13: warning: nonnull argument ‘annotate_img’ compared to NULL [-Wnonnull-compare]\n if (&annotate_img!=NULL) {\n ^~\ncc1plus: some warnings being treated as errors\nmodules/contrib/CMakeFiles/opencv_contrib.dir/build.make:158: recipe for target 'modules/contrib/CMakeFiles/opencv_contrib.dir/src/chamfermatching.cpp.o' failed\nmake[2]: *** [modules/contrib/CMakeFiles/opencv_contrib.dir/src/chamfermatching.cpp.o] Error 1\nCMakeFiles/Makefile2:2974: recipe for target 'modules/contrib/CMakeFiles/opencv_contrib.dir/all' failed\nmake[1]: *** [modules/contrib/CMakeFiles/opencv_contrib.dir/all] Error 2\nMakefile:151: recipe for target 'all' failed\nmake: *** [all] Error 2"
] | [
"opencv",
"ubuntu",
"installation",
"ubuntu-18.04"
] |
[
"unable to pass array entry as data argument - internal sever error",
"I am trying to invoke c# mvc controller method from custom js script using ajax but it seems it does not accept array entries as argument inside the ajax.\n\nI tried to assign them to a non-array variables and it worked, but I need to pass them as array elements.\n\npublic async Task<ActionResult> CallEngineAsync(int id, string command)\n{\n string path = Server.MapPath(\"/PluginDLLs/\");\n\n string output = await EngineBroker.CallEngine(command, path, AppDomain.CurrentDomain);\n\n // Session[\"output\"] = output;\n // Session[\"calledPlugin\"] = id;\n\n var redirectUrl = new UrlHelper(Request.RequestContext).Action(\"Index\", \"Home\");\n return Json(new { Url = redirectUrl });\n}\n\n\nvar pluginIDs = [];\nvar pluginCommands = [];\nvar pluginIntervals = [];\n\n$(\".p-container\").find(\".p\").each(function ()\n{\n var confi = $(this).find(\"#command\").attr(\"value\");\n\n var interval = 1000 * confi.replace(/\\D/g, '');\n\n if (confi.includes(\"interval\") && interval > 0)\n {\n var id = $(this).attr(\"data-pluginid\");\n pluginIDs.push(id);\n\n pluginCommands.push(confi);\n\n pluginIntervals.push(interval);\n }\n});\n\nfor (p = 0; p < pluginIDs.length; p++)\n{\n window.setInterval(function (event, ui)\n {\n $.ajax(\n {\n url: 'Home/CallEngineAsync',\n data: { id: pluginIDs[p], command: pluginCommands[p] },\n traditional: true,\n type: 'POST',\n\n success: function (data)\n {\n window.location.href = data.Url\n },\n\n error: function (xhr, status, error) { }\n });\n\n }, pluginIntervals[p]);\n}\n\n\nI'm gettint the following error: POST https://localhost:44381/Home/CallEngineAsync 500 (Internal Server Error)"
] | [
"javascript",
"c#",
"ajax",
"asp.net-mvc"
] |
[
"Are you allowed to modify func_defaults (__defaults__ in Python 3.x) in Python?",
"I've tried doing this in Python 2.6, and it does \"work\":\n\n>>> def f(i='I'): return i\n...\n>>> f.func_defaults = (10,)\n>>> f()\n10\n\n\nBut is this officially specified behavior, or am I hitting an implementation-specific behavior?"
] | [
"python"
] |
[
"SMS Personalization using AMPScript in Salesforce Marketing Cloud",
"My CRM team is running into problems when attempting to personalize SMS using AMPScript. The syntax used is as follows:\n\n%%[\nVar @subscriberKey \nSet @subscriberKey = _subscriberKey \n]%%\n\n%%= v(@subscriberKey) =%%\n\n\nThank you for signing up for a 45 day risk-free hearing aid trial! One of our expert hearing consultants will call you soon to discuss next steps. During this call, we'll discuss your hearing loss situation and go over the details of the 45 day risk-free trial. We look forward to speaking with you shortly! \n\nI have created a data extension in Marketing Cloud with just me in it, and used it on a journey that sends a text message with this content to my phone. The text message delivers, however the personalization content is not in there, just the plain text is shown. Of course, once the personalization works, we will change it so that other information is in there and not subscriberKey, but for now it would be a ton of help to know why the syntax is not working when it should. \n\nKind regards,\nMichael"
] | [
"javascript",
"salesforce",
"ampscript"
] |
[
"Dapper Postgres stored procedure with parameter",
"try\n{\n return Connection.QuerySingleOrDefault<T>(sql, param, _transaction,\n commandType: CommandType.StoredProcedure);\n}\ncatch (Exception orig)\n{\n var ex = new Exception($\"Dapper proc execution failed!\", orig);\n AddDetailsToException(ex, sql, param);\n throw ex;\n}\n\n\nWith SQL:\n\nCREATE OR REPLACE PROCEDURE public.\"GetChildBank\"(\n \"bankId\" integer DEFAULT NULL::integer)\nLANGUAGE 'sql'\n\nAS $BODY$\n\n )\n select * from cte where ParentBank is not null\n and \"Id\" <> \"bankId\"\n$BODY$;\n\n\nI am using Dapper with PostgreSQL and using stored procedure to get data\nbut it always throws errors.\n\nIt converts into a SQL statement\n\nSELECT * \nFROM \"GetChildBank\"(\"bankId\" := $1)\n\n\nwhich is wrong."
] | [
"c#",
"postgresql",
"dapper"
] |
[
"Share django page to user who does not have an account",
"I am trying to implement sharing in my registration-required website. I would like the user to be able to share a page for a certain duration of time (1 day, 1 week, etc.) so that anyone with a special link can access that page. Is this possible in Django?\n\nEDIT: My solution (based on Saurabh Goyal’s answer):\n\n\nAdd a new model to your models.py, something like this:\n\nclass ShareKey(models.Model):\n location = models.TextField() # absolute path\n token = models.CharField(max_length=40, primary_key=True)\n creation_date = models.DateTimeField(auto_now_add=True)\n expiration_seconds = models.BigIntegerField()\n data = PickledObjectField() # custom sharing data\n\n\n(The data field is optional, and requires django-picklefield).\nIn your views.py, add a decorator function like this:\n\ndef allow_shares(view_func):\n def sharify(request, *args, **kwargs):\n shared = kwargs.get('__shared', None)\n if shared is not None:\n if '__shared' not in view_func.func_code.co_varnames[:view_func.func_code.co_argcount]:\n del kwargs[\"__shared\"]\n return view_func(request, *args, **kwargs)\n else: return login_required(view_func)(request, *args, **kwargs)\n return sharify\n\n\nThis decorator allows a view to require a login, unless the page is shared.\nDecorate any views you want to be shareable with @allow_shares.\nAdd a new Exception subclass, SharifyError, like this:\n\nclass SharifyError(Exception):pass\n\nAlso in views.py, add a view to resolve the shared URLs, like this:\n\ndef sharedPage(request, key):\n try:\n try:\n shareKey = ShareKey.objects.get(pk=key)\n except: raise SharifyError\n if shareKey.expired: raise SharifyError\n func, args, kwargs = resolve(shareKey.location)\n kwargs[\"__shared\"] = True\n return func(request, *args, **kwargs)\n except SharifyError:\n raise Http404 # or add a more detailed error page. This either means that the key doesn’t exist or is expired.\n\nAdd a url to urls.py, like this:\n\nurlpatterns = patterns('',\n # ...\n url(r'^access/(?P<key>\\w+)$', views.sharedPage, name=\"sharedPage\"),\n # ...\n)\n\nFinally, add URLs to create a shared link, and implement the view like this:\n\n# in imports\nfrom django.utils.crypto import get_random_string\n\ndef createShare(request, model_id):\n task = MyModel.objects.get(pk=model_id)\n key = ShareKey.objects.create(pk=get_random_string(40),\n expiration_seconds=60*60*24, # 1 day\n location = task.get_absolute_url(),\n )\n key.save()\n return render(request, 'share.html', {\"key\":key});\n\n\n\n(Your share.html template should look something like this):\n\n{% extends 'base.html' %}\n{% block content %}\n<h1>Sharing link created.</h1>\n<p>The link is <a href=\"{{ base_url }}{% url 'taskShared' key.pk %}\">{{ base_url }}{% url 'taskShared' key.pk %}</a>. It will be valid until {{ key.expiration_date|date:\"l, N dS\" }} at {{ key.expiration_date|time:\"g:i a\" }}.</p>\n{% endblock %}\n\n\nThis will require users to login to view the decorated pages unless they have entered a key."
] | [
"python",
"django"
] |
[
"Cannot fire and catch event using gwt-channel-api when onMessage() is called",
"I'm using GWT + App engine channel api, and I want to fire an event when a message is received.\nI created an interface DataUpdateHanlder (extends EventHandler) and a class DataUpdateEvent (extends GwtEvent) and I use addHandler(...) and fireEvent(...) methods in SimpleEventBus to register handlers and treat events when a message is received.\nThe problem is that although the event is fired, the event does not reach it's handler (nothing happens onDispatch(event) ).\n\nIf I just create and use a simple interface, and just call it's method, everything works ok (but then i have to create a list of objects for each class that wants to handle onMessage(...)).\nWhat am I doing wrong?"
] | [
"java",
"google-app-engine",
"gwt",
"channel-api"
] |
[
"Refer resource folder and not the content in jar",
"We have a simple ML model, compiled and saved as SavedModel/*.pb format. We load the SavedModel/ using TensorFlow 1.5 (Java) for inferencing.\n\nWe are using the below approach to load the model:\n\nString path = 'models/SavedModel'\nFile modelFile = new File(getClass().getClassLoader().getResource(path).getPath());\n\nmodel = SavedModelBundle.loader(modelFile.getAbsolutePath())\n .withTags(\"serve\")\n .load();\nGraph g = model.graph();\n...\n\n\nWe are able to inference the model and get the output using IDE but it does not work, once we build a Jar.\n\nImportant notes: \n\n\nWe have kept the SavedModel in resources dir, like src/main/resources/models/SavedModel/*.pb.\nSavedModelBundle.loader takes String exportDir as first parameter. exportDir is the directory path containing a saved model.\nOnce we create the Jar of the project, we are able to see models/SavedModel/* on the root of the Jar.\n\n\nWe are not able to refer the correct path of the exportDir within the jar. Can anyone please help me here? I'm new to Java world!"
] | [
"java",
"tensorflow"
] |
[
"assets folder not accessible in production?",
"When the grails 3 application with asset pipeline is deployed to production then the css files are bundled as shown below. When we click the link it is not accessible. Because of this the styles are not applied to the pages. The styles works in development in local machine but doesnt work when it is in remote server. How can we make so that the assets files are publicly accessible so that the styles could be applied to the pages? Thanks for help!"
] | [
"grails",
"asset-pipeline",
"grails3"
] |
[
"Attachments on iPad in iFrame docusign",
"I am using iframe to get document signed by clients on ipad. There are attachments as well for each signer, but before attaching the captured image, I want to resize it. Is there a way to resize an image before attaching it with document."
] | [
"docusignapi"
] |
[
"IIS allow access to a specific controller but not all website with windows authentication",
"I have a ASP.NET website set up with Windows Authentication for a specific domain group (MYDOMAIN\\MY_SITE_USERS). I want to add a controller with some actions that can be performed from a special Windows account, without access to the rest of the website.\n\nSo:\n\n~ ==> only MYDOMAIN\\MY_SITE_USERS\n~/DoSomething ==> only MYDOMAIN\\MY_SITE_USERS\n~/SpecialAction/Do ==> only MYDOMAIN\\SPECIAL_ACCOUNT\n\n\nI've seen other answers (using location in Web.Config) for example:\n\n<location path=\"~/SpecialAction/Do\">\n <system.webServer>\n <security>\n <authorization>\n <add accessType=\"Deny\" users=\"*\"/>\n <add accessType=\"Allow\" users=\"MYDOMAIN\\SPECIAL_ACCOUNT\"/>\n </authorization>\n </security>\n </system.webServer>\n</location>\n\n\nbut my the problem is that with the above, then SPECIAL_ACCOUNT can access all the other pages since I need to add to the general:\n\n<authentication mode=\"Windows\" />\n<identity impersonate=\"true\"/>\n<authorization>\n <allow users=\"MYDOMAIN\\SPECIAL_ACCOUNT\" />\n <allow users=\"MYDOMAIN\\MY_SITE_USERS\"/>\n <deny users=\"?\" />\n <deny users=\"*\" />\n</authorization>\n\n\notherwise MYDOMAIN\\SPECIAL_ACCOUNT can't login at all."
] | [
"asp.net-mvc",
"iis",
"web-config",
"windows-authentication"
] |
[
"How to center a table of the screen (vertically and horizontally)",
"I have these code block:\n\n<table border=\"1px\">\n<tr>\n<td>\nmy content\n</td>\n</tr>\n</table>\n\n\nI'd like to show my table in the center of the screen (vertically and horizontally).\n\nHere is a demo.\n\nHow can I do that?"
] | [
"html",
"html-table"
] |
[
"three.js cylinder wireframe without diagonals?",
"I am trying to draw a THREE.js wireframe cylinder without the diagonals in the faces. I am moving the vertices of the cylinder each frame as well, and am wondering if there is a solution to drawing it with quad faces without having to manually create a new set of THREE.Line every frame. EdgesHelper is flickering because it has to create a new one each frame."
] | [
"javascript",
"html",
"three.js",
"wireframe",
"diagonal"
] |
[
"How to remove NA and missing values(blank) from a CSV file and replace them as 0",
"How to remove NA and missing values(blank) from a CSV file and replace them as 0\nI tried the following but not working\n\nmoviedata = read.csv(\"moviedata.csv\", header=TRUE, sep=\",\", dec = \".\", na.strings=c(\"\",\" \",0))"
] | [
"r"
] |
[
"Will moving contents of git clone break git?",
"I created a clone of a git repo using the git clone command. It created a directory /home/xyz in which the src folder exists.\nBut I want it to be cloned to an existing directory, /home/root/xyz.\n\nIt's not creating a clone into /home/root/xyz as it has some other files and folders in it along with src.\n\nMy question is...Suppose I create a clone at /home/xyz and move all the contents of /home/xyz, will it break git? Will it create problems when checking out and in ?"
] | [
"git",
"clone"
] |
[
"Extracting Nested JSON data to SQL Server 2014",
"I have thousands of JSON files and I need those files to import to SQL Server tables. We are using SQL Server 2014. I have given the sample data from the json file. It would be great if someone can help me in flattening the data into csv or xlsx.\n\nThe challenge here is, I need to parse the JSON data into tables with column name and values. It has to loop through n number of times , if the file has n number of nodes\n\nSample Jason Data:\n\n{\n \"RRC-TAPE-RECORD-ID\": \"01\",\n \"WB-API-CNTY\": \"003\",\n \"WB-API-UNIQUE\": \"39808\",\n \"WB-NXT-AVAIL-SUFFIX\": \"0\",\n \"WB-NXT-AVAIL-HOLE-CHGE-NBR\": \"0\",\n \"WB-FIELD-DISTRICT\": \"0\",\n \"WB-RES-CNTY-CODE\": \"3\",\n \"WB-ORIG-COMPL-CC\": \"\",\n \"WB-ORIG-COMPL-CENT\": \"0\",\n \"WB-ORIG-COMPL-YY\": \"0\",\n \"WB-ORIG-COMPL-MM\": \"0\",\n \"WB-ORIG-COMPL-DD\": \"0\",\n \"WB-TOTAL-DEPTH\": \"0\",\n \"WB-VALID-FLUID-LEVEL\": \"0\",\n \"WB-CERT-REVOKED-CC\": \"0\",\n \"WB-CERT-REVOKED-YY\": \"0\",\n \"WB-CERT-REVOKED-MM\": \"0\",\n \"WB-CERT-REVOKED-DD\": \"0\",\n \"WB-CERTIFICATION-DENIAL-CC\": \"0\",\n \"WB-CERTIFICATION-DENIAL-YY\": \"0\",\n \"WB-CERTIFICATION-DENIAL-MM\": \"0\",\n \"WB-CERTIFICATION-DENIAL-DD\": \"0\",\n \"WB-DENIAL-REASON-FLAG\": \"\",\n \"WB-ERROR-API-ASSIGN-CODE\": \"\",\n \"WB-REFER-CORRECT-API-NBR\": \"0\",\n \"WB-DUMMY-API-NUMBER\": \"339808\",\n \"WB-DATE-DUMMY-REPLACED\": \"0\",\n \"WB-NEWEST-DRL-PMT-NBR\": \"613876\",\n \"WB-CANCEL-EXPIRE-CODE\": \"\",\n \"WB-EXCEPT-13-A\": \"N\",\n \"WB-FRESH-WATER-FLAG\": \"N\",\n \"WB-PLUG-FLAG\": \"N\",\n \"WB-PREVIOUS-API-NBR\": \"0\",\n \"WB-COMPLETION-DATA-IND\": \"N\",\n \"WB-HIST-DATE-SOURCE-FLAG\": \"0\",\n \"WB-EX14B2-COUNT\": \"0\",\n \"WB-DESIGNATION-HB-1975-FLAG\": \"0\",\n \"WB-DESIGNATION-EFFEC-CC\": \"0\",\n \"WB-DESIGNATION-EFFEC-YY\": \"0\",\n \"WB-DESIGNATION-EFFEC-MM\": \"0\",\n \"WB-DESIGNATION-REVISED-CC\": \"0\",\n \"WB-DESIGNATION-REVISED-YY\": \"0\",\n \"WB-DESIGNATION-REVISED-MM\": \"0\",\n \"WB-DESIGNATION-LETTER-CC\": \"0\",\n \"WB-DESIGNATION-LETTER-YY\": \"0\",\n \"WB-DESIGNATION-LETTER-MM\": \"0\",\n \"WB-DESIGNATION-LETTER-DD\": \"0\",\n \"WB-CERTIFICATION-EFFEC-CC\": \"0\",\n \"WB-CERTIFICATION-EFFEC-YY\": \"0\",\n \"WB-CERTIFICATION-EFFEC-MM\": \"0\",\n \"WB-WATER-LAND-CODE\": \"L\",\n \"WB-TOTAL-BONDED-DEPTH\": \"0\",\n \"WB-OVERRIDE-EST-PLUG-COST\": \"0\",\n \"WB-SHUT-IN-DATE\": \"0\",\n \"WB-SHUT-IN-YEAR\": \"0\",\n \"WB-SHUT-IN-MONTH\": \"0\",\n \"WB-OVERRIDE-BONDED-DEPTH\": \"0\",\n \"WB-SUBJ-TO-14B2-FLAG\": \"N\",\n \"WB-PEND-REMOVAL-14B2-FLAG\": \"N\",\n \"WB-ORPHAN-WELL-HOLD-FLAG\": \"0\",\n \"RRC-TAPE-FILLER\": \"\"\n}\n\n\nThanks a lot in advance"
] | [
"python",
"json",
"sql-server-2014-express"
] |
[
"Can't read interpolated values in Java validation",
"In my Spring MVC application I'm making use of @Validated objects in my controllers, using JSR-303. In my Spring application context I have defined a custom MessageSource, to read messages from a resources/messages.properties file.\n\nI'm able to read and override javax.validation default messages (such as NotNull), but I get an error if I try to use message interpolation to read a parameter (e.g.: min or max from @Size(max=...).\n\nNote that if I set a message directly in my model, it correctly shows the \"interpolated\" message (default message works fine too).\n\nModel class:\n\n public class Customer {\n\n @JsonProperty(\"name\")\n @NotNull\n @Size(max = 50) // if I add message = \"This field must be less than {max} characters long\" it works!\n private String name;\n\n // Other fields here + getters and setters\n }\n\n\nmessages.properties:\n\nSize=This field must be less than {max} characters long\nNotNull=This field must be set."
] | [
"java",
"spring",
"spring-boot",
"spring-mvc",
"javax.validation"
] |
[
"Add extra fee based on Woocommerce product categories and user country",
"I need to add extra fee based on categories and country!\nThe code is working well with country and single category, but I can not add exceptions for the other categories.\n\n\nMy goal is to create an extra fee for medium packs of € 30 with category (1,2,3) and an extra fee for large packs of € 50 with category (4,5,6), both valid for Europe country.\nAn extra fee of 10 € dedicated to Italy with category (1,2,3,4,5,6)\n\n\nHere my code:\n\nfunction df_add_ticket_surcharge_large( $cart_object ) {\nglobal $woocommerce;\n\n$specialfeecat = 1; // category id for the special fee\n$spfee = 0.00; // initialize special fee\n$spfeeperprod = 50; //special fee per product\n$county = array('BE','EL','LT','PT','BG','ES','LU','RO','CZ','FR','HU','SI','DK','HR','MT','SK','DE','NL','FI','EE','CY','AT','SE','IE','LV','PL','UK');\n\nforeach ( $cart_object->cart_contents as $key => $value ) {\n $proid = $value['product_id']; //get the product id from cart\n $quantiy = $value['quantity']; //get quantity from cart\n $itmprice = $value['data']->price; //get product price\n\n $terms = get_the_terms( $proid, 'article-type' ); //get taxonamy of the prducts\n if ( $terms && ! is_wp_error( $terms )) :\n foreach ( $terms as $term ) {\n $catid = $term->term_id;\n if($specialfeecat == $catid ) {\n $spfee = $spfeeperprod;\n }\n }\nendif; \n}\n\nif ( in_array( $woocommerce->customer->get_shipping_country(), $county ) ) {\n $woocommerce->cart->add_fee( 'Large Pack', $spfee, true, 'standard' );\n }\n }add_action('woocommerce_cart_calculate_fees','df_add_ticket_surcharge_large');\n\n\nAnyone can help me please?"
] | [
"php",
"wordpress",
"woocommerce",
"cart",
"fee"
] |
[
"Are the new object literals backwards compatible with iOS 5?",
"I'm trying to figure out if I should start using the recently added object literals to subscripting dictionaries, arrays and so on. This following post seems to indicate that iOS5 doesn't support them, and I read that the functionality was added in iOS6.\n\nIs that the case? Is anybody using the new literals in iOS5 successfully?"
] | [
"objective-c",
"ios",
"ios5"
] |
[
"Update tkinter widget parameters with \"pointer\"",
"If I create a tkinter.Label with parameter fg = PRIMARY_COLOR and than .pack() it, if I change the value of PRIMARY_COLOR variable, call the .update() method of the widget, foreground color will not change. I know, why this is happening, but can I somehow do, that the widget will change foreground color with the PRIMARY_COLOR variable change? Can I make some kind of \"pointer\"?"
] | [
"python",
"pointers",
"variables",
"tkinter",
"parameters"
] |
[
"How to point Eclipse to another ECJ (internal compiler)",
"There is a bug in EJC (Eclipse's internal Java compiler) and I do not want to wait for an official bugfix. Is there way to point an existing Eclipse installation (let's say 4.6) to an ECJ version from 4.7 beta?\n\nI know, I could just replace .jar(s), but is there an \"official\" way of doing so?"
] | [
"java",
"eclipse",
"javacompiler"
] |
[
"Javascript variable not acting global",
"I'm just learning Javascript after starting out in PHP.\n\nI'm trying some basic stuff, but for some reason the below code doesn't act as I expect. I have researched it, and from what I can tell it should work.\n\n<script type=\"text/javascript\">\nshowIndex=4;\n\nfunction test(){\nshowIndex++;\nalert(showIndex);\n}\n</script>\n\n\nI am calling the script with an image:\n\n<div style=\"display:inline-block;margin-left:25px;\">';\n<a href=\"\" onclick=\"test()\" ><img src=\"_images/next.png\" width=\"100\" /> </a>\n</div>\n\n\nIt runs fine the first time, but when I hit the button again, it still has the initial variable plus one. (which makes me think it's acting as a local variable...)\nIt seem so straight forward... what am I doing wrong?"
] | [
"javascript",
"variables"
] |
[
"Does simple 'crypto' in code fall under iOS Export Compliance?",
"I programmed an App that performs some simple encryption. A user enters a text and a codeword and the app shows back an 'encrypted' text. My 'encryption' just shifts some characters (e.g. 'a' becomes a '5' depending on the codeword). Reading the export compliance in the App Store, made me unsure about whether my app is now using encryption or not? I thought they just mean encryption like RSA or SSL or things like that or does the encryption function in my app also fall under that?"
] | [
"ios",
"encryption",
"app-store"
] |
[
"FlashBuilder PersistenceManager working on devices, but not in Windows",
"I am using FlashBuilder 4.6 for building Mobile applications.\nI am using PersistenceManager and it works great on all devices (phew..)\nMy problem is in my Windows computer - it does not save anything. The function calls are successful, but when I relaunch my app in Windows, it's like nothing had been saved.\n\nprivate var saveManager:PersistenceManager = new PersistenceManager();\nsaveManager.setProperty(\"Radiohead\", \"Thomyourke\");\nsaveManager.save();\n\n\nAny suggestions ?"
] | [
"actionscript-3",
"apache-flex",
"actionscript",
"flash-builder",
"flex-mobile"
] |
[
"tsql - delete last row",
"I want to delete the last row from the table that satisfies some condition.\n\nDELETE TOP 1 FROM SOME_TABLE\nWHERE SOME_COULMN = @VALUE\nORDER BY 1 DESC"
] | [
"tsql"
] |
[
"using django.core JSON serializer with JQuery, syntax inconsistency",
"I'm trying to pass a 'User' object (which is a Django.models.Model) to my web view, however Django and jQuery don't seem to be agreeing on what constitutes valid JSON.\n\nThe relevant pieces of code:\n\nThe object in question, User (in models.py)\n\nclass User(models.Model):\n def __unicode__(self):\n return self.name\n name = models.CharField(max_length = 255)\n adress = models.CharField(max_length = 255)\n city = models.CharField(max_length = 255)\n bank_account = models.CharField(max_length = 9)\n email = models.EmailField()\n barcode = models.CharField(max_length = 10)\n isAdmin = models.BooleanField()\n credit = models.IntegerField()\n\n\nThe view (in views.py):\n\ndef user(request, user_id):\n user = User.objects.filter(pk=user_id)\n\n JSONSerializer = serializers.get_serializer(\"json\")\n json_serializer = JSONSerializer()\n json_serializer.serialize(user)\n\n data = json_serializer.getvalue()\n\n if request.is_ajax():\n return render_to_response(\"pos/user.json\", {'user': data});\n else:\n return HttpResponse(status=400);\n\n\nThe Django template (pos/user.json):\n\n{{user}}\n\n\nThe jQuery code:\n\n var resp = $.getJSON(\"user/\" + $('#elem').text() + \".json\",function(json) {\n $('#debug').html(\"json gotten!\");\n });\n resp.error(function(){$('#debug').html(resp.responseText);});\n\n\nThe result is that #elem remains unchanged, #debug gets the value:\n\n[{\"pk\": 4, \"model\": \"pos.user\", \"fields\": {\"city\": \"test\", \"name\": \"test\", \"barcode\": \"test\", \"credit\": 10, \"isAdmin\": false, \"adress\": \"test\", \"email\": \"[email protected]\", \"bank_account\": \"000000000\"}}]\n\n\nIf I remove the square brackets from the output, #debug becomes \"json gotten!\". \n\nFrom the information I have so far I'm guessing that the issue may be that the Django serializer outputs something almost, but not quite, entirely unlike JSON. I haven't been able to find the square brackets in any specification of JSON (atleast, not in this position). \n\nThe solution many suggest is using the simplejson library, but as my User is a django.models.Model and its fields are of the type django.models.*Field, simplejson gave an error of the \"do not want\" variety.\n\nIs there any way I can fix this code, without resorting to manually trimming the '[' and ']' from my serialized string?\n\nP.S.: There are some questions on SO that are similar to this one, I have however not been able to find an actual answer\n\nEdit: added the 'User' object, to avoid confusion. \n\nEdit: simply passing one object to the serializer does not work, this gives the error: \"'User' object is not iterable\""
] | [
"jquery",
"python",
"django",
"json"
] |
[
"What does a string literal mean in Coffeescript",
"The Coffeescript docs contain the following blurb\n\n\n String Interpolation, Block Strings, and Block Comments\n Ruby-style string interpolation is included in CoffeeScript. Double-quoted strings allow for interpolated values, using #{ ... }, and single-quoted strings are literal.\n\n\nCan someone explain what \"single-quoted strings are literal\" means here?\n\nDoes it just mean that there will be no interpretation? Is there a more javascripty meaning?\n\nI ask because I was seeing a difference when using a single quoted string vs a double quoted as a object key."
] | [
"coffeescript"
] |
[
"Spring.NET attributes based configuration",
"I have my asp.net MVC application and I need to configure spring objects with attributes like [Service], [Repository], [PostConstruct] and [Autowired] (In Java i can do this with option in context-config file), but i cannot find any information how i can do this...\n\nI've found a lot of docs about Spring.CodeConfig, but all of them shows how use [Configuration] and [Definition] attributes on config classes...\n\nSo, is it possible to configure Spring.NET to scan some assemblies for [Service] and other attributes and automatically add them to context?"
] | [
"c#",
".net",
"asp.net-mvc-4",
"spring.net"
] |
[
"How to filter out rows based on multiple conditions in R",
"Using base R I want to filter out rows based on different conditions.\nFirst example is a really simple one but i seem to be missing something. I want to filter out all rows in to a new DF that contain values \"A\" and \"C\". To filter out based on just one condition \"A\" I would use the code:\n\nDF2 <- DF1 [DF1$letters == \"A\",] \n\n\nThis works great. But to get out both I can't seem to get the code to work. I tried:\n\nDF2 <- DF1 [DF1$letters == \"A\" & \"B\" ,] \n\nit did not work. \n\nSecond situation is slightly more complex. In this case I want to filter out all rows that contain \"A\" and \"C\" from the column \"Letters\" and all the rows from column \"Numbers\" that contain \"2\" \n\n\"Letters\" \"Numbers\" \"ID\"\n A 10 A1\n B 2 B1\n C 15 A2\n D 7 A3\n E 32 B2\n\n\nEnd up with a new DF\n\n\"Letters\" \"Numbers\" \"ID\"\n A 10 A1\n B 2 B1\n C 15 A2\n\n\nThank you for any help."
] | [
"r"
] |
[
"Windows Store App - XAML - Bind two values for Height Property",
"I want to bind the height of a control the sum of two other heights, so the UI looks nice various screen sizes.\n\n<GridView\n AutomationProperties.AutomationId=\"ItemDetails\"\n ItemsSource=\"{Binding data}\"\n IsSwipeEnabled=\"False\"\n SelectionMode=\"None\" Height=\"{Binding Height, (ElementName=item - ElementName=itemTitle)}\" >\n <GridView.ItemTemplate>\n <DataTemplate>\n <dll:TaskItemControl/>\n </DataTemplate>\n </GridView.ItemTemplate>\n</GridView>\n\n\nThe above XAML is invalid, but it demonstrates what I want to do. I have two elements, item and itemTitle. item is a ScrollView that gets set to the height of the screen and I want the GridView to be the same height as the ScrollView minus the height of the itemTitle.\n\nIs there a way to do this in XAML?\n\nNote: The reasons for doing this are beyond the scope of this question. So please don't comment about restricting the height of a control within a ScrollView."
] | [
"c#",
"xaml",
"windows-store-apps"
] |
[
"Is there a way to parse a application manifest?",
"I am looking for a way to have the hosting website parse out the [appname].manifest file to pull out the application name, version, and icon if available. This way I can put it into a control for easy deployment. Are there any framework calls that will assist me in parsing out the manifest file?\n\nThe files I am looking for are [appname].application and/or [appname].manifest"
] | [
"c#",
"clickonce",
"manifest"
] |
[
"Convert .pem file into .crt using openssl",
"I want to be able to send certificates in my API requests.\nPlease see - Add certificate on request with RestSharp\nAs shown in that post. I need to convert .crt and .key to .pfx , however my current certificates are .pem, so I thought I will need to convert them into .crt and .key first and then use the openssl comand used in that post to convert them into .pfx and then carry on with the rest of the solution.\nMy certificates are -\nCRT file -\nC:\\Users\\JohnSmith\\Downloads\\certsh\\client-crt.pem\nKey file -\nC:\\Users\\JohnSmith\\Downloads\\certsh\\client-key.pem\nI was able to convert the Key file to a .key , but when trying to convert the CRT file I am getting this error.\nunable to load certificate 13668:error:0906D06C:PEM routines:PEM_read_bio:no start line:.\\crypto\\pem\\pem_lib.c:697:Expecting: TRUSTED CERTIFICATE error in x509\n\nI am using this command to try and convert the .pem to .crt\nx509 -outform der -in client-csr.pem -out client.crt"
] | [
"ssl",
"postman",
"restsharp",
"pem",
"crt"
] |
[
"Library not loaded: @rpath/libpython3.5m.dylib --> Jupyter Notebook Kernel does not start",
"I tried to update the notebook version from the Anaconda Navigator and got an error. After that the notebook starts, but the kernel does not. I uninstalled anaconda with anaconda clean and installed again, but the error persists. The message it prints on the terminal is: \n\n[I 17:03:55.689 NotebookApp] KernelRestarter: restarting kernel (4/5), new random ports\nkernel eaf804ca-e585-4dfa-b30c-09cd1de604eb restarted\ndyld: Library not loaded: @rpath/libpython3.5m.dylib\n Referenced from: /Users/phribeiro/anaconda/bin/python3\n Reason: no suitable image found. Did find:\n /Users/phribeiro/anaconda/bin/../lib/libpython3.5m.dylib: file too short\n[W 17:03:58.699 NotebookApp] KernelRestarter: restart failed\n[W 17:03:58.700 NotebookApp] Kernel eaf804ca-e585-4dfa-b30c-09cd1de604eb died, removing from map.\nkernel eaf804ca-e585-4dfa-b30c-09cd1de604eb restarted failed!\n[W 17:03:58.718 NotebookApp] 410 DELETE /api/sessions/865314d0-bcc2-42e1-ae17-98c82511ebef (::1): Kernel deleted before session\n[W 17:03:58.718 NotebookApp] Kernel deleted before session\n[W 17:03:58.719 NotebookApp] 410 DELETE /api/sessions/865314d0-bcc2-42e1-ae17-98c82511ebef (::1) 4.14ms referer=http://localhost:8889/notebooks/Untitled11.ipynb\n\n\nAny suggestions?"
] | [
"anaconda",
"jupyter-notebook",
"dylib"
] |
[
"How to format date in JSTL",
"I have a loop that goes through all the news items we have on our site. One of the fields is date ${newsitem.value['Date']}, given in millliseconds. I'd like to display this date in month/day/year format on the webpage. I thought JSTL format tag, <fmt:formatDate>, would help, but I haven't succeeded. Do you know how to do it? \n\n<cms:contentaccess var=\"newsitem\" />\n<h2><c:out value=\"${newsitem.value['Title']}\" /></h2>\n// display date here \n<c:out value=\"${newsitem.value['Text']}\" escapeXml=\"false\" />"
] | [
"datetime",
"jstl",
"formatdatetime"
] |
[
"complicated query entry mysql php",
"I'm having great trouble with \"INSERT INTO\"...\n\nI have a variable part number so this my code...:\n\n<?php\ninclude (\"db_conn.php\");\n\n$mem_id = \"1\";\n$descript = \"chair\";\n$qualifier = \"sitting\";\n$major = \"Y\";\n$value = \"6\";\n//$mesh_cell_string = \"tree_0,tree_1,tree_2,tree_3,tree_4\";\n//$mesh_values_string = \"'C23','550','291','687','500'\";\n\n$part_number = \"C23.550.291.687.500\";\n$parts = explode('.', $part_number);\n\n$n = 0;\nforeach ($parts as $something => $number)\n {\n $mesh_cell_string .= \"tree_\" . $n . \",\";\n $mesh_values_string .= \"'\" . $number . \"',\" ;\n\n $n++;\n } \n\n$mesh_values_string = substr($mesh_values_string, 0, -1);\n$mesh_cell_string = substr($mesh_cell_string, 0, -1);\n\n\n\n\n$insert_string = \"mem_id,mesh_heading_name,\" . $mesh_cell_string . \",qualifier_name,major,rank\";\n$values_string = \"'$mem_id','$descript',\" .$mesh_values_string. \",'$qualifier','$major','$value'\"; \n\n\n$sql = \"INSERT INTO mesh_table (\" . $insert_string .\") VALUES (\" . $values_string .\")\";\n\n$result = mysqli_query($cxn,$sql) or die (\"couldn't execute the query\");\n\n\n?>\n\n\nThe strange thing is... i don't get an error (\"couldn't execute the query\") so i thought it went alright but when i look into my database there aren't any values written... when i un-comment the the 2 variables:\n\n//$mesh_cell_string = \"tree_0,tree_1,tree_2,tree_3,tree_4\";\n//$mesh_values_string = \"'C23','550','291','687','500'\";\n\n\nAnd comment the foreach loop, it works...? So there goes something wrong in the foreach loop, but when i echo the $sql on both methods i get the same:\n\nINSERT INTO mesh_table (mem_id,mesh_heading_name,tree_0,tree_1,tree_2,tree_3,tree_4,qualifier_name,major,rank) VALUES ('1','Chair','C23','550','291','687','500','sitting','Y','6')\n\n\nI really don't know what i am doing wrong...?\n\nBest regards,\nThijs"
] | [
"php",
"mysql",
"insert",
"foreach"
] |
[
"How to use the same Scanner across multiple classes in Java",
"I have a program that uses multiple classes, I want the other classes to be able to access the same scanner that I have declared in the main class, I assume it would be done using some sort of get method, however I am unable to find any resources to help me. \n\nHere are the Scanners that I have made in my main class:\n\n Scanner in = new Scanner(System.in);\n System.out.println(\"Enter a filename\");\n String filename = in.nextLine();\n File InputFile = new File (filename);\n Scanner reader = new Scanner(filename);\n\n\nThe reader Scanner is the one I want to be able to access across the other classes that make up the program, can anyone give me some guidance on how I can do this? Thanks a lot for any help!"
] | [
"java",
"class",
"java.util.scanner"
] |
[
"Winforms Datagridview MultiSelect option not working as expected",
"According to MSDN, MultiSelect option allows user to select multiple rows with Ctrl or Shift modifier, but I can select multiple rows with left mouse button only without pressing any control modifier. Is it possible to stop multiple selection without pressing Shift or Ctrl modifiers?\nI'm using Windows 10 and Visual Studio 2019."
] | [
"winforms",
"datagridview"
] |
[
"how to create a webpage with simple controls and python back end",
"i have a python function which takes text and some parameters as an input.\ni want to build a simple web page with some controls:\n\n\na file upload control\na text box\nsome radio buttons to choose parameters\na submit button\n\n\nuser will either use the upload control or enter some text in the box.\nupon submission my python function will run in the back end and return results to be displayed on the page.\n\nas a complete web newbie i am wondering what would be the easiest way to approach this.\n\ni am not sure on what machine this will run and what permissions i will have, so lets assume a generic LAMP server (if this makes any sense)"
] | [
"python",
"web"
] |
[
"How to solve psql: FATAL: role \"ubuntu\" does not exist",
"When i run rails db i get the below error. \npsql: FATAL: role \"ubuntu\" does not exist \n\nFirst i want to know the exact meaning of what it says before solving it. \nI have tried http://stackoverflow.com/questions/11919391/postgresql-error-fatal-role-username-does-not-exist this link as well but nothing seems to workout for me .."
] | [
"ruby-on-rails",
"postgresql",
"ubuntu",
"psql"
] |
[
"Maven: How a project can be able to reference a class from a secondary previous dependency",
"I am working with Maven and creating my own modules. \n\nI have the 01CentralDomain project\nwith the simple com.manuel.jordan.domain package with three @Entities\none of them is for example Product\n\nPart of its pom.xml is:\n\n<modelVersion>4.0.0</modelVersion>\n<groupId>com.manuel.jordan.centraldomain</groupId>\n<artifactId>central-domain</artifactId>\n<packaging>jar</packaging>\n<name>01CentralDomain</name>\n<version>1.0.1</version>\n<url>https://github.com/manueljordan/</url>\n\n\nI have the other 02CentralDomain project\nagain with the same simple com.manuel.jordan.domain package with two new @Entities\none of them is for example User\n\nConsider this how an extension of the first project\n\nPart of its pom.xml is:\n\n<modelVersion>4.0.0</modelVersion>\n<groupId>com.manuel.jordan.centraldomain</groupId>\n<artifactId>central-domain</artifactId>\n<packaging>jar</packaging>\n<name>02CentralDomain</name>\n<version>1.0.2</version>\n<url>https://github.com/manueljordan/</url>\n...\n<dependencies>\n\n <dependency>\n <groupId>com.manuel.jordan.centraldomain</groupId>\n <artifactId>central-domain</artifactId>\n <version>1.0.1</version>\n </dependency>\n\n</dependencies>\n\n\nTherefore practically my second project has access to the first project, it about to be able to reference the three entities, like Product, we can assume my domain package now has a total of 5 entities, 3 from the first + 2 for the second. \n\nNow I have a third project (02CentralExecution)\n\nPart of its pom.xml is:\n\n<modelVersion>4.0.0</modelVersion>\n<groupId>com.manuel.jordan.centralexecution</groupId>\n<artifactId>central-execution</artifactId>\n<packaging>jar</packaging>\n<name>02CentralExecution</name>\n<version>1.0.2</version>\n<url>https://github.com/manueljordan/</url>\n...\n<dependencies>\n\n <dependency>\n <groupId>com.manuel.jordan.centraldomain</groupId>\n <artifactId>central-domain</artifactId>\n <version>1.0.2</version>\n </dependency>\n\n</dependencies>\n\n\nTheoretically the third project has access to the second project source code and therefore for the first project source code too.\n\nIt does not work, the third project only can access the second project source code.\nI can use the User class but not the Product class.\n\nEven if I declare both\n\n<dependencies>\n\n <dependency>\n <groupId>com.manuel.jordan.centraldomain</groupId>\n <artifactId>central-domain</artifactId>\n <version>1.0.1</version>\n </dependency>\n <dependency>\n <groupId>com.manuel.jordan.centraldomain</groupId>\n <artifactId>central-domain</artifactId>\n <version>1.0.2</version>\n </dependency>\n\n</dependencies>\n\n\nIt does not work.\n\nHow I can get working this?"
] | [
"java",
"maven"
] |
[
"SharpZipLib - adding folders/directories to a zip archive",
"From examples, I've got a pretty good grasp over how to extract a zip file.\n\nIn nearly every example, the method of identifying when a ZipEntry is a directory is as follows\n\nstring directoryName = Path.GetDirectoryName(theEntry.Name);\nstring fileName = Path.GetFileName(theEntry.Name);\n\nif (directoryName.Length > 0)\n Directory.CreateDirectory(Path.Combine(destinationDirectory, directoryName)); \n\nif (fileName != String.Empty)\n{\n //read data and write to file\n}\n\n\nNow is is fine and all (directory encountered, create it), directory is available when the file is extracted.\n\nI can add files to a zip fine, but how do I add folders? I understand I'll be looping through the directories, adding the files encountered (and their ZipEntry.Name property is populated properly), but how do I add a ZipEntry to the archive and instruct the ZipOutputStream that it is a directory?"
] | [
"c#",
"zip",
"sharpziplib"
] |
[
"Php logging to a file with fwrite",
"Question 1:\nWhat is the best way to write multiple variables?\n\nI'm currently writing them like this.\n\nfwrite($fp, $var1);\nfwrite($fp, $var2);\nfwrite($fp, $var3);\n ...etc\n\n\nAnd that makes one long healthy string of output. \n\nQuestion 2:\nHow do I add line breaks and comments without writing something like:\n\nfwrite($fp, 'var1:');\nfwrite($fp, &var1); \n<br>?"
] | [
"php"
] |
[
"Created website launcher - want it to close after it launches browser",
"This is my first android app. I've searched around and tried different ways to create an app that will just open a browser to my website.\n\nIt works well except for the fact that it stays running. If I re-open it, it's just a black screen with a title since it's already done its job of launching the browser.\n\nThe code is:\n\npackage pro.linuxos.weblaunch;\nimport android.app.Activity;\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.os.Bundle;\nimport android.webkit.WebView;\npublic class LinuxOSProWeblaunchActivity extends Activity\n{\nWebView webview;\n@Override\npublic void onCreate(Bundle savedInstanceState)\n{\nsuper.onCreate(savedInstanceState);\nIntent viewIntent = new Intent(\"android.intent.action.VIEW\", Uri.parse(\"http://LinuxOS.pro\")); \nstartActivity(viewIntent);\n}\n}\n\n\nThere may be some extra webview things in there now that I look at it :) I was using that, but was having issues turning on javascript..\n\nAnyway, is there a way to exit after it launches the browser so I don't have to back-button out of it to use it again?\n\nThanks!"
] | [
"android"
] |
[
"Usage of Redis for very large memory cache",
"I am planning to consider Redis for storing large amount of data in cache. Currently I store them in my own cache written in java. My use case is below.\n\nI get 15 minutes data from a source and i need to aggregate the data hourly. So for a given object A every hour I will get 4 values and I need to aggregate them to one value the formula I will use will max / min / sum.\n\nFoe making key I plan to use like below\n\na) object id - long\n\nb) time - long\n\nc) property id - int (each object may have many property which I need to aggregate for each property separately)\n\nSo final key would look like;\n\nobjectid_time_propertyid\n\nEvery 15 minutes I may get around 50 to 60 Million keys , I need to fetch these keys every time convert the property value to double and apply the formula (max/min/sum etc.) then convert back to String and store back.\nSo I see for every key I have one read and one write and conversion in each case.\n\nMy questions are following.\n\n\nIs is advisable to use redis for such use case , going forward I may aggregate hourly data to daily , daily to weekly and so on.\nWhat would be performance of read and writes in cache (I did a sample test on Windows and 100K keys read and write took 30-40 seconds thats not great , but I did on windows and I finally need to run on linux.\nI want to use persistence function of redis, what are pros and cons of it ?\n\n\nIf any one has real experience in usage of redis as memcache which requires frequent updation please give a suggestion."
] | [
"node.js",
"caching",
"redis",
"jedis"
] |
[
"\"aliasing detected during transposition\" in Eigen",
"I have the following code:\n\ntemplate <typename T>\nusing Arr = Array<T, Dynamic, 1>;\n\ntemplate <typename T>\nusing Arr2 = Array<T, Dynamic, Dynamic>;\n\ntemplate <typename T>\nArr2<typename T::Scalar> reshape (const ArrayBase<T> & A, const uint n, const uint m) {\n return Map<const Arr2<typename T::Scalar>>(A.eval().data(), n, m);\n}\n\nArr<double> v = Arr<double>::LinSpaced(16, 0, 15);\nauto w = reshape(v, 4, 4).transpose();\nstd::cout << w << std::endl;\n\n\nwhich produces the error\n\n\n static void Eigen::internal::checkTransposeAliasing_impl::run(const Derived&, const\n OtherDerived&) [with Derived = Eigen::Array; OtherDerived = Eigen::Transpose >; bool MightHaveTransposeAliasing = true]: Assertion\n `(!check_transpose_aliasing_run_time_selector ::IsTransposed,OtherDerived>\n ::run(extract_data(dst), other)) && \"aliasing detected during\n transposition, use transposeInPlace() \" \"or evaluate the rhs into a\n temporary using .eval()\"' failed.\n\n\nAdding eval indeed fixes the issue:\n\nauto w = reshape(v, 4, 4).transpose().eval();\n\n\n(but adding it do the printing line as << w.eval() << doesn't).\n\nI would like to have a better understanding of what going on and to find out if there's another way to fix this.\n\nThank you"
] | [
"c++",
"eigen"
] |
[
"Unable to automate a click using Python and Selenium",
"I'm trying to automate adding requirements to a TestLink database. I'm running into an issue trying to click on this anchor/span. \n\n<a hidefocus=\"on\" class=\"x-tree-node-anchor\" href=\"javascript:REQ_SPEC_MGMT(17473)\" tabindex=\"1\">\n<span unselectable=\"on\" id=\"extdd-6\">0:Project-0 (0)</span>\n</a>\n\n\nHere is the section of Python code with things I've tried:\n\nanchor = browser.find_element_by_xpath('//a[contains(@href, \"REQ_SPEC_MGMT\")]')\nspan = anchor.find_element_by_xpath('.//span')\n\nanchor.click() # Doesn't work\nspan.click() # Doesn't work\nbrowser.execute_script(\"arguments[0].click();\", anchor) # Doesn't work\nbrowser.execute_script(\"arguments[0].click();\", span) # Doesn't work\n\n\nI don't get any errors, but I still don't get the page that appears when I manually click on the link. I verified that I'm finding the correct anchor/span by dumping out the properties so I know I have the correct elements. I've also tried long pauses just to make sure that the element is clickable before I try it. Any ideas on what I am doing wrong? Thanks!\n\nUpdate - Here's a larger section of the HTML:\n\n<div id=\"tree_div\" style=\"overflow:auto; height:100%;border:1px solid #c3daf9;\" class=\" x-panel x-tree\">\n<div class=\"x-panel-bwrap\" id=\"ext-gen12\"><div class=\"x-panel-body x-panel-body-noheader\" id=\"ext-gen13\" style=\"overflow: auto;\">\n<ul class=\"x-tree-root-ct x-tree-arrows\" id=\"ext-gen14\">\n<li class=\"x-tree-node\"><div ext:tree-node-id=\"17472\" class=\"x-tree-node-el x-unselectable x-tree-node-expanded\" unselectable=\"on\" id=\"extdd-1\">\n<span class=\"x-tree-node-indent\"></span>\n<img alt=\"\" src=\"http://192.168.11.111/third_party/ext-js/images/default/s.gif\" class=\"x-tree-ec-icon x-tree-elbow-end-minus\">\n<img alt=\"\" src=\"http://192.168.11.111/third_party/ext-js/images/default/s.gif\" class=\"x-tree-node-icon\" unselectable=\"on\" id=\"extdd-2\">\n<a hidefocus=\"on\" class=\"x-tree-node-anchor\" href=\"javascript:TPROJECT_REQ_SPEC_MGMT(17472)\" tabindex=\"1\">\n<span unselectable=\"on\" id=\"extdd-3\">ProjTasks (0)</span>\n</a>\n</div>\n<ul class=\"x-tree-node-ct\" style=\"\">\n<li class=\"x-tree-node\">\n<div ext:tree-node-id=\"17473\" class=\"x-tree-node-el x-unselectable folder x-tree-node-collapsed\" unselectable=\"on\" id=\"extdd-4\">\n<span class=\"x-tree-node-indent\"><img alt=\"\" src=\"http://192.168.11.111/third_party/ext-js/images/default/s.gif\" class=\"x-tree-icon\"></span>\n<img alt=\"\" src=\"http://192.168.11.111/third_party/ext-js/images/default/s.gif\" class=\"x-tree-ec-icon x-tree-elbow-plus\">\n<img alt=\"\" src=\"http://192.168.11.111/third_party/ext-js/images/default/s.gif\" class=\"x-tree-node-icon\" unselectable=\"on\" id=\"extdd-5\">\n<a hidefocus=\"on\" class=\"x-tree-node-anchor\" href=\"javascript:REQ_SPEC_MGMT(17473)\" tabindex=\"1\">\n<span unselectable=\"on\" id=\"extdd-6\">0:Project-0 (0)</span></a></div><ul class=\"x-tree-node-ct\" style=\"display:none;\">\n</ul>\n</li>"
] | [
"selenium",
"selenium-webdriver",
"xpath",
"css-selectors",
"webdriverwait"
] |
[
"HAS ANCESTOR and HAS DESCENDANT clauses in google cloud datastore",
"I'm studying the Google Cloud Datastore GQL grammar - specifically the HAS ANCESTOR and HAS DESCENDANT comparison operators.\n\nGiving the following Person entities:\n\n\nAmy \nFred, parent = Amy\nLaura, parent = Amy\nPaul\nAgnes ...\n\n\nWould the GQL queries below produce the same output?\n\nSELECT * FROM Person WHERE key_name='Fred' HAS ANCESTOR KEY('Person', 'Amy')\n\nSELECT * FROM Person WHERE KEY('Person', 'Amy') HAS DESCENDANT key_name='Fred'\n\n\nIf so, I don't understand the existence of HAS DESCENDANT clause.\n\nThanks in advance!"
] | [
"gql",
"google-cloud-datastore"
] |
[
"How to speedup php soap client",
"I'm using a web service to send SMS in PHP. The code in like below:\n\n$options = array(\n'login' => 'yourusername',\n'password' => 'yourpassword'\n);\n$client = new SoapClient('http://sms.hostiran.net/webservice/?WSDL', $options);\ntry\n{\n $messageId = $client->send(destination mobile number, 'test sms');\n sleep(3);\n print ($client->deliveryStatus($messageId));\n var_dump($client->accountInfo());\n}\ncatch (SoapFault $sf)\n{\n print $sf->faultcode.\"\\n\";\n print $sf->faultstring.\"\\n\";\n}\n\n\nThe problem is that when i run this code on a WAMP server, it runs rapidly.But when i use this code in an ubuntu server, the speed of running this code is very low.\nIs there any configuration in php.ini to solve this problem ?\n\nThanks!"
] | [
"php",
"soap"
] |
[
"ImportError: cannot import name objects",
"I am using python Facebook Ads SDK, I try to get my ad accounts: \n\nfrom facebookads import FacebookAdsApi\nfrom facebookads import objects\nmy_app_id = 'my_app_id'\nmy_app_secret = 'my_app_secret'\nmy_access_token = 'my_access_token'\nFacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)\n\nme = objects.AdUser(fbid='me')\nmy_accounts = list(me.get_ad_accounts())\nprint my_accounts\n\n\nbut when I run the script I got ImportError: cannot import name objects"
] | [
"python",
"facebook-ads-api"
] |
[
"Cordova build: Error converting bytecode to dex: Dex cannot parse version 52 byte code",
"Error occurs when trying to build cordova app on android with firebase plugin:\n\ncordova-build error : Dex: Error converting bytecode to dex:\ncordova-build error : Cause: Dex cannot parse version 52 byte code."
] | [
"android",
"firebase",
"cordova"
] |
[
"Plotting with multiple y values with subplot and groupby",
"I have a df. See below for the head:\n\nCountry Date suspected case confirmed cases suspected deaths confirmed deaths \n\n0 Guinea 2014-08-29 25.0 141.0 482.0 648.0\n1 Nigeria 2014-08-29 3.0 1.0 15.0 19.0\n2 Liberia 2014-08-29 382.0 674.0 322.0 1378.0\n\n\nBy using df.groupby('Country') I want to plot the suspected case against the confirmed case using the Date column for the xaxis. Plotting these as (5, 2) subplots\n\nWhat I've done so far hasn't quite got it yet:\n\nfig, ax = plt.subplots(2, 5, sharey=True)\ndf.groupby('Country').plot(x='Date', y=['suspected cases', 'confirmed cases'], title=f'Suspected vs. Confirmed cases {country}')\nplt.show()\n\n\n\nWhat's happened so far is that there is an empty 5x2 subplot and below displays each graph individually. Why is this?\n\nAlso just a minor issue but would like some clarification. Within my .plot() function, why is the last grouped country only being shown in the title? For instance I have 10 countries grouped together for this plot but the title Suspected vs. Confirmed cases USA is showing fr each graph.\n\nLooked at a few SO posts and combined a few answers to try to solve my problem but I seem to be going in circles."
] | [
"pandas",
"matplotlib",
"pandas-groupby",
"subplot"
] |
[
"OpenGL ES 2 Translation after rotation",
"I'm working on a augmented reality app in android. At the moment I have some problems with the Open GL ES 2.0 stuff..\nFirst I want to rotate an object and then translate it but it doesn't work.. Single transformations, means only rotation or translation, are working. \nI think my question is similar to OpenGL - Translate after rotate but the answers there don't help me.\nFor example how can I rotate the object by 45 degrees about the z-axis and then translate it 100px left or right?\n\nHere is some code:\n\nMatrix.setIdentityM(mModelMatrix, 0);\n// Euler angles in res[] from opencv \nMatrix.setRotateEulerM(mRotateMatrix, 0, (float) res[0], (float) res[1], (float) res[2]);\nMatrix.multiplyMM(mModelMatrix, 0, mRotateMatrix , 0, mModelMatrix, 0);\nMatrix.translateM(mModelMatrix, 0, (x-hmWidth),(y-hmHeight)*(-1), 0);\nMatrix.scaleM(mModelMatrix, 0, (float) arc.getSize().width, (float) arc.getSize().height, 10);\ndrawBlock(gl);\n\n\nUdate:\nI found out that sometimes the euler angles must be wrong or I use them in a incorrect way. I don't know. When I use Matrix.rotateM(mModelMatrix, 0, 90, 0, 0, 1); AFTER translation everything works fine. \nNow I don't know how I can use my euler angles with rotateM(). I have tried to call the methode three times but then I get a wrong rotation:\n\nMatrix.rotateM(mModelMatrix, 0, (float) res[0], 1, 0, 0);\nMatrix.rotateM(mModelMatrix, 0, (float) res[1], 0, 1, 0);\nMatrix.rotateM(mModelMatrix, 0, (float) res[2], 0, 0, 1);"
] | [
"android",
"opengl-es",
"matrix",
"rotation",
"translation"
] |
[
"Best practice to manage date and days",
"I am working on a project where I have many operations to manage.\nEach operation have an end date and is composed by a certain amount of tasks.\n\nI want to display reminders (a text displayed on the screen) if a task is not done before [end date] - X days.\n\nAll the data is stored in MySQL database and I work with PHP and HTML5.\n\n\nWhich datatype is (are) the best to work with date and days (to\nperform calculations)?\nCan I work with Date() and subtract days in a easy way?\n\n\nI do not have a specific technical question, but I think sharing best way to proceed is a good thing, right?\n\nI'm curious to know what are the best ways to proceed and open to any proposal!"
] | [
"php",
"mysql",
"sql",
"date",
"date-manipulation"
] |
[
"Magento - Display Wishlist button to registered users only",
"I have been searching around several threads and found a couple posts that allowed me to put together a solution, but I'm having a syntax problem.\n\nThere is an \"add all to wishlist\" button on my cart page that I want to display to logged in customers only.\n\nI found this on another thread:\n\nif($this->helper(‘customer’)->isLoggedIn()){\n//block1\n} else {\n//block2\n}\n\n\nThis works, but when I enter the code for my \"block1\", which is the button I need to display in that case, everything breaks.\n\nThis is the code for my \"block1\":\n\n<button type=\"button\" title=\"<?php echo $this->__('A&ntilde;adir todos a Lista de Compras') ?>\" class=\"button btn-continue\" onclick=\"setLocation('<?php echo $this->getUrl('checkout/cart/updatePost').$params?>')\"><span><span><?php echo $this->__('A&ntilde;adir todo a Lista de Compras') ?></span></span></button>\n\n\nAny help would be greatly appreciated.\n\nThanks!"
] | [
"magento",
"cart"
] |
[
"More idiomatic way of reading JSON file and creating a map from it in Scala",
"In the code snippet below I am reading a JSON file with a structure similar to this one:\n\n{ \"c7254865-87b5-4d34-a7bd-6ba6c9dbab14\": \"72119c87-7fce-4e17-9770-fcfab04328f5\"}\n{ \"36c18403-1707-48c4-8f19-3b2e705007d4\": \"72119c87-7fce-4e17-9770-fcfab04328f5\"}\n{ \"34a71a88-ae2d-4304-a1db-01c54fc6e4d8\": \"72119c87-7fce-4e17-9770-fcfab04328f5\"}\n\n\nEach line contains a key value pair which should be then added to a map in Scala. This is the Scala code which I used for this purpose:\n\nval fs = org.apache.hadoop.fs.FileSystem.get(new Configuration())\n\ndef readFile(location: String): mutable.HashMap[String, String] = {\n val path: Path = new Path(location)\n val dataInputStream: FSDataInputStream = fs.open(path)\n val m = new mutable.HashMap[String, String]()\n for (line <- Source.fromInputStream(dataInputStream).getLines) {\n val parsed: Option[Any] = JSON.parseFull(line)\n m ++= parsed.get.asInstanceOf[Map[String, String]]\n }\n m\n}\n\n\nThere must be a more elegant way to do this in Scala for sure. Especially you should be able to get rid of the mutable map and ingest the lines directly via a stream into a map. How can you do that?"
] | [
"json",
"scala"
] |
[
"Calculating dataframe column dependant on group",
"I have a dataframe that I would like to calculate a new column for. The column would contain ax+by; x and y are columns while a and b are scalars. The catch is that the scalar coefficients are different for different groups defined in a third column 'groups'. I tried doing this by looping over the groups but I get NULL as my output. \"Coefficients\" is a dictionary of lists [a,b]\n\nfor group in df['groups'].unique():\n coef_list = Coefficients[group]\n temp = df[df['groups']==group ]\n df['calculation'] = coef_list[0] * temp['x'] + coef_list[1] * temp['y'] \n\n\nI thought it would work by only adding values by matching on index. Do I need to use assign or something."
] | [
"python",
"pandas",
"math"
] |
[
"Code skipping print() function and going straight to break",
"I am writing a code for a game in which the computer picks a random number from 1 to 100 and then the player has to figure out what the number is. When you guess the number, you are either told if the number is higher or lower. \n\nWhen you guess the number it is supposed to print a message saying that you've guessed it and after that it is supposed to break. When you guess the number it entirely skips the print function and breaks. \n\nI haven't tried anything because I don't know what to try. I am still fairly new in programming.\n\nHere is the code:\n\nimport random\nnum = random.randint(1, 100)\nguess = int(input(\"Guess which number I chose from 1 to 100: \"))\n\nwhile guess != num:\n if guess > num:\n print (\"That number is too high\")\n guess = int(input(\"Guess which number I chose from 1 to 100: \"))\n elif guess < num:\n print (\"That number is too low\")\n guess = int(input(\"Guess which number I chose from 1 to 100: \"))\n elif guess == num:\n print (\"You guessed it! Want to play again?\")\n option = input(\"Press Y for yes or N for no: \")\n if option.lower() == \"y\":\n guess = int(input(\"Guess which number I chose from 1 to 100: \"))\n elif option.lower() == \"n\":\n break\n else:\n print (\"Not valid\")\n break\n\n\nThere are no error messages. Once you find the number, the code just breaks."
] | [
"python",
"python-3.x",
"python-requests"
] |
[
"Storing simulation results in R",
"I want to estimate Mantel-Haenszel Differential Item Functioning (DIF) Odds Ratio and HMDDIF index. I wrote the function below. It seems to me I am making a mistake when storing the results. Would you please take a look at this and give me feedback?\nHere is the sample data:\n\n# generate dataset\nr <- 1000\nc <- 16\ntest <- matrix(rbinom(r*c,1,0.5),r,c)\n# create sum scores for each student using first 15 columns\ntest <- cbind(test, apply(test[,1:15],1,sum))\ncolnames(test) <- c(\"v1\",\"v2\",\"v3\",\"v4\",\"v5\",\"v6\",\"v7\",\"v8\",\"v9\",\"v10\",\"v11\",\"v12\",\"v13\",\"v14\",\"v15\",\"group\",\"score\")\ntest <- as.data.frame(test)\n\n\nThe first 15 columns are the student True/false responses to items/questions. The group membership column is the 16th column. The student \"score\" variable is the sum of item scores at the last (17th) column. The formula can be found here in the picture that I got from Wikipedia (https://en.wikipedia.org/wiki/Differential_item_functioning).\n\n\nFor each of the score category, I want to estimate the last two formulas in this picture. Rows are 10 students and columns are six items/questions. Again, the 16th column is group membership (1-focal, 0-reference)\nHere is my function code.\n\n library(dplyr)\n\n# this function first starts with the first item and loop k scores from 1-15. Then move to the second item.\n# data should only contain the items, grouping variable, and person score.\n\nMantel.Haenszel <- function (data) { \n # browser() #runs with debug\n for (item in 1:15) { #item loop not grouping/scoring\n\n item.incorrect <- data[,item] == 0 \n item.correct <- data[,item] == 1\n Results <- c() \n\n for (k in 1:15) { # for k scores\n\n Ak <- nrow(filter(data, score == k, group == 0, item.correct)) # freq of ref group & correct\n\n Bk <- nrow(filter(data, score == k, group == 0, item.incorrect)) # freq of ref group & incorrect\n\n Ck <- nrow(filter(data, score == k, group == 1, item.correct)) # freq of foc group & correct\n\n Dk <- nrow(filter(data, score == k, group == 1, item.incorrect)) # freq of foc group & incorrect\n\n nrk <- nrow(filter(data, score == k, group == 0)) #sample size for ref\n\n nfk <- nrow(filter(data, score == k, group == 1)) #sample size for focal\n\n if (Bk == 0 | Ck == 0) { \n\n next\n }\n\n nominator <-sum((Ak*Dk)/(nrk + nfk))\n denominator <-sum((Bk*Ck)/(nrk + nfk))\n odds.ratio <- nominator/denominator\n\n if (odds.ratio == 0) { \n\n next\n }\n\n MH.D.DIF <- (-2.35)*log(odds.ratio) #index\n\n # save the output\n out <- list(\"Odds Ratio\" = odds.ratio, \"MH Diff\" = MH.D.DIF)\n results <- rbind(Results, out)\n return(results)\n\n } # close score loop\n\n } # close item loop\n\n } #close function\n\n\nHere is what I get \n\n# test funnction\nMantel.Haenszel(test)\n\n> Mantel.Haenszel(test)\n Odds Ratio MH Diff \nout 0.2678571 3.095659\n\n\nWhat I want to get is \n\n> Mantel.Haenszel(test)\n Odds Ratio MH Diff \nout 0.2678571 3.095659\n ## ##\n .. ..\n (15 rows here for 15 score categories in the dataset)"
] | [
"r",
"function",
"save"
] |
[
"How to pass id of a control in GridView to Jquery?",
"SCRIPT\n\n<script type=\"text/javascript\">\n$(function () {\n $(\".ttip\").hide();\n $(\".txttwo\").keyup( \n function () {\n var one = $(this).val();\n $(\".ttip\").fadeIn().text(one);\n });\n\n $(\".txttwo\").blur(\n function () {\n var one = $(this).val();\n $(\".ttip\").hide();\n });\n}); \n </script>\n\n\nCODE:\n\n <asp:GridView ID=\"GridView1\" runat=\"server\" EnableModelValidation=\"True\">\n <Columns>\n <asp:TemplateField>\n <ItemTemplate>\n <p class=\"ttip bubble\" class=\"bubble\"></p>\n <asp:TextBox ID=\"abc\" class=\"txttwo tipin\" runat=\"server\" ></asp:TextBox>\n </ItemTemplate>\n </asp:TemplateField>\n </Columns>\n </asp:GridView>\n\n\nFIDDLE\nhttp://jsfiddle.net/w96LX/7/\n\nAlso it would be just great if someone can tell me how can I set the width of bubble such that it expands according to the length of text.\nI get tooltip for all the textboxes because I have used class. I need to show tooltip just for the one at a time."
] | [
"javascript",
"jquery",
"asp.net",
"css",
"gridview"
] |
[
"how to insert a - symbol before the last alphabet in a string using regex pattern in java",
"hi i have a value for example 023A i need to replace or format it to 23-A by removing leading 0, it is 123A it should be 123-A\ncan anyone help me out in java regex how to do this?"
] | [
"java",
"arrays",
"regex",
"performance",
"regexp-replace"
] |
[
"Vertx Junit5 Concurrent timeout exception",
"I am getting an exception when I am running this code, I am closing the testContext in beforeEach and test Method.\n\n\n The test execution timed out. Make sure your asynchronous code includes calls to either VertxTestContext#completeNow(), VertxTestContext#failNow() or Checkpoint#flag()\n java.util.concurrent.TimeoutException: The test execution timed out. Make sure your asynchronous code includes calls to either VertxTestContext#completeNow(), VertxTestContext#failNow() or Checkpoint#flag()\n at io.vertx.junit5.VertxExtension.joinActiveTestContexts(VertxExtension.java:230)\n\n\n@DisplayName(\"Test Case Workflow\")\n@ExtendWith(VertxExtension.class)\npublic class OrchestrationDBVerticleTest {\n // tag::prepare[]\n private Vertx vertx;\n private OrchestrationDBService service;\n public static final String CONFIG_JDBC_URL = \"test.jdbc.url\";\n public static final String CONFIG_JDBC_DRIVER_CLASS = \"test.jdbc.driver_class\";\n public static final String CONFIG_JDBC_MAX_POOL_SIZE = \"test.jdbc.max_pool_size\";\n\n @BeforeEach\n public void prepare(VertxTestContext testContext) throws InterruptedException {\n vertx = Vertx.vertx();\n JsonObject config = new JsonObject()\n .put(\"url\", vertx.getOrCreateContext().config().getString(CONFIG_JDBC_URL, \"jdbc:hsqldb:mem:testdb\"))\n .put(\"driver_class\", vertx.getOrCreateContext().config().getString(CONFIG_JDBC_DRIVER_CLASS, \"org.hsqldb.jdbcDriver\"))\n .put(\"max_pool_size\", vertx.getOrCreateContext().config().getInteger(CONFIG_JDBC_MAX_POOL_SIZE, 30));\n JsonObject dbConfig = new JsonObject().put(\"jdbcConfig\", config);\n\n vertx.deployVerticle(new OrchestrationDBVerticle(), new DeploymentOptions().setConfig(dbConfig),\n testContext.succeeding(id -> {\n service = OrchestrationDBService.createProxy(vertx, OrchestrationDBVerticle.CONFIG_ORCHESTRATION_DB_QUEUE);\n testContext.completeNow();\n }));\n }\n // end::prepare[]\n\n // tag::finish[]\n @AfterEach\n public void finish(VertxTestContext testContext) {\n System.out.println(\"after\");\n vertx.close();\n }\n // end::finish[]\n\n\n // tag::crud[]\n @Test\n public void crud_operations(VertxTestContext testContext) {\n// Checkpoint callProxy = testContext.checkpoint();\n JsonObject jobInput = (new JsonObject()).put(\"requestInput\", new JsonObject().put(\"test\", \"test\"))\n .put(\"workflow\", \"WorkFlowHandler\");\n service.saveJobDetails(jobInput, testContext.succeeding(response -> {\n System.out.println(\"Service Response : \" + response);\n Assertions.assertThat(response.toString().contains(\"IN_QUEUE\"));\n testContext.completeNow();\n// callProxy.flag();\n }));\n }\n // end::crud[]\n}\n\n\nEDIT: - \nI was not completing testContext in the finish method.\n\n@AfterEach\n public void finish(VertxTestContext testContext) {\n System.out.println(\"after\");\n vertx.close(testContext.succeeding(response -> {\n testContext.completeNow();\n }));\n }\n\n\nBut Even after that my asserstion condtions are always true if I provide wrong input."
] | [
"unit-testing",
"asynchronous",
"vert.x",
"junit5"
] |
[
"Android Activity and Fragment Options menu ordering",
"I have at most two option menu items created by my activity. Depending on the current fragment being displayed (changes using a tab control), I display another one or two items.\n\nAll the items created should always show (3 at most at any given time).\n\nMy question really is about the ordering of the items. I can't find any standard on this. Should my activity's items be far right and then fragment items to the left of those? or vice versa?\n\nThanks"
] | [
"android",
"android-actionbar",
"android-optionsmenu"
] |
[
"How can you tell programmatically if a Word Macro is signed from VB.Net/C#",
"I have an VB.Net/C# application that programmatically:\n\n\nCreates an RTF document\nOpen it up in Microsoft Word\nRuns a Word macro that exists in the Word Template using code like this:\n\n\nCode: \n\nProtected mobjWordApp As Word.Application = Nothing\n'\n' lots more code snipped for clarity\n'\nWith mobjWordApp.Dialogs.Item(Word.WdWordDialog.wdDialogToolsMacro)\n .Name = MacroName\n .Run = True\n .Execute()\nEnd With\n\n\nThis has worked happily for years.\n\nI now have a new requirement; My application is required to only run SIGNED Word Macros.\n\nThis is easy enough to do in the Word user interface, as follows:\n\nFile > Options > Trust center > Macro Settings\nSelect \"Disable all macros except digitally signed macros\"\n\n\n\n\nOnce this is set, if the person running Word displays the Macros dialog, any unsigned (or signed but untrusted) macros are not listed. This is all as I would expect.\n\nHowever, my VB.Net code, which is opening the Word Application can bypass this. When I run this code it will run a unsigned macro:\n\nWith mobjWordApp.Dialogs.Item(Word.WdWordDialog.wdDialogToolsMacro)\n .Name = MacroName\n .Run = True\n .Execute()\nEnd With\n\n\nWhat I need to know is:\n\nIs there a way for my code to identify if a Macro is signed (and trusted) before I run it?"
] | [
".net",
"vb.net",
"vba",
"ms-word"
] |
[
"GORM - Model Relationships Between Like Entities",
"For my project I'm using Grails, but this is kind of a general ORM question.\n\nI'm new to ORMs and ER diagrams, and trying to figure out how to best describe/implement the following:\n\nI have 2 Entities: User, Connection\n\nA Connection consists of 2 Users (and other primitive attributes). A user can be found in more than one Connection. How would you describe the relationship between User and Connection? I don't know what you would call it, 2 to many? How would you draw it in an ER diagram.\n\nIn GORM, should it be a bi-directional relationship?\n\nEdit\n\nAs an added requirement, assume the users have specific roles in the relationship. Like student and teacher. So Connection would have student and teacher properties of type User."
] | [
"grails",
"orm",
"gorm"
] |
[
"How to use PreventDefault in AspNetCore?",
"I have a bootstrap modal which allow to the user to update some information of his account. Actually I want keep the modal open when the form is submitted, because if the user submit the form then the modal for default will be closed by the page refresh.\n\nFor doing so I added the following form inside the modal:\n\n@model Demo.ViewModels.UserProfileViewModel;\n\n<form asp-controller=\"User\" asp-action=\"UpdateUser\" asp-antiforgery=\"true\" id=\"userInformations\">\n <div class=\"form-group\">\n <label class=\"col-lg-3 control-label\">Email</label>\n <div class=\"col-lg-12\">\n <input class=\"form-control\" type=\"text\" asp-for=\"User.Email\" value=\"@Model.User.Email\" />\n </div>\n <div class=\"form-group\">\n <label class=\"col-lg-3 control-label\">Password</label>\n <div class=\"col-lg-12\">\n <input class=\"form-control\" asp-for=\"User.??\" type=\"password\" value=\"?\" />\n </div>\n </div>\n <button type=\"submit\">Update</button>\n</div>\n\n\nwhere UserViewModel is the object which contains the fields to update.\n\nFor prevent the modal closing I created a javascript function with the following content:\n\n$('#userInformations').on(\"submit\", function (event) {\n event.preventDefault();\n $.ajax({\n url: \"some url\",\n type: \"POST\",\n data: some data,\n success: function (result) {\n console.log(result)\n }\n });\n});\n\n\nI'm stucked on the ajax part, in particular I need to call the method UpdateUser available in the User controller:\n\n [HttpPost]\n [ValidateAntiForgeryToken]\n public IActionResult UpdateUser(UserProfileViewModel updateUser)\n {\n if (ModelState.IsValid)\n {\n updateUser = _repo.UpdateUser(updateUser);\n }\n\n return RedirectToAction(\"Profile\");\n }\n\n\nthe main problem is: I have no idea of how to do this, and I actually didn't found anything related, so I don't know if this is possible or maybe the situation is more simple than this.\n\nUPDATE\n\nAs suggested:\n\n $.ajax({\n url: this.action,\n type: \"POST\",\n data: this.serialize,\n success: function (result) {\n alert(true);\n console.log(result)\n },\n error: function (data) {\n console.log(data);\n }\n });"
] | [
"asp.net",
"asp.net-core"
] |
[
"Finding element/elements using RSelenium",
"I am trying to find one singular element on this website using findElement\n\nhttps://shiny.rstudio.com/gallery/datatables-options.html\n\nFor example \"Display length\".\n\nLater I would like to find all elements using findElements. That is, \"Display length\", ..., \"Function callback\". Total of 5.\n\nMy attempt for just finding the first element (Display length):\n\nremDr$navigate(\"https://shiny.rstudio.com/gallery/datatables-options.html\")\nelems <- remDr$findElement(\"css selector\", \"#showcase-app-container > nav > div > ul > li.active > a\") \n# Unable to locate element \n\nelems <- remDr$findElement(\"xpath\", \"//*[@id='showcase-app-container']/nav/div/ul/li[1]/a\") \n# Unable to to locate element\n\n\nMy attemp on finding several elements:\n\nelems <- remDr$findElements(\"class\", \"nav navbar-nav\") \n# Invalid or does not result in a WebElement\n\nelems <- remDr$findElements(\"css selector\", \"#showcase-app-container > nav > div > ul\") \n# list of 0\n\nelems <- remDr$findElements(\"xpath\", \"//*[@id='showcase-app-container']/nav/div/ul\") \n# list of 0"
] | [
"r",
"shiny",
"rselenium"
] |
[
"Automation of test suite generation in eclipse",
"I would like to automate test suite generation in eclipse which includes following steps in manual process.\ncan anyone help me how to achive this using java or any other comfortable language.\n\nRight click on package -> select 'New' -> 'other'\n\nclick on 'test' ->select 'TPTP junit test' -> click on 'next'\n\ngive package and Test name -> click Finish \n\nAdd testcases in 'Test methods' tab\n\ncomplete invocation in 'behavior' tab\n\nsave and close.\n\nTool should ask Test name and number of test cases needs to be generated and with this info test suite should be generated.\n\nStep 4\nStep 5"
] | [
"java",
"eclipse",
"junit",
"automation"
] |
[
"When boolean method returns False, it still moves to the next Activity",
"I have a boolean method and when it returns false, I expect it to stay in the same activity (so user can fill in the blank fields). If boolean is true, then it should move to the next activity. \n\nI'm still new at coding.\n\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case R.id.calculate:\n switch (spinnerAPos) {\n\n case 1:\n\n Y = x * b;\n break;\n case 2:\n etc...\n break\n }\n\n if(checkAnswer(y));\n Intent intent = new Intent(this, NextActivity.class);\n intent.putExtra(\"A\", Math.round(Y * 100.0) / 100.0);\n startActivity(intent);\n }\n return true ;\n default:\n return super.onOptionsItemSelected(item);\n }\n}\n\n public boolean checkAnswer(double y){\n\n boolean pass = false;\n if (y == 0 ){\n editText.setError(\"add a number greater than Zero\");\n }\n pass = false;\n }else{\n pass =true;\n }\n return pass;\n }\n }"
] | [
"android",
"android-studio"
] |
[
"How avoid to extracting same files multiple times using zip4j lib?",
"I am able to extract files successfully using the Zip 4j, but I don't want to extract the same file multiple times, is there any way to achieve it? Assume I have a zip file A.zip, the user clicked on it and files are extracted. If the user clicks on the same file(A.zip) next time I don't want to extract it again. Is there any way to find it with Zip 4j."
] | [
"android",
"zip4j"
] |
[
"Salesforce Managed Package Install Failure",
"I have updated my managed package - going from beta 14 to beta 15. The 14 previous versions all worked just fine. I am able to upload without problem and an install link is generated. However, when I try to install the beta in a separate developer org, I get the following message (i'd call it an error but there is no detail at all suggest whether it is an error or not):\n\n\n Your requested install failed. Please try this again.\n \n None of the data or setup information in your salesforce.com\n organization should have been affected by this error.\n \n If this error persists, contact salesforce.com Support through your\n normal channels and reference number: 35557683-12022 (1510032338)\n\n\nI've submitted a ticket with SFDC support, but since I'm not a premier customer, they say it will take 2 days to get back to me. Does anyone no how to dig into this? Is there a log file somewhere that I can look at that will indicate what the problem is? Thanks in advance you can provide any guidance."
] | [
"salesforce",
"apex-code",
"visualforce"
] |
[
"Increment a number in a string and zero fill it",
"In VB.NET, I would like to increment a number in a string and have it zeroed filled. \n\nHere is the sample string with the 5 digit number:\nR00099\n\nWhat I would like returned after incrementing it by one:\nR00100"
] | [
"regex",
"vb.net",
"string"
] |
[
"useState keeps getting cleared while handling promises",
"The useState of my react app keeps resetting to default value. It resets when my promise function completes. I have observed this while console logging.\nThe value imageUpload state is meant to be set then sent with axios but, just as it moves to the next promise the state is reset. It happens only with imageupload\nHere is a snippet of the useState function:\nconst [values, setValues] = useState({\nname: "",\ncaption: "",\n...\nimageUpload: "",\n})\n\nHere is the main code giving issues:\nconst clickSumbit = (event) => {\nsetValues({...values, error: '', loading: true})\n\nevent.preventDefault();\nonFileUpload().then( data => {\n setValues({...values, imageUpload: `https://${storageAccountName}.blob.core.windows.net/all/${event.target.files[0].name}`})\n\n console.log("imageUpload", imageUpload);\n}).then( () => {\n axios.post('/.netlify/functions/addData', values)\n .then(data => {\n console.log("Values posted!")\n setValues({\n ...values,\n name: '',\n description: '',\n photo: '',\n error: "",\n loading: false,\n createdProduct: name\n })\n })\n .catch(error => setValues({...values, error: error})\n)\n \n})\n\n\n\n};\n\nHere is a snippet of the onFileupload function\nconst onFileUpload = async () => {\n\nconst blobsInContainer = await uploadFileToBlob(fileSelected);\nreturn blobInContainer\n};\n\nThis code was made with intention that, until response if gotten on the succesful completion of onFileUpload function, axios post request will then be successful.\nThis was worse when I tried to make the OnSumbit() a async function. I am new to async and await, is this normal?"
] | [
"reactjs",
"asynchronous",
"promise",
"use-state"
] |
[
"silent post url is not getting the response in authorize.net simple checkout",
"I have been using Authorize.Net payment gateway in my asp.net application.\nI have generated the donate button along with key from authorize.net account. And also I included the silent post url in the account. When I click the donate button it redirects to the site and payment is works well. But I didn't get the any response from authorize.net.\nAnyone please help me , thanks in advance"
] | [
"asp.net",
"authorize.net"
] |
[
"How can I change MaxRequestsPerChild in ssh?",
"My website has been crashing after a minute of running with a fatal error saying it ran out of memory. Now, the memory being allocated, does not exceed the memory limit set in the php.ini file, so I'm thinking this has to do with an endless loop somehwere or a plugin not being compatible with another one.\n\nTo fix that I found online that people have changed the MaxRequestsPerChild setting on their websites to fix issues like this one. The problem is, I can't seem to find where and how to set that setting..."
] | [
"php",
"html",
"wordpress",
"ftp"
] |
[
"Making Documentation Compulsory In Android Studio",
"Is there a way to make documentation compulsory in a class,in android studio.?"
] | [
"android",
"android-studio",
"javadoc"
] |
[
"Append Strategy on field in Mongodb Document through kafka sink connector",
"first stream of kafka insert Document in Mongodb. second independent stream will update single field in existing Document in Mongodb.\n\nwhat strategy /transformation we have to use for it , how we configure our kafka mongo sink connector ?"
] | [
"mongodb",
"apache-kafka",
"apache-kafka-connect"
] |
[
"How meteor enforce that queries that share same records are updated in same time?",
"if i publish two sources:\n\n\nnewest-message: this will be always the newest message\nmessages: this can be parametrized by interval (for pagination). For instance messages 1-10 will be 10 newest messages.\n\n\nOn my site, i will show the newest-message and messages separately, but in same screen.\n\nQuestion: It can happen that newest-message and messages will share exactly one record (in case user is subscribed to newest-message and messages [1..N]). How meteor enforce that if i have two queries, one leading to record from newest-message and one to records from messages 1-10 (results of these queries will share one record - the newest message), these reactive sources will be updated SAME TIME, so it does not happend that user will see there is new newest message, but still not noticed this message in message area where first 10 newest messages are shown."
] | [
"meteor"
] |
[
"Compare Date and time in Hibernate",
"I have a defined column notification_date as DATETIME in Database. \n\nWhen the user filter I get only Date. So I'm converting as data and time using Java. For an Example if the userSearch Date is '2012-09-26'. The final converted date and time format will be '2012-09-26 17:34:00'\n\nWhen I want to search Date filter operations like equal,Less than , Greater than and date between, I'm not able to get the proper result using Hibernate criteria Query for Greater than and Less than operation.\n\nThe code used \n\ncrit.add(Restrictions.gt(\"notificationDate\",notificationVO.getNotificationDate()));\n\n\nThe restriction will change according to the condition\n\nTo compare only date, is there any functions available in Hibernate?\n\nAny other idea to fix this issue?"
] | [
"hibernate",
"compare"
] |
[
"How to make a custom alertdialog fullscreen",
"I wish to make a custom AlertDialog full screen like a new activity screen.\n\nTried these answers and still not working\n\n\nAndroid make a dialog appear in fullscreen\nMake AlertDialog Custom\nHow to make an Alert dialog in full screen in Android?\n\n\npublic void newDialog(final Context c){\n\n final AlertDialog alertDialog;\n\n LayoutInflater layoutInflater = LayoutInflater.from(c);\n dialogueView = layoutInflater.inflate(R.layout.layout_dialogue, null);\n\n final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(c);\n alertDialogBuilder.setView(dialogueView);\n\n alertDialog = alertDialogBuilder.create();\n\n dialogueView.findViewById((R.id.closeBtn)).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n alertDialog.dismiss();\n }\n });\n\n alertDialog.show();\n}\n\n\nlayout_dialogue.xml \n\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout \nxmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:app=\"http://schemas.android.com/apk/res-auto\"\nstyle=\"@style/full_screen_dialog\"\nandroid:layout_width=\"match_parent\"\nandroid:layout_height=\"match_parent\"\nandroid:background=\"@drawable/frame\">\n\n<android.support.design.widget.FloatingActionButton\n android:id=\"@+id/closeBtn\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:background=\"@drawable/background_sky\"\n android:clickable=\"true\"\n app:layout_constraintEnd_toEndOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\"\n app:srcCompat=\"@android:drawable/ic_delete\" />\n\n</android.support.constraint.ConstraintLayout>\n\n\nstyle.xml\n\n<style name=\"full_screen_dialog\" parent=\"@android:style/Theme.Dialog\">\n <item name=\"android:windowNoTitle\">true</item>\n <item name=\"android:windowFullscreen\">true</item>\n <item name=\"android:windowIsFloating\">true</item>\n</style>\n\n\nI had also tried \n\nandroid.R.style.Theme_Black_NoTitleBar_Fullscreen \n\nViewGroup.LayoutParams params = getDialog().getWindow().getAttributes();\nparams.width = WindowManager.LayoutParams.MATCH_PARENT;\nparams.height = WindowManager.LayoutParams.MATCH_PARENT;\n\n\nNone of them are working for me. Any suggestion on how to accomplished it?"
] | [
"android",
"android-alertdialog",
"android-dialog"
] |
[
"Writing D-Bus service with pygobject?",
"I'm trying to write a D-Bus service. But I'm confused about the python\npackages pygobject and dbus-python.\n\nIs it possible to write a D-Bus service with pygobject alone (without using\ndbus-python)? My understanding was that pygobject provides everything\nthat dbus-python does. Is this correct? Or do I need dbus-python?\n\nI succeeded in calling methods of other programs via D-Bus by just using\npygobject. But how do I provide my own interface and own methods as a service in D-Bus? As far as I understand I have to inherit my interface class from\nGio.DBusInterfaceSkeleton[1]. But how do I export my own methods?\n\n[1] https://lazka.github.io/pgi-docs/Gio-2.0/classes/DBusInterfaceSkeleton.html"
] | [
"python",
"dbus",
"pygobject"
] |
[
"DataBind string to DataTemplated checkbox",
"I want to create a ListBox filled with checkboxes in WPF, and I want to databind the \"Content\" value with a simple string value. However when I try <CheckBox Margin=\"5\" Content=\"{Binding}\" /> the app crashes.\n\nThis is what I have. ( I'm sure I am missing something simple )\n\n<ListBox Grid.Row=\"1\" IsSynchronizedWithCurrentItem=\"True\" x:Name=\"drpReasons\">\n <ListBox.ItemsPanel>\n <ItemsPanelTemplate>\n <WrapPanel Orientation=\"Horizontal\" >\n </WrapPanel>\n </ItemsPanelTemplate>\n </ListBox.ItemsPanel>\n <ListBox.Resources>\n <DataTemplate DataType=\"{x:Type System:String}\">\n <CheckBox Margin=\"5\" Content=\"{Binding}\" />\n </DataTemplate>\n </ListBox.Resources>\n </ListBox>"
] | [
"wpf",
"data-binding",
".net-3.5"
] |
[
"Is it bad practice if I have to organise Compile Sources",
"I am working on a C++ project in Xcode, and one of my .cpp files instantiates some variables. Another .cpp file in the application uses these variables to instantiate another object and needs them to be instantiated to not throw a null-pointer exception. My solution so far was simply to drag-drop (XCode simplicity) the first file over the second one in the build-phase order. It works fine now, but I have a feeling that it is not the optimal solution, and that there is something fundamentally wrong with my code if I need to organise the compile order manually for the application to run properly.\n\nShould I never instantiate something outside of functions, or what is the golden rule? Thanks.\n\nEDIT: An example as requested.\nThe problem lies in a Observer/Event system.\nIn a source-file I do this:\n\nTrigger* mainMenu_init = new Trigger(std::vector<Event*> {\n // Event(s):\n event_gameInit,\n\n}, [](Event* e) {\n // Action(s):\n std::cout << \"Hello World\" << std::endl;\n\n});\n\n\nIn the trigger's constructor the Event is asked to add is as an observer:\n\nfor(Event* event : events)\n event->addObserver(this);\n\n\nBUT, the events are just external pointers, so if they are not initialised (which they are in another source-file) this initialisation will fail. So what I found was that if I do not organise the compilation-phase myself, random triggers will not work while other will, depending on if they are built before or after the Event.cpp file."
] | [
"c++",
"xcode",
"nullpointerexception",
"organization"
] |
[
"Detect mouse over bezier or quadratic curve",
"Possible Duplicate:\n Detect mouseover of certain points within an HTML canvas? \n\n\n\n\nI have some Bezier and/or quadratic curves drawn on an HTML5 canvas.\n\nHow can I detect when the mouse is over a curve and select it when the mouse is clicked?\n\nIs there a quick way of checking if the mouse pointer lies over a curve?\n\nI'm using the JavaScript InfoVis Toolkit and JQuery."
] | [
"javascript",
"jquery",
"math"
] |
[
"get all children recursively using a mongoose schema",
"I am using the express framework with mongoose, and I have the following Schema:\n\nvar DocumentSchema = new Schema({\n name: String,\n description: String,\n parent: {\n type: Schema.Types.ObjectId,\n ref: \"Document\"\n },\n children: [{\n type: Schema.Types.ObjectId,\n ref: 'Document'\n }]\n});\n\n\nI'm trying to get a dynamic hierarchy tree of children but I could not find any suitable solution.\n\nIs it possible to do that using this schema? If not, what schema structure should I should use ?"
] | [
"node.js",
"mongodb",
"express",
"mongoose",
"mongoose-schema"
] |
[
"How to organize two functions different in the middle part",
"I would like to ask how to nicely organize the below two functions.\n\nI apologize for not uploading the complete code.\n\nvoid prepend_float(t_ptr *x, float f)\n{\n int ac = x->num;\n t_atom *av = static_cast<t_atom *>(malloc(sizeof(t_atom) * ac));\n av[0].type = A_FLOAT; //not common\n av[0].f = f; //not common\n for (int i = 1; i < ac; ++i)\n {\n av[i].type = A_FLOAT;\n av[i].f = x->fv[i - 1];\n }\n do_something(x, ac, av);\n free(av);\n}\n\nvoid prepend_string(t_ptr *x, std::string s)\n{\n int ac = x->num;\n t_atom *av = static_cast<t_atom *>(malloc(sizeof(t_atom) * ac));\n av[0].type = A_STRING; //not common\n av[0].s = s; //not common\n for (int i = 1; i < ac; ++i)\n {\n av[i].type = A_FLOAT;\n av[i].f = x->fv[i - 1];\n }\n do_something(x, ac, av);\n free(av);\n}\n\n\nAs you can see the two functions have identical code except for the two lines where I marked not common.\n\nHow can I create a common function to reduce the duplicated code?\n\nWhat I can think now is to create a common function that has 4 arguments like the following.\n\nvoid common_function(t_ptr *x, float f, std::string, t_type type)\n{\n int ac = x->num;\n t_atom *av = static_cast<t_atom *>(malloc(sizeof(t_atom) * ac));\n if (type == A_FLOAT)\n {\n av[0].type = type;\n av[0].f = f; \n }\n else if (type == A_STRING)\n {\n av[0].type = type;\n av[0].s = s; \n } \n for (int i = 1; i < ac; ++i)\n {\n av[i].type = A_FLOAT;\n av[i].f = x->fv[i - 1];\n }\n do_something(x, ac, av);\n free(av);\n}\n\n\nIs there a better way to organize the two functions?"
] | [
"c++"
] |
[
"Laravel app.js and bootstrap.js are not included?",
"I installed a fresh Laravel 5.8 and included the \n\n<script src=\"{{asset('js/app.js')}}\"></script>\n\n\nat the bottom of welcome.blade.php. To avoid error, set a div with id=app.\n\nIf I write alert(123) inside public/js/app.js it will be alerted when I visit this page and it is ok. I noticed that in line 60329 of public/js/app.js it has\n\n\n webpack_require(/*! C:\\xampp\\htdocs\\br1\\resources\\js\\app.js */\"./resources/js/app.js\");\n\n\nsounds it includes the resources\\js\\app.js and resources\\js\\app.js includes resources\\js\\bootstrap.js\n\nWhen I write the alert(22) in resources\\js\\app.js or resources\\js\\bootstrap.js nothing will be alerted while it must alert something.\n\nThanks in advance."
] | [
"jquery",
"node.js",
"laravel",
"laravel-5"
] |
[
"Spinner Item Selection - Android Studio",
"Hi Guys I am having trouble with a spinner Item selection. The concept is a calorie calculator and the current code that I have placed below is the button to calculate the action as well as the spinner listener. I have tested the users input which is working fine as well as testing what the spinner string is equaling, however it is not setting my if statement to true. Can anyone enlighten me on what is the issue?\n\nenum Discount {\n STEAK(2.71f),\n CHICKEN(2.39f), \n PORK(2.42f), \n HAM(1.45f), \n VEAL(1.72f), \n WHITEFISH(1.72f), \n SALMON(2.08f);\n\n private float amount;\n Discount(float amount) {\n this.amount = amount;\n }\n\n\n}\n\n\n\n\ndropDownList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {\n @Override\n public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {\n itemSelectedDiscount = dropDownList.getSelectedItem().toString();\n }\n\n @Override\n public void onNothingSelected(AdapterView<?> parent) {\n\n }\n });\n\n\n\n Button calculate = (Button)findViewById(R.id.calculate);\n calculate.setOnClickListener(new View.OnClickListener(){\n public void onClick(View v){\n totalCaloriesInt = value;\n status.setText(itemSelectedDiscount);\n if (itemSelectedDiscount == \"STEAK\") {\n Discount steak = Discount.STEAK;\n calculatedCalories.setText(\"\" + totalCaloriesInt * steak.amount);\n }\n\n else if (itemSelectedDiscount == \"CHICKEN\") {\n Discount chicken = Discount.CHICKEN;\n calculatedCalories.setText(\"\" + totalCaloriesInt * chicken.amount);\n }\n\n\n }\n }); \n\n\n`"
] | [
"java",
"android",
"spinner"
] |
[
"Why does this (javascript) closure fail?",
"The variable \"called\" is false when is should be set to true.. why is that?\nIt is set to true when called by the plugin but outside the closure it remains false.\nIts a bit baffling. Thanks in advance for any pointers.\n\n(function() {\n module(\"when InitializedApplication() is called\");\n test(\"it should call the success function\", function () {\n // arrange\n $(\"#qunit-fixture\").append(\n '<script id=\"events-catalog-view-template\"' +\n ' type=\"text/html\"'+\n ' src=\"_events-catalog.view.html\">' +\n '</script>' +\n '<div id=\"events-catalog-view-container\"' +\n ' data-bind=\"template: {' +\n ' name=\"events-catalog-view-template\" ' +\n ' afterRender=\"tpw.mediator.eventscatalog.setupViewDataBinding\" ' +\n ' }\"' + \n '</div>'\n ); \n\n var called = false;\n\n // act\n var init = TPW.InitializeApplication();\n\n init({\n logLevel: \"debug\",\n success: function (successfullResolution) { \n called = true;\n },\n error: function (failedResolution) { \n }\n });\n\n // assert \n ok(called, \"success function called\");\n }); \n})();"
] | [
"closures",
"qunit"
] |
[
"Use Data From One SQL Table and Correlate It To Data In Another Table",
"First off, I'm doing this for purely educational purposes. I have a Kodi (XBMC) plugin that goes through my TV Show database and stores which episodes have been watched and how many times. I figured out how to use HTML forms to retrieve data (TheTVDB ID number, Season, Episode numbers, and how many times the episode has been played) from my database using PHP. In an attempt to further my knowledge, I'm trying to convert the \"friendly\" show name which is taken by the form, then convert it to the ID number, and use that stored value in another query on a different table in the same database to return the Episode and Season Numbers. \n\nFor example, Friends is ID# 79168. The table tvshows contains columns idShow and titles, whereas the table episode_watched contains columns idShow, season, episode and playCount. After idShow is correlated to title, I would like to output a table with the columns Season and Episode which match the specific playcount and title.\n\nHere's my code: http://pastebin.com/i7Y2ZWpR\n\nThis is the PHP error that I'm getting:\n\n\n Notice: Trying to get property of non-object in\n /usr/share/webapps/pydio/sql.php on line 15\n\n\n0 Results"
] | [
"php",
"html",
"mysql"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.