texts
sequence | tags
sequence |
---|---|
[
"Incompatible type in Android AutoCompleteTextView",
"I'm trying to add multiple values in AutoCompleteTextView from SQlite Database in Android.But it shows incompatible type for this method =\n\n@Override\npublic String getItem(int position) {\n return fullList.get(position);\n} \n\npublic class AutoCompleteAdapter extends ArrayAdapter<AutoCompleteObject> implements Filterable {\n\n private ArrayList<AutoCompleteObject> fullList;\n private ArrayList<AutoCompleteObject> mOriginalValues;\n private ArrayFilter mFilter;\n\n public AutoCompleteAdapter(Context context, int resource, int textViewResourceId, ArrayList<AutoCompleteObject> fullList) {\n\n super(context, resource, textViewResourceId, fullList);\n this.fullList = fullList;\n mOriginalValues = new ArrayList<AutoCompleteObject>(fullList);\n\n }\n\n @Override\n public int getCount() {\n return fullList.size();\n }\n\n @Override\n public String getItem(int position) {\n return fullList.get(position);\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n return super.getView(position, convertView, parent);\n }\n\n @Override\n public Filter getFilter() {\n if (mFilter == null) {\n mFilter = new ArrayFilter();\n }\n return mFilter;\n }\n\n private class ArrayFilter extends Filter {\n private Object lock;\n\n @Override\n protected FilterResults performFiltering(CharSequence prefix) {\n FilterResults results = new FilterResults();\n\n if (mOriginalValues == null) {\n synchronized (lock) {\n mOriginalValues = new ArrayList<AutoCompleteObject>(fullList);\n }\n }\n\n if (prefix == null || prefix.length() == 0) {\n synchronized (lock) {\n ArrayList<AutoCompleteObject> list = new ArrayList<AutoCompleteObject>(\n mOriginalValues);\n results.values = list;\n results.count = list.size();\n }\n } else {\n final String prefixString = prefix.toString().toLowerCase();\n\n ArrayList<AutoCompleteObject> values = mOriginalValues;\n int count = values.size();\n\n ArrayList<AutoCompleteObject> newValues = new ArrayList<AutoCompleteObject>(count);\n\n for (int i = 0; i < count; i++) {\n String item = values.get(i);\n if (item.toLowerCase().contains(prefixString)) {\n newValues.add(item);\n }\n\n }\n results.values = newValues;\n results.count = newValues.size();\n }\n\n return results;\n }\n\n @SuppressWarnings(\"unchecked\")\n @Override\n protected void publishResults(CharSequence constraint,\n Filter.FilterResults results) {\n\n if (results.values != null) {\n fullList = (ArrayList<AutoCompleteObject>) results.values;\n } else {\n fullList = new ArrayList<AutoCompleteObject>();\n }\n if (results.count > 0) {\n notifyDataSetChanged();\n } else {\n notifyDataSetInvalidated();\n }\n }\n }\n }"
] | [
"android"
] |
[
"What is reason for Firefox web browser connection setting change to \"use system proxy setting\"?",
"I use default browser as Firefox. I have set to connection setting to \"Manual Proxy Configuration \" and has added localhost to proxy by pass. But when I'm trying to load localhost web address through selenium web driver that automatically change the proxy setting to \"use system proxy setting \" and my localhost web addresses not working. How can I chage it"
] | [
"firefox",
"selenium",
"proxy",
"selenium-webdriver"
] |
[
"How to use AWS CDK to set EventBridge Rule Target for Lambda with Alias",
"In my Lambda CDK stack, I want to setup an event rule to send an event to my Lambda every 10 minutes.\n\naws-events Rule\naws-events RuleProps\naws-events-targets LambdaFunction\n\nThis works and deploys the rule with the lambda as the target\n // ... setup lambdaFunction construct...\n // -- EVENTBRIDGE RULES --\n\n const meetingSyncEvent = {\n path: "/v1/meeting/sync",\n httpMethod: "GET"\n };\n\n const eventTarget = new awsEventTarget.LambdaFunction(lambdaFunction, {\n event: awsEvents.RuleTargetInput.fromObject(meetingSyncEvent)\n });\n\n\n\n /**\n TODO how do I add target to ARN with alias/version\n * */\n\n const eventRule = new awsEvents.Rule(this, generateConstructName("event-rule"), {\n enabled: true,\n description: "event to invoke GET /meeting/sync",\n ruleName: "meeting-sync-rule",\n targets : [\n eventTarget\n ],\n schedule: awsEvents.Schedule.rate(EVENT_MEETING_SYNC_RATE)\n });\n\n\n // -- end EVENTBRIDGE RULES --\n\nThe problem is this only targets the base ARN without an Alias or version (effectively always pointing to $Latest). There is this option in AWS console to set an Alias or version for a target (pics below), how can I do this in the CDK?\naws console UI allows alias and version for target\ntarget arn has alias when configured through UI"
] | [
"javascript",
"amazon-web-services",
"aws-lambda",
"aws-cdk",
"aws-event-bridge"
] |
[
"Swift struct type recursive value",
"Structs can't have recursive value types in Swift. So the follow code can't compile in Swift\n\nstruct A {\n let child: A\n}\n\n\nA value type can not be recursive, because it would have infinite size.But I wonder why the follow code can compile?\n\nstruct A {\n let children: [A]\n}"
] | [
"swift",
"recursion",
"struct"
] |
[
"Golang hierarchical routing",
"I want to make RESTful API which has multi layer route like :\n\n/api/auhtorization/getUserdata\n\n\nwhere api stands for webservice name,\nauhtorization stands for a function to check validation of token.\nand getUserdata stands for a function that get specific user data ( if only request past authorization level )\n\nfunc main(){\n http.HandleFunc(\"api/\", func(rw, req){\n http.HandleFunc(\"authorization/\", func(){\n\n if (auth passed)\n {\n http.HandleFunc(\"getUserdata\", getUserFunction())\n }\n\n })\n\n })\n}\n\n\nI know above code isn't a good example but I seek for best practice or framework for doing this.\nAny answer will be highly appreciated!"
] | [
"go"
] |
[
"Display only distinct values based on property in the markup in Knockout.js",
"I have this markup:\n\n<div data-bind=\"foreach: package() ? package().Products() : []\">\n <ul data-bind=\"foreach: Items\">\n <li>\n <div>\n <img data-bind=\"attr: { src: ImageUrl, alt: 'ItemId_' + ItemId }\">\n </div>\n </li>\n </ul>\n</div>\n\n\nWhat I want to achieve (in the markup if possible) is to display only distinct items based on the ItemId, so if there are multiple items with the same ItemId I'll display only one of them.\n\nIs it possible to do that in the markup data-bind property?"
] | [
"javascript",
"jquery",
"knockout.js",
"knockout-2.0",
"knockout-mapping-plugin"
] |
[
"TypeError from Python 3 async for loop",
"I'm learning about Python's relatively new async features. I found this in PEP 492:\n\n\n The following is a utility class that transforms a regular iterable to\n an asynchronous one. While this is not a very useful thing to do, the\n code illustrates the relationship between regular and asynchronous\n iterators.\n\nclass AsyncIteratorWrapper:\n def __init__(self, obj):\n self._it = iter(obj)\n\n def __aiter__(self):\n return self\n\n async def __anext__(self):\n try:\n value = next(self._it)\n except StopIteration:\n raise StopAsyncIteration\n return value\n\nasync for letter in AsyncIteratorWrapper(\"abc\"):\n print(letter)\n\n\n\nI attempted to run this code, by adding the given async for loop to a function, and then calling that using an event loop.\n\nFull example code (run in the interpreter):\n\nclass AsyncIteratorWrapper:\n def __init__(self, obj):\n self._it = iter(obj)\n def __aiter__(self):\n return self\n async def __anext__(self):\n try:\n value = next(self._it)\n except StopIteration:\n raise StopAsyncIteration\n return value\n\nasync def aprint(str):\n async for letter in AsyncIteratorWrapper(str):\n print(letter)\n\nimport asyncio\nloop = asyncio.get_event_loop()\nco = aprint(\"abcde\")\nloop.run_until_complete(co)\n\n\nHowever, I'm getting an error:\n\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"/opt/rh/rh-python35/root/usr/lib64/python3.5/asyncio/base_events.py\", line 337, in run_until_complete\n return future.result()\n File \"/opt/rh/rh-python35/root/usr/lib64/python3.5/asyncio/futures.py\", line 274, in result\n raise self._exception\n File \"/opt/rh/rh-python35/root/usr/lib64/python3.5/asyncio/tasks.py\", line 239, in _step\n result = coro.send(None)\n File \"<stdin>\", line 2, in aprint\nTypeError: 'async for' received an invalid object from __aiter__: AsyncIteratorWrapper\n\n\nWhat am I doing wrong? How can this example be fixed? I'm a little surprised that code right out of the PEP is failing.\n\nI'm using python version 3.5.1."
] | [
"python",
"asynchronous",
"python-3.5"
] |
[
"\"Input string was not in a correct format\" when setting a NumericUpDown value",
"I don't understand why this doesn't work. \n\nI am using a file to set bunch of in my program. I am reading the content of a file by using separators. My text file looks like this: The Message$1$5001&5002&5003\n\nWhen I am trying to read a value of a numeric values in my file I am getting error: Input string was not in a correct format. on line: nudInterval.Value = decimal.Parse(setting);\n\nThis is how I do it:\n\nif (!lastUsed.EmptyFile())\n{\n string[] allSettings = lastUsed.Text.Split('$');\n int settingCount = 0;\n\n foreach (string setting in allSettings)\n {\n settingCount++;\n\n if (settingCount == 1)\n {\n txtText.Text = setting;\n }\n else if (settingCount == 2)\n {\n if (setting == \"0\") tbType.SelectedTab = tbInterval;\n else tbType.SelectedTab = tbRange;\n }\n else if (settingCount == 3)\n {\n nudInterval.Value = decimal.Parse(setting);\n }\n else if (settingCount == 4)\n {\n nudMin.Value = decimal.Parse(setting);\n }\n else if (settingCount == 5)\n {\n nudMax.Value = decimal.Parse(setting);\n }\n }\n}"
] | [
"c#"
] |
[
"oracle not a group by function with nested query",
"I do not understand why this query does not work.\n\nOriginal query working on 3x servers.\n\nSELECT (\n SELECT to_char(RTRIM(XMLAGG(XMLELEMENT(e, TEXT, ',').EXTRACT('//text()')).GetClobVal(), ',')) CM_LINES\n FROM (\n SELECT DISTINCT to_char(cmline) TEXT\n FROM CCP.comms_matrix_data\n WHERE comms_matrix_id = :pkid\n AND src_net = t1.SRC_NET\n AND dst_net = t1.DST_NET\n ORDER BY cmline\n )\n ) CM_LINES\n ,t1.SRC_NET\n ,t1.DST_NET\n ,t1.SRC_NETZONE\n ,t1.DST_NETZONE\n ,t1.RPA\n ,t1.RPN\nFROM CCP.comms_matrix_data t1\nWHERE (t1.COMMS_MATRIX_ID = :pkid)\n AND (LOWER(t1.STATUS) LIKE '%implement%')\nGROUP BY t1.SRC_NET\n ,t1.DST_NET\n ,t1.SRC_NETZONE\n ,t1.DST_NETZONE\n ,t1.RPA\n ,t1.RPN\n\n\nOn dev server this errors with ORA-00904: \"T1\".\"DST_NET\": invalid identifier\n00904. 00000 - \"%s: invalid identifier\"\n\non my dev server it does not work so I decided to rewrite the query to:\n\nSELECT CM_LINES.CM_LINES\n ,t1.SRC_NET\n ,t1.DST_NET\n ,t1.SRC_NETZONE\n ,t1.DST_NETZONE\n ,t1.RPA\n ,t1.RPN\nFROM CCP.comms_matrix_data t1,\n(\n SELECT to_char(RTRIM(XMLAGG(XMLELEMENT(e, TEXT, ',').EXTRACT('//text()')).GetClobVal(), ',')) CM_LINES, src_net, dst_net\n FROM (\n SELECT DISTINCT to_char(cmline) TEXT, src_net, dst_net\n FROM CCP.comms_matrix_data\n WHERE comms_matrix_id = :pkid\n\n ORDER BY cmline\n )\n ) CM_LINES\nWHERE (t1.COMMS_MATRIX_ID = :pkid)\n AND (LOWER(t1.STATUS) LIKE '%implement%')\n AND CM_LINES.src_net = t1.SRC_NET\n AND CM_LINES.dst_net = t1.DST_NET\nGROUP BY CM_LINES.CM_LINES\n ,t1.SRC_NET\n ,t1.DST_NET\n ,t1.SRC_NETZONE\n ,t1.DST_NETZONE\n ,t1.RPA\n ,t1.RPN;\n\n\non dev server this errors with ORA-00937: not a single-group group function\n00937. 00000 - \"not a single-group group function\"\n\n@Gordon\n\nUPDATE\n\nSELECT x.CM_LINES\n ,t1.SRC_NET\n ,t1.DST_NET\n ,t1.SRC_NETZONE\n ,t1.DST_NETZONE\n ,t1.RPA\n ,t1.RPN\nFROM CCP.comms_matrix_data t1\nJOIN (\n SELECT to_char(RTRIM(XMLAGG(XMLELEMENT(e, cml.TEXT, ',').EXTRACT('//text()')).GetClobVal(), ',')) CM_LINES\n ,src_net\n ,dst_net\n FROM (\n SELECT DISTINCT to_char(cmline) TEXT\n ,src_net\n ,dst_net\n FROM CCP.comms_matrix_data\n WHERE comms_matrix_id = :pkid\n ORDER BY cmline\n ) cml ON cml.src_net = t1.SRC_NET /* sql developer reports problem here*/\n AND cml.dst_net = t1.DST_NET\n WHERE t1.COMMS_MATRIX_ID = :pkid\n AND LOWER(t1.STATUS) LIKE '%implement%'\n GROUP BY src_net\n ,dst_net\n ) x\nGROUP BY x.CM_LINES\n ,t1.SRC_NET\n ,t1.DST_NET\n ,t1.SRC_NETZONE\n ,t1.DST_NETZONE\n ,t1.RPA\n ,t1.RPN;\n\n\nUPDATE 2\n\nIf I Try the following i get error on group by ORA-00905: missing keyword\n00905. 00000 - \"missing keyword\"\n\nSELECT x.CM_LINES\n ,t1.SRC_NET\n ,t1.DST_NET\n ,t1.SRC_NETZONE\n ,t1.DST_NETZONE\n ,t1.RPA\n ,t1.RPN\nFROM CCP.comms_matrix_data t1\nJOIN (\n SELECT to_char(RTRIM(XMLAGG(XMLELEMENT(e, cml.TEXT, ',').EXTRACT('//text()')).GetClobVal(), ',')) CM_LINES\n ,src_net\n ,dst_net\n FROM (\n SELECT DISTINCT to_char(cmline) TEXT\n ,src_net\n ,dst_net\n FROM CCP.comms_matrix_data\n WHERE comms_matrix_id = :pkid\n ORDER BY cmline\n ) cml \n join cml ON cml.src_net = t1.SRC_NET\n AND cml.dst_net = t1.DST_NET\n WHERE t1.COMMS_MATRIX_ID = :pkid\n AND LOWER(t1.STATUS) LIKE '%implement%'\n GROUP BY src_net\n ,dst_net\n ) x /* should there not be an on clause here? */\nGROUP BY x.CM_LINES /* error here */\n ,t1.SRC_NET\n ,t1.DST_NET\n ,t1.SRC_NETZONE\n ,t1.DST_NETZONE\n ,t1.RPA\n ,t1.RPN;"
] | [
"sql",
"oracle"
] |
[
"Marker requires clicking twice to keep InfoWindow open",
"I have a map application that uses Android Google Maps API V2, although, when the user clicks on any Marker, the InfoWindow appears for a second and becomes invisible right after. If the user clicks again, the InfoWindow is displayed without problem this time.\n\nI'm extending the SupportMapFragment using the code from the link below and creating a fragment that extends the SherlockMapFragment class.\n\nhttps://gist.github.com/galex/4392030\n\nThe fragment class overrides the onMarkerClick method and returns false, indicating that the application has not handled the event \"manually\".\n\nCan you help me?\n\nThanks."
] | [
"android",
"google-maps",
"google-maps-android-api-2"
] |
[
"Script works as WSH, but in a HTA Sub it goes berzerker",
"I'm trying to build some Subs inside an HTA that run the following code. The script works fine as standalone WSH script, but when I put the code in a sub in my HTA it goes BERZERK. My command window appears a bunch of times, I think it is launching a new process for each WshShell.Sendkeys. I have tried numerous things, but am obviously missing something. Even when I have the HTA call the script externally I get the same wacky behavior, but I can run this in a wsh script and it works fine... \n\nPlease help!!\n\nset WshShell=CreateObject(\"WScript.Shell\")\nWshShell.run \"cmd.exe\"\nWScript.Sleep 500\n\n\nWshShell.SendKeys \"telnet 130.160.176.219 4998\"\n\nWshShell.SendKeys (\"{Enter}\")\nWScript.Sleep 5000\n\n\nWshShell.SendKeys \"sendir,1:1,1,37764,1,1,340,168,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,64,21,64,21,64,21,64,21,64,21,64,21,64,21,64,21,22,21,64,21,22,21,64,21,22,21,22,21,22,21,22,21,64,21,22,21,64,21,22,21,64,21,64,21,64,21,64,21,4833\"\nWshShell.SendKeys (\"{Enter}\")\nWScript.Sleep 500\nWshShell.SendKeys \"sendir,1:1,10,37764,1,1,340,168,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,64,21,64,21,64,21,64,21,64,21,64,21,64,21,64,21,64,21,64,21,22,21,22,21,22,21,22,21,64,21,22,21,22,21,22,21,64,21,64,21,64,21,64,21,22,21,64,21,4833\"\nWshShell.SendKeys (\"{Enter}\")\nWScript.Sleep 500\nWshShell.SendKeys \"sendir,1:1,5,37764,1,1,340,168,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,64,21,64,21,64,21,64,21,64,21,64,21,64,21,64,21,64,21,22,21,64,21,22,21,22,21,22,21,22,21,22,21,22,21,64,21,22,21,64,21,64,21,64,21,64,21,64,21,4833\"\nWshShell.SendKeys (\"{Enter}\")\nWScript.Sleep 500\nWshShell.SendKeys \"sendir,1:1,11,37764,1,1,340,168,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,64,21,64,21,64,21,64,21,64,21,64,21,64,21,64,21,22,21,64,21,64,21,64,21,64,21,22,21,64,21,22,21,64,21,22,21,22,21,22,21,22,21,64,21,22,21,64,21,4833\"\nWshShell.SendKeys (\"{Enter}\")\nWScript.Sleep 500\nWshShell.SendKeys \"sendir,1:1,1,37764,1,1,340,168,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,22,21,64,21,64,21,64,21,64,21,64,21,64,21,64,21,64,21,22,21,64,21,22,21,64,21,22,21,22,21,22,21,22,21,64,21,22,21,64,21,22,21,64,21,64,21,64,21,64,21,4833\"\nWshShell.SendKeys (\"{Enter}\")\nWScript.Sleep 1000\nWshShell.SendKeys (\"^{]}q{Enter}exit{Enter}\")\n//WScript.Quit"
] | [
"hta"
] |
[
"Need help to understand - context node and current node in XPath/XSLT",
"I was going through some online materials from Understanding XPath Processor Terms. Here I found definitions of current node and context node as below.\n\nCurrent Node\nCurrent node is the node that the XPath processor is looking at when it begins evaluation of a query. In other words, the current node is the first context node that the XPath processor uses when it starts to execute the query. During evaluation of a query, the current node does not change. If you pass a document to the XPath processor, the root node is the current node. If you pass a node to the XPath processor, that node is the current node.\n\n\nContext Node\nA context node is the node the XPath processor is currently looking at. The context node changes as the XPath processor evaluates a query. If you pass a document to the XPath processor, the root node is the initial context node. If you pass a node to the XPath processor, the node that you pass is the initial context node. During evaluation of a query, the initial context node is also the current node.\n\nAlthough the definitions are a bit good to understand the difference between current node and context node,examples are not good to understand the differences practically to me.\nCan any give me some good examples to show the below two things explicitly ?\n\nDuring xpath evaluation current node is fixed,but context nodes are keep changing.\ncontext node and current node are co-incised with each other."
] | [
"xslt",
"xpath",
"nodes"
] |
[
"Multi thread Writing data in TinyXMl",
"for TinyXML is a good XMl libuary, i use it to save packet data in network transmission, such as the client receive some packet from the server in UDP muticast mode. client join more than one muticast groups, so it must create multi-thread to receive and write the data in different files(of course, the numbers of file equals the nums of muticast groups).\ni design a writeXML class which has a DoWrite(char*,size_t) function.\n\nsuch as :\n\nvoid DoWrite(char*,size_t)\n{\nboost::unique_lock<boost::mutex> lLock(m_lock);\nlLock.lock();\n}\n\n\nbut the problem is whenever the DoWrite function is called, the boost:lock_error comes.\nwho can help me? tks very much! emphasized text"
] | [
"c++",
"boost-thread",
"streamwriter"
] |
[
"Scala trait implementation",
"I have a case class:\n\ncase class EvaluateAddress(addressFormat: String,\n screeningAddressType: String,\n value: Option[String]) {\n}\n\n\nThis was working fine until I have a new use case where \"value\" parameter can be a class Object instead of String.\n\nMy initial implementation to handle this use case:\n\ncase class EvaluateAddress(addressFormat: String,\n screeningAddressType: String,\n addressId: Option[String],\n addressValue: Option[MailingAddress]) {\n\n @JsonProperty(\"value\")\n def setAddressId(addressId: String): Unit = {\n val this.`addressId` = Option(addressId)\n }\n\n def this(addressFormat: String, screeningAddressType: String, addressId: String) = {\n this(addressFormat, screeningAddressType, Option(addressId), None)\n }\n\n def this(addressFormat: String, screeningAddressType: String, address: MailingAddress) = {\n this(addressFormat, screeningAddressType, None, Option(address))\n }\n}\n\n\nbut I don't feel this is a good approach and it might create some problem in future.\n\nWhat are the different ways I can accomplish the same?\n\nEdit: Is there a way I can create a class containing three parameters: ** addressFormat, screeningAddressType, value** and handle both the use cases?"
] | [
"scala",
"traits",
"case-class"
] |
[
"Angular2 Form Validation scoping issue (Template Driven)",
"I am unable to get the input in component2 to invalidate the form located in component1. The input that is in component1 invalidates the form fine. Is there anyway to invalidate a form using the inputs in child components in angular2? I would like to not have to propagate my form down through all the children and register the controls one by one\n\nComponent1:\n\n@Component({\nselector: 'app-component1',\ntemplate: `\n <form #f=\"ngForm\"> \n <input name=\"value1\" [(ngModel)]=\"value1\" customvalidator>\n <app-component2></app-component2> \n <input type=\"submit\" value=\"submit\" [disabled]=\"!f.form.valid\">\n </form>`\n})\nexport class Component1 {\n}\n\n\nComponent2:\n\n@Component({\n selector: 'app-component2',\n template: '<input name=\"value2\" [(ngModel)]=\"value2\" customvalidator>'\n})\nexport class Component2 {\n}"
] | [
"angular",
"angular2-forms"
] |
[
"SCRIPT1010: Expected Identifier in IE11 when compiled",
"I have been having an odd issue in Vue.js for a bit now, my application works on all browsers in my local (including IE 11). When I compile my application with npm run build and push it over to my server (which is just a CDN serving content from an S3 bucket) I get this message on my chunk-vendors.js. I have pollyfills in place that are working on my local, any ideas why it would be different once compiled and minified?\nThe original problem that seemed to solve this in my local was adding transpileDependencies: ['vuex-persist'], to my vue.config.release. There are so many answers online I can't make heads or tails or what could be the problem.\n\nUPDATE 1: Attempted to use https://babeljs.io/docs/en/babel-plugin-transform-destructuring and still no luck. Works on my local but not compiled."
] | [
"javascript",
"vue.js",
"internet-explorer-11",
"vue-cli"
] |
[
"Add custom android webview error page",
"In my app i want an error activity \"NOT A ERROR HTML PAGE\". Which contain refresh button and a layout. I have search for it but i found is just a custom html error page from assets folder.\n\nI have created a some code which is below,\ni want is that when ever network error occurs it will open an activity like this and user can easily refresh page using button.\n\n\n I want to make error page like this one..\n\n\n\n\nThis is not a html error page. This contains layout with refresh button,\n\npublic WebView mWebview ;\n@Override\nprotected void onCreate(final Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.map);\n mWebview = new WebView(this);\n mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript\n\n mWebview.setWebViewClient(new WebViewClient() {\n public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {\n\n\n // Do Something Here, I don't know what to do.. :(\n\n\n }\n });\n\n mWebview.loadUrl(\"google.com\");\n setContentView(mWebview);\n}\n\n@Override\npublic boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.option, menu);\n return true;\n}\n\n@Override\npublic boolean onOptionsItemSelected(MenuItem item) {\n // Handle presses on the action bar items\n switch (item.getItemId()) {\n\n case R.id.refresh:\n startActivity(new Intent(this, CeS1.class));\n finish();\n return true;\n\n case R.id.about:\n startActivity(new Intent(this, Credits_activity.class));\n finish();\n return true;\n\n case R.id.gotomain:\n startActivity(new Intent(this, MenuActivity.class));\n return true;\n default:\n return super.onOptionsItemSelected(item);\n }\n}"
] | [
"android",
"android-activity",
"webview",
"android-webview",
"custom-error-pages"
] |
[
"TTreeview limit the node editing text length",
"I am using TTreeView in C++ Builder XE7. I am allowing users to edit the node text on certain nodes, but I need to limit the amount of characters they can type in to 10.\n\nHow, and when, should I get the edit control and set it text limit?"
] | [
"c++builder"
] |
[
"Does the documentation for rep tell us that it is an internal generic function?",
"Because it is on the list of Internal Generic Functions, I know that rep is an internal generic function. Could this fact have been derived by only reading the documentation for rep? I have located the following two relevant-looking sections:\n\nrep replicates the values in x. It is a generic function, and the (internal) default method is described here.\n\n\nFor the internal default method these can include:\n\nDo either of these specifically tell the reader that rep is an internal generic function?\nTo be totally clear, I'm asking about the terminology that is used in these extracts. I'm not an expert on R's terminology, so what I'm asking is about what is implied by the words that they've used. For example, if the R documentation says that a function "is generic" and has an "internal default method", does that mean that the function is therefore an internal generic function?\nA link to some sort of glossary of R terms, or the relevant section in one of the R manuals, would be a very strong component of a good answer. A simple yes or no will probably not suffice."
] | [
"r",
"generics",
"replication",
"r-s3"
] |
[
"Is it better to use `null` or `-1` to indicate \"infinite\" in integer columns of the database",
"I often have fields in my database which store \"a number or infinite\". Examples could be maxFileSize, maxUsers, etc. It shall be possible to set a maximum value or just don't restrict it at all.\nI currently sometimes use null to indicate \"infinite / no restriction\" and sometimes use -1.\n\nI was wondering if there is any reason to use the one or the other. For the record, I work with PHP / MySQL / Doctrine / Symfony, if that matters.\n\nEdit: \n\nI am not asking for opinions but for facts (as you see in the answers already given) related to the usage of -1 or null. These might include speed, query complexity, database size, and so on."
] | [
"php",
"mysql",
"database",
"doctrine-orm",
"storage"
] |
[
"Stop a macro if rows generated in a structured table repeat X number of times",
"I've got a workbook containing a Summary sheet and 200 numbered sheets that the user fills in one after the other.\nThe following macro checks about 125 cell values on every numbered sheet, and fills in the Summary, one line per numbered sheet.\nIf a numbered sheet hasnt been used yet, the macro fills in every column from column D to column DV with the minus sign "-" and goes on to check every numbered sheet one after the other till there's no more to check.\nIs there a way to set it so that if an arbitrary number (let's say 10 lines) of the newly generated lines contain only the minus sign "-" from D to DV (Iw,4 to Iw, 126), then the macro would reach its end as it means all the remaining numbered sheets aren't used yet?\nSub SummaryMacro()\nDim Sh As Worksheet\nRange("B2:L1000").ClearContents\nIw = 2 ' Index Write\nFor Each Sh In ActiveWorkbook.Sheets\n If Sh.Name = "Summary" Then GoTo EndConsolidation\n Cells(Iw, 1).Select\nWith Selection\n .Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:="'" & Sh.Name & "'" & "!" & "A1", TextToDisplay:="Go to"\nEnd With\n Cells(Iw, 2) = Sh.Name\n If Sh.Range("D8") = "" Then\n Cells(Iw, 3) = "-"\n Else\n Cells(Iw, 3) = Sh.Range("D8")\n End If\n \n 'Here the rest of the process (Iw, 4 till Iw, 125)\n 'The process also includes a few variations:\n \n 'Something like 20 of those with various text\n If Sh.CheckBoxes("Check Box 1").Value = 1 Then Cells(Iw, 40) = "Declared" Else Cells(Iw, 40) = "-" \n \n 'Something like 30 of those with various text\n If Sh.Range("H33") = "Issued" Then\n Cells(Iw, 42) = "-"\n Else\n Cells(Iw, 42) = Sh.Range("H33")\n End If\n \n 'But all in all they are mostly like that\n If Sh.Range("C134") = "" Then\n Cells(Iw, 126) = "-"\n Else\n Cells(Iw, 126) = Sh.Range("C134")\n End If\n \n Iw = Iw + 1\nEndConsolidation:\nNext Sh\n\nEnd Sub"
] | [
"excel",
"vba"
] |
[
"angular-ui replace'?' with '#' on redirect from facebook oauth",
"I'm implementing facebook ouath login in angularjs without SDK.\n\nEverything works as expected except one thing.\n\nWhen user click on login button, which redirects to facebook login page, after successfull login, facebook fires redirect_uri URL, and user is again in the app.\n\nProblem is, that ui-router (probably) replaces '?' with '#' in path, so\n\nhttp://localhost/fbauth?access_token=xxx&code=yyy\nbecomes\nhttp://localhost/fbauth#access_token=xxx&code=yyy\n\nBecause of that, i cannot use $stateParams to get object with query params.\n\nSuprisingly, when I manually enter in browser or click link to \nhttp://localhost/fbauth?access_token=xxx&code=yyy\n everything works properly, and ui-router does not replace '?' with '#'.\n\nI guess, that it's related to redirection scenario itself.\n\nCan someone point me what I do wrong, or how to change ui-router behaviour in this case?\n\nThis is the state, that handles fb redirect:\n\n.state('fbauth', {\n url: '/fbauth?access_token&code&expires_in',\n templateUrl: 'static/public/public.html',\n controller: 'publicCtrl'\n});\n\n\nPS ui-router is set to work in html5 mode with $locationProvider.html5Mode(true);"
] | [
"angularjs",
"facebook",
"facebook-graph-api",
"oauth",
"angular-ui-router"
] |
[
"How to replace the video track of a part of a video file?",
"I have an mp4 file like this(same format but longer):\n\nInput #0, mov,mp4,m4a,3gp,3g2,mj2, from 'N1.2.mp4':\n Metadata:\n major_brand : mp42\n minor_version : 0\n compatible_brands: mp42mp41\n creation_time : 2018-10-31T13:44:21.000000Z\n Duration: 00:28:54.21, start: 0.000000, bitrate: 10295 kb/s\n Stream #0:0(eng): Video: h264 (Main) (avc1 / 0x31637661), yuv420p(tv, bt709), 1920x1080, 9972 kb/s, 50 fps, 50 tbr, 50k tbn, 100 tbc (default)\n Metadata:\n creation_time : 2018-10-31T13:44:21.000000Z\n handler_name : ?Mainconcept Video Media Handler\n encoder : AVC Coding\n Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 317 kb/s (default)\n Metadata:\n creation_time : 2018-10-31T13:44:21.000000Z\n handler_name : #Mainconcept MP4 Sound Media Handler\n\n\nI also have another video file that is 3 minutes long. and has no audio. What is the fastest way to encode the other video in a way that it is encoded like my main video and then replace the last three minutes of the video track of my original video with this?\n\nIn other words.\nI have video A that is 1 hour long. With the encoding shown above.\n\nI have video B that is 3 minutes long with no audio. with a random encoding.\n\nI want to have video C with the same encoding and same audio as A. But it's video track would be the first 57 minutes of A + B(which is 3 minutes).\n\nI want to do this as fast as possible so I would like to not re encode A.\n\nI know how to concatenate two videos, I use this command:\n\nffmpeg -f concat -i files.txt -c copy res.mp4"
] | [
"audio",
"video",
"ffmpeg",
"media",
"mp4"
] |
[
"Whenever Plugin Help",
"I am trying to use the Whenever plugin for rails to perform a model process at certain times. My schedule.rb is as follows:\n\n every 1.day, :at => '5:30 am' do\n runner \"User.mail_out\"\n end\n\n\nMy model is as follows:\n\nclass User < ActiveRecord::Base\n\n acts_as_authentic\n\n def mail_out\n\n weekday = Date.today.strftime('%A').downcase\n\n @users = find(:conditions => \"#{weekday}sub = t\")\n\n @users.each { |u| UserMailer.deliver_mail_out(u)} \n\n\n end\n\nend\n\n\nWhen I try to run the script/runner -e development \"User.mail_out\" command, I get the following error:\n\n/var/lib/gems/1.8/gems/rails-2.3.5/lib/commands/runner.rb:48: undefined method `mail_out' for #<Class:0xb708bd50> (NoMethodError)\n from (eval):1\n from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `eval'\n from /var/lib/gems/1.8/gems/rails-2.3.5/lib/commands/runner.rb:48\n from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `gem_original_require'\n from /usr/lib/ruby/1.8/rubygems/custom_require.rb:31:in `require'\n from script/runner:3\n\n\nCan anyone point out what is going wrong? Also how can I manually invoke the mail_out process (from command line) to test the functionality of my mailing system.\n\nThank you!"
] | [
"ruby-on-rails",
"ruby-on-rails-plugins",
"whenever"
] |
[
"Apache Beam Wall Time keeps increasing",
"I have a Beam pipeline that reads from a pubsub topic, does some small transformations and then writes the events to some BigQuery tables.\nThe transforms are light on processing, maybe removing a field or something else, but, as you can see from the image below, the Wall Time is very high for some steps. What can actually cause this?\nEvery element is actually a tuple of the form ((str, str, str), {**dict with data}). By this key we actually try to do a naive deduplication by taking the latest event by this key.\nBasically whatever I add after that Get latest element per key is slow, and tagging is also slow, even tho it just adds a tag to the element."
] | [
"python-3.x",
"google-cloud-dataflow",
"apache-beam"
] |
[
"Inserting products into Magento stops after x items",
"I am trying to insert products into a Magento Web Shop using the following code:\n\npublic static function addProduct($product, $categorieId) {\n $productModel = Mage::getModel('catalog/product');\n\n $productModel->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)\n ->setWebsiteIDs(array(1))\n ->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)\n ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)\n ->setCreatedAt(strtotime('now'))\n ->setName($product->PRODUCT_DETAILS[0]->DESCRIPTION_SHORT)\n ->setCategoryIds(array($categorieId))\n ->setDescription($product->PRODUCT_DETAILS[0]->DESCRIPTION_LONG ? $product->PRODUCT_DETAILS[0]->DESCRIPTION_LONG : $product->PRODUCT_DETAILS[0]->DESCRIPTION_SHORT)\n ->setShortDescription($product->PRODUCT_DETAILS[0]->DESCRIPTION_SHORT)\n ->setPrice($product->PRODUCT_PRICE_DETAILS->PRODUCT_PRICE->PRICE_AMOUNT)\n ->setAttributeSetId($productModel->getResource()->getEntityType()->getDefaultAttributeSetId());\n\n $productModel->setStockData(array(\n 'is_in_stock' => 1,\n 'qty' => 99999\n ));\n\n try {\n $productModel->save();\n return $productModel->getId();\n } catch (Exception $ex) {\n Mage::log($ex->getMessage());\n }\n}\n\n\nNevertheless, the code inserts items into the right categories. After about 38 items it stops, with no error and nothing. The Ajax call returns no errors, nothing. Any ideas what this can be caused by?\n\ncheers\nWolfgang"
] | [
"magento",
"magento-1.7"
] |
[
"syncing data between two Hbase clusters",
"In the current up, we have two independent pipelines, one for each data center, writing data to separate HBase clusters. The data between the clusters may be out of sync at times if there were issues writing to one of the clusters due to DC being down or other issues in a pipeline. \n\nAs the query API randomly picks one of the two available hbase clusters as its data source, the data returned may be incomplete. One option is to query both the clusters and take union of the data set, however, this is resource intensive and adds to overall latency.\n\nLooking for ways to bring the data between clusters in the two DCs in sync periodically (once per day ideally - the clusters should continue to function reads/writes during sync). I believe native Hbase replication works with a master-slave paradigm in which only master accepts writes, however, we don't use native replication as we are writing to both clusters for resiliency. \n\nIts a large scale set up. some approx stats per cluster:\n\n100 tables\n60 region servers\n600 regions per region server\n200 billion new rows added per day\n\n\nAppreciate your insights."
] | [
"hbase",
"data-synchronization"
] |
[
"Power BI REST authentication and permissions",
"I'm attempting to create a bridge between another service (as a data source) and Microsoft Power BI. However, I can't get the REST API to work properly.\n\nSo far I've succeeded in creating a web application in Azure AD, getting the Client ID and secret, receiving an access token for the API, but after this all I get is 403 Forbidden with no error message. However, if I try to access the API with an expired token, I get an error message telling me that the token is expired.\n\nI've read some posts on the subject, but they all suggest that the REST API cannot be accessed without having a user log in and access Power BI first, which isn't possible in a service-to-service application.\n\nHow do I properly access the service without any user interaction?\n\nHere are the requests and responses, censored a little bit.\n\nRequest 1:\n\nPOST /[our domain].com/oauth2/token HTTP/1.1\nContent-Type: application/x-www-form-urlencoded\nCookie: flight-uxoptin=true; stsservicecookie=ests; x-ms-gateway-slice=productiona; stsservicecookie=ests\nHost: login.microsoftonline.com\nConnection: close\nUser-Agent: Paw/2.3 (Macintosh; OS X/10.11.3) GCDHTTPRequest\nContent-Length: 203\n\ngrant_type=client_credentials&client_id=[client id]&client_secret=[client secret]&resource=https%3A%2F%2Fanalysis.windows.net%2Fpowerbi%2Fapi\n\n\nResponse 1:\n\nHTTP/1.1 200 OK\nCache-Control: no-cache, no-store\nPragma: no-cache\nContent-Type: application/json; charset=utf-8\nExpires: -1\nServer: Microsoft-IIS/8.5\nx-ms-request-id: 52d6713c-d50b-4073-b030-aa10e33fdf27\nclient-request-id: 3aef4765-d602-46a6-a8ce-4b7792f678e5\nx-ms-gateway-service-instanceid: ESTSFE_IN_209\nX-Content-Type-Options: nosniff\nStrict-Transport-Security: max-age=31536000; includeSubDomains\nP3P: CP=\"DSP CUR OTPi IND OTRi ONL FIN\"\nSet-Cookie: x-ms-gateway-slice=productiona; path=/; secure; HttpOnly\nSet-Cookie: stsservicecookie=ests; path=/\nX-Powered-By: ASP.NET\nDate: Wed, 24 Feb 2016 08:24:29 GMT\nConnection: close\nContent-Length: 1243\n\n{\"token_type\":\"Bearer\",\"expires_in\":\"3599\",\"expires_on\":\"1456305870\",\"not_before\":\"1456301970\",\"resource\":\"https://analysis.windows.net/powerbi/api\",\"access_token\":\"[access token]\"}\n\n\nRequest 2:\n\nGET /v1.0/myorg/datasets HTTP/1.1\nAuthorization: Bearer [access token]\nContent-Length: 0\nHost: api.powerbi.com\nConnection: close\nUser-Agent: Paw/2.3 (Macintosh; OS X/10.11.3) GCDHTTPRequest\n\n\nResponse 2:\n\nHTTP/1.1 403 Forbidden\nContent-Length: 0\nServer: Microsoft-HTTPAPI/2.0\nStrict-Transport-Security: max-age=31536000; includeSubDomains\nX-Frame-Options: deny\nX-Content-Type-Options: nosniff\nRequestId: 803cc0cb-c65d-4212-9ab8-aed4ffa9862a\nDate: Wed, 24 Feb 2016 08:25:13 GMT\nConnection: close"
] | [
"api",
"rest",
"azure",
"powerbi"
] |
[
"Write file from cStringIO",
"I am trying to write a cStringIO buffer to disk. The buffer may represent a pdf, image or html file.\n\nThe approach I took seems a bit wonky, so I am open to alternative approaches as a solution as well.\n\ndef copyfile(self, destfilepath):\n if self.datastream.tell() == 0:\n raise Exception(\"Exception: Attempt to copy empty buffer.\")\n with open(destfilepath, 'wb') as fp:\n shutil.copyfileobj(self.datastream, fp)\n self.__datastream__.close()\n\n@property\ndef datastream(self):\n return self.__datastream__\n\n#... inside func that sets __datastream__\nwhile True:\n buffer = response.read(block_sz)\n self.__datastream__.write(buffer)\n if not buffer:\n break\n# ... etc ..\n\ntest = Downloader()\nok = test.getfile(test_url)\nif ok:\n test.copyfile(save_path)\n\n\nI took this approach because I don't want to start writting data to disk until I know I have successfully read the entire file and that it's a type I am interested in.\n\nAfter calling copyfile() the file on disk is always zero bytes."
] | [
"python",
"python-2.7",
"cstringio"
] |
[
"How to prevent duplicate through grouping two columns? MYSQL/Codeigniter",
"I have a predicament where I'm trying to make a facebook-style wall where you have the wall table, users table, wall post table and images table (for this scenario). To simplify the process, the image is posted in the images table, and an entry is made as a wall post. It groups by wall id but when comments are made, it repeats the wall post for every new comment. Essentially I just want ONE post per wall post.\n\nMYSQL Query (Codeigniter):\n\n $this->db->select('*');\n $this->db->from('wall_posts AS p');\n $this->db->join('users AS k', 'p.wall_poster = k.user_id AND p.wall_owner = k.user_id', 'left');\n $this->db->group_by('p.wall_id');\n $this->db->where('p.wall_poster', $pid); // $pid = given user id\n $this->db->or_where('p.wall_owner', $pid);\n $this->db->order_by('p.wall_id', 'desc');\n $this->db->limit($lim); // $lim = limit number\n\n return $this->db->get();\n\n\nTable example\n\n wall_id|owner_id|reference_id|wall_poster\n 1 |0 |55 | 2\n 2 |0 |30 | 1\n 3 |0 |32 | 2\n 4 |2 |19 | 3\n 5 |0 |0 | 4\n 6 |0 |0 | 2\n 7 |0 |32 | 3\n 8 |0 |18 | 4\n\n\nNow, you can see that ID 3 and ID 7 has the same reference_id (image in this case), so later when the result is displayed, any posts referencing that image will be displayed multiple times instead of just once. I also have a column called post_type to help afterwards in the controller which determines if it's a normal post, comment, an image post, comment of an image etc...\n\nThanks ahead of time! This is bugging me to no end and I'd like to keep this as a single query if possible."
] | [
"php",
"mysql",
"codeigniter"
] |
[
"How Does This Website Block Pinch-to-Zoom on iPad?",
"I visited mobile-apps-news on an iPad and noticed there's no way I can pinch-to-zoom, it's using a responsive layout - but I'm very curious to how they've blocked pinch zooming under iOS. It's definitely not Javascript.\n\nAnyone know how they've done this?\n\nThanks!"
] | [
"ipad",
"html",
"mobile",
"zooming",
"responsive-design"
] |
[
"Sign in via the opened browser issue (Ubuntu 18.04 LTS)",
"I have a sign in issue with my android studio running on ubuntu 18.04 LTS: The \"Please sign in via the opened browser\" dialog is popping up and staying still no actions of browser opening is observed. I have tried many times by changing my system's default browser and also by giving the custom path of the browser in the android studio web browser settings, still I could not figure out the way to do it."
] | [
"android",
"linux",
"android-studio",
"ubuntu-18.04"
] |
[
"How do I use this google IdToken to get the users email address using PHP?",
"I have an android app that uses google sign in.\n\nI have successfully requested and retrieved an IdToken as such...\n\n GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)\n .requestEmail()\n .requestIdToken(getString(R.string.google_server_client_id))\n .build();\n\n\nlater retrieved by..\n\n GoogleSignInAccount acct = result.getSignInAccount();\n if(acct != null) {\n email = acct.getEmail();\n gToken = acct.getIdToken();\n }\n\n\nI then successfully sent this IdToken to the server.\n\nIf possible, using PHP, how do I use this IdToken to get the users email address? I'm so confused between IdToken, Authorization Token, Access Token, Oauth2. I just can't weed out the garbage to get the info I need. I need your help! lol."
] | [
"php",
"android",
"access-token",
"google-signin"
] |
[
"Will it be fine if we use msse and msse2 option of gcc in RTOS devices",
"As per my knowledge msse and msse2 option of gcc will improve the performance by performing arithmetic operation faster. And also I read some where like it will use more resources like registers, cache memory. \n\nWhat about the performance if we use the executable generated with these options on RTOS devices(like vxworks board) ?"
] | [
"c",
"performance",
"gcc"
] |
[
"Android app slows down after adding minSdkVersion",
"I'm building my first Android game. I integrated Fabric-Crashlytics SDK this morning and my game is considerably slow after that. When I investigated the issue, I realized that the issue is caused by the android:minSdkVersion specification in my application manifest file. When I get rid of the following lines:\n\n<uses-sdk android:minSdkVersion=\"8\" android:targetSdkVersion=\"21\"/>\n\n\nfrom the manifest, the game works as usual. I know, it's not the Crashlytics SDK. I already tried changing both minSdkVersion and targetSdkVersion. But, the issue continues."
] | [
"android",
"performance",
"android-manifest"
] |
[
"Accessing the contents of a table cell in Javascript",
"I've got a checkbox nested inside a table cell element in HTML. How can I access the inner checkbox from Javascript? All of the examples I've seen alter the inner HTML itself, or the visual properties, which is not what I'm interested in. I've tried the childNodes array, but it's empty, apparently."
] | [
"javascript",
"html"
] |
[
"How can I set a CSS Select for all but the last child?",
"I have this CSS:\n\n.btn-group > .btn {\n margin-right: 0; // << I want this for all except last child\n position: relative;\n border-radius: 0;\n}\n\n\nIs there a way that I can make this margin-right work for all .btn except the last child?"
] | [
"css"
] |
[
"Towers of Hanoi Closed Form Solution",
"So I'm trying to find the closed form solution for the Towers of Hanoi problem. I understand that the recurrence relation is T(n) = 2T(n-1) + 1, because it takes T(n-1) to move the top of the tower back and forth which is why there are two, and the \"+ 1\" is to move the base. However, I cannot understand why the closed solution is 2^n - 1. \n\nWhen I am trying to solve for the answer and I use back substitution, I get as far as: T(n) = 8T(n-3) + 4 + 2 + 1, which is T(n) = 2^k (T(n - k)) + 2^k-1 + 2^k-2 + 2^k-3 where k is the step? I know the last part is also geometric series, which means it is 2^(n + 1) - 1/(2-1). But I just can't understand where the answer comes from.\n\nedit:\nis it because the geometric series part is not 2^k + 2^k-1 + ... + 2^k-k? which means that the geometric series is not 2^n + 1 - 1, but rather 2^n - 1. and we use H(0) as the base case --> so H(n - k), use k = n?"
] | [
"algorithm",
"recurrence",
"towers-of-hanoi"
] |
[
"share link (facebook) of youtube video with different title and description",
"How create in my webpage a share link(Facebook) of youtube video but change the title and description\n\nThanks"
] | [
"html",
"facebook",
"youtube",
"social-networking"
] |
[
"merging JSON Array with object - Rails 4- Ruby",
"I am using Rails 4 and got following JSON output from different sources\n\nsource1\n\n@something1 = book.find().to_json\n\n\noutput\n\n\"[{\\\"a\\\": \\\"val1\\\"}]\"\n\n\nsource2\n\n@something2 = Author.where(title: :autitle).pluck(:val2).to_json\n\n\nOutput\n\n\"[{\\\"b\\\": \\\"val2\\\"}]\"\n\n\nsource 3\n\n@something3 = Publications.find_by_pub_id(id)\n\n\nOutput\n\n{ \n \"c\":\"val3\",\n \"d\":\" val4\"\n}\n\n\nI want the final output like\n\n{\n \"a\": \"val1\",\n \"b\": \"val2\",\n \"c\":\"val3\",\n \"d\":\" val4\"\n}\n\n\nI have used merge like \n\n@newval= @something1[0].merge(@something2[0]).merge(@something3)\n\n\nBut, it gives error\n\n\n undefined method merge!\n\n\nThose variables are inside index method like\n\nclass Test controller < api::controller\n def index\n @something1 = ..\n @something2 = ..\n @something3 = ..\n end\nend\n\n\nHope it is clear."
] | [
"ruby-on-rails",
"json",
"ruby"
] |
[
"Swift xml parser causing an error",
"I am trying to parse a simple xml file but I keep getting the error\n\n\n \"Error Description:The operation couldn’t be completed. (Cocoa error -1.)\n Line number: 0\"\n\n\nXML File (named mathquiz.xml placed in a folder called img):\n\n<quiz>\n <title>\n Y1 Maths Quiz\n </title>\n <question>\n <description>\n What is 2+2\n </description>\n <answer>\n 4\n </answer>\n <answer>\n 3\n </answer>\n <answer>\n 2\n </answer>\n <answer>\n 1\n </answer>\n </question>\n</quiz>\n\n\nParser:\n\n//\n// QuizXMLParser.swift\n// MathQuiz\n//\n// Created by Raees on 22/06/2017.\n// Copyright © 2017 Raees Apps. All rights reserved.\n//\n\nimport Foundation\n\npublic class QuizXMLParser : NSObject, XMLParserDelegate {\n\n var currentContent = \"\"\n var quiz = Quiz()\n var question = Question()\n\n public func beginParsing(file url: String) {\n guard let myURL = NSURL(string:url) else {\n print(\"URL not defined properly\")\n return\n }\n guard let parser = XMLParser(contentsOf: myURL as URL) else {\n print(\"Cannot Read Data\")\n return\n }\n parser.delegate = self\n if !parser.parse(){\n print(\"Data Errors Exist:\")\n let error = parser.parserError!\n print(\"Error Description:\\(error.localizedDescription)\")\n print(\"Line number: \\(parser.lineNumber)\")\n }\n }\n\n public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]){\n print(\"Beginning tag: <\\(elementName)>\")\n if elementName == \"question\" {\n question = Question()\n }\n currentContent = \"\"\n }\n\n public func parser(_ parser: XMLParser, foundCharacters string: String){\n currentContent += string\n print(\"Added to make \\(currentContent)\")\n }\n\n public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?){\n print(\"ending tag: </\\(elementName)> with contents:\\(currentContent)\")\n switch elementName{\n case \"question\":\n quiz.questions.append(question)\n print (\"model has \\(question)\")\n case\"title\":\n quiz.title = currentContent\n case \"description\":\n if let index = Int(currentContent) {\n quiz.currentQuestionIndex = index\n }\n case \"answer\":\n question.answers.append(currentContent)\n default:\n return\n }\n }\n}\n\n\nCall to parser in view controller:\n\nlet parser = QuizXMLParser()\nparser.beginParsing(file: \"img/mathquiz.xml\")\n\n\nHow can I make it successfully parse the XML file? I don't see anything wrong with it."
] | [
"xml",
"swift"
] |
[
"How to show progress dialog in Android?",
"I want to show ProgressDialog when I click on Login button and it takes time to move to another page. How can I do this?"
] | [
"android",
"progressdialog"
] |
[
"Pandas: Grouping by date, aggregating on other column",
"I have this dataframe. It's information about license usage:\n\n usuario feature fini ffin delta\n0 USER-1 PROGRAM-1 2016-06-30 21:03:21 2016-06-30 21:03:34 00:00:13\n2 USER-1 PROGRAM-1 2016-06-30 21:09:20 2016-06-30 21:09:32 00:00:12\n4 USER-1 PROGRAM-1 2016-06-30 21:14:40 2016-06-30 21:15:34 00:00:54\n6 USER-1 PROGRAM-1 2016-06-30 21:16:42 2016-06-30 21:17:24 00:00:42\n8 USER-1 PROGRAM-1 2016-06-30 21:18:09 2016-06-30 21:18:21 00:00:12\n\n\nSorry for the fields in spanish, but you get the idea. fini means fecha inicial (inital date) and ffin fecha final (ending date), as you have guess delta is ffin-fini\n\nSo, I want to know how much time USER-1 has spent in whatever program he has been working (PROGRAM-1) in this case.\n\nIf I do a table['delta'].sum() I get what I want, it says he used it 00:02:13.\n\nNow suppose I have more users, more features, and I want to group them by days (maybe hours), to see how people are using their licenses\n\nI tried the resample, but I really don't understand how it works. I saw there's a Grouper function but I don't have it installed."
] | [
"python",
"python-3.x",
"pandas"
] |
[
"Why does the following assembly result with 0?",
"I accidentally tried to call a virtual function of a class that was destructed. During the debugging with GDB I got to this assembly (AT&T syntax) and I need help understanding it. The outcome of the following is $rax = 0. Why?\n\nmov -0x188(%rbp),%rax\nmov (%rax),%rax\nadd $0x58,%rax\nmov (%rax),%rax\ncallq *%rax\n\n\nI tried running the following in gdb:\n\np $rbp gives 0x7f70277a2680\np $rbp - 0x88 gives 0x7f70277a25f8\nx 0x7f70277a25f8 gives 0x0185b4cb\np 0x0185b4cb + 0x58 gives 25539875\nx 25539875 gives 0x8d481f76\n\n\nIf p $rax is 0 shouldn't x 25539875 also give 0? What am I missing?\n\n\n\nEdit:\n\nAs @prl said I accidentally reduced 0x88 instead of 0x188. After fixing all is well and p $rax results with 0. Thank you.\n\np $rbp gives 0x7f70277a2680\np $rbp - 0x188 gives 0x7f70277a24f8\nx/a 0x7f70277a24f8 gives 0x7ffc52e591d0\np 0x7ffc52e591d0 + 0x58 gives 140721699263016\nx/a 140721699263016 gives 0"
] | [
"assembly",
"gdb",
"x86-64"
] |
[
"Controlling someone else's window screen",
"I have a webpage where an admin can login as well as a random user. I want the admin to be able to hit an exit button which will bring the user to a different screen. In other words, using PHP I can show the exit button only when it's an admin logging in, but how do I modify my code so that pressing exit bring the user to a post-activity screen. \n\nPart of the current code below:\n\n //exit is currently controlled on the user's screen - i want to modify that\n //only the admin should control this\n $(\"#exit\").click(function(){\n $(\"#MainScreen\").hide();\n $(\"#PostScreen\").show();\n });"
] | [
"php",
"javascript",
"jquery"
] |
[
"Android Video Upload to Youtube",
"I am developing an app that uploads a video in the sdcard to youtube and returns the youtube video url after. However, I have not been able to successfully do so.\n\nI have tried with ACTION_SEND:\n\npublic void onUploadClick(View v) {\n Intent uploadIntent = new Intent(Intent.ACTION_SEND);\n // In a real app, video would be captured from camera.\n File f = new File(\"/sdcard/test.mov\");\n uploadIntent.setDataAndType(Uri.fromFile(f), \"video/quicktime\");\n startActivity(Intent.createChooser(uploadIntent, \"Upload\"));\n}\n\n\nBut, oddly, with this implementation I do not have Youtube as an option for the upload. I have Bluetooth, Mail, Dropbox, Facebook, Flickr, Gmail and Handcent. But not Youtube. Any thoughts on this?\nBesides, is it possible using this method to have the url of the youtube video after uploaded? How?\n\nI have also tried using Youtube API for Java, and again no success. I added all the libraries needed (gdata-client-1.0.jar, gdata-media-1.0.jar and gdata-youtube-2.0,jar). However, when I run it I get a NoClassDefFoundError for com.google.gdata.client.youtube.YouTubeService, despite having the right libs and imports.\nHere is the code I am using:\n\nYouTubeService service = new YouTubeService(clientID, developer_key);\nVideoEntry newEntry = new VideoEntry();\n\nYouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();\nmg.setTitle(new MediaTitle());\nmg.getTitle().setPlainTextContent(\"My Test Movie\");\nmg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, \"Autos\"));\nmg.setKeywords(new MediaKeywords());\nmg.getKeywords().addKeyword(\"cars\");\nmg.getKeywords().addKeyword(\"funny\");\nmg.setDescription(new MediaDescription());\nmg.getDescription().setPlainTextContent(\"My description\");\nmg.setPrivate(false);\nmg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, \"mydevtag\"));\nmg.addCategory(new MediaCategory(YouTubeNamespace.DEVELOPER_TAG_SCHEME, \"anotherdevtag\"));\n\nnewEntry.setGeoCoordinates(new GeoRssWhere(37.0,-122.0));\n// alternatively, one could specify just a descriptive string\n// newEntry.setLocation(\"Mountain View, CA\");\n\nMediaFileSource ms = new MediaFileSource(new File(\"file.mov\"), \"video/quicktime\");\nnewEntry.setMediaSource(ms);\n\nString uploadUrl =\n \"http://uploads.gdata.youtube.com/feeds/api/users/default/uploads\";\n\nVideoEntry createdEntry = service.insert(new URL(uploadUrl), newEntry);\n\n\nTo sum up, my questions are:\n- What am I doing wrong in both approaches?\n- Regarding my simple objective of uploading a video to youtube and getting its youtube link after, which method do you recommend? Even if it's neither of those above.\n\nThank you.\n\n---- Update 04/10 ----\n\n\nAfter trying with a differente phone I found out that Youtube not showing up as choice to upload the video is my phone's problem (probably due to the ROM).\nHowever, even if it does work using intents is not the way to go because I cannot get the URL back and that is essential.\nAfter some research it seems that the second method is not possible. The Youtube API for Java does not work in Android.\n\n\nThat being said, I am looking for suggestions on how to upload a video to Youtube in Android.\nWhat I really want is to choose a video file, upload it to Youtube and get the youtube URL. Preferably without any interference from the user, who only chooses the file and then the uploading and URL retrieving runs \"in the background\".\nAny suggestions? What is the easiest and fastest way to achieve this?\n\nThanks."
] | [
"android",
"video",
"upload",
"youtube"
] |
[
"Maintain DataTable & Variables throughout Session",
"I have created the website in which i have to maintain the datatables & some variables in memory. Data/values in datatable or varibales will be different as per the logged user. how to maintain it?"
] | [
"c#",
"asp.net",
"session",
"datatable"
] |
[
"How to set \"BR2_PACKAGE_HOST_ENVIRONMENT_SETUP\" in buildroot",
"I want to various projects for various platforms, and as such I've concluded that the easiest way to to this is probably going to just have buildroot create the toolchain and then alter the environment to use said toolchain.\nFrom section 8.14.1 of the buildroot manual:\n\nFor your convenience, by selecting the option\nBR2_PACKAGE_HOST_ENVIRONMENT_SETUP, you can get setup-environment\nscript installed in output/host/and therefore in your SDK. This script\ncan be sourced with . your/sdk/path/environment-setup to export a\nnumber of environment variables that will help cross-compile your\nprojects using the Buildroot SDK: the PATH will contain the SDK\nbinaries, standard autotools variables will be defined with the\nappropriate values, and CONFIGURE_FLAGS will contain basic ./configure\noptions to cross-compile autotools projects. It also provides some\nuseful commands. Note however that once this script is sourced, the\nenvironment is setup only for cross-compilation, and no longer for\nnative compilation.\n\nAlright, that sounds pretty much like exactly what I want. However, I have not figured out how to set BR2_PACKAGE_HOST_ENVIRONMENT_SETUP. I found no mention of anything similar when looking through make menuconfig, I tried to grep the entire buildroot source tree for that string with no luck, and simply exporting it as an environment variabl did not produce a different result either. So, how do I set BR2_PACKAGE_HOST_ENVIRONMENT_SETUP, exactly?"
] | [
"makefile",
"buildroot",
"toolchain"
] |
[
"Getting error messages from QtCreator when trying to build hello world program but the code can still be executed",
"Im doing another QtCreator setup on a new system, and now Im getting errors when I try to build even a hello world program.Seems something is wrong with my C++ libs of how Qt is trying to put them together. I'm truly stumped here, any suggestions at all are appreciated.\n\n\n\nLooked at this a bit more, and it is even stranger than i thought. There is build errors on several lines of several of my projects, but they are actually building and can be ran and even debugged! Unknown type name errors on almost every Qt type, but it still works fine.\n\nSo I know even less about the issue: many errors, but everything runs fine....\n\nAnyone seen this before?"
] | [
"c++",
"qt",
"qt-creator"
] |
[
"Laravel queue is not doing job in the background",
"I am trying to use laravel queue to send bulk emails. So far I have written down the logic and it works fine, but the problem is that when I wrote the logic in controller it takes a lot of time so I thought of using jobs but again the problem persists.\nMy Problem\nMy problem is that I am not able send the email in background even if I am using queue.\nController\n public function newsletter(Request $request)\n {\n //dd($request->all());\n dispatch(new SendEmail($request));\n\n Session::flash('message', 'Email Sent');\n Session::flash('class', 'success');\n return redirect()->route('news');\n }\n\nJobs\n public function handle(Request $request)\n {\n //\n $data = array(\n 'message' => $request->message,\n 'subject' => $request->subject,\n 'file' => $request->file("file")\n );\n \n $teachingLevel = $request->highest_teaching_level;\n $school = $request->school;\n $province = $request->province;\n $district = $request->district;\n\n $subject = $request->subject;\n\n if ($teachingLevel != "" && $school != "" && $province != "" && $district != "") {\n $email = User::where('highest_teaching_level', $teachingLevel)->where('current_school_name', $school)->where('address','LIKE', '%'.$province.'%')->where('address','LIKE', '%'.$district.'%')->pluck('email');\n }else{\n $email = User::pluck('email');\n }\n \n foreach($email as $e)\n {\n Mail::to($e)->send(new NewsLetter($data, $subject));\n }\n }\n\nThe email is sent but it doesn't happen in the background. Maybe it has to do with the way I have passed $request variable in the handle() function.\nAny help will be appreciated. Thanks!"
] | [
"php",
"laravel",
"eloquent",
"laravel-queue"
] |
[
"post-redirect-get (PRG) re-inserts same page into history in Webkit browsers",
"Let's say I'm on /page?id=1\n\nThen I navigate to /page?id=2\n\nAnd I make a change on that page, which implements a post and then redirects back to /page?id=2\n\nIn Firefox, I can hit the back button once and return to /page?id=1, but in Chrome and Safari on iPhone, I have to hit the back button twice because /page?id=2 is in the browser history twice. (And if I made multiple posts from id=2, I'd have to hit the back button that many times to finally return to id=1.)\n\nIn some ways, this seems like normal browser behavior, as each GET is simply pushed into the history, but since the URL is identical to the previous entry, this results in a poor user experience, which typically seems to be avoided by other web applications... and is naturally avoided in Firefox. Is this an unavoidable bug in Webkit browsers, or can I implement the PRG in a different way to avoid this?\n\nbtw- the behavior appears to be the same redirecting with 302 or 303.\n\nUPDATE: I've mocked up some sample code... don't know if there's a platform like jsfiddle where I could upload this for you to see in action:\n\nform.php:\n\nid=<?=$_REQUEST['id']?>\n<form action=\"submit.php\" method=\"post\">\n<input type=\"hidden\" name=\"id\" value=\"<?=$_REQUEST['id']?>\">\n<input type=\"submit\" value=\"submit\">\n</form>\n\n\nsubmit.php:\n\n<?php\nheader(\"Location: form.php?id=\" . $_REQUEST['id']);\ndie($_REQUEST['id']);\n?>\n\n\nIf I start on form.php?id=4 (just to put it in the browser history) and then go to form.php?id=5 and then hit submit (as though to execute a database change), in Firefox I get one entry in the history for each; in Chrome I get one entry for id=4 and then two entries for id=5. Why the difference in behavior? I think Firefox's behavior is better, since hitting back twice to get away from id=5 is counter-intuitive to the user."
] | [
"html",
"google-chrome",
"webkit",
"mobile-safari",
"post-redirect-get"
] |
[
"MARL for intrusion detection",
"I'm building multi agent reinforcement learning to detect intrusion. The agents should cooperate to find the best policy that maximize the number of detected attacks. The agents should also communicate with each other to share their experiences.\nMy question is what is the best algorithm that is suitable for this project and if there are any python implementations of it.\nThanks"
] | [
"reinforcement-learning"
] |
[
"A very annoying NSPredicate crash on iPhone 5 and iPad 4th gen with iOS 10.3",
"As title of this question says, below my code is crashing when NSPredicate is initializing. So far i found out that crashing is occuring only on iPhone 5 and iPad 4th gen with iOS 10.3.\nOn other devices with the same iOS 10.3 everything is OK. \n\nfunc getPredicate(for serviceId: Int64, startingFrom step: Int) -> NSPredicate {\n let predicate = NSPredicate(format: \"serverID == %i AND step == %i AND type == %@\", \n serviceId, step, \"button\")\n return predicate\n}\n\n\nThis blog post perfectly describes my problem, and I also have the same crashing problem on 32 bit CPU devices.\nAlthough the solutions given in the post helped me to stop crashing, but CoreData always returned nil result when I used it in fetch requests.\n\nIs there any workaround to solve this problem?\n\nDevelopment Tools:\n\n\nXCode version: 11.2.1 \nSwift Language Version: Swift 5\nDevices: iPhone 5 and iPad 4th gen"
] | [
"ios",
"swift",
"nspredicate"
] |
[
"paging techniques for datagridview using in winforms applications",
"I am looking for paging techniques for datagird view used in winforms applications...\n\nFor this i have looked around the google but dint find any options for winforms datagrdiview but i have found the solutions for web apps..\n\nwould any one pls give any idea or any source code for how to implement the paging techniques for datagrid view ...\n\nI am using linq ,for getting the data from database.. I am using linq and mysql as database.. and i am binding the datagrid view using linq to entities....\n\nso if there are any techniques for linq to implement the paging techniques for datagrid view.. will be help ful to me ...\n\nThanks In advance for greatful ideas..."
] | [
"c#",
"winforms",
"linq",
"datagridview"
] |
[
"React Native Making Changes and Updates After Publishing iOS App for TestFlight",
"Finally, I got my app uploaded to Testflight! This is a big stepping stone for me, however, what happens when you need to make a change? Is there a process that you need to do? I built my app again on XCode. Does it automatically update on the users' phones?"
] | [
"ios",
"xcode",
"react-native"
] |
[
"iterating through a list of records in a second (html) page, where the first page orders the results",
"I'm building this site using jsp / servlets on the backend. \n\nThe first page (or \"search\" page) allows one to search for records from a table, and also allows the user to sort the records. The sorting mechanism is quite complicated, and is not just a matter of appending an \"order by\" to an sql query.\n\nThe first page then also fills in the results after the user hit's \"search\". Basically, it's just a list of the items in \"short\" format, where each item also contains a link to display the item in the second page. The sorting mechanism is run in the first page, while the list is being created. The mechanism uses java code to sort, not sql (for reasons I won't get into, but they are definitely needed).\n\nWhen the second page (or \"details\" page) loads, it grabs the id of the record from the url, then displays the details for that record.\n\nProblem is that we now want to put \"back\" / \"next\" type iteration features in the details page, so that the users don't have to return to the search or list page to then navigate to the next item in the list.\n\nI'm looking for some ideas on how to implement this as something tells me I'm missing the obvious here. Basically, the problem is that the details page has no concept of the sorting used in the search page, and so has no idea of what the next or previous record in the list should be. There are a few ideas running around but they all suffer from one problem or the next."
] | [
"iteration"
] |
[
"Save many-to-many in form manually",
"I have a model with 3 tables Many to 1 to many as below\n\n(shortened schema.yml)\n\nPeerEngagement:\n columns:\n id: { type: integer(4), notnull: true, unique: true, primary: true, autoincrement: true }\n peer_id: { type: integer(4), notnull: true }\n\n relations:\n Peer: { local: peer_id, class: Person }\n\nPerson:\n columns:\n id: { type: integer(4), notnull: true, unique: true, primary: true, autoincrement: true }\n nhi: { type: string(7) }\n name: { type: string(100), notnull: true }\n\n relations:\n Ethnicity: { class: Ethnicity, refClass: PersonEthnicity, local: person_id, foreign: ethnicity_id }\n\nPersonEthnicity:\n columns:\n id: { type: integer(4), notnull: true, unique: true, primary: true, autoincrement: true }\n person_id: { type: integer(4), notnull: true }\n ethnicity_id: { type: integer(4), notnull: true }\n relations:\n Person:\n class: Person\n local: person_id\n onDelete: CASCADE\n Ethnicity:\n class: Ethnicity\n local: ethnicity_id\n onDelete: RESTRICT\n\n\nEthnicity:\n columns:\n id: { type: integer(4), notnull: true, unique: true, primary: true, autoincrement: true }\n name: { type: string(50) }\n\n\nSaving these things in auto-generated forms is fine. However in a special case I need to save nhi and ethnicity separately from within PeerEngagementForm.\n\nFor saving nhi i have working:\n\nfunction doSave($con=null){\n\n ...\n\n if(isset($this->values['nhi'])){\n $this->getObject()->getPeer()->setNhi($this->values['nhi']);\n $this->getObject()->getPeer()->save();\n }\n\n ...\n\n\nbut the same technique doesn't work with\n\nif(isset($this->values['ethnicity_list'])){\n\n $this->getObject()->getPeer()->setEthnicity($this->values['ethnicity_list']);\n $this->getObject()->getPeer()->save();\n}\n\n\nThe error message I get is that it expects a Doctrine_Collection.\n\nHow do I create this collection correctly, or how can I save the many to many relationship from within the top form or action?"
] | [
"forms",
"symfony1",
"doctrine",
"save"
] |
[
"How to get a single output from a function with multiple outputs?",
"I have the following simple function:\n\ndef divide(x, y):\n quotient = x/y\n remainder = x % y\n return quotient, remainder \n\nx = divide(22, 7)\n\n\nIf I accesss the variable x I get:\n\nx\nOut[139]: (3, 1)\n\n\nIs there a way to get only the quotient or the remainder?"
] | [
"python",
"function",
"return"
] |
[
"MYSQL - GROUP_CONCAT results of UNION ALL into one row",
"I have the following statement:\n\nSELECT DISTINCT Concat(\"table1.\", column_name) \nFROM information_schema.columns \nWHERE table_name = \"table1\" \nUNION ALL \nSELECT DISTINCT Concat(\"table2.\", column_name) \nFROM information_schema.columns \nWHERE table_name = \"table2\";\n\n\nWhich produces the following results:\n\n+---------------------------------+\n| CONCAT(\"table1.\", column_name) |\n+---------------------------------+\n| table1.column1 |\n| table1.column2 |\n| table1.column3 |\n| table2.column4 |\n| table2.column5 |\n| table2.column6 |\n| table2.column7 |\n+---------------------------------+\n\n\nI would like it to be in the following format:\n\n+-----------------------------------------------------------------------------------------------------------+\n| CONCAT(\"table1.\", column_name) |\n+-----------------------------------------------------------------------------------------------------------+\n| table1.column1,table1.column2,table1.column3,table2.column4,table2.column5,table2.column6,table2.column7 |\n+-----------------------------------------------------------------------------------------------------------+\n\n\nI have tried using GROUP_CONCAT like this:\n\nSELECT Group_Concat(DISTINCT Concat(\"table1.\", column_name)) \nFROM information_schema.columns \nWHERE table_name = \"table1\" \nUNION ALL \nSELECT Group_Concat(DISTINCT Concat(\"table2.\", column_name)) \nFROM information_schema.columns \nWHERE table_name = \"table2\";\n\n\nBut this incorrectly produced the following results:\n\n+--------------------------------------------------------------+\n| CONCAT(\"table1.\", column_name) |\n+--------------------------------------------------------------+\n| table1.column1,table1.column2,table1.column3 |\n| table2.column4,table2.column5,table2.column6,table2.column7 | \n+--------------------------------------------------------------+\n\n\nFrom this I naturally tried to do a GROUP_CONCAT it as a sub query, like so:\n\nSELECT GROUP_Concat(\n SELECT Group_Concat(DISTINCT Concat(\"table1.\", column_name)) \n FROM information_schema.columns \n WHERE table_name = \"table1\" \n UNION ALL \n SELECT Group_Concat(DISTINCT Concat(\"table2.\", column_name)) \n FROM information_schema.columns \n WHERE table_name = \"table2\" t)\nFROM t;\n\n\nBut there is a syntax error in the above statement. How would I concatenate the results of UNION ALL into one row?\n\nI have reviewed the following questions without any success:\n\nCombing results from union all into one row when some columns have different values\n\nHow do I combine two queries (union all) into one row? \n\nMySQL COUNT results of UNION ALL statement\n\nThis is kind of related to my previous question:\nMySQL - Subquery in SELECT clause"
] | [
"mysql",
"group-concat",
"union-all"
] |
[
"What is the TypeScript equivalent of React.PropTypes.node?",
"I have searched high and low, and I can find TypeScript equivalents for everything except React's PropTypes.node. I know that TypeScript doesn't need any PropTypes, but there are some PropTypes that I don't know how to convert to TypeScript.\n\nIs it just as simple as var node: any? This doesn't seem right as node seems to have some properties."
] | [
"reactjs",
"typescript2.0"
] |
[
"How to scale system font in SwiftUI to support Dynamic Type?",
"In UIKit, I can change a UILabel's font size like this to support dynamic type using the system font:\n\nUIFontMetrics.default.scaledFont(for: UIFont.systemFont(ofSize: 16))\n\n\nAm I mistaken or is there no way to do such thing in SwiftUI?\nCan I only use the default font styles .title, etc. if I want to use the system font but also support Dynamic Type?\n\nThis solution from HackingWithSwift seems to only work with custom fonts, right?\n\nThanks in advance for any suggestions!"
] | [
"ios",
"swiftui",
"dynamic-type-feature"
] |
[
"Google Analytics proxy",
"I have a special situation where the sites visitors can access the page from a certain domain but no others. So HTML and assets are no problem as long as they are stored on the server. Google Analytics on the other hand requires a download of analytics.js from Googles servers, which is impossible.\n\nSo I'm looking for a way to proxy this. The webserver itself has internet access and could relay the trafic. To report to Google about my page view, a single pixel GIF is downloaded from Google, described here: https://developers.google.com/analytics/resources/concepts/gaConceptsTrackingOverview\n\nI think it would be kind of easy to get all the parameters in the GIF and use the measurement protocol to report to Google from the server - but the hard bit is to get all this info to the server. To download analytics.js and modify it to go to my own server seems to me as a hack that ain't future proof at all. To just get the current page from the user to the server is not a big deal, but we would like to get the user id, browser version and everything you get with Analytics.\n\nHow would you do it? Do you find a solution for this?"
] | [
"google-analytics",
"proxy",
"measurement-protocol"
] |
[
"deployment package of your Lambda function is too large to enable inline code",
"After creating a AWS Lambda Function using Node JS 6.10 I cannot use the Inline Code Editor.\n\nIt has an error message:\n\n\n deployment package of your Lambda function is too large to enable inline code\n\n\nHow can I add code to the editor?"
] | [
"aws-lambda",
"editor"
] |
[
"Faster way to subset data table instead of a for loop R",
"I have a data table (you'll need the data table package installed) in R generated with X and Y coordinates and random data values from both normal and uniform distributions. The coordinates represent points on a 2000x1600 array and has to be divided into 16 smaller \"sectors\" each 500x400. These sectors need their mean of Normal Distribution values taken, divided by the min^2 of the Uniform Distribution values. I also created two variables x and y using a provided function startstop, that have the coordinates for the 16 sectors and a function that calculates the numbers for each sector. \n\nlibrary(data.table)\nDT <- data.table(X = rep(1:2000, times = 1600), Y = rep(1:1600, each = 2000), Norm =rnorm(1600*2000), Unif = runif(1600*2000))\n\nsectorCalc <- function(x,y,DT) {\n sector <- numeric(length = 16)\n for (i in 1:length(sector)) {\n sect <- DT[X %between% c(x[[1]][i],x[[2]][i]) & Y %between% c(y[[1]][i],y[[2]][i])]\n sector[i] <- sCalc(sect)\n }\n return(sector)\n }\n\nstartstop <- function(width, y = FALSE) {\n startend <- width - (width/4 - 1)\n start <- round(seq(0, startend, length.out = 4))\n stop <- round(seq(width/4, width, length.out = 4))\n if (length(c(start,stop)[anyDuplicated(c(start,stop))]) != 0) {\n dup <- anyDuplicated(c(start,stop))\n stop[which(stop == c(start,stop)[dup])] <- stop[which(stop == c(start,stop)[dup])] - 1\n}\n if (y == TRUE) {\n coord <- list(rep(start, each = 4), rep(stop, each = 4))\n } else if (y == FALSE) {\n coord <- list(rep(start, times = 4), rep(stop, times = 4))\n }\n return(coord)\n}\n\nx <- startstop(2000)\ny <- startstop(1600, T)\n\nsectorNos <- sectorCalc(x,y,DT)\n\n\nThe startstop function isn't really an issue but I need a faster way to subset the data table. Some modifications have to be made to the 'sectorCalc' function. The for loop was the best way I could think of but I don't have too much experience with data tables. Any ideas on a faster method of breaking up the data table?"
] | [
"r",
"for-loop",
"indexing",
"data.table",
"subset"
] |
[
"SQL You can't specify target table",
"all structure tables in sqlfile:\n\nUPDATE MenuPosition \n SET Position = (SELECT Position FROM MenuPosition WHERE MenuId ='2') \nWHERE MenuId ='1'\n\n\nWhen we use query we get error:\n\nYou can't specify target table 'MenuPosition' for update in FROM clause \n\n\nTell me please where my error nd how will be right?"
] | [
"mysql",
"sql"
] |
[
"NSClickGestureRecognizer - how to pass on the click once recognised",
"In my ViewController I have set up a NSGestureRecognizer in order to know when particular TextField is clicked in by the user.\n\nin viewDidLoad() override I have \n\nlet gesture = NSGestureRecognizer()\ngesture.buttonMask = 0x1\ngesture.numberOfClicksRequired = 1\ngesture.target = self\ngesture.action = #selector(ViewController.textOutputClicked)\ntextOutput.addGestureRecognizer(gesture)\n\n\nthen later in my ViewController I have\n\n@objc func textOutputClicked(sender: NSGestureRecognizer){\n print(\"textOutput was clicked\")\n}\n\n\nThis all works and when I click in the textOutput field, I get the message \"textOutput was clicked\", however the processing of the click stops. What I want to do, and I'm not sure of the right way to describe it, is to continue passing the click onto the control to process. So for example the insert point is set in the control - right now this is ignored \n\nThanks\nGS"
] | [
"swift",
"macos",
"user-interface",
"mouseevent",
"gestures"
] |
[
"NHibernate 2nd lvl cache, custom query, sqldialect",
"I got trunk version of NH and FNH. When i try to add 2nd level cache, some parts of NHibernate forgets about chosen sqldialect.\n\n\n\nInitial configuration:\n\nvar cfg = Fluently.Configure()\n .Database(MsSqlConfiguration.MsSql2008\n .ConnectionString(connectionString)\n .DefaultSchema(\"dbo\")\n .UseReflectionOptimizer() \n .Mappings(m => ................);\n\n\nGuilty custom query:\n\nvar sql = @\"with Foo(col1,col2,col3)\n as (select bla bla bla...)\n Select bla bla bla from Foo\";\n\nlist = Session.CreateSQLQuery(sql)\n .AddEntity(\"fizz\", typeof(Fizz))\n .SomethingUnimportant();\n\n\nWhen i change configuration to:\n\nvar cfg = Fluently.Configure()\n .Database(MsSqlConfiguration.MsSql2008\n .ConnectionString(connectionString)\n .DefaultSchema(\"dbo\")\n .UseReflectionOptimizer()\n .Cache(c=>c\n .UseQueryCache()\n .ProviderClass<HashtableCacheProvider>())\n .ShowSql())\n .Mappings(m => ................);\n\n\nQuery throws error (WITH clause was added in mssql2008):\n\n\n The query should start with 'SELECT' or 'SELECT DISTINCT'\n \n [NotSupportedException: The query should start with 'SELECT' or 'SELECT DISTINCT']\n NHibernate.Dialect.MsSql2000Dialect.GetAfterSelectInsertPoint(SqlString sql) +179\n NHibernate.Dialect.MsSql2000Dialect.GetLimitString(SqlString querySqlString, Int32 offset, Int32 limit) +119\n NHibernate.Dialect.MsSql2005Dialect.GetLimitString(SqlString querySqlString, Int32 offset, Int32 last) +127\n NHibernate.Loader.Loader.PrepareQueryCommand(QueryParameters queryParameters, Boolean scroll, ISessionImplementor session) +725\n NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +352\n NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +114\n NHibernate.Loader.Loader.DoList(ISessionImplementor session, QueryParameters queryParameters) +205\n\n\n\n\nAny ideas what exactly confuses nhibernate and how to fix it?\n\n\n\nGuilty NHibernate code (in NHibernate/Dialect/MsSql200Dialect.cs): \n\nprivate static int GetAfterSelectInsertPoint(SqlString sql)\n{\n if (sql.StartsWithCaseInsensitive(\"select distinct\"))\n {\n return 15;\n }\n else if (sql.StartsWithCaseInsensitive(\"select\"))\n {\n return 6;\n }\n throw new NotSupportedException\n (\"The query should start with 'SELECT' or 'SELECT DISTINCT'\");\n }\n}\n\n\nLooks that .SetMaxResults(123) causes this. Fortunately, i can unbound that query. \n\nHopefully that will fix this."
] | [
"nhibernate",
"second-level-cache"
] |
[
"How to make a multi-join query in MySQL?",
"I'm new to SQL, and find I don't quite understand which joins to use when. Sub-queries also seem confusing. I have the following tables set up, and I'm trying to get a specific outcome:\n\n`+--------------------------+ +---------------+ +---------------+ +---------------+`\n`| Table_A | | Table_B | | Table_C | | Table_D |`\n`+--------------------------+ +---------------+ +---------------+ +---------------+`\n`| id | f2 | f3 | f4 | d_id | | a_id | c_id | | id | fc | | id | fs |`\n`+--------------------------+ +---------------+ +---------------+ +---------------+`\n\n\nAnd this is what I'm trying to get:\n\n`+----------------------------------+`\n`| a.f2 | a.f3 | a.f4 | d.fs | c.fc |`\n`+----------------------------------+`\n\n\nI've found that I can get the first four columns with the following query:\n\nSelect t1.f2, t1.f3, t1.f4, t2.fs\n From Table_A AS t1 INNER JOIN Table_D AS t2\n ON t1.d_id = t2.id;\n\n\nHow can I get from A.id to C.fc? I can't figure out how to get the fifth column, let alone in conjunction with the previous query. This is about as far as I got with the final column: \n\nSelect t1.flow_control\n FROM Table_D AS t1 INNER JOIN policy t2\n ON t1.id = t2.c_id;"
] | [
"mysql",
"join"
] |
[
"Write all items from list to a character vector from GET httr request",
"I am trying to extract data from a GET request and parse it as below:\n\n# Function to get details from all experiments\ngetData<- function()\n{\n server_url <- \"http://127.0.0.1:5000/experiments\"\n r <- GET(url = server_url, verbose())\n return(r)\n}\n\n# Get all experiments\nx <- getData()\n\n# Retrieve content and parse for processing\ny <- content(x, \"parsed\")\n\n\nThe output is as follows i.e. a single list containing all 17 experiments.\n\n> y\n$experiments\n$experiments[[1]]\n$experiments[[1]]$end\nNULL\n\n$experiments[[1]]$id\n[1] 1\n\n$experiments[[1]]$name\n[1] \"reprehenderit\"\n\n$experiments[[1]]$start\n[1] \"Mon, 30 Mar 2015 17:29:13 GMT\"\n\n\n$experiments[[2]]\n$experiments[[2]]$end\nNULL\n\n$experiments[[2]]$id\n[1] 2\n\n$experiments[[2]]$name\n[1] \"explicabo\"\n\n$experiments[[2]]$start\n[1] \"Mon, 30 Mar 2015 17:29:44 GMT\"\n\n.......\n\n$experiments[[17]]\n$experiments[[17]]$end\nNULL\n\n$experiments[[17]]$id\n[1] 17\n\n$experiments[[17]]$name\n[1] \"dsagfsdzg\"\n\n$experiments[[17]]$start\n[1] \"Wed, 01 Apr 2015 01:45:01 GMT\"\n\n\nI want to extract 17 \"name\" elements from this list of elements into a single character vector (have done it manually for the first 2 elements).\n\nz <- c(unlist(y[[1]][1])[\"name\"], unlist(y[[1]][2])[\"name\"])\nz\n\n name name \n\"reprehenderit\" \"explicabo\" \n\n\nCould anyone help me automate the above? Is there a simple way to extract this from the GET request?"
] | [
"r",
"httr"
] |
[
"Many to Many wherehas",
"I want to search a post that has a similar tag only with tags id number\n\nI've tried this\n\n$tags = Tag::find($id);\n$post = Post::whereHas('tags', function($q) use ($id){\n$q->where('id',$id);})->paginate(5);\n\n return view('tagdetail', compact('tags', 'post'));\n\n\nbut the output is SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (23000).\n\nI've already search through the internet and still cant.\n\nTag.php\n\npublic function post()\n {\n return $this->belongsToMany('App\\Post');\n }\n\n\nPost.php\n\npublic function tags()\n {\n return $this->belongsToMany('App\\Tag');\n }\n\n\ncontroller\n\npublic function detailTag($id)\n {\n //i know this will get all the post with the tag id, but i want to paginate it too. \n $tags = Tag::find($id);\n\n $post = Post::whereHas('tags', function($q) use ($id){\n $q->where('id',$id);\n})->paginate(5);\n\n return view('tagdetail', compact('tags', 'post'));\n }\n\n\nThe expected result: to show all post that has a similar tag with paginating.\n\nActual result : SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (23000)"
] | [
"laravel",
"laravel-5.8"
] |
[
"How to get data page by page and sort column",
"How to create a SP, using which I can get result page vise. I want to pass pageSize, pageNo, sortCol and direction into SP and want result based on this info. Can I handle this in SP's logic?\n\nTable1 { First, Last, Location }\n\nSP_GetAll(pageNo=3, pageSize=10, sortCol=\"First\", direction=\"ASC\")\n\n\nAny new feature provided by SQL Server 2008 for this?"
] | [
"sql-server"
] |
[
"FXML template or a way to generate placeholders in javafx",
"I am making a GUI in Java where I am getting the data I need through SPARQL-queries. The program is about exercises, and I would like to make a container (hbox/vbox) for each exercise with relevant information. The problem is that right now, the program looks really ugly, because I am generating the hbox with pure javafx with the code below: \n\nResultSet result = Querying.ontologyQuery(Strings.getFeatured());\n List<Resource> exerciseList = new ArrayList<>();\n List<Resource> mainMuscleList = new ArrayList<>();\n List<Literal> equipmentList = new ArrayList<>();\n while (result.hasNext()) {\n QuerySolution qs = result.next();\n Resource exercise = qs.getResource(\"Exercise\");\n Resource mainMuscle = qs.getResource(\"mainMuscle\");\n Literal equipment = qs.getLiteral(\"Equipment\");\n exerciseList.add(exercise);\n mainMuscleList.add(mainMuscle);\n equipmentList.add(equipment);\n }\n\n for (int i = 0; i < 4; i++) {\n HBox hbox = addHbox();\n vbox.getChildren().add(hbox);\n Label exercise = new Label();\n Label mainMuscle = new Label();\n Label equipment = new Label();\n\n mainMuscle.setText(mainMuscleList.get(i).getLocalName());\n equipment.setText(equipmentList.get(i).getString());\n exercise.setText(exerciseList.get(i).getLocalName());\n\n hbox.getChildren().add(exercise);\n hbox.getChildren().add(mainMuscle);\n hbox.getChildren().add(equipment);\n\n\nI guess what I am asking, is it if it's possible to make a template sort of in fxml, and just deploy the information from the SPARQL-queries into the placeholders in the \"template\". Any help is appriciated on how to go about this"
] | [
"java",
"user-interface",
"javafx",
"fxml"
] |
[
"Session variable 'unsetted' automatically + with a bit of code",
"Why the session isnt saved? After reload the session variable 'mucciusersess' disapears! Why? Thanks...\n\nI have an cookie on client-side with value like 'mucciuserid' set to '122341212'\n\nsession_start();\n\n$userid = $_SESSION['usersess'];\n// if session var not already exists --> get from cookie and set\nif(!isset($userid)) {\n\n $usercokie = $_COOKIE['userid'];\n echo $usercokie.' < > '.$userid;\n $_SESSION['usersess'] = $usercokie;\n $userid = $_SESSION['usersess'];\n echo '-'.$userid; \n}"
] | [
"javascript",
"php",
"session",
"cookies",
"session-variables"
] |
[
"npm request conditional piping based on response",
"I need to download a file by POSTing to a REST server.\n\nI was first using http when it was get. But now i need to use POST, and node's http post is way too complicated, I dont want to build a low level request, so I dont want to use it.\n\nI am now using request. https://www.npmjs.com/package/request\n\nNow, my server either sends {isUpdateAvailable:false} or it sends a tar file.\n\nSo i need to save the file, or show 'Already up to date'. How do I pipe to a filestream by checking the response header?\n\nI need to set the pipe along with the request code, so I'm not able to separate the code properly. I need to fs.createWriteStream only if its necessary. Will it be possible?\n\nSo, how do i do it?"
] | [
"node.js",
"npm-request"
] |
[
"jQuery Resize Not Working Consistently",
"Running into an issue where my function works as expected when width of window is larger than 1024px, works as expected when I resize lesser than 1024px, but when I scale back up it doesn't work.\n\nWhat am I trying to achieve, to run a scrollTop function but only when the browser is lesser than 1024px width. I just can't seem to see the mistake I've made.\n\nHere's my Codepen and JS code:\nCodepen\n\nfunction buttonClick() {\n var width = $(window).innerWidth(); \n console.log( width );\n\n if ( width < 960 ) {\n $('.click').on('click', function() { \n $('body').animate({ scrollTop: $('.div2').offset().top - 10 }, 300);\n });\n } \n}\n\n\n$(function() { buttonClick(); })\n$(window).on('resize',function() {\n buttonClick();\n});"
] | [
"jquery"
] |
[
"plotting multiple lines in ggplot R",
"I have neuroscientific data where we count synapses/cells in the cochlea and quantify these per frequency. We do this for animals of different ages. What I thus ideally want is the frequencies (5,10,20,30,40) in the x-axis and the amount of synapses/cells plotted on the y-axis (usually a numerical value from 10 - 20). The graph then will contain 5 lines of the different ages (6 weeks, 17 weeks, 43 weeks, 69 weeks and 96 weeks).\nI try this with ggplot and first just want to plot one age. When I use the following command:\nggplot(mydata, aes(x=Frequency, y=puncta6)) + geom_line()\n\nI get a graph, but no line and the following error: 'geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?'\nSo I found I have to adjust the code to:\nggplot(mydata, aes(x=Frequency, y=puncta6, group = 1)) + geom_line()\n\nThis works, except for the fact that my first data point (5 kHz) is now plotted behind my last data point (40 kHz)......... (This also happens without the 'group = 1' addition). How do I solve this or is there an easier way to plot this kind of data?\nI couldnt add a file so I added a photo of my code + graph with the 5 kHz data point oddly located and I added a photo of my data in excel.\nexample data\n\nexample code and graph"
] | [
"r",
"ggplot2",
"graph"
] |
[
"set different background colors to partials based on database value",
"Trying to make different colors for different partials based on their type; so far there are 3 types all defined by an integer 1, 2 or 3 and I am struggling to find a way to make the partials in the view appear with different background colors. I am trying to get Red for 1, Blue for 2, Green for 3. I have tried multiple things but none have seemed to work. \n\nI've tried making before_action :set_colours, having if statements in the partial but nothing has worked so far.\n\nHere is the html, calling the type would be done like o.type\n\n<div class=\"dropdown\" style=\"background-color: <%= set_background(number) %>;\">\n <button class=\"btn btn-block\" type=\"button\" id=\"dropdownMenuButton\"\n data-toggle=\"dropdown\" aria-haspopup=\"true\" aria-expanded=\"false\"> <%=o.id%>, <%=o.user_id%> \n </button>\n <div class=\"dropdown-menu btn-block\" aria-labelledby=\"dropdownMenuButton\">\n <li><a class=\"dropdown-item\">Order Type</a></li>\n <li><a class=\"dropdown-item\"> Event type:</a> <p><%=o.event_type%></p></li>\n <li><a class=\"dropdown-item\"> Requirements/Ideas</a> <p><%=o.description%></p></li>\n </div>\n</div>"
] | [
"html",
"css",
"ruby-on-rails"
] |
[
"Manipulating Variables in HTML-Embedded Ruby",
"I'm using embedded Ruby in HTML and am trying to create a new variable; however, this seems to be modifying the HTML formatting over the code even though I am just trying to create a new variable and modify it. It seems like when I manipulate newfood, I am also changing the value stored in \"food\" (almost in a pass-by-reference way). How can I pass it by value (if possible)? \n\n<% newfood = food%>\n\n<% newfood.gsub!('a','b')%>"
] | [
"html",
"ruby",
"embedding"
] |
[
"C# iText long paragraph in table cell overlap",
"I an using IText version 7 on C#. I'm adding a system.data.DataTable to a iText.Layout.Element.Table.\nMy challenge was when the Paragraph in the cell was long, the 2nd line of the Paragraph was "overlap" with the first line.\nI have try to set the Paragraph height to 12. But it still fail. May I know how to fix this?\n\npublic void AddByTable(DataTable dbResult)\n {\n float[] columnWidths = { 25, 3, 3, 3 };\n Table table = new Table(UnitValue.CreatePercentArray(columnWidths)).UseAllAvailableWidth();\n //add header\n table.AddCell(_AddNewParagraph("Desc", padding: 1)) ;\n table.AddCell(_AddNewParagraph("DO", padding: 1));\n table.AddCell(_AddNewParagraph("Rec", padding: 1));\n table.AddCell(_AddNewParagraph("Var", padding: 1));\n\n table.SetKeepWithNext(true);\n var strItemDesc="";\n foreach (DataRow row in dbResult.Rows)\n {\n strItemDesc = row["vch_desc"].ToString();\n //table.AddCell(_AddNewParagraph(strItemDesc, padding: 1,fontSize:6));\n //table.AddCell(\n // new Paragraph(strItemDesc)\n // .SetFixedLeading(2.0f)\n // .SetFont(_font)\n // .SetFontSize(6)\n // .SetPadding(1)\n // );\n\n Cell c= new Cell();\n c.Add(\n new Paragraph(strItemDesc)\n .SetFixedLeading(2.0f)\n .SetFont(_font)\n .SetFontSize(6)\n .SetPadding(1)\n .SetHeight(12) //this height did no solve the overflow problem.\n );\n table.AddCell(c) ;\n\n table.AddCell(_AddNewParagraph(row["DOQty"].ToString(), padding: 1, fontSize: 6));\n table.AddCell(_AddNewParagraph(row["RcvQty"].ToString(), padding: 1, fontSize: 6));\n table.AddCell(_AddNewParagraph(row["VAR"].ToString(), padding: 1, fontSize: 6));\n }\n\n _doc.Add(table);\n }"
] | [
"c#",
"itext7"
] |
[
"How to get iTunes app description?",
"How do I obtain the iTunes Store app description from within my iPhone app? I need it to make a \"help\" screen in my app.\n\nI don't know if this is possible, but I know there are special link to make the user go to reviews of apps and so maybe it's also possibile to get the app description?"
] | [
"iphone",
"objective-c",
"ios",
"itunes"
] |
[
"Rails: CanCan, models",
"I installed devise, cancan and rolify.\n\nUsers who are logged in, created Citys.\n\nI want cancan to show only the Citys from each User.\n\nTherefor:\n\nI dont understand the relationship between User and City? There is no foreign key.\n\nI found this:\nhttps://github.com/ryanb/cancan/wiki/defining-abilities\n\ncan :read, City, :active => true, :user_id => user.id"
] | [
"cancan"
] |
[
"SQL - How to create a new relation between tables A & C based on an existing relationship between A & B - en mass?",
"I have the following tables in a MySQL 5.x database:\n\nUsers:\n id\n county_id\n state_id\n\nCounties:\n id\n state_id\n\nStates:\n id\n\n\nStates is a new table, each County belongs to one State, each user up until now has belonged to a single County - I want to be able to directly associate a user with a State and then delete the Counties table.\n\nI can find out which state a user belongs to be referencing user-> county-> state & can re-associate individual users with something like the following pseudo-SQL:\n\nUPDATE users\n SET state_id = (SELECT id FROM state WHERE state_id=(SELECT state_id FROM counties WHERE id=users.county_id) )\nWHERE user_id=324235;\n\n\nbut not sure how to do this for all 320k+ users in my database.\n\nAny ideas?"
] | [
"mysql",
"sql"
] |
[
"How not to change the id of variable when it is substituted",
"I don't want to change the id of variable. How can I do this?\n\n def _increaseParam(param):\n print id(param) # -> 140503442059208\n pitch = 50\n param += pitch\n print id(param) # -> 140503442058968\n # different!"
] | [
"python"
] |
[
"Set Pixel colour in an array",
"I have an array of pixels stored in a vector as follows:\n\ntypedef union RGBA\n{\n std::uint32_t Colour;\n struct\n {\n std::uint8_t R, G, B, A;\n };\n} *PRGB;\n\nstd::vector<RGBA> Pixels; //My pixels are read into this vector.\n\n\nI process it using the following two functions. One is for reading, the other is for writing.\nThe read function takes an array of bytes and flips them and stores them into the struct above. It takes padding into consideration so it works for both 24 and 32 bit bitmaps. The write function flips it back and writes it to an array of bytes.\n\nvoid ReadPixels(const std::uint8_t* In, RGBA* Out)\n{\n for (std::size_t I = 0; I < height; ++I)\n {\n for (std::size_t J = 0; J < width; ++J)\n {\n Out[(height - 1 - I) * width + J].B = *(In++);\n Out[(height - 1 - I) * width + J].G = *(In++);\n Out[(height - 1 - I) * width + J].R = *(In++);\n Out[(height - 1 - I) * width + J].A = (BitsPerPixel > 24 ? * (In++) : 0xFF);\n }\n if(BitsPerPixel == 24)\n In += (-width * 3) & 3;\n }\n}\n\nvoid WritePixels(const RGBA* In, std::uint8_t* Out)\n{\n for (std::size_t I = 0; I < height; ++I)\n {\n for (std::size_t J = 0; J < width; ++J)\n {\n *(Out++) = In[(height - 1 - I) * width + J].B;\n *(Out++) = In[(height - 1 - I) * width + J].G;\n *(Out++) = In[(height - 1 - I) * width + J].R;\n\n if (BitsPerPixel > 24)\n *(Out++) = In[(height - 1 - I) * width + J].A;\n }\n if(BitsPerPixel == 24)\n Out += (-width * 3) & 3;\n }\n}\n\n\nThe thing is, if I want to change just one pixel in the array, I have to flip and copy the whole image into the vector, change the pixel using:\n\ninline void SetPixel(int X, int Y, std::uint32_t Color)\n{\n Pixels[Y * width + X].Colour = Color;\n}\n\n\nAnd then flip it back into the array. Is there a better way to change a single pixel in the array without having to do this every single time?\n\nI tried this formula (so that padding is taken into consideration):\n\nByteArray[((height - 1 - Y) * width + X) + (Y * ((-width * 3) & 3))] = Color;\n\n\nBut it doesn't work. Any ideas?"
] | [
"c++",
"image-processing",
"pixels"
] |
[
"Dynamically generated drop downs",
"I am trying to generate dynamically inputs with angular and angular material. Whenever the user clicks on the Add button a new dropdown needs to be generated. Right now I got the following error :\n\n\n 'Error: [$parse:syntax] Syntax Error: Token '{' invalid key at column 2 of the expression [{{choiceTest.Name}}] starting at [{choiceTest.Name}}].'\n\n\nHow do I need to modify my code to work properly?\n\n<div ng-repeat=\"choiceTest in $ctrl.inputsFilterRowsTest\">\n <md-input-container flex=\"30\">\n <label>Filter Type</label>\n <md-select ng-model={{choiceTest.Name}} name=\"\">\n <md-option ng-repeat=\"filter in $ctrl.filters\" value=\"{{filter.value}}\">\n {{filter.value}}\n </md-option>\n </md-select>\n </md-input-container>\n</div>\n<md-button class=\"md-raised\" ng-click=\"$ctrl.addFilterTest()\">ADD</md-button>\n\n\nController\n\nself.inputsFilterRowsTest = [];\n\nself.filters = [\n { value: 'Filter1' },\n { value: 'Filter2' },\n { value: 'Filter3' }\n];\n\nself.addFilterTest = function () {\n var newItemTestNo = self.inputsFilterRowsTest.length + 1;\n self.inputsFilterRowsTest.push({ 'value': 'inputFilter' + newItemTestNo, 'name': 'inputFilter' + newItemTestNo });\n};"
] | [
"javascript",
"angularjs"
] |
[
"Get the name of a variable in a string",
"Hi I want to create a function in which I can pass a variable and output the name of the variable and its value as a sting. Something like this:\n\n$firstname = 'John';\n$lastname = 'Doe';\n\necho my_function($firstname); // outputs: \"Var name: firstname , has: John\"\necho my_function($lastname); // outputs: \"Var name: lastname , has: Doe\""
] | [
"php",
"function",
"variables"
] |
[
"NodeJS crypto.createHmac SHA256 not working properly",
"I'm currently trying to implement the authentication part of a library we're using but I've stumbled upon a weird issue with the signing of the data, the output of crypto.createHmac in NodeJS is roughly half the size of that of hash_hmac in PHP and this is the only part of the data which differs between PHP and NodeJS (and we need to use NodeJS here)\n\nThe exact code used for creating the signature in NodeJS is,\n\nauthorization[\"oauth_signature\"] = crypto.createHmac('SHA256', process.env.SECRET).update(toSign).digest('base64');\n\n\nAnd for PHP it is\n\n$authorization[\"oauth_signature\"] = base64_encode(hash_hmac(\"SHA256\", $signatureString . $signingKey, $secret));\n\n\nHowever the output of the NodeJS version is\n\n7LkQP+qKR1gSdPq/AgH/3No3ps7EtZXnqwjivMixvM8=\n\n\nAnd for PHP it is\n\nNmQ0MWIzYmJiMjI2YzFlMDhiYzY3NzVmMWY0MzEwNDlhNDU3NDI0ZGJlMzU3NjJhYmMwYjgwYzZjMDE4NDM4OA==\n\n\nWhich has more then double the data\n\nDo I have to use a different library for the NodeJS version rather then the build in one? We're hosting our NodeJS backend on Microsoft Azure btw, not sure if this is related but seems at least valid to mention.\n\nEdit:\n\nI've found the issue, hash_hmac in PHP automatically exports it's data as hexidecimal data, crypto.createHmac exports it's data as raw binary data which I directly converted into base64, all I needed to do was first export the data to hex and then convert that to base64."
] | [
"php",
"node.js",
"azure",
"sha256",
"hmac"
] |
[
"How can I perform click on input using xpath",
"I have used the below code to click the element.But it failed to locate the element and shows element not visible.\n\nelem3=driver.find_element_by_xpath(\".//*[@id='check-box']\")\nelem3.click()\n\n\nThe html code:\n\n<span id=\"Some-span\" class=\"urCWhl\" title=\"Indicator\">\n<input id=\"check-box\" class=\"urC\" type=\"checkbox\" hidefocus=\"hidefocus\" ti=\"-1\" tabindex=\"-1\" ct=\"C\"/>\n<span id=\"label-lbl\" class=\"name_class\" style=\"width:100%;box-sizing:border-box;\" unselectable=\"on\" f=\"some-id\" ti=\"0\" tabindex=\"0\" title=\"Indicator\"></span>"
] | [
"python",
"selenium"
] |
[
"Using with RIA and WCF without RIA, which one is suggested?",
"what is the advantages/disadvantages of using RIA against WCF without RIA?"
] | [
"c#",
"silverlight",
"wcf-ria-services"
] |
[
"Can't create a Hive Table from an avro file",
"I can create a table atop an avro file using the following syntax without any errors. It is an empty table at firs. \n\nCREATE EXTERNAL TABLE tableName \nPARTITIONED BY (ingestiondatetime BIGINT, recordtype STRING)\nROW FORMAT SERDE\n'org.apache.hadoop.hive.serd2.avro.AvroSerDe'\nSTORED AS INPUTFORMAT\n'org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat'\nOUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat'\nTABLEPROPERTIES ('avro.schema.url'='hdfs:///user/file.avsc');\n\n\nWhen I add the LOCATION line to point to the actual avro file loctaion, I get a permission error\n\nCREATE EXTERNAL TABLE tableName \nPARTITIONED BY (ingestiondatetime BIGINT, recordtype STRING)\nROW FORMAT SERDE\n'org.apache.hadoop.hive.serd2.avro.AvroSerDe'\nSTORED AS INPUTFORMAT\n'org.apache.hadoop.hive.ql.io.avro.AvroContainerInputFormat'\nOUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.avro.AvroContainerOutputFormat'\nLOCATION '/local/avro_dir/'\nTABLEPROPERTIES ('avro.schema.url'='hdfs:///user/file.avsc');\n\n\nThe error is\n\n> FAILED: Error in metadata..... \n> org.apache.hadoop.security.AccessControlException: Permission denied: \n> user=hive, access=WRITE, inode=\"/\" hdfs:supergroup:drwxr-xr-x\n\n\nI am running hive as me. My permissions on hdfs:/ are wide open (777). Where is hive trying to write to that it thinks it does not have permission?"
] | [
"hive",
"create-table",
"avro"
] |
[
"Object of class WP_Error could not be converted to string",
"I create a subdomain in Wordpress MU and then when I go to that subdomain, I get this error:\n\nCatchable fatal error: Object of class WP_Error could not be converted \nto string in /home/pahouse1/public_html/wp-content/mu-plugins/lifetime\n/syncronize.php on line 450**\n\n\nDid anyone face the same issue? What can I do about this?"
] | [
"php",
"wordpress"
] |
[
"Stop numbers going into Scientific notation",
"I have doubles that are very big and keep going into Scientific notation (e.g. 3.12002769e+27) when outputted. How can I stop this as I'm writing to a file and can't have this."
] | [
"c++",
"scientific-notation"
] |
[
"Import dmp file to Oracle",
"my customer has provided a dmp file (10 GO), and i tried the following:\nCreate a user:\ncreate user USERNAME identified by PASSWORD;\nGrant read write access\nImport the dump file(using imp and impdp)\nimpdp or imp system/password@db dumpfile=EXPDAT.DMP FULL=Y logfile=dice.log\nand here's the error message:\nImport: Release 18.0.0.0.0 - Production on Tue Feb 23 11:46:07 2021\nVersion 18.4.0.0.0\nCopyright (c) 1982, 2019, Oracle and/or its affiliates. All rights reserved.\nConnected to: Oracle Database 18c Express Edition Release 18.0.0.0.0 - Production\nORA-39002: invalid operation\nORA-39059: dump file set is incomplete\nORA-39246: cannot locate master table within provided dump files\nCan anyone help on that?"
] | [
"oracle",
"dmp"
] |
[
"Dynamodb: Placeholders for Attribute Names and Values",
"i read the following link that explains to use placeholders by means of expression attribute name\n\nhttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ExpressionPlaceholders.html#ExpressionAttributeValues\n\nMy json document is stored as follows: \n\n{\"user_json\": {\"profile.title\":\"abc\"} }\"\n\n\nmy java code is as follows\n\n Map<String, String> expressionAttributeNames = new HashMap<String, String>();\n expressionAttributeNames.put(\"#u1\", \"user_json.profile.title\");\n\n String projectionExpression = \"user_id, #u1\";\n QuerySpec spec = new QuerySpec()\n .withProjectionExpression(projectionExpression)\n .withKeyConditionExpression(\"user_id = :v_id\")\n .withNameMap(expressionAttributeNames)\n .withValueMap(new ValueMap()\n .withString(\":v_id\", userId))\n .withConsistentRead(true);\n\n ItemCollection<QueryOutcome> items = table.query(spec);\n Iterator<Item> iterator = items.iterator();\n String jsonPretty=\"\";\n while (iterator.hasNext()) {\n jsonPretty = iterator.next().toJSON();\n System.out.println(jsonPretty);\n } \n\n\nProblem: not able to retrieve Document path which has a dot in it.\n\ncan someone please point out the problem? thanks"
] | [
"java",
"database",
"amazon-web-services",
"amazon-dynamodb",
"nosql"
] |
[
"Plot margin of pdf plot device: y-axis label falling outside graphics window",
"I tried simply plotting some data in R with the y-axis label horizontal and left of the y-axis tick labels. I thought the code below would work:\n\nset.seed(1)\nn.obs <- 390\nvol.min <- .20/sqrt(252 * 390)\neps <- rnorm(n = n.obs, sd = vol.min)\nmar.default <- c(5,4,4,2) + 0.1\npar(mar = mar.default + c(0, 4, 0, 0)) # add space to LHS of plot\npdf(\"~/myplot.pdf\", width=5.05, height=3.8)\nplot(eps, main = \"Hello World!\", las=1, ylab=\"\") # suppress the y-axis label\nmtext(text=\"eps\", side=2, line=4, las=1) # add horiz y-axis label\n # 4 lines into the margin\n\n\n\n\nInstead, as you may see, the y-axis label almost fell completely outside of the graphics window. This phenomenon still exists no matter how much I expand the LHS margin. \n\nQ: What am I doing wrong? Is there something I need to do with the oma parameter? What do I need to do to plot things the way I'm intending? I'm a little overwhelmed by all of this!"
] | [
"r",
"plot"
] |
[
"Using Service worker how do we chain subsequent requests for a fetch call followed after an update data call?",
"Is there any way we can chain request for sync and next subsequent fetch request where we call an update and subsequent fetch call? Currently I am seeing the fetch call 'jsonGetMyData' is getting called and give me back old data, but if I pause this call in debugger for a sec, it give me updated data. So it seems service worker update is not happening before fetch call, if that's the case how can we control it so that service worker update will happen first then only fetch will be called?\nPlease advise.\nBelow is calling part.\n if ('serviceWorker' in navigator && 'SyncManager' in window) {\n navigator.serviceWorker.ready\n .then(function(sw) {\n writeData('myStore', dataObject)\n .then(function() {\n return sw.sync.register('case0-sync');\n })\n .then(function(){\n debugger;\n this.jsonGetMyData(this.get("dataId"));\n })\n .catch(function(err) {\n console.log(err);\n }); \n });\n}\n\nBelow is sample service worker code .\n self.addEventListener("sync", function(event) {\n console.log("Background Syncing started...");\n\n if(event.tag === 'case0-sync'){\n //my update post call goes here\n\n }else if(event.tag === 'case1-sync'){\n \n }else if(event.tag === 'case2-sync'){\n \n }else if(event.tag === 'case3-sync'){\n \n }else if(event.tag === 'case4-sync'){\n \n }\n});\n\nself.addEventListener('fetch', function (event) {\n if (event.request.url.indexOf('jsonGetMyData') > -1\n event.respondWith(\n fetch(event.request).then(function(resp){\n return resp;\n }).catch(function(err){\n })\n );\n }\n});"
] | [
"javascript",
"service-worker",
"service-worker-events"
] |
[
"Convert between imaginary temperature units and output fraction",
"I'm currently working on some java code that converts temperatures between temperature units and outputs the new temperature as a reduced fraction.\nThe way it works is that it first takes in the units systems equivalent to 0 degrees C and 100 degrees C (freezing and boiling).\n32 212 //Unit 1\n88 7 //Unit 2\n\nOne important thing is that all these unit systems are related to the Celsius unit in a linear fashion.\nIt then takes inputs a, b and c, which means, convert c degrees in unit a into degrees in unit b.\n1 2 212\n\nShould turn 212 degrees in the first unit above into temperature in the second unit which is 7 in this case.\nThen I have to convert this new temperature into a fraction. In my example the new temperature is 7 so I return 7/1\nWhat I have done is firstly to convert the temperature from unit1 into equivalent in Celsius.\nThen I convert the Celsius degrees into unit2.\nAnd finally converting this double into a fraction.\nMy problem is however that it fails in some test cases and I suspect that it fails when converting the double to a fraction. Does anybody know if my method for doing this is flawed?\nAny help is greatly appreciated. I'm not looking from someone to fix my code, but rather something to point me in the right direction. I wan't to be able to solve it myself.\nHere's what I've got going so far:\npublic class Temperature {\n\n\n public static double[][] temps;\n\n public static void main(String[] args) {\n Kattio io = new Kattio(System.in, System.out);\n\n int N = io.getInt();\n int Q = io.getInt();\n\n // temps[unit][0] is freezing\n // temps[unit][1] is boiling\n // temps[unit][2] is for converting from\n // temps[unit][3] is for converting to\n temps = new double[N+1][4];\n\n\n for(int i = 0; i < N; i++) {\n double t1 = io.getInt();\n double t2 = io.getInt();\n temps[i+1][0] = t1;\n temps[i+1][1] = t2;\n\n temps[i+1][2] = (t2-t1)/100;\n temps[i+1][3] = 100/(t2-t1);\n }\n\n for(int i = 0; i < Q; i++) {\n // from is unit we are converting from\n int from = io.getInt();\n\n // to is unit converting to\n int to = io.getInt();\n\n // t is temperature in unit "from"\n double t = io.getInt();\n\n // get converted as double -> later converted to fraction\n double converted = solve(from, to, t);\n\n \n String ans = getFraction(converted);\n \n \n System.out.println(ans);\n \n }\n }\n \n // Get the new temperature as a double\n public static double solve(int from, int to, double t) {\n\n\n // Convert to celsius first\n double a = temps[from][3];\n\n // Take temperatur and subtract freezing point temp before \n // multiplying with rate\n double celsius = (t - temps[from][0]) * a;\n\n\n // Convert the celsius to desired unit\n double b = temps[to][2];\n\n // Multiply temp with rate before adding freezing temp value\n double degrees = (b * celsius) + temps[to][0];\n\n // Return double of degrees in new unit\n return degrees; \n \n }\n\n //Turn double into fraction\n public static String getFraction(double x){\n\n // If we have a negative number\n if (x < 0){\n return "-" + getFraction(-x);\n }\n\n double tolerance = 1.0E-6;\n\n double h1=1; \n double h2=0;\n double k1=0; \n double k2=1;\n\n double b = x;\n do {\n double a = Math.floor(b);\n double aux = h1; \n h1 = a*h1+h2; \n h2 = aux;\n aux = k1; \n k1 = a*k1+k2; \n k2 = aux;\n b = 1/(b-a);\n } while (Math.abs(x-h1/k1) > x*tolerance);\n \n return (int)h1+"/"+(int)k1;\n }\n}"
] | [
"java",
"double",
"fractions",
"units-of-measurement",
"temperature"
] |
[
"Bash , listing files according to the file names with numbers and strings",
"I am trying to sort the files based on their files names\nfirst sort based on number, then sort based on the letters it has. \nthe numbers are the age, so the adult will be the last. \nif the same numbers are used, sort based on rep1,rep2, and rep 3\n\nthe original files are ls like this \n\nabc.0.5\nabc.1.2\nabc.15.3\nabc.2.3\nabc.35.5dpp\nabc.35.5dpp.rep2\nabc.7.3\nabc.adult\nabc.adult.rep2\nabc.adult.rep3\n\n\nthe result should be \n\nabc.0.5\nabc.1.2\nabc.2.3\nabc.7.3\nabc.15.3\nabc.35.5dpp\nabc.35.5dpp.rep2\nabc.adult\nabc.adult.rep2\nabc.adult.rep3\n\n\nI have tried \n\nls -v a*| sed 's/\\.adult\\./.99./' | sort -V | sed 's/\\.99\\./.adult./'\n\n\nBut it won't order correctly if there is dpp or rep after the numbers and adult."
] | [
"linux",
"bash"
] |
[
"Is there a B-Tree Database or framework in Python?",
"I heard that B-Tree databases are faster than Hash tables, so I thought of using a B-Tree database for my project. Is there any existing framework in python which allows us to use such Data structure or will I have to code from scratch?"
] | [
"python",
"b-tree"
] |
[
"Regular Expression, find expression in string.",
"I am trying to figure out what the regular expression would be for me to find the following within a massive string, and extract the value that's inside the value field - the value will always be a mixture of both numbers and letters. The length of the value will vary and I want to ignore case.\n\n<input type=\"text\" name=\"NAME_ID\" value=\"id2654580\" maxlength=\"25\">\n\n\nSo in the above example, I would get 'id2654580' as the value, if that control/text was located within my massive string."
] | [
"c#",
".net",
"regex"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.