texts
sequence | tags
sequence |
---|---|
[
"Incorrect Base URL for Application",
"I have an ASP.net MVC app, built using the ASPnet Module Zero framework. For some reason all of the page URLs seem to be prefixed with /Account/Login, even when I'm already logged in. For example, the login page's URL is:\n\nlocalhost:62114/Account/Login/Account/Login\n\n\nOnce logged in, the one application page is\n\nlocalhost:62114/Account/Login/App/ListAllAccount\n\n\nTrying to access any page without the /Account/Login in the URL, automatically causes an Error 404. appsettings.json looks like this:\n\n\"App\": {\n \"WebSiteRootAddress\": \"http://localhost:62114/\",\n \"CorsOrigins\": \"http://localhost:62114\"\n},\n\n\nThe route configuration looks as follows:\n\n routes.MapRoute(\n name: \"default\",\n template: \"{controller=Home}/{action=Index}/{id?}\");\n\n routes.MapRoute(\n name: \"defaultWithArea\",\n template: \"{area}/{controller=Home}/{action=Index}/{id?}\");\n\n\nAll of the services and resources also use the correct URLs, which means that you actually cannot log in, as you cannot access the service URLs.\n\nEDIT: One thing that I noticed now is that it is only when I debug the application locally. Once published, the issue seems to go away."
] | [
"c#",
"asp.net",
"model-view-controller",
"aspnetboilerplate"
] |
[
"Cant connect from python client to meteor server using python-ddp",
"I am trying to connect meteor server using python-ddp package \nhttps://github.com/hharnisc/python-ddp\n\nWhen i run the py file,just nothing happens and programme terminates.Server is running port and everything is correct.\n\n from DDPClient import DDPClient\n\nclient = DDPClient('ws://127.0.0.1:3000/websocket')\nclient.connect()\ndef connected():\n print(\"connected\")\n\nclient.on('connected', connected)\n\n\nI guess python-ddp package is outdated and thats why its not working ? Is there anyone who is using this package to communicate with meteor server ?\n\nDo you guys recommend any other package/way to communicate with meteor using python client ? \n\nthanks"
] | [
"python",
"meteor",
"ddp"
] |
[
"How to implement min left/right in css",
"I have an element in my css which look like below\n\n.xyz{\n position:absolute;\n left:50%;\n }\n\n\nNow as expected when I reduce the width of browser window, this element moves towards left. However I want it to stop at a certain point since otherwise it starts overlapping other elements. In principle, this is very similar to min-height and and min-width properties. But there is no such property like min-left or min-top. How can I implement this."
] | [
"html",
"css"
] |
[
"Search for substring matches in a file bash",
"The premise is to store a database file of colon separated values representing items.\n\nvar1:var2:var3:var4\n\n\nI need to sort through this file and extract the lines where any of the values match a search string.\nFor example\n\nSearch for \"Help\"\nHey:There:You:Friends\nI:Kinda:Need:Help (this line would be extracted)\n\n\nI'm using a function to pass in the search string, and then passing the found lines to another function to format the output. However I can't seem to be able to get the format right when passing. Here is sample code i've tried of different ways that I've found on this site, but they don't seem to be working for me\n\n#Option 1, it doesn't ever find matches\nfunction retrieveMatch {\n if [ -n \"$1\" ]; then\n while read line; do\n if [[ *\"$1\"* =~ \"$line\" ]]; then\n formatPrint \"$line\"\n fi\n done\n fi\n}\n\n#Option 2, it gets all the matches, but then passes the value in a\n#format different than a file? At least it seems to...\nfunction retrieveMatch {\n if [ -n \"$1\" ]; then\n formatPrint `cat database.txt | grep \"$1\"`\n fi\n}\n\nfunction formatPrint {\n list=\"database.txt\" #default file for printing all info\n if [ -n \"$1\" ]; then\n list=\"$1\"\n fi\n IFS=':'\n while read var1 var2 var3 var4; do\n echo \"$var1\"\n echo \"$var2\"\n echo \"$var3\"\n echo \"$var4\"\n done < \"$list\"\n}\n\n\nI can't seem to get the first one to find any matches\nThe second options gets the right values, but when I try to formatPrint, it throws an error saying that the list of values passed in are not a directory."
] | [
"regex",
"bash"
] |
[
"how to tap into PostgreSQL DDL parser?",
"The DDL / SQL scripts used to create my PostgreSQL database are under version control. In theory, any change to the database model is tracked in the source code repository. \n\nIn practice however, it happens that the structure of a live database is altered 'on the fly' and if any client scripts fail to insert / select / etc. data, I am put in charge of fixing the problem.\n\nIt would help me enormously if I could run a quick test to verify the database still corresponds to the creation scripts in the repo, i.e. is still the 'official' version.\n\nI started using pgTAP for that purpose and so far, it works great. However, whenever a controlled, approved change is done to the DB, the test scripts need changing, too.\n\nTherefore, I considered creating the test scripts automatically. One general approach could be to\n\n\nrun the scripts to create the DB\naccess DB metadata on the server\nuse that metadata to generate test code\n\n\nI would prefer though not having to create the DB, but instead read the DB creation scripts directly. I tried to google a way to tap into the DDL parser and get some kind of metadata representation I could use, but so far, I have learned a lot about PostgreSQL internals, but couldn't really find a solution to the issue.\n\nCan someone think of a way to have a PostgreSQL DDL script parsed ?"
] | [
"database",
"postgresql",
"metadata",
"ddl"
] |
[
"Save realm result in a variable and write in realm without changing the variable",
"I am saving realm result in a variable in the hope to use it for different purpose. After i update it in Realm the variable in which i stored the original result also gets updated. I want to keep the variable in which I get original realm results unaltered.\n\nBelow i save the variable \n\ncomponentDidMount(){\nthis.showFromRealm();\nthis.oldOpts = Array.from(Realm.objects('Device')[0].ns);\n\n\n}\n\nThis is how i update in realm \n\n if(device){\n Realm.write(() => {\n device.ns.forEach((ns)=>{\n if(ns.idx == selectedType){\n ns.opt.forEach((opt)=>{\n if(opt.idx == selectedOpt.idx) opt.val = !selectedOpt.val;\n });\n }\n });\n });\n}\n\n\nThis is how i re-write the variable in realm.\n\n Realm.write(() => {\n device.ns = this.oldOpts;\n });\n\n\nAny insight would be helpful.\nI want to write the original result again in realm so as to make it appear as initial."
] | [
"javascript",
"android",
"react-native",
"realm"
] |
[
"clearing console in cpp",
"system(\"cls\") doesnt work, it finishes the program without printing anything. \nthe program works without it but doesnt look nice in the console without all the previous prints cleared. I've tried putting the command in different places but it doesnt matter where i put it the program finishes instantly.\n\n#include <iostream>\n#include <math.h>\n#include <windows.h>\n#include <stdlib.h>\n\nusing namespace std;\n\nfloat c, temp, eq;\nchar odp = 't';\n\nint main()\n{\n do\n {\n cout << \"Choose from what value you'd like to convert.\" << endl;\n cout << \"Celsius = 1 ; Fahrenheit = 0\" << endl;\n cin >> c;\n\n if (c==1)\n {\n cout << \"Insert Celsius value: \";\n cin >> temp;\n\n eq = temp * 1.8 + 32;\n cout << \"It is \" << eq << \" degrees Fahrenheit.\" << endl;\n cout << \"If you want to continue converting please insert: t\" << endl;\n cin >> odp;\n }\n else if (c==0)\n {\n cout << \"Insert Fahrenheit value: \";\n cin >> temp;\n\n eq = (temp * 1.8) - 32;\n cout << \"It is \" << eq << \" degrees Celsius.\" << endl;\n cout << \"If you want to continue converting please insert: t\" << endl;\n cin >> odp;\n }\n else\n {\n cout << \"Please choose correctly\" << endl;\n }\n }\n while(odp = 't');\n\nreturn 0;\n}\n\n\n\nhow i put the command and it finishes the whole program instantly \n\n#include <iostream>\n#include <math.h>\n#include <windows.h>\n#include <stdlib.h>\n\nusing namespace std;\n\nfloat c, temp, eq;\nchar odp = 't';\n\nint main()\n{\n do\n {\n cout << \"Choose from what value you'd like to convert.\" << endl;\n cout << \"Celsius = 1 ; Fahrenheit = 0\" << endl;\n cin >> c;\n\n if (c==1)\n { system(\"cls\") //here\n cout << \"Insert Celsius value: \";\n cin >> temp;\n\n eq = temp * 1.8 + 32;\n cout << \"It is \" << eq << \" degrees Fahrenheit.\" << endl;\n cout << \"If you want to continue converting please insert: t\" << endl;\n cin >> odp;\n }\n else if (c==0)\n {\n cout << \"Insert Fahrenheit value: \";\n cin >> temp;\n\n eq = (temp * 1.8) - 32;\n cout << \"It is \" << eq << \" degrees Celsius.\" << endl;\n cout << \"If you want to continue converting please insert: t\" << endl;\n cin >> odp;\n }\n else\n {\n cout << \"Please choose correctly\" << endl;\n }\n }\n while(odp = 't');\n\nreturn 0;\n}\n\n\ni really dont know, thanks for the replies"
] | [
"c++",
"console"
] |
[
"VBA Create table for each filter data in another sheet",
"I need to make a table for each unique value of a column. I used autofilter to select each filter to then copy and paste to another sheet. Due to the amount of data (large) i would like to automate and maybe do a for each cycle where each filter is select individually and copied to a differente sheet. It´s this even possible? Does anyone knows how to maybe simplify this problem ?"
] | [
"excel",
"vba"
] |
[
"Placing JavaScript ad tag on different location in page",
"I have a page, that calls \"first.js\" script. This script ads to a call to \"second.js\" script:\n\nfirst.js:\n\nvar head= document.getElementsByTagName('head')[0];\nvar script= document.createElement('script');\nscript.type= 'text/javascript';\nscript.src= 'second.js';\ndocument.getElementsByTagName(\"head\")[0].appendChild(script)\n\n\nnow, if I put in second.js alert(\"test\"), I will see a good alert.\nHowever, if I put in second.js document.write(\"something\"), I will not get that document.write.\n\nAny idea why?"
] | [
"javascript",
"document.write"
] |
[
"hibernate doesn't create middle tables with hbm2ddl.auto set to \"update\"",
"I was under the impression that when hbm2ddl.auto is set to \"update\",hibernate(version 3.6) would scan the entity annotations and update database references and create new tables,it has been working fine until today,\nthere are two beans:role and menu,I have defined a unidirectional ManyToMany association for them\n\n@Id\n@GenericGenerator(name=\"uuidGenerator\", strategy=\"uuid\")\n@GeneratedValue(generator=\"uuidGenerator\")\nprivate String roleId;\n@Column\nprivate String roleName;\n@ManyToMany(cascade=CascadeType.REMOVE)\n@JoinTable( name=\"roleMenu\",\n joinColumns=\n @JoinColumn(name=\"roleId\"),\n inverseJoinColumns=\n @JoinColumn(name=\"menuid\")\n )\nprivate Set<Menu> Menus;\n\n\nI already have table ROLE and table MENU in the database so I'm expecting hibernate to create the middle table ROLEMENU for me,but it will only try to update the foreign key references in ROLEMENU which results in error cause ROLEMENU doesn't exist yet, but it works fine if I set hbm2ddl.auto to \"create\", so could someone explain why hibernate doesn't create ROLEMENU before?"
] | [
"java",
"spring",
"hibernate"
] |
[
"Divide form submissions evenly between two email addresses",
"I did search Stack Overflow to the best of my ability to make sure this has not been answered and I could not find anything.\n\nI have a form on which you can select your nearest town, but in one specific town I have two branches.\n\nLets say... Cape Town has two branches across the street of each other... \n([email protected] and [email protected])\n\nWhat I want to achieve is that If 10 people select cape town the emails should be send as follows:\n\ncpt1\ncpt2\ncpt1\ncpt2\ncpt1\ncpt2\ncpt1\ncpt2\ncpt1\ncpt2\n\n\nDoes this make sense?\n\nI basically want 1 locations mail to be split between two branches, 1 for you, 1 for you, etc etc.\n\nI was thinking of putting them in an array and then use a random number between 1 and 2 to select the mail from the array, but I want to know what would be best here as I actually have no clue.\n\nMy current code is as follow: \n\nHTML:\n\n<fieldset>\n\n<!-- Form Name -->\n<legend>Contact Us</legend>\n\n<!-- Name input-->\n<div class=\"form-group\">\n <label class=\"col-md-4 control-label\" for=\"name\">Name</label> \n <div class=\"col-md-4\">\n <input id=\"name\" name=\"name\" type=\"text\" placeholder=\"Enter Name Here\" class=\"form-control input-md\">\n\n </div>\n</div>\n\n<!-- E-mail input-->\n<div class=\"form-group\">\n <label class=\"col-md-4 control-label\" for=\"email\">E-mail</label> \n <div class=\"col-md-4\">\n <input id=\"email\" name=\"email\" type=\"text\" placeholder=\"Enter E-mail Here\" class=\"form-control input-md\">\n\n </div>\n</div>\n\n<!-- Select Town -->\n<div class=\"form-group\">\n <label class=\"col-md-4 control-label\" for=\"town\">Town</label>\n <div class=\"col-md-4\">\n <select id=\"town\" name=\"town\" class=\"form-control\">\n <option value=\"Cape Town\">Cape Town</option>\n <option value=\"Bellville\">Bellville</option>\n <option value=\"Pretoria\">Pretoria</option>\n <option value=\"Johannesburg\">Johannesburg</option>\n </select>\n </div>\n</div>\n\n<!-- Message -->\n<div class=\"form-group\">\n <label class=\"col-md-4 control-label\" for=\"message\">Message</label>\n <div class=\"col-md-4\"> \n <textarea class=\"form-control\" id=\"message\" name=\"message\" placeholder=\"Enter Message Here\"></textarea>\n </div>\n</div>\n\n</fieldset>\n\n\nPHP:\n\n$town = $_POST['town'];\nswitch ($town) {\n case 'capetown':\n $email_address = '[email protected]';\n break;\n case 'bellville':\n $email_address = '[email protected]';\n break;\n case 'pretoria':\n $email_address = '[email protected]';\n break;\n default:\n $email_address = '[email protected]';\n}\nmail($email_address, etc etc etc )"
] | [
"php",
"html",
"forms",
"email"
] |
[
"Merging a general wordpress search with a woocommerce product search?",
"I am using the following two codes to generate a wordpress search and a woo commerce product search? Is there a code to merge theme into one search bar doing both functions?\n\n <?php get_search_form(); ?>\n <?php get_product_search_form(); ?>"
] | [
"php",
"wordpress",
"woocommerce"
] |
[
"Group mysql query by months or weeks with proper start/endings",
"I have searched and viewed a lot of answers on SO but even trying to apply all I found I get incorrect results.\n\nI am trying to group my mysql results by week mon-sun, and by month from day 1 to last day of month\n\nI have tried different types of grouping like:\n\nGROUP BY YEARWEEK(data)\nGROUP BY WEEK(data)\n\n\nfor weeks and\n\nGROUP BY MONTH(data)\n\n\nfor months\n\nall these grouping methods return uncorrect groupings. some results start in random days of the month or the week.\n\nthis is example query which get results from last month entries divided by week although the week grouping is not resulting in weeks from mon-sun.\n\nSELECT *, count(id) AS count FROM leadz WHERE YEAR(data) = YEAR(CURRENT_DATE - INTERVAL 1 MONTH) AND MONTH(data) = MONTH(CURRENT_DATE - INTERVAL 1 MONTH) GROUP BY YEARWEEK(data)\n\n\nthese are the week segments I get as results:\n\n 2016-07-01 2016-07-04 2016-07-16 2016-07-17 2016-07-25 2016-07-31\n\n\nNext is a sample query of total entries grouped by month, again gropuing does not start from 1st of the month\n\nSELECT *, count(id) AS count FROM leadz GROUP BY MONTH(data)\n\n\nthese are the month segments I get as result:\n\n2016-04-18 2016-05-25 2016-06-01 2016-07-25 2016-08-02\n\n\nAny help appreciated"
] | [
"mysql",
"group-by"
] |
[
"How to limit results with same field value to X amount of documents every time it shows up multiple times in a row",
"I have an issue that I am not quite sure how to solve. Really hope someone here can help me figure out how to go about it.\n\nImagine that I have 100 documents, all with user_id fields. I know that most documents are from different user_ids, but documents 1-10 and 20-29 are from the same user_id.\n\nWhat I want to do, is make sure that I only see the the latest two documents whenever a the same user_id is returned in a row more than twice. So if user_id 1 shows up more than twice in a row, I want to limit those documents. I want this to happen every time it happens for that user_id, not limit it completely after that.\n\n\n\nIf I just request all documents as they are indexed now, I would get a result like: \n\n[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, ...]\n\n\n\nWhat I am loooking for, us a way to make sure these groups of 1s, are limited to two documents in a row, like so: \n\n[1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 1, 12, ...] \n\nNotice that 1, 1, ..., 1, 1, ... happens here, meaning that the rows of identical user ids have been cut down to two, instead of removing them all together, which would result in something like:\n\n[1, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ...] \n\n\n\nI also want this to work if the request is paginated (Multiple queries). \n\nSo imagine that I request the first two pages, with a size of 5, then I would like to get:\n\nPage1: [1, 1, 2, 3, 4]\n\nPage2: [5, 6, 7, 8, 9]\n\nInstead of:\n\nPage1: [1, 1, 2, 3, 4]\n\nPage2: [1, 1, 1, 1, 1]\n\n\n\nI hope that I have described the issue well enough for someone to understand. If not, then please let me know so I can try explaining it another way."
] | [
"elasticsearch",
"search",
"lucene",
"kibana"
] |
[
"How to create a button to go back to the top of the page?",
"I created a button with a link to go back to the top of the page.\n\nHere is the JS code :\n\n(function ($) {\n\n/*--Scroll Back to Top Button Show--*/\n\n$(window).scroll(function(){\n if ($(this).scrollTop() > 100) {\n $('#back-to-top').fadeIn();\n } else {\n $('#back-to-top').fadeOut();\n }\n});\n\n//Click event scroll to top button jquery\n\n$('#back-to-top').click(function(){\n $('html, body').animate({scrollTop : 0},600);\n return false;\n});\n\n})(jQuery);\n\n\nHere is the HTML code:\n\n<a id=\"back-to-top\" href=\"#\">\n <i class=\"fas fa-chevron-circle-up fa-4x\"></i>\n</a>\n\n\nIt works very well, but I want to create a button instead of a link.\n\nI tested the following HTML code but it does not work. There is the button but it does not go back up the page :\n\n<button type=\"button\" id=\"back-to-top\" href=\"#\">\n <i class=\"fas fa-chevron-circle-up fa-4x\"></i>\n</button>\n\n\nHow to create a button to go back to the top of the page ?"
] | [
"javascript",
"jquery",
"css",
"button",
"scroll"
] |
[
"Angular 2 CLI - AoT Compilation - Unable to use HTML5 form validators",
"I'm attempting to build an Angular 2 project, using angular-cli with the --prod and --aot arguments. The build is failing with the following error:\nProperty 'required' does not exist on type '{ [key: string]: any; }'.\nIn my HTML, I'm using HTML5 validators on some of my inputs (required, pattern).\nUsing JiT compilation, these work as expected. It is only during AoT compilation that the errors occur.\nHas anyone seen this before? I was hoping not to have to resort to defining all of my forms using the ReactiveForms method and using the Angular Validators, unless there's no way around it."
] | [
"angular",
"command-line-interface",
"angular2-aot",
"html5-validation"
] |
[
"Get value from numberpicker and putting it in a textview",
"// i need to get newVal out of all these numberpickers methods separately , and i set them in to textviews , but when try to get value from the text view app crash.can you help me . how can i get numberpicker value outside it's onValuechange method?\n\n public class MainActivity extends AppCompatActivity {\n\n\n\n\nImageButton start,pause,reset;\nTextView total,mintimer,sectimer,textView6,textView7,textView8;\n\n\n\n@Override\nprotected void onCreate(Bundle savedInstanceState) {\n\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n start=(ImageButton)findViewById(R.id.start);\n pause=(ImageButton)findViewById(R.id.pause);\n reset=(ImageButton)findViewById(R.id.reset);\n\n total=(TextView)findViewById(R.id.total);\n mintimer=(TextView)findViewById(R.id.mintimer);\n sectimer=(TextView)findViewById(R.id.sectimer);\n\n //this is how i tried to get textview value as a string. then the app \n crashes\n String a=textView6.getText().toString();\n\n NumberPicker min = (NumberPicker) findViewById(R.id.min);\n NumberPicker sec = (NumberPicker) findViewById(R.id.sec);\n NumberPicker brk = (NumberPicker) findViewById(R.id.brk);\n\n\n min.setMinValue(1);\n min.setMaxValue(20);\n min.setWrapSelectorWheel(true);\n min.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {\n @Override\n public void onValueChange(NumberPicker picker, int oldVal, int newVal) { \n textView6=(TextView)findViewById(R.id.textView6);\n textView6.setText(\" \"+newVal);\n\n }\n });\n\n //beep sound breake\n sec.setMaxValue(60);\n sec.setMinValue(0);\n sec.setWrapSelectorWheel(true);\n sec.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {\n\n @Override\n public void onValueChange(NumberPicker picker, int oldVa2, int newVal2) {\n textView7=(TextView)findViewById(R.id.textView7);\n textView7.setText(\" \"+newVal2);\n }\n });\n //Break\n\n brk.setMaxValue(5);\n brk.setMaxValue(60);\n brk.setWrapSelectorWheel(true);\n brk.setOnValueChangedListener(new NumberPicker.OnValueChangeListener(){\n @Override\n public void onValueChange(NumberPicker picker ,int oldVal3,int newVal3){\n textView8=(TextView)findViewById(R.id.textView8);\n\n textView8.setText(\" \"+newVal3);\n\n\n }\n\n });\n\n\n}\n\n\n}"
] | [
"android",
"textview",
"android-number-picker"
] |
[
"asp.net mvc3, knockout.js form submit to server",
"I have a view displaying a list of users populating from a ViewModel.\n\n function MyUser(data) {\n this.Id = ko.observable(data.Id);\n this.phone = ko.observable(data.Phone);\n this.Company = ko.observable(data.Company);\n this.SelectedGrowerID = ko.observable(data.SelectedGrowerID);\n\n this.setSelectedClass = function (item, event) {\n $('#hfGrowerID').val(event.target.id);\n\n this.SelectedGrowerID = event.target.id;\n };\n }\n\n function UserListViewModel() {\n // Data\n var self = this;\n self.users = ko.observableArray([]);\n\n // Load initial state from server, convert it to MyUser instances, then populate self.users\n $.getJSON(\"UserList/GetAllUsers\", function (allData) {\n var mappedUsers = $.map(allData, function (item) { return new MyUser(item) });\n self.users(mappedUsers);\n });\n\n\nI have a simple form with list items bound to the Company of each user. Additionally, I have a hidden field into which I save the id of the user when each listitem is clicked.\n\n <form action=\"UserList/Save\" method=\"post\">\n <ul id=\"UserList\" data-bind=\"foreach: users\" data-role=\"listview\">\n <li data-bind=\"click: setSelectedClass\"><a data-bind=\"attr: {id: Id}\">\n <span data-bind=\"text: Company\" /></a></li>\n </ul>\n\n <input id=\"hfGrowerID\" type=\"hidden\" />\n <input type=\"hidden\" name=\"users\" data-bind=\"value: ko.toJSON(users)\" />\n\n <button type=\"submit\">Save</button>\n </form>\n\n\nIn my UserListController, I want to get the value of the hidden field 'hfGrowerID'. The Save function looks like this:\n\n <HttpPost()>\n Public Function Save(<FromJson()> users As IEnumerable(Of MyUserModel),\n hfGrowerID As String) As ActionResult\n 'do stuff\n Return View (\"Index\", users)\n End Function\n\n\nNow, the problem is, hfGrowerID does not have any value and doing Request.Form(\"hfGrowerID\") returns nothing as well. I verified that hfGrowerID is getting a value after clicking a list item by doing alert and console.log.\n\nHow do I get the value of the hidden field that is not part of my ViewModel?\n\nThanks a lot in advance for any help."
] | [
"asp.net-mvc-3",
"jquery-mobile",
"knockout.js"
] |
[
"Nuclide + Atom failed to find symbol with ctags",
"So I've installed Facebook's Nuclide on top of my Atom editor.\nSeems it provides many features.\nMy problem is that when I setup a remote project folder, I cannot get find symbol functioning any more. \n\nThe alt+cmd+g will through errors instead of generating ctags file in the project folder.\nI ssh to the server and manually ctags -R . in the folder.\nHowever, inside Atom/Nuclide, cmd+shift+r complains no tags file... \n\nPlease help. Any clues welcome."
] | [
"atom-editor",
"remote-server",
"ctags",
"nuclide-editor"
] |
[
"Ext , Grid , scrolling after edit cell with RTL",
"I have a RTL webpage with a Ext.Net c# Grid control. I allow scrolling for the grid.\nThis all works fine. After I change value of a cell in RTL \"Ext grid\" , scroll bar lose correct size."
] | [
"jquery",
"grid",
"scrollbar",
"right-to-left",
"ext.net"
] |
[
"Rails routing: putting matches for routing in a function to reduce complexity",
"I have a rails application that does some upfront scoping to handle multiple subdomains and multiple languages but results in having two sets of inner matches that are identical. I would like to break these inner matches out to a function so that I can reduce and reuse code I cannot find any examples of someone doing this in the routes. \n\nCode: \n\nconstraints lambda { |request| request.subdomains[0].include? \"internal\" } do\n scope \":hash\" do \n get '/', to: 'product#index'\n get '/:productID', to: 'product#show'\n end\n get \"\", to: 'product#no_hash'\n get \"/*path\", to: 'product#no_hash'\nend\n\nconstraints lambda { |request| !request.subdomains[0].include? \"internal\" } do\n scope \":hash\" do \n get '/', to: 'product#index'\n get '/:productID', to: 'product#show'\n end\nend\n\n\nAgain the goal is to get the inner matches placed into a function so that I can reduce duplication, reuse code, and save the world. Please help."
] | [
"ruby-on-rails",
"lambda",
"routing",
"rails-routing"
] |
[
"Unknown file appear while trying to load image data set and convert it into array",
"I'm trying to load a data set of images and convert it into array for further processing, but it keeps give me an error with a file that doesn't exist in my data set. I'm using PyCharm on Windows 10.\n\nThis is the error:\n\n\n [INFO] Loading images ...\n \n [INFO] Processing 00416648-be6e-4bd4-bc8d-82f43f8a7240___GCREC_Bact.Sp\n 3110.JPG ...\n \n Error : [WinError 267] The directory name is invalid:\n 'C:\\Users\\vipek\\Desktop\\PlantVillage\\Tomato_Bacterial_spot\\00416648-be6e-4bd4-bc8d-82f43f8a7240___GCREC_Bact.Sp\n 3110.JPG'\n\n\nThe image is not in my data set. \n\nfrom typing import List\n\nimport numpy as np\nimport pickle\nimport cv2\nfrom os import listdir\nfrom sklearn.preprocessing import LabelBinarizer\nfrom keras.models import Sequential\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.convolutional import MaxPooling2D\nfrom keras.layers.core import Activation, Flatten, Dropout, Dense\nfrom keras import backend as k\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.optimizers import Adam\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import img_to_array\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\n\nEPOCHS = 25\nINIT_LR = 1e-3\nBS = 32\ndefault_image_size = tuple((256, 256))\nimage_size = 0\ndirectory_root = Path(\"C:/Users/vipek/Desktop/PlantVillage\")\nwidth = 256\nheight = 56\ndepth = 3\n\n\ndef convert_image_to_array(image_dir):\n try:\n images = cv2.imread(image_dir)\n if images is not None:\n images = cv2.resize(images, default_image_size)\n return img_to_array(images)\n else:\n return np.array([])\n except Exception as E:\n print(f\"Error : {E}\")\n return None\n\n\nimage_list, label_list = [], []\ntry:\n print(\"[INFO] Loading images ...\")\n root_dir: List[str] = listdir(directory_root)\n\n for plant_folder in root_dir:\n plant_disease_folder_list = listdir(directory_root / plant_folder)\n\n for plant_disease_folder in plant_disease_folder_list:\n print(f\"[INFO] Processing {plant_disease_folder} ...\")\n plant_disease_image_list = listdir(directory_root / plant_folder / plant_disease_folder)\n\n for image in plant_disease_image_list[:200]:\n image_directory = f\"{directory_root}/{plant_folder}/{plant_disease_folder}/{image}\"\n if image_directory.endswith(\".jpg\"):\n label_list.append(plant_disease_folder)\n print(\"[INFO] Image loading completed\")\nexcept Exception as e:\n print(f\"Error : {e}\")"
] | [
"python",
"image",
"keras",
"directory",
"dataset"
] |
[
"Strange dialog with GooglePlayServicesUtil",
"I'm checking avalibility of google play services on device. I do it with these code:\n\nfinal int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);\nif (resultCode != ConnectionResult.SUCCESS) {\n final DialogInterface.OnCancelListener cancelListener = new DialogInterface.OnCancelListener() {\n @Override\n public void onCancel(final DialogInterface dialog) {\n finish();\n }\n };\n final Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(\n resultCode, this, GOOGLE_PLAY_SERVICES_REQUEST_CODE, cancelListener\n );\n errorDialog.show();\n}\n\n\nI get resultCode = 2 (it's mean that Google Play Services needs to update). Dialog is shown, but instead of text, I get paths to layout.\n\n\n\nIt's looks like there are some interference of resource in app and resource in PlaYServices lib. But how it's possible and how to avoid id?"
] | [
"android"
] |
[
"WebClient not reporting 0Kb file",
"i'm writing an application that downloading .xml files from our server, and retreive some data from them.\n\nThe file are data from parts we are using in my Department.\n\nSome of files are 0Kb, meaning we don't have data from this part.\n\nNow my problem is that the Webclient DownloadFileCompleted event is not firing when finishing downloading the 0Kb file.\n\nHere's my code:\n\n private void Get_Tool_Model()\n {\n if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())\n {\n download_Tool_Model = true;\n using (WebClient wc = new WebClient())\n {\n wc.UseDefaultCredentials = true;\n wc.DownloadProgressChanged += (o, e) =>\n {\n double bytesIn = double.Parse(e.BytesReceived.ToString());\n double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());\n double percentage = bytesIn / totalBytes * 100;\n Dispatcher.Invoke(() => {\n txt_progress.Text = \"Downloaded \" + e.BytesReceived + \" of \" + e.TotalBytesToReceive;\n progress.Value = e.ProgressPercentage;\n });\n };\n wc.DownloadFileCompleted += new AsyncCompletedEventHandler(Wc_DownloadFileCompleted);\n wc.DownloadFileAsync(\n // Param1 = Link of file\n new System.Uri(path),\n // Param2 = Path to save\n \"C:\\\\Tool_Model.xml\"\n );\n }\n }\n }\n\n private void Wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)\n {\n download_completed = true;\n }\n\n\nThank you for your help."
] | [
"c#",
"wpf"
] |
[
"How to restart server remotely and be sure that it's up",
"I have a simple code with restart server remotely. I'm using the Invoke Command to execute the script block on one server from another one. Question is how to restart this server and be sure that after the restart it's up?\n\nI know that invoke command opens the session, but after restart it will be closed. How to bypass this issue?\n\nCode\n\n try {\n $RestartResult = Invoke-Command -ComputerName $AppServer -ScriptBlock \n {\n Write-EventLog –LogName Application –Source \"Powershell restart script\" –EntryType Information –Message \"Server restart initiated\"\n Restart-Computer -Wait -For WMI -ea Stop -Delay 30\n }\n }\n catch { \n # Get the exception message.\n $RestartResult = $_.Exception.Message \n }\n\n if ($error) {\n Write-Log ERROR -Message $RestartResult\n }\n else {\n Write-Log INFO -Message 'Host $AppServer has been restarted'\n }"
] | [
"windows",
"powershell",
"server",
"powershell-3.0"
] |
[
"Send data to controller using Ajax - MVC 3 razor",
"I have a set of PartialView that are dynamicaly changed in a page. A PartialView loads the next and so on using ajax. One of them have a form of like 20 inputs, currently I'm just sending one input but how can I send the rest of them? I have this in this partialview:\n\nvar shipping= $(\"input[name='shipping']:checked\").val()\n $.ajax(\n {\n url: '/Home/Payment',\n type: \"POST\",\n data: { 'shipping': shipping},\n success: function (data) {\n $(\"#cart\").html(data);\n\n }\n });\n\n\nAnd this in the controller:\n\npublic ActionResult Payment(string shipping)\n {\n **do stuff*\n return PartialView(\"NextPartialView\");\n }\n\n\nThe controller recieves every input of the form but as I said before there are 20 of them. Is there a way to keep the code clean and readable using another technique to send the data?\n\nI'm new in MVC and razor\n\nThanks"
] | [
"ajax",
"asp.net-mvc-3",
"razor"
] |
[
"Using the Ends With jquery selector and get the options of a listbox",
"I have the following code:\n\n$(\"input[id$=UserField_hiddenSpanData],input[title=Title]\").each(function(){\n\n var rb = $('#ctl00_m_g_c6ae303a_6013_4adb_8057_63a214bcfd24_ctl00_ctl04_ctl07_ctl00_ctl00_ctl04_ctl00_ctl00_SelectResult option').length;\n var val = $(this).val();\n if(val != 0 && val.length != 0 && rb != 0) { \n\n //add one to the counter\n controlsPassed += 1;\n }\n\n });\n\n\nIt works fine but I don't want to have the ID hardcoded so I thought I could use\n\nvar rb = $('id$=SelectResult option').length;\n\n\nbut it doesn't work, what's wrong with my syntax?\n\nThanks in advance."
] | [
"jquery"
] |
[
"Can I annotate on a OneToMany relationship for performance?",
"I have the following simplified models.\n\nclass Service(models.Model):\n ...\n\nclass ServiceLogs(models.Model):\n service = models.ForeignKey(Service, related_name='logs', ...)\n who_did = models.ForeignKey(User, ...)\n role_played = models.CharField(choices=(('CA','CA'),\n ('CO', 'CO'),\n ('TO', 'TO')), ...)\n\n\nI know I can find out who played what role by calling \n<service obj>.logs.filter(role='CA'), but this approach hits the database 3 times per object given I have 3 roles.\n\nI was reading the documentation about aggretation and annotation, but all the examples use numeric values like Sum, Avg, etc. I tried using Q for lookups, but Django complains with the message 'WhereNode' object has no attribute 'output_field'\n\nCan I make this query more efficient so I hit the database once per object?"
] | [
"django",
"performance",
"django-aggregation"
] |
[
"Replace page document.getElementById(ID Name); with count up timer",
"I have a script that reloads a page once in a while randomly between a time set, and i want to add a timer since the page loaded.\n\nA timer like HH(24):MM(60):SS(60), so i know exactly how many minutes/seconds have elapsed since the page reload.\n\nPreferably i want to replace a ElementById with the timer, duckduckgo as an example, replacing the logo with a visible timer on the page:\n\n// ==UserScript==\n// @name Timer Duck\n// @namespace Timer Duck\n// @description Simple counter\n// @include https://duckduckgo.com/\n// @version 1.0.0\n// @grant none\n// ==/UserScript==\n\n\n$(document).ready(function() { \n\n//Replace 'logo-wrap--home' with a visible counter formated '24(hours):60(minutes):60(seconds)'\n\n});\n\n\nI just don't know how to actually show it on the page."
] | [
"javascript",
"jquery",
"timer",
"counter",
"greasemonkey"
] |
[
"Splitting row data into columns in Pandas",
"I have a dataframe as per the below.\n\nID Party Votes\n\nRS-24 D 31\n\nRS-24 R 12\n\n\nWhat I'd like to do is split the row data into a new column as per the below so that I can run some basic calculations.\n\nID D_Votes R_Votes\n\nRS-24 31 12\n\n\nDoes anyone have any idea how I could go about this?\n\nYour help would be greatly appreciated."
] | [
"python-3.x",
"pandas"
] |
[
"Compute similarity between n entities",
"I am trying to compute the similarity between n entities that are being described by entity_id, type_of_order, total_value.\n\nAn example of the data might look like:\n\nNR entity_id type_of_order total_value\n 1 1 A 10\n 2 1 B 90\n 3 1 C 70\n 4 2 B 20\n 5 2 C 40\n 6 3 A 10\n 7 3 B 50\n 8 3 C 20\n 9 4 B 50\n 10 4 C 80\n\n\nMy question would be what is a god way of measuring the similarity between entity_id 1 and 2 for example with regards to the type_of_order and the total_value for that type of order.\n\nWould a simple KNN give satisfactory results or should I consider other algorithms?\n\nAny suggestion would be much appreciated."
] | [
"machine-learning",
"similarity",
"data-science",
"cosine-similarity"
] |
[
"MVC 4 : Postback returns a array for property of type object in my model",
"I have a model with one of the property of type object . This property is a dynamic property and could sometime contain a string or a date or a Boolean.\n\nI have a editor template for each type i.e boolean , string , date etc . \n\nThe problem I have is when the page is posted , the postback contains a array instead of the actual value. The first element of the array contains the actual value.\n\n\n\nWhy is the value being returned as a array ?\n\nMy model \n\n public string Description;\n public string Name { get; set; }\n public Type Type{ get; set; }\n object _value;\n public object Value { get;set;}\n\n\nstatement in the view\n\n @Html.EditorFor( m => m.Value)\n\n\nEdit : Corrected the object name from _value to Value. It was a wrong Ctrl V operation.\n\nEdit : The HTML rendered in the browser\n\nWhen the object contain a boolean value (checkbox):\n\n<div>\n<input checked=\"checked\" data-val=\"true\" data-val-required=\"The BoolJPY field is required.\" id=\"FurtherInformationFieldObject_Properties_1__Value\" name=\"FurtherInformationFieldObject.Properties[1].Value\" type=\"checkbox\" value=\"true\"><input name=\"FurtherInformationFieldObject.Properties[1].Value\" type=\"hidden\" value=\"false\">\n\n\n\n\nWhen the object contains a string(Textbox) : \n\n<div id=\"divStringField\"><input class=\"text-box single-line valid\" data-val=\"true\" data-val-required=\"The String Field field is required.\" id=\"FurtherInformationFieldObject_Properties_2__Value\" name=\"FurtherInformationFieldObject.Properties[2].Value\" type=\"text\" value=\"\"> </div>\n\n\nEdit 2 : Posting the complete model and view code.\n\nController code :\n\npublic ActionResult Edit(string name =\"field1\" )\n{\n Models.DynamicData data1 = new Models.DynamicData();\n\n //all this comes from the database table. I am putting the value directly in field just for simplicity\n // this is exactly how I convert the value from the entity to the model\n data1.Description = \"Field1 Description\";\n data1.Name = \"field1\";\n data1.Type = typeof(string);\n data1.Value = Convert.ChangeType(\"MyStringValue\", data1.Type);\n\n //similarly add few more fields to the model collection\n\n return View(data1);\n}\n[HttpPost]\npublic ActionResult Edit(Models.DynamicData model)\n{\n // break point here : model.Value shows a array of string instead of the edited value.\n return View(model);\n}\n\n\nView : \n\n @model SampleDynamicDataProject.Models.DynamicData\n\n@{\n ViewBag.Title = \"Edit\";\n}\n\n<h2>Edit</h2>\n\n@using (Html.BeginForm()) {\n @Html.AntiForgeryToken()\n @Html.ValidationSummary(true)\n\n <fieldset>\n <legend>DynamicData</legend>\n\n <div class=\"editor-label\">\n @Model.Description\n </div>\n <div class=\"editor-field\">\n @Html.EditorFor(model => model.Value)\n @Html.ValidationMessageFor(model => model.Value)\n </div>\n\n <p>\n <input type=\"submit\" value=\"Save\" />\n </p>\n </fieldset> \n\n\n}\n\nI should explain I used object as type for Value property because the value could be string or bool or date ex data1 in above controller could look like below \n\n data1.Description = \"Field2 Description\";\n data1.Name = \"field2\";\n data1.Type = typeof(bool);\n data1.Value = Convert.ChangeType(\"true\", data1.Type); // database stores \"true\" as string which is converted into a boolean and stored in the object.\n\n\nAs shown in the code , my problem is in the post action for Edit , I get Value as an array even for a simple string.\nThe sample project code here https://drive.google.com/file/d/0B3xCaeRk2IQZSTM0aHdoWEtNYW8/edit?usp=sharing"
] | [
"c#",
"asp.net-mvc",
"asp.net-mvc-4"
] |
[
"Service Fabric - Dynamic resource government per service instance",
"TL;DR: Is there a way to dynamically set the parameters or resource policies for ServicePackageResourceGovernancePolicy and/or ResourceGovernancePolicy when we create a new instance of a certain ServiceType at runtime?\n\nWe have a use case to have dynamic resource government per service instance (not type).\n\nSo basically, we have a service type: VotingDataType.\n\nSo you describe the resource government in the ApplicationManifest, taken from the docs here is an example:\n\n<ApplicationManifest>\n ... \n <ServiceManifestImport>\n <ServiceManifestRef ServiceManifestName=\"VotingDataPkg\" ServiceManifestVersion=\"1.0.0\" />\n ... \n <!-- Set resource governance at the service package level. -->\n <ServicePackageResourceGovernancePolicy CpuCores=\"[CpuCores]\" MemoryInMB=\"[Memory]\"/>\n\n <!-- Set resource governance at the code package level. -->\n <ResourceGovernancePolicy CodePackageRef=\"Code\" CpuPercent=\"10\" MemoryInMB=\"[Memory]\" BlockIOWeight=\"[BlockIOWeight]\" \n MaximumIOBandwidth=\"[MaximumIOBandwidth]\" MaximumIOps=\"[MaximumIOps]\" MemoryReservationInMB=\"[MemoryReservationInMB]\" \n MemorySwapInMB=\"[MemorySwapInMB]\"/>\n\n </Policies>\n </ServiceManifestImport>\n ...\n</ApplicationManifest\n\n\nNow for every customer, my custom placement service will instantiate a new instance of the VotingDataType. However, by some meta data we get before we are about to instantiate a new instance, we decide if it needs a bigger instance to begin with. so instead of 10% CPU limit, we want a 20% CPU limit.\n\nOur placement service will then use the following method to create a new instance of that VotingDataType service. fabricClient.ServiceManager.CreateServiceAsync(...). However, we're not able to customize the Parameters for the ResourceGovernancePolicy. \n\nIs there a way to dynamically set the parameters or resource policies for ServicePackageResourceGovernancePolicy and/or ResourceGovernancePolicy when we create a new instance of a certain ServiceType at runtime?"
] | [
"c#",
"azure",
"azure-service-fabric",
"service-fabric-stateless"
] |
[
"Infinite scroll fires too often although flag is used",
"So, I tried my hands on infinite scrolling with jQuery. Problem is, as soon as I scroll down a few pixels, the function fires something like 50 times which has a very high impact on my server due to a LOT of huge gifs on the page. I was advised to use a flag but it doesn't seem to fix the problem.\n\n<script>\n $(window).data('ajaxready', true).scroll(function(e) {\n if ($(window).data('ajaxready') == false) return;\n\n if ($(window).scrollTop() >= $(document).height() - $(window).height() - 0) {\n $(window).data('ajaxready', false);\n var box = $(\"#maincontent\");\n //Just append some content here\n $.get(\"more.php\", function(data){\n box.html(box.html() + data);\n });\n $(window).data('ajaxready', true);\n } \n });\n</script>\n\n\nThe actual body looks just like this:\n\n<body>\n<div id=\"maincontent\">\n<?php\n include ('more.php');\n echo \"ENDE<br>\";\n?>\n</div>\n</body>\n\n\nThe more.php generates enough content to exactly fill a little bit more than a fullscreen on a standart FULL HD display.\n\nedit: as far as I understand it, this code should do the following: ONLY load more content, when the bottom border of the viewport hits the bottom border of the document. This is the desired result but not what is actually happening. What IS happening is: content gets appended EVERY time the user scrolls ONE pixel."
] | [
"javascript",
"php",
"jquery"
] |
[
"Response code 404 (Not Found) for https://github.com/electron/electron/releases/download/v9.4.4/electron-v9.4.4-darwin-arm64.zip",
"I'm trying to install node modules for react native project in M1 macbook pro. While trying to run npm install or yarn install I'm having this error.\nerror /Users/akash/Documents/Projects/business-hub/node_modules/electron: Command failed.\nExit code: 1\nCommand: node install.js\nArguments:\nDirectory: /Users/akash/Documents/Projects/business-hub/node_modules/electron\nOutput:\nHTTPError: Response code 404 (Not Found) for https://github.com/electron/electron/releases/download/v9.4.4/electron-v9.4.4-darwin-arm64.zip\n at EventEmitter.<anonymous> (/Users/akash/Documents/Projects/business-hub/node_modules/got/source/as-stream.js:35:24)\n at EventEmitter.emit (node:events:369:20)\n at module.exports (/Users/akash/Documents/Projects/business-hub/node_modules/got/source/get-response.js:22:10)\n at ClientRequest.handleResponse (/Users/akash/Documents/Projects/business-hub/node_modules/got/source/request-as-event-emitter.js:155:5)\n at Object.onceWrapper (node:events:476:26)\n at ClientRequest.emit (node:events:381:22)\n at ClientRequest.origin.emit (/Users/akash/Documents/Projects/business-hub/node_modules/@szmarczak/http-timer/source/index.js:37:11)\n at HTTPParser.parserOnIncomingClient [as onIncoming] (node:_http_client:636:27)\n\nI'm unable to find which of my packages are using electron for that I can not upgrade the version of electron."
] | [
"react-native",
"electron",
"apple-m1"
] |
[
"Fill GridLayout cells with ImageView",
"I have a GridLayout and I'm setting it's number of columns and rows programmatically. Then I want to fill these cells with imageView. So, how can I create enought ImageViews to fill all cells?\n\nHere's part of my xml for GridLayout\n\n<GridLayout\n android:id=\"@+id/dgLayout\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_margin=\"20dp\">\n <ImageView\n android:id=\"@+id/imageView2\"\n />\n</GridLayout>\n\n\nAnd here's the part of code from my activity class\n\ndgLayout.setColumnCount(dwInt);\ndgLayout.setRowCount(dhInt);"
] | [
"android",
"imageview"
] |
[
"VS code VIM extension copy and paste",
"Is there a normal way to copy and paste in vs code using vim extension?\n\nI've tried mapping VIM register commands to the shortcut commands I'm used to (ctrl + c for copying and ctrl + v for pasting), but the results are pretty weird and I'm not sure how to do this correctly.\n\nWhile using vim the key bindings were quite simple,\nvimrc file:\n\nmap <C-c> \"+y\nmap <C-v> \"+p\n\n\nNow I try to migrate those to vs-code by editting json.settings file:\n\n{\n \"vim.visualModeKeyBindings\": [\n {\n \"before\": [\"<C-c>\"],\n \"after\": [\"\\\"\", \"+\", \"y\"]\n },\n {\n \"before\": [\"<C-v>\"], \n \"after\": [\"\\\"\", \"+\", \"p\"]\n },\n ], }\n\n\nI want this to operate both in visual mode and in normal mode (for pasting), and be able to copy and paste from clipboard using these shortcuts.\n\nHow to do this correctly? \nIs there another way to do this?"
] | [
"vim",
"visual-studio-code",
"vscodevim"
] |
[
"JSF (Container Managed Security) Group Roles",
"For a JSF application running on JBoss 4.2 with JSF 1.2, Container Managed Security and EJB 3.0 I'm looking for a solution to have several roles combined in one role. For example:\n\n\nRoles: IT-Support, Phone-Support, Technical-Support, Deliver-Support\n\n\nNow, I want to specify one role which includes for example three of these roles:\n\n\nRole: Senior-Suppoert (IT-Support, Technical-Support, Deliver-Support)\n\n\nIs this possible with the container managed security and Jboss?"
] | [
"security",
"jsf"
] |
[
"How to trim characters of match in Vim?",
"I want to trim the last five characters of a match in Vim. The search pattern is not a direct word, instead it is something like foo.*bar\nHere I want to trim the last five characters of the above match. \n\nI tried :g/foo.*bar/norm $5X\nbut this trims five characters at the end of the lines matching this pattern"
] | [
"regex",
"vim",
"replace",
"vi",
"trim"
] |
[
"How to use res.send in passport strategy?",
"I'm trying to make Node.js ajax authentication with passport.js, I want to show messages in /login page. I should use res.send in my passport strategy, then ajax call ended successfully will display success data to its page. But I can't guess how can I use res. in strategy. Please see below code, \n\nlogin.ejs \n\n<div id=\"messages\"></div>\n\n<!-- and there is a form, when form submitted, the ajax call executed.-->\n<!-- ...ajax method : POST, url : /login, data: {}, success:... -->\n<!-- If ajax call success, get 'result' data and display it here -->\n\n\napp.js\n\n// and here is ajax handler \n// authentication with received username, password by ajax call\n\napp.post('/login', passport.authenticate('local'), \nfunction(req, res, next){\n res.redirect('/');\n});\n\n// and here is passport strategy \n\n passport.use(new passportLocal.Strategy(function(userid, password, done) {\n Members.findOne({'user_id' : userid}, function(err, user){\n\n // if user is not exist\n if(!user){\n\n // *** I want to use 'res.send' here. \n // *** Like this : \n // *** res.send('user is not exist');\n // *** If it is possible, the login.ejs display above message. \n // *** That's what I'm trying to it. How can I do it?\n\n return done(null, null);\n }\n\n // if everything OK,\n else {\n return done(null, {id : userid});\n }\n\n })\n\n\n}));\n\n\nI searched some document on google, people usually use 'flash()' in connect-flash module, but I thought this module needed to reload page, this is not what I want to, So please help me and let me know if there is better way. Thanks."
] | [
"node.js",
"express",
"passport.js"
] |
[
"Replacement for COSName.DOCMDP in PDFBox 2.0.4",
"I'm testing the example codes from this page:\nhttps://svn.apache.org/viewvc/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/\n\nBut inside the file CreateSignatureBase.java, exactly in the functions getMDPPermission and setMDPPermission, it calls a property that doesn't exist anymore: COSName.DOCMDP. I perused the Pdfbox page and its migration guide and it doesn't mention this property and how to replace it. I also looked into the PDfbox source code (exactly the file COSName.java) and It doesn't have that property, despite this file:\nhttps://svn.apache.org/viewvc/pdfbox/branches/2.0/pdfbox/src/main/java/org/apache/pdfbox/cos/COSName.java?view=markup does have it.\n\nI checked both pdfbox-2.0.4.jar and pdfbox-app-2.0.4.jar adding them to the Netbeans project where I'm testing the java files from the pdfbox examples. None of them have the property COSName.DOCMDP in the COSName class.\nBoth jars and the pdfbox sourcecode are downloaded from here:\nhttps://pdfbox.apache.org/download.cgi#20x\n\nHow can I replace the property COSName.DOCMDP in the CreateSignatureBase class? Am I getting the right jars?"
] | [
"java",
"pdfbox"
] |
[
"Why does btnOpen return null when I invoke it on onCreateView with Kotlin?",
"I get the error information \n\n Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference\n\n\nwhen I run the code btnOpen.setOnClickListener.\n\nBut the system is OK when I run the code \n\nvar s= rootView.findViewById<Button>(R.id.btnOpen)\n\n\nwhy?\n\nCode\n\nimport kotlinx.android.synthetic.main.layout_tab_clipboard.*\n\nimport info.dodata.clipboard.R\nimport utility.openActivity\n\nclass UITabClipboard: Fragment(){\n private lateinit var mContext: Context\n\n override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {\n val rootView = inflater.inflate(R.layout.layout_tab_clipboard, container, false)\n mContext = rootView.context\n\n var s= rootView.findViewById<Button>(R.id.btnOpen) //It's OK\n s.setOnClickListener(){\n mContext.openActivity<UIAbout>()\n } \n\n\n btnOpen.setOnClickListener { //It cause error\n mContext.openActivity<UIAbout>()\n }\n\n return rootView\n }\n\n\n}"
] | [
"android",
"kotlin"
] |
[
"Extracting interval based on data/tag",
"times = pd.to_datetime(pd.Series(['2020-08-05','2020-08-12', '2020-08-16', '2020-08-22', '2020-08-30', '2020-09-11', '2020-09-20']))\nevent = [0, 0, 1, 1, 0, 0, 1]\ndf = pd.DataFrame({'v': event}, index=times)\n\n\nAbove is my dataframe. I am trying to extract interval where the value switched from 0 to 1.\n\nMy ideal out put in above case would be : \n\n[['2020-09-11 00:00:00', '2020-09-20 00:00:00'],\n ['2020-08-12 00:00:00', '2020-08-16 00:00:00']]\n\n\nHow I am approaching:\nI am iterating over the df in reverse and trying to find first occurrence of '1'. \nThere after I am looking for first occurrence of 0. These correspond to the first interval.\nI am repeating above over the df.\n\nBut, the output, I am getting is:\n\n[['2020-09-11 00:00:00', '2020-09-20 00:00:00'],\n ['2020-08-12 00:00:00', '2020-08-22 00:00:00']]\n\n\nI know that the issue is because of consecutive 1 in the timeseries. But, not able to find the workaround. Any leads would be appreciated."
] | [
"pandas"
] |
[
"sqlite3 syntax for regexp in \"search and replace\"",
"I can use regexp to list hits from a Sqlite3 db, but what is the syntax for a \"search and replace\" using regexp."
] | [
"sqlite"
] |
[
"Chrome font-face not loading local font",
"I am running into an odd issue. Using the webfont link through google's webfonts api works just fine and loads the font, however... The app i'm creating is local only, so having any kind of overhead connecting to the internet is noticeable when rendering the fonts for the first time, plus no font would be loaded if there is no internet connection.\n\n@font-face {\nfont-family: Pt Sans;\nfont-style: normal;\nfont-weight: 400;\nsrc: url(http://themes.googleusercontent.com/static/fonts/ptsans/v4/jduSEW07_j4sIG_ERxiq4Q.woff);\n}\n\n\nThe above is the working code.\n\n@font-face {\nfont-family: Pt Sans;\nfont-style: normal;\nfont-weight: 400;\nsrc: url(fonts/ptsans.woff);\n}\n\n\nThis works when running directly from the browser locally, however i'm using a framework which embeds the chrome webview into my C# application, called CefSharp. The difference is, i'm simulating a link to a site, rather then loading the pages directly. It would be as if I created my own http:// link to the font, like the webfont.\n\nIf I open up Chromes dev tools > resources tab > fonts and click the locally loaded font, it shows a default font, however if I click the font loaded through google's api, it renders the correct font.\n\nWhat is the google api sending to the browser that i'm not? I've tried numerous mimeTypes to no avail."
] | [
"c#",
"css",
"font-face",
"google-webfonts"
] |
[
"Python: Most elegant way to merge two dictionaries with the same key",
"I am working on genome-scale models and trying to create a minimal medium that suits two optimal flux conditions. I get two dictionaries with the required medium components looking like this: \n\nEX_C00001_ext_b 1.132993\nEX_C00011_ext_b 1.359592\nEX_E1_ext_b 16.000000\n\nEX_C00034_ext_b 0.000088\nEX_C00244_ext_b 0.259407\nEX_C00182N_cyt_b 0.006079\nEX_C00009_ext_b 0.020942\nEX_C01330_ext_b 0.000110\nEX_C00080_ext_b 0.258331\nEX_C00001_ext_b 0.780699\nEX_C14819_ext_b 0.000197\nEX_C00059_ext_b 0.005162\nEX_C00011_ext_b 1.198398\nEX_C14818_ext_b 0.000217\nEX_C00305_ext_b 0.000802\nEX_C00038_ext_b 0.000088\nEX_C00070_ext_b 0.000088\nEX_C06232_ext_b 0.000088\nEX_C00076_ext_b 0.000131\nEX_C00238_ext_b 0.004925\nEX_E1_ext_b 16.000000\nEX_C00175_ext_b 0.000094\n\n\nI want to merge both dictionaries to selected the highest value for each metabolite in the most elegant way and it should be usable regardless of the dictionary size. \n\nIt should give me the following result:\n\nEX_C00034_ext_b 0.000088\nEX_C00244_ext_b 0.259407\nEX_C00182N_cyt_b 0.006079\nEX_C00009_ext_b 0.020942\nEX_C01330_ext_b 0.000110\nEX_C00080_ext_b 0.258331\nEX_C00001_ext_b 1.132993\nEX_C14819_ext_b 0.000197\nEX_C00059_ext_b 0.005162\nEX_C00011_ext_b 1.359592\nEX_C14818_ext_b 0.000217\nEX_C00305_ext_b 0.000802\nEX_C00038_ext_b 0.000088\nEX_C00070_ext_b 0.000088\nEX_C06232_ext_b 0.000088\nEX_C00076_ext_b 0.000131\nEX_C00238_ext_b 0.004925\nEX_E1_ext_b 16.000000\nEX_C00175_ext_b 0.000094\n\n\nHere are the example dicts for you to use. \n\n{'EX_C00034_ext_b': 8.757888959017035e-05, 'EX_C00244_ext_b': 0.2594073529471562, 'EX_C00182N_cyt_b': 0.006078784247428623, 'EX_C00009_ext_b': 0.02094224214212716, 'EX_C01330_ext_b': 0.00010954587179767827, 'EX_C00080_ext_b': 0.2583314448433369, 'EX_C00001_ext_b': 0.7806992563484072, 'EX_C14819_ext_b': 0.00019712476138777617, 'EX_C00059_ext_b': 0.005162038491279668, 'EX_C00011_ext_b': 1.1983981620820985, 'EX_C14818_ext_b': 0.00021724189246195394, 'EX_C00305_ext_b': 0.0008020492051022175, 'EX_C00038_ext_b': 8.757888959017035e-05, 'EX_C00070_ext_b': 8.757888959017036e-05, 'EX_C06232_ext_b': 8.757888959017035e-05, 'EX_C00076_ext_b': 0.00013122381476546977, 'EX_C00238_ext_b': 0.0049252286422986884, 'EX_E1_ext_b': 16.000000000000245, 'EX_C00175_ext_b': 9.42845999482296e-05}\n\n{'EX_C00001_ext_b': 1.1329932376320115, 'EX_C00011_ext_b': 1.3595918851584152, 'EX_E1_ext_b': 16.000000000000387}\n\n\nPlease note that I don't know in which of the dictionarys the higher values are.\n\nEDIT\n\nAs you can see from my example even though both dictionary's contain the same keys, not all keys are in both dictionary's. So I can't loop through the keys since I don't know if I skip one of the keys. \nI guess you could first create a set out of all keys from all the dictionary's I need to merge but I am not sure if it is a good way. \n\nYes only the highest value should be saved. \n\nEDIT 2\n\nUnfortunatly after updating the medium this way I get an error \n\nTypeError: in method 'Reaction_setReversible', argument 2 of type 'bool'\n\n\nwhen I try to write the model with the updated medium to an xml file.\n\n**Last EDIT **\n\nIf anyone encounters the same problem, you just need to specify that the values are floats. Everything worked afterwards."
] | [
"python",
"cobra"
] |
[
"Using blade components and javascript",
"I'm using Laravel, and I'm trying to use javascript to fill a list of users.\nThe problem is that each entry of the list is based on a view, which I made in a Blade component:\n\npro_list_entry.blade.php:\n\n@if( isset($pro_id) && isset($pro_avatar) && isset($pro_name))\n <a onclick='selectProfessional( {{ $pro_id }} , {{ $pro_avatar }}, {{ $pro_name }} )' style='cursor: pointer'>\n <div class='row'>\n <div class='col-4'>\n <img class='u-avatar rounded-circle' src='{{ $pro_avatar }}'>\n </div>\n <div class='col-8 d-flex align-items-center'>\n <h6 class='fm-wrapped-text'>{{ $pro_name }}</h6>\n </div>\n </div>\n </a>\n @endisset\n\n\nThen I would like to feed all those components to the list using Javascript:\n\nvar listOfPhysicians = buildProfessionalListFromData(jsonData.professionals);\n\n$('#pc_new_app_med_list').empty();\n$('#pc_new_app_med_list').html(listOfPhysicians);\n\n\n...\n\nfunction buildProfessionalListFromData(data) {\n var list = \"\";\n\n if (data != null) {\n for (i = 0; i < data.length; i++) {\n\n var entry =\n \"@component('patrons.clinic.shared.pro_list_entry')\"\n + \"@slot('pro_id')\" + data[i].professional_id + \"@endslot\"\n + \"@slot('pro_avatar') ../../user_uploads/avatars/\" + data[i].avatar + \"@endslot\"\n + \"@slot('pro_name')\" + data[i].prefix + \" \" + data[i].first_name + \" \" + data[i].last_name + \"@endslot\"\n + \"@endcomponent\";\n\n list = list + entry;\n }\n }\n return list;\n}\n\n\nAfter a little research, I found that what I am trying to do is simply impossible.\n\nIs there any other way to do this? Adding list entries, which are based on a view, and filling their data with javascript? Maybe I'm just not seeing the obvious solution.\n\nAny help?\n\nThank you."
] | [
"javascript",
"php",
"html",
"laravel",
"laravel-blade"
] |
[
"Query database to display the total count of data based on current date and month",
"I want to query my SQL database to display the total count of data in it based on current date and month but my query counts both current and previous date. For instance, if there is 2 entries for 20/08/2018 and 4 entries for 20/07/2018, it returns 6 as total count while I want the query to return only the entries for the current day or month not previous entries.\n\nHere is the query:\n\n var today = db.QueryValue(\"select count(*) FROM UserName where DAY(signed_in ) = datepart(DAY, getdate());\");\n var month = db.QueryValue(\"select count(*) FROM UserName where MONTH(signed_in ) = datepart(month,getdate());\");"
] | [
"c#",
"sql",
"asp.net",
"sql-server"
] |
[
"DRAG AND DROP OF A VIEW : view returning to original position even after dragging to new position",
"I want to add drag and drop functionality to a textview in my testing app\nThe main layout contains a relativelayout(RL1) , which inturn contains another relativelayout(RL2) \nnow the RL2 contains a textview which can able to be dragged and dropped anywhere\n\nBut when i perform drag on the textview its getting dragged but went i drop it it returns back to its originsl position\nplease help me\n\nmy mainactivity\n\npublic class MainActivity extends Activity\n{\n\nTextView tv;\nLayoutParams lParams;\nRelativeLayout layout;\nprivate static final String Tv_TAG =\" TV_DRAG\";\n@Override\nprotected void onCreate(Bundle savedInstanceState)\n{\n super.onCreate(savedInstanceState);\n setContentView(R.layout.main);\n\n tv = (TextView) findViewById(R.id.mainTextView1);\n tv.setTag(Tv_TAG);\n tv.setOnTouchListener(new MyTouchListener());\n\n layout = (RelativeLayout) findViewById(R.id. draggableRelativeLayout );\n layout.setOnDragListener(new MyDragListener());\n}\n\n\nprivate class MyTouchListener implements OnTouchListener\n{\n\n @Override\n public boolean onTouch(View v, MotionEvent event)\n {\n ClipData.Item item = new ClipData.Item((CharSequence) v.getTag());\n String[] mimeTypes ={ClipDescription.MIMETYPE_TEXT_PLAIN};\n ClipData dragData = new ClipData(v.getTag().toString(), mimeTypes, item);\n\n View.DragShadowBuilder shdwbldr = new View.DragShadowBuilder(v);\n\n v.startDrag(dragData, shdwbldr, v, 0);\n v.setVisibility(View.INVISIBLE);\n return true;\n }\n\n\n}\n\nprivate class MyDragListener implements OnDragListener\n{\n\n @Override\n public boolean onDrag(View v, DragEvent event)\n {\n\n View view = (View) event.getLocalState();\n\n switch (event.getAction()) { \n case DragEvent.ACTION_DRAG_STARTED: \n lParams =(RelativeLayout.LayoutParams)view.getLayoutParams(); \n break;\n case DragEvent.ACTION_DRAG_ENTERED: \n\n int x_cord = (int) event.getX();\n int y_cord = (int) event.getY();\n\n break; \n case DragEvent.ACTION_DRAG_EXITED:\n\n x_cord = (int) event.getX();\n y_cord = (int) event.getY();\n lParams.leftMargin = x_cord;\n lParams.topMargin = y_cord;\n\n view.setLayoutParams(lParams);\n\n break;\n case DragEvent.ACTION_DROP: \n // Dropped, reassign View to ViewGroup \n\n ViewGroup owner = (ViewGroup) view.getParent(); \n owner.removeView(view);\n RelativeLayout container = (RelativeLayout) v;\n container.addView(view);\n view.setVisibility(View.VISIBLE);\n break; \n case DragEvent.ACTION_DRAG_ENDED: \n\n break;\n default: break;\n\n }\n\n return true;\n }\n}\n\n}\n\n\n**my layout **\n\n<RelativeLayout\nxmlns:android=\"http://schemas.android.com/apk/res/android\"\nandroid:layout_height=\"fill_parent\"\nandroid:layout_width=\"fill_parent\"\nandroid:background=\"#AE9C9B\"\nandroid:id=\"@+id/ draggableRelativeLayout \">\n\n<RelativeLayout\n android:layout_height=\"match_parent\"\n android:layout_width=\"match_parent\"\n android:background=\"@null\"\n android:id=\"@+id/mainRelativeLayout1\">\n\n <TextView\n android:layout_height=\"wrap_content\"\n android:text=\"DRAG ME\"\n android:textAppearance=\"?android:attr/textAppearanceLarge\"\n android:layout_width=\"wrap_content\"\n android:layout_margin=\"10dp\"\n android:id=\"@+id/mainTextView1\"/>\n\n</RelativeLayout>"
] | [
"android",
"drag-and-drop",
"android-relativelayout"
] |
[
"Even after injection of http, Uncaught TypeError: Cannot read property 'get' of undefined",
"I have following simple code but I get the error even though $http is injected:\n\nangular.module('bizapp')\n.controller('SalesCtrl', ['$scope', '$http', GetSalesInvoices]);\n\nfunction GetSalesInvoices($scope, $http) {\n $scope.invoices = [];\n $scope.refresh = function($scope, $http) {\n var url = \"https://foo.ic/api/salesinvoice/SalesInvoices\";\n $http.get(url)\n .success(function(data) {\n $scope.invoices = data.d.results;\n })\n .error(function(){\n console.log('opss')\n })\n .finally(function() {\n $scope.$broadcast('scroll.refreshComplete');\n });\n }\n}\n\n\nUncaught TypeError: Cannot read property 'get' of undefined\nWhat am I missing?"
] | [
"javascript",
"angularjs"
] |
[
"SQL Syntax select something from a table and insert the result into a new table if it doesn't exist",
"I am pretty new to SQL syntax and I have the following Scenario on Windows Server using MSSQL 2012:\n\n2 tables, lets call them table1 and table2 \n\nI now want to select a user by email from dbo.table1 and take out his UserID , later I need to insert this UserID into dbo.table2 if the table doesn't have this UserID already.\n\nSo I start doing a simple select :\n\nSelect from dbo.table1 where 'email' = '[email protected]'\n\n\nnow I need to select the UserID of that account and push it to dbo.table2 if dbo.table2 has no UserID like that.\n\nHow do I achieve that ?"
] | [
"sql",
"sql-server",
"windows-server-2012"
] |
[
"ViewModels and IsolatedStorageSettings",
"Im working on a MVVM Windows phone app that displays weather info. \n\nWhen the app loads up it opens MainPage.xaml. It makes a call the the service to get weather info and binds that data to the UI. Both Fahrenheit and Celcius info are returned but only one is displayed. \n\nOn the setting page, the user can select to view the temp in either Fahrenheit or Celcius.\nThe user can change this setting at any time and its stored in IsolatedStorageSettings.\n\nThe issue Im having is this:\nwhen the user navigates to the Settings page and changes their preference for either Fahrenheit or Celcius, this change is not reflected on the main page.\n\nThis issue started me thinking about this in a broader context. I can see this being an issue in ANY MVVM app where the display depends on some setting in IsolatedStorage. Any time any setting in the IsoStore is updated, how does the ViewModels know this? When I navigate back in the NavigationStack from the settings page back to MainPage how can I force a rebind of the page?\n\nThe data in my model hasnt changed, only the data that I want to display has changed.\n\nAm I missing something simple here?\n\nThanks in advance.\nAlex"
] | [
"windows-phone-7",
"mvvm",
"isolatedstorage"
] |
[
"Is it possible set wrapContent attribute on view without parrent?",
"I have a simple button view, and set it as content view. Is it possible to resize this view programmaticly to \"wrap_content\"?\n\nButton button = new Button(getContext());\nbutton.setText(\"Some text\");\nsetContentView(button);"
] | [
"android",
"view",
"android-wrap-content"
] |
[
"Node.js php peformance",
"Here's the scenario I anticipate: I have an app written in PHP which has a domain layer (complete with validators, etc). I want to use node.js for my web services for performance in high concurrency situations. If I create a command line interface for my php domain layer (see below), will this give me better performance than just using Apache? Is this even a good way to do this? I'm new to node.js and am trying to get my bearings. Node: The command line interface for the domain layer will return json encoded objects.\n\n//Super simple example:\nvar http = require(\"http\");\nvar exec = require('child_process').exec;\n\nfunction onRequest(request, response) {\n exec(\"php domain-cli.php -model Users -method getById -id 32\", function(error, stdout, stderr){\n response.writeHead(200, {\"Content-Type\": \"application/json\"});\n response.write(stdout);\n response.end();\n });\n\n}\n\nhttp.createServer(onRequest).listen(80);"
] | [
"php",
"performance",
"node.js"
] |
[
"hl-line-mode + scroll-step + highlight-parentheses -> emacs goes crazy",
"Yesterday I was customizing my emacs. Today I've been working in emacs when suddenly stumbled upon an interesting effect. After some investigation I figured out the minimal initialization that leads to this effect. Still effect does not seem stable. I hope you will be able to reproduce it.\n\nFirst, evaluate the following elisp code:\n\n(add-to-list 'load-path \"~/.emacs.d/\")\n(require 'highlight-parentheses)\n(global-hl-line-mode 1)\n(setq scroll-step 1)\n\n\nIn order to be sure no other extension gets on the way, I use the file with this code as init file.\n\nYou will also need the highlight-parentheses module, of course.\n\nThen you will need a file where the effect could be revealed. Unfortunately, I wasn't able to figure out the exact conditions that reveal the effect. Try the README.md file of the Visible bookmarks extension. I'm sorry for asking do download some specific files to observe the effect, but I don't know the other way.\n\nIf you're still not scared away then open the README.md file and turn on the highlight-parentheses mode:\n\nM-x highlight-parentheses-mode RET\n\n\nThen press and hold the down-arrow key. The pointer will start moving down line-by-line. But when it leaves the line 45 (which is at the bottom of the screen at the moment) it suddenly jumps back to the middle of the screen (line 24). W-what!?\n\nAnd it happens every time you approach line 46 when it is right below the bottom edge of the screen. Moreover, it seems to effect other extensions too (e.g. visual bookmarks start to make strange things like messing up the bookmarks order).\n\nI'm new to elisp so I hardly can find a bug in the source of these three modes. If this is a bug at all.\n\nIf it matters, I use emacs 23.2.1 under Debian squeeze. Sorry for my english and thanks for your attention."
] | [
"emacs",
"elisp"
] |
[
"CWAC : pass data to WakefulIntentService between alarms when used with AlarmManager",
"When using WakefulIntentService without alarm, one can call \n\nWakefulIntentService.sendWakefulWork(context, intentOfWork);\n\n\nto pass data to the service through the intent.\n\nWhen used with AlarmManager one can call\n\nAlarmListener.scheduleAlarms(AlarmManager mgr, PendingIntent pi, Context ctxt); \n\n\nto pass data through a PendingIntent.\n\nHowever, this intent is set at the beginning and will always be the same each time the alarm will goes off. What if we need to update the intent data between 2 alarms ?\nWe could stop the schedule, update the intent and start the alarm again, but is it the correct way ?"
] | [
"android",
"commonsware-cwac"
] |
[
"Active record delete_all issue with empty field",
"My Course model has a field called user_ids which is an array of ObjectIds. \n\nI am trying to find all courses with non empty user_ids and unset only the user_id field.\n\nlist = Course.where({ :user_ids.nin => [[], nil] })\nlist.each do |course|\n course.user_ids = []\n course.save \nend\n\n\nHowever, I always seem to get two courses which have:\n\n\"user_ids\" : [ ObjectId(\"560dc9998b3c5b003f000000\") ]\n\n\nIs my query wrong? Any help is appreciated."
] | [
"ruby",
"activerecord",
"activemodel"
] |
[
"How To hook unmanaged function inside managed function?",
"Here is my C++ Code:\nThis function is exported in my DLL. \n\nEXPORT set_hook(fnc_public_hook hook){\n public_hook = hook;\n}\n\n\nNow if I hook it from unmanaged code like following everything works fine.\n\nset_hook(my_fnc);\n\n\nNow before every event in my DLL my_fnc is called, so I can do some pre process on data.\n\nThe problem is that I don't know how to do this in .NET.\nHow to get .NET function pointer ? And how to use set_hook() to call my .NET function before every event ?"
] | [
"c#",
"c++",
".net",
"vb.net"
] |
[
"Protection against antiLVL",
"I am using the LVL from Google to protect my app for copying.\n\nIt can be easily cracked with the tool antiLVL.\n\nThere is a commercial library called na LVL which states that it is safe.\n\nBut I dont want to buy this commercial library, thus I tried to find an other method.\n\nI found out that antiLVL injects a new class for hooking. It was called smaliHook.java\n\nSo I tried this code:\n\npublic static boolean isAntiLVL(){\n try{\n Class.forName(\"smaliHook\");\n return true;\n }catch(Exception e){}\n return false;\n}\n\n\nBut unfortunatelly with current antiLVL it does not work. \n\nHave you some hints for creating a first small line of defense against script kiddies?"
] | [
"android",
"android-lvl"
] |
[
"How to prevent NestedServletException when testing Spring endpoints?",
"I am trying to test the security configuration of some of my endpoints which are secured with @PreAuthorize(#oauth2.hasScope('scope'). When accessing such an endpoint via Postman with a access token that does not have the required scope, the following is returned with HTTP status code 403 (forbidden):\n\n{\n \"error\": \"insufficient_scope\",\n \"error_description\": \"Insufficient scope for this resource\",\n \"scope\": \"scope\"\n}\n\n\nWhich is the expected behaviour that I want.\n\nWhen trying to test this configuration, Springs NestedServletException interferes with my test case before it can complete with my expected result.\n\nThis is a simplified version of the controller I want to test:\n\n@RestController\n@RequestMapping(value = \"/api\")\npublic class OauthTestingResource {\n\n @PreAuthorize(#oauth2.hasScope('scope'))\n @RequestMapping(value = \"/scope\", method = RequestMethod.GET)\n public void endpoint() {\n // ...\n }\n}\n\n\nAnd this is the corresponding test case:\n\n@RunWith(SpringJUnit4ClassRunner.class)\n@SpringBootTest(classes = MyApplication.class)\n@WebAppConfiguration\npublic class AuthorizationTest {\n\n @Autowired\n protected WebApplicationContext webApplicationContext;\n\n protected SecurityContext securityContext = Mockito.mock(SecurityContext.class);\n\n @Before\n public void setup() throws Exception {\n\n this.mvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();\n SecurityContextHolder.setContext(securityContext);\n }\n\n protected Authentication createMockAuth(Client client) {\n\n final List<GrantedAuthority> authorities = new ArrayList<>();\n authorities.add(new SimpleGrantedAuthority(\"ROLE_USER\"));\n\n final Authentication pwAuth = new UsernamePasswordAuthenticationToken(\"testuser\", \"testpw\", authorities);\n\n final TokenRequest request = new TokenRequest(new HashMap<>(), client.getClientId(), client.getScopes(), \"password\");\n\n final OAuthClient oauthClient = new OAuthClient(client, GrantType.PASSWORD);\n\n return new OAuth2Authentication(request.createOAuth2Request(oauthClient), pwAuth);\n }\n @Test\n public void testAppScope() throws Exception {\n\n final Client client = new Client(\"id1\", \"secret1\");\n\n client.setScope(\"scope\");\n Mockito.when(securityContext.getAuthentication()).thenReturn(createMockAuth(client));\n // this test passes\n mvc.perform(get(\"/api/scope\")).andExpect(status().isOk()); \n\n client.setScope(\"other_scope\");\n Mockito.when(securityContext.getAuthentication()).thenReturn(createMockAuth(client));\n // NestedServletException thrown here\n mvc.perform(get(\"/api/scope\")).andExpect(status().isForbidden()); \n }\n}\n\n\nThe exception that is thrown is the following (which is expected):\n\n\n org.springframework.web.util.NestedServletException: Request\n processing failed; nested exception is\n org.springframework.security.access.AccessDeniedException:\n Insufficient scope for this resource\n\n\nMy question is how can I prevent this exception from interfering with my test case?"
] | [
"spring",
"unit-testing",
"integration-testing",
"mockmvc"
] |
[
"Practical uses for compound literal expressions?",
"What are the practical applications of compound literals? I am not quite sure how an address of an unnamed region of storage could be useful. \n\nint *pointer = (int[]){2, 4};\n\n\nI found them mentioned here: https://en.cppreference.com/w/c/language/compound_literal"
] | [
"c",
"compound-literals"
] |
[
"How to best see, with some level of lenience, if a given string is inside another string?",
"I am trying to create a program in laravel where a person can answer a question. In the controller, I want to check if the givenAnswer matches any of the actual answers.\n\nI have seen a few things suggested online. The majority of people recommend using strpos. I have found however that it doesnt work as well as I would like it to.\n\nFor example, if one of the CORRECT answers is 'Quorin Halfhand', then strpos will show return true for answers such as \"Quo, Half, Hand, alf,\" etc etc. \n\nI would an option that lets me sanitize and state to what degree of error I would be willing to accept.\n\nIs there anything out there that might be useful?\n\nif (strpos($answers[$i], $request->answer) !== false) {\n return 'an answer matches!';\n } else {\n return 'no answer mathches'\n }"
] | [
"php",
"laravel",
"strpos"
] |
[
"How to make a discord bot kick someone when they say a trigger word",
"How to make a discord bot kick someone when they say a trigger word? Like for example when someone says 'idiot' they will get kicked from the server.\nHere is what I tried:\n**import discord\nimport time\nfrom discord.ext import commands\n\nclient = discord.Client()\n\[email protected]\nasync def on_ready():\n print("Bot is ready?")\n\[email protected]\nasync def on_message(message):\n if message.content.find("lol") != -1:\n await message.channel.send("HI!")\n\[email protected]\nasync def on_message(message):\n if message.content.find('matei') != -1:\n await kick('minionulLuiMatei#5893')\n return\n\n\n\n\nclient.run(token)**"
] | [
"python",
"discord",
"discord.py"
] |
[
"store function results in a vector",
"I have a function here that takes samples, it works however I'm struggling to store the samples taken in a vector so that I may plot them; here is my function below: \n\nInvCDF = function(n, sd) {\nfor (i in 1:n) {\nu=runif(1, min = 0, max = 1)\nx = sqrt(-2*(sd^2)*log(1-u))\nprint(x)\n}\n}\n\n\nI have tried creating a vector of 0's initially with\n\nx = vector(mode=\"numeric\",length=n)\n\n\nthen somehow fill in these 0's with the samples taken but it isn't working. \n\nIf someone could please assist with with storing my print(x) values in a vector I would be so happy"
] | [
"r",
"function",
"vector",
"sampling",
"storing-data"
] |
[
"Any recommendations for learning the basics of event-driven programming?",
"My task for today is to fully understand event-driven programming and how it works. Now there are several ways this can be achieved. The first one is to actually program a basic program that covers the key concepts, and the second approach is to watch a video that explains the key concepts in a way I can understand. Which approach do people recommend? \n\nDoes anyone have videos/program demos they found useful and could recommend to me? My major experiences are with ASP.NET MVC, so it would be best if the tutorial were with WebForms ASP.NET."
] | [
"asp.net",
"asp.net-mvc",
"events",
"event-handling"
] |
[
"asp.net mvc web application page loading slowness issue",
"we have developed an application using ASP.NET/C# MVC 4.0, SQL SERVER 2012 DB, Entity Framework, WCF Service.\napplication website is hosted on IIS 10 and the operating system used is Windows Server 2016 and this is standalone WEB server dedicated for our project.\napplication WCF web service is hosted using Windows Service and this is standalone APP server dedicated for our project.\napplication database is hosted on SQL Farm and this is a common database server, where other projects databases (more than 60) are also hosted.\n\napplication is already running absolutely fine in PROD environment from couple of years.\nbut suddenly from couple of months, we started facing as intermittent issue and i.e. application slow response\n\nThere are no errors, but the response time is too long, and sometimes it doesn't respond either, the browser keeps waiting for the web server. \ncustomer has complained that his web application gets slow sometimes. \nIt happens at random times, the system just gets slow then after few hours (2-3) it gets back on track with normal response times. \nthis slowness issue is affecting only to one specific MVC View, whereas other MVC views are rendering correctly at the same time when slowness issue occurs.\n\nerror handling is already in place in the .net code, but nothing gets logged in error log file.\nalso DBA has confirmed that there are no issues on the SQL Farm and none of the other projects apart from us has reported slowness issue whose database is also hosted on the SQL Farm. \n\nwhen tried to reproduce the same issue on UAT with the same PROD database copy & same user, was not able to reproduce it.\nUAT environment is exactly similar for WEB & APP server. \nonly in case of UAT database server, we do not have SQL Farm here. we have standalone database server dedicated for our project.\n\nhere tried doing some R&D and verified few things, but still unable to resolve the issue.\nso could you please guide me here that what should i do/verify to resolve this issue.\n\nthank you in advance for your inputs."
] | [
"sql",
"asp.net",
"wcf",
"model-view-controller"
] |
[
"Program with phreads works for some time and then stops",
"I am struggling with a program that uses pthreads. Here is a simplified version of the code I have difficulties with:\n\n#include <cstdlib>\n#include <iostream>\n#include <pthread.h>\n\npthread_t* thread_handles;\npthread_mutex_t mutex;\npthread_cond_t cond_var = PTHREAD_COND_INITIALIZER;\nint thread_count;\nconst int some_count = 76;\nconst int numb_count = 5;\nint countR = 0;\n\n//Initialize threads\nvoid InitTh(char* arg[]){\n /* Get number of threads */\n thread_count = strtol(arg[1], NULL, 10);\n /*Allocate space for threads*/\n thread_handles =(pthread_t*) malloc (thread_count*sizeof(pthread_t));\n}\n\n//Terminate threads\nvoid TermTh(){\n for(long thread = 0; thread < thread_count; thread++)\n pthread_join(thread_handles[thread], NULL);\n free(thread_handles);\n}\n\n//Work for threads\nvoid* DO_WORK(void* replica) {\n /*Does something*/\n pthread_mutex_lock(&mutex);\n countR++;\n if (countR == numb_count) pthread_cond_broadcast(&cond_var);\n pthread_mutex_unlock(&mutex);\n pthread_exit(NULL);\n}\n\n//Some function\nvoid FUNCTION(){\n pthread_mutex_init(&mutex, NULL);\n for(int k = 0; k < some_count; k++){\n for(int j = 0; j < numb_count; j++){\n long thread = (long) j % thread_count;\n pthread_create(&thread_handles[thread], NULL, DO_WORK, (void *)j);;\n }\n /*Wait for threads to finish their jobs*/\n while(pthread_cond_wait(&cond_var,&mutex) != 0);\n countR = 0;\n /*Does more work*/\n }\n pthread_cond_destroy(&cond_var);\n pthread_mutex_destroy(&mutex);\n}\n\n\nint main(int argc, char* argv[]) { \n /*Initialize threads*/\n InitTh(argv);\n\n /*Do some work*/\n FUNCTION();\n\n /*Treminate threads*/\n TermTh();\n\n pthread_exit(NULL);\n}\n\n\nWhen some_count, (in this particular case,) is less than 76, the program works fine, but if I specify a larger value the program works for some time and then stalls. Maybe somebody can point what am I doing wrong?\n\nP.S. this is my first post of this sort ever and I am obviously a newbie, so please be forgiving. :)"
] | [
"c++",
"pthreads"
] |
[
"Adding elements between elements in list",
"If I have a list eg.\n\n[1,2,3]\n\n\nand a function f(), how do I insert such that the new list is like:\n\n[1, f(1), 2, f(2), 3, f(3)]?"
] | [
"python",
"list"
] |
[
"Refresh view after calling webservice",
"Possible Duplicate:\n Refresh view after UIBarButtonItem is clicked \n\n\n\n\nI want to refresh my entire view after clicking a refresh button on my UINavigationBar. The refresh it self works fine, but the view is not picking up the animations. I tried using an NSThread, and it worked, but a got a lot of junk in my console. Is there a good way to do this? \n\nEverything works as it should when my view methods are called, but not when I call the same methods in my action method for my refresh button.\n\nAny ideas?\n\nCode:\n\n-(void)buttonItemClicked{\n NSLog(@\"buttonItemclicked\");\n\n myView.labelName.text = nil;\n myView.otherLabelName.text = nil;\n [spinner startAnimating];\n [spinnerView setHidden:NO];\n [self requestAPI];\n}\n-(void)requestAPI{\n //After requests to the API are done\n [spinner stopAnimating];\n [spinnerView setHidden:YES];\n}\n\n\nin requestAPI method I do the request to the web service and set the spinnerView´s hidden property to YES and [spinner stopAnimating];"
] | [
"iphone",
"objective-c",
"xcode",
"web-services",
"uiview"
] |
[
"How do I get a JPanel with an empty JLabel to take up space in a GridBagLayout",
"I am working on a GUI for a project at school. I am using a GridBagLayout in swing.\n\nI want to have a label indicating the input(a type of file @ x = 0, y = 0), followed by another label(the actual file name once selected @ x = 1, y = 0), followed by a browse button for a file chooser( @ x = 2, y = 0). The label at (1,0) is initially blank, however I want the area that the text will occupy to take up some space when the label contains no text. I also want the space between the label at (0,0) and the button at (2,0) to remain constant.\n\nTo achieve this, I'm trying to put the label onto a panel and then play with the layouts. However I can't seam to achieve the desired results. Could anyone offer some suggestions? The next three rows of the GridBagLayout will be laid out exactly the same way. \n\nHere is a link to a screen shot of the GUI. \n\n\n\n calibrationFileSelectionValueLabel = new JLabel(\"\",Label.LEFT);\n calibrationFileSelectionValueLabel.setName(\"calibrationFileSelection\");\n calibrationFileSelectionValueLabel.setMinimumSize(new Dimension(100,0));\n\n\n\n calibrationFileSelectionValuePanel = new JPanel();\n calibrationFileSelectionValuePanel.setBorder(BorderFactory.createEtchedBorder());\n calibrationFileSelectionValuePanel.add(calibrationFileSelectionValueLabel);\n\n c.gridx = 0;\n c.gridy = 0;\n c.fill = GridBagConstraints.NONE;\n\n filesPanel.add(calibrationFileLabel,c);\n\n c.gridy = 1;\n filesPanel.add(frequencyFileLabel,c);\n\n c.gridy = 2;\n filesPanel.add(sampleFileLabel,c);\n\n c.gridy = 3;\n filesPanel.add(outputFileLabel,c);\n\n c.gridx = 1;\n c.gridy = 0;\n c.fill = GridBagConstraints.BOTH;\n\n // filesPanel.add(calibrationFileSelection,c);\n filesPanel.add(calibrationFileSelectionValuePanel,c);\n\n c.gridy = 1;\n // filesPanel.add(frequencyFileSelection,c);\n filesPanel.add(frequencyFileSelectionValueLabel,c);\n\n c.gridy = 2;\n // filesPanel.add(sampleFileSelection,c);\n filesPanel.add(sampleFileSelectionValueLabel,c);\n\n c.gridy = 3;\n // filesPanel.add(outputFileSelection,c);\n filesPanel.add(outputFileSelectionValueLabel,c);\n\n c.gridx = 2;\n c.gridy = 0;\n c.fill = GridBagConstraints.NONE;\n filesPanel.add(calibrationFileSelectionButton,c);\n\n c.gridy = 1;\n filesPanel.add(frequencyFileSelectionButton,c); \n\n c.gridy = 2;\n filesPanel.add(sampleFileSelectionButton,c);\n\n c.gridy = 3;\n filesPanel.add(createOutputFileButton,c); \n\n panelForFilesPanelBorder = new JPanel();\n panelForFilesPanelBorder.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(5,10,5,10), BorderFactory.createEtchedBorder()));\n panelForFilesPanelBorder.add(filesPanel);\n\n buttonsPanel = new JPanel();\n buttonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER));\n buttonsPanel.setBorder(BorderFactory.createCompoundBorder(new EmptyBorder(5,10,10,10), BorderFactory.createEtchedBorder()));\n buttonsPanel.add(startButton);\n buttonsPanel.add(stopButton);\n basePanel.add(panelForFilesPanelBorder);\n basePanel.add(numericInputPanel); \n basePanel.add(buttonsPanel);"
] | [
"java",
"swing",
"gridbaglayout"
] |
[
"Arraylist and List with Final keyword",
"Which advantages/disadvantages of making ArrayList (or other Collection) final? And what if we try to do so like:\n\nfinal List<Integer> A=new ArrayList<Integer>(1,2,3,4,5);\nList<Integer> l=new ArrayList<Integer>(4,8,16);\nA=l;\n\n\nIs this is valid?\nNow the reference A will point to this Array list pointed by l? Please help."
] | [
"java",
"arraylist",
"final"
] |
[
"Parsing GIF Raster Data - LZW",
"I've been trying to decompress GIF's in PHP and seem to have everything except the LZW decompression down. I have saved an image that is shown: \n\nThis image is 3 x 5 like this:\n\nBlue Black Black\nBlack Blue Black\nBlack Black Black\nWhite White White\nWhite White White\n\n\nI decided to go through manually in Binary and parse this file. The result of manual parsing is below. I am still stuck as to how to decode the raster data here. Can someone break down how the raster data becomes the image? I've been able to break down one image, but nothing else (not this image). I have posted my understanding of how this should break down, but I am obviously doing it wrong.\n\n01000111 G\n01001001 I\n01000110 F\n00111000 8\n00111001 9\n01100001 a\n\nScreen Descriptor\nWIDTH\n00000011 3\n00000000\n\n00000101 5\n00000000\n\n10010001 GCM (1), CR (001), BPP (001), CD = 2, COLORS = 4\n\n00000000 BGCOLOR Index\n\n00000000 Aspect Ratio\n\nGCM\nBLUE\n00110101 | 53\n00000000 | 0\n11000001 | 193\n\nWHITE\n11111111 | 255\n11111111 | 255\n11111111 | 255\n\nBLACK\n00000000 | 0\n00000000 | 0\n00000000 | 0\n\n00000000 | 0\n00000000 | 0\n00000000 | 0\n\nExtension\n00100001 | 21\nFunction Code\n11111001 | F9\nLength\n00000100 | 4\n00000000\n00000000\n00000000\n00000000\nTerminator\n00000000\n\nLocal Descriptor\n00101100 Header\nXPOS\n00000000 | 0\n00000000\n\nYPOS\n00000000 | 0\n00000000\n\nWidth\n00000011 | 3\n00000000\n\nHeight\n00000101 | 5\n00000000\n\nFlags\n00000000 (LCM = 0, Interlaced = 0, Sorted = 0, Reserved = 0, Pixel Bits = 0)\n\nRASTER DATA\nInitial Code Size\n00000010 | 2\nLength\n00000101 | 5\n\nData\n10000100\n01101110\n00100111\n11000001\n01011101\n\nTerminator\n00000000\n\n00111011 | ;\n00000000\n\n\nMy Attempt\n\n10000100\n01101110\n00100111\n11000001\n01011101\n\n\nInitial Code Size = 3\nRead 2 bits at a time\n\n10\n00\nAppend last bit to first (010)\nString becomes 010 or 2. 2 would be color # 3 or BLACK\n\n\nAt this point, I am already wrong. The first color should be blue.\n\nResources I have been using:\n\nhttp://www.daubnet.com/en/file-format-gif\nhttp://en.wikipedia.org/wiki/Graphics_Interchange_Format\nhttp://www.w3.org/Graphics/GIF/spec-gif87.txt"
] | [
"algorithm",
"gif",
"decoding",
"lzw"
] |
[
"R - Getting values from other columns when conditions are met",
"I have a data table something like this. \n\nFirm Year Moveyear Address OriginAddress DestinationAddress\n A 2000 \n A 2001 2001 15Grand_Ave 700Grand_Ave\n A 2002\n A 2003 2003 700Grand_Ave 20Washington_Ave\n A 2004\n B 2000\n B 2001 \n B 2002 2002 2730State_st 40Washington_Ave\n B 2003\n B 2004\n C\n .\n .\n\n\nIt is a panel dataset showing relocation information of each firm for multiple years. I want to add (or assign) address information to 'Address' column by using 'OriginAddress' and 'DestinationAddress' columns. \n\nFor example, 15Grand_Ave should be assigned to Firm A's Address column in 2000 since it was the original address before the firm moves to 700Grand_Ave in 2001. And 700Grand_Ave should be assigned to Firm A's Address column in 2001 and 2002 since it was its address before it moves to 20Washington_Ave in 2003. \n\nSo the result that I want :\n\nFirm Year Moveyear Address OriginAddress DestinationAddress\n A 2000 15Grand_Ave \n A 2001 2001 700Grand_Ave 15Grand_Ave 700Grand_Ave\n A 2002 700Grand_Ave\n A 2003 2003 20Washington_Ave 700Grand_Ave 20Washington_Ave\n A 2004 20Washington_Ave\n B 2000 2730State_st\n B 2001 2730State_st\n B 2002 2002 40Washington_Ave 2730State_st 40Washington_Ave\n B 2003 40Washington_Ave\n B 2004 40Washington_Ave\n C\n .\n .\n\n\nI am guessing I need to use for-loop and ifelse statement in R but I am having trouble with coding. Please share any ideas with me."
] | [
"r",
"for-loop",
"if-statement"
] |
[
"Django rest framework serialize filtered Foreign keys",
"Models.py\n\nclass ModelA(models.Model):\n views = models.PositiveBigIntegerField()\n\n\nclass ModelB(models.Model):\n parent = models.ForeignKey(ModelA, on_delete=models.CASCADE, related_name='modelB', blank=True, null=True)\n string = models.CharField()\n\n\nViews.py\n\nclass ModelAListView(generics.ListAPIView):\n serializer_class = ModelASerialezer\n queryset = ModelA.objects.all().prefetch_related('modelb')\n\n def list(self, request, *args, **kwargs):\n queryset = self.filter_queryset(self.get_queryset())\n\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(queryset.filter(modelb__string__icontains=request.GET['string']), many=True)\n return Response(serializer.data)\n\n\nSerializers.py\n\nclass ModelASerializer(serializers.ModelSerializer):\n id = serializers.ReadOnlyField()\n modelB = ModelBSerializer(source='modelB', many=True, read_only=False)\n\n class Meta:\n model = ModelA\n exclude = ('views',)\n\nclass ModelBSerializer(serializers.ModelSerializer):\n id = serializers.IntegerField(required=False)\n\n class Meta:\n model = ModelB\n fields = '__all__'\n\n\nIf I need to search by \"string\" field I can write\n\nmodelA.objects.filter(modelB__string__icontains=request.GET['string']).values('modelB__string')\n\n\nWhich return ModelB instances only with necessary string values:\n\n<QuerySet [{'modelB__string': 'Test1'}]>\n\n\nWhen I filter by modelb_string I expect to get only filtered FK value:\n\n{\n \"id\": 1,\n \"views\": 0,\n \"modelb\": [\n {\n \"id\": 46,\n \"string\": \"Test1\",\n \"item\": 1\n }\n ]\n}\n\n\nbut I get all FK values:\n\n{\n \"id\": 1,\n \"views\": 0,\n \"modelb\": [\n {\n \"id\": 46,\n \"string\": \"Test1\",\n \"item\": 1\n },\n {\n \"id\": 47,\n \"string\": \"Test85\",\n \"item\": 1\n },\n {\n \"id\": 48,\n \"string\": \"Test64\",\n \"item\": 1\n }\n ]\n}"
] | [
"django",
"django-rest-framework",
"django-serializer"
] |
[
"Inserting data through gsa-template to atg sql with resume on error",
"I am currently trying to insert a large amount of data into my repository through an xml (calling inputFiles within TemplateParser). However when a single record throws an error, like a key constraint, no more records will be processed. I understand it would be good to clean the data so that bad rows are not getting inserted, but because I cannot consistently control our subset of data in the test environments I can't guarantee that the tables referenced by the foreign constraints will have consistent data.\n\nIf I wrap the entire contents in a transaction then no records get inserted, if I wrap it with import-items it fails because of null constraints on the table (import-items tries to insert partial records). Wrapping each element in it's own transaction doesn't trap the error and it inserts each row up to the bad row but nothing after.\n\nIs there another way that to allow for a resume on error scenario while importing data into the repository? Or a way to check constraints within the gsa-template before inserting?\n\nThe file for reference\n\n<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n<!DOCTYPE gsa-template SYSTEM \"dynamosystemresource:/atg/dtds/gsa/gsa_1.0.dtd\">\n<gsa-template>\n<transaction>\n<add-item item-descriptor=\"vendorSku\">\n <set-property name=\"skuItem\"><![CDATA[0065-OC-OS]]></set-property>\n <set-property name=\"vendorSkuId\"><![CDATA[853-6520]]></set-property>\n <set-property name=\"vendorItem\"><![CDATA[781]]></set-property>\n</add-item>\n<add-item item-descriptor=\"vendorSku\">\n <set-property name=\"skuItem\"><![CDATA[0189-CRGONET-ONSI]]></set-property>\n <set-property name=\"vendorSkuId\"><![CDATA[8007146]]></set-property>\n <set-property name=\"vendorItem\"><![CDATA[76]]></set-property>\n</add-item>\netc..\n</gsa-template>"
] | [
"atg"
] |
[
"Minimising number of calls to std::max in nested loop",
"I'm trying to reduce the number of calls to std::max in my inner loop, as I'm calling it millions of times (no exaggeration!) and that's making my parallel code run slower than the sequential code. The basic idea (yes, this IS for an assignment) is that the code calculates the temperature at a certain gridpoint, iteration by iteration, until the maximum change is no more than a certain, very tiny number (e.g 0.01). The new temp is the average of the temps in the cells directly above, below and beside it. Each cell has a different value as a result, and I want to return the largest change in any cell for a given chunk of the grid.\n\nI've got the code working but it's slow because I'm doing a large (excessively so) number of calls to std::max in the inner loop and it's O(n*n). I have used a 1D domain decomposition\n\nNotes: tdiff doesn't depend on anything but what's in the matrix\n\nthe inputs of the reduction function are the result of the lambda function\n\ndiff is the greatest change in a single cell in that chunk of the grid over 1 iteration\n\nblocked range is defined earlier in the code\n\nt_new is new temperature for that grid point, t_old is the old one\n\nmax_diff = parallel_reduce(range, 0.0,\n //lambda function returns local max\n [&](blocked_range<size_t> range, double diff)-> double\n {\n for (size_t j = range.begin(); j<range.end(); j++)\n {\n for (size_t i = 1; i < n_x-1; i++)\n {\n t_new[j*n_x+i]=0.25*(t_old[j*n_x+i+1]+t_old[j*n_x+i-1]+t_old[(j+1)*n_x+i]+t_old[(j-1)*n_x+i]);\n tdiff = fabs(t_old[j*n_x+i] - t_new[j*n_x+i]);\n diff = std::max(diff, tdiff);\n } \n }\n return diff; //return biggest value of tdiff for that iteration - once per 'i'\n },\n //reduction function - takes in all the max diffs for each iteration, picks the largest\n [&](double a, double b)-> double\n {\n convergence = std::max(a,b);\n return convergence;\n }\n );\n\n\nHow can I make my code more efficient? I want to make less calls to std::max but need to maintain the correct values. Using gprof I get:\n\nEach sample counts as 0.01 seconds.\n % cumulative self self total \n time seconds seconds calls ms/call ms/call name \n 61.66 3.47 3.47 3330884 0.00 0.00 double const& std::max<double>(double const&, double const&)\n 38.03 5.61 2.14 5839 0.37 0.96 _ZZ4mainENKUlN3tbb13blocked_rangeImEEdE_clES1_d\n\n\nETA: 61.66% of the time spent executing my code is on the std::max calls, it calls over 3 million times. The reduce function is called for every output of the lambda function, so reducing the number of calls to std::max in the lambda function will also reduce the number of calls to the reduce function"
] | [
"parallel-processing",
"tbb",
"processing-efficiency"
] |
[
"Autoconfig prevent my website redirection to https",
"I have a website in an apache server and a mail server in the same machine. I want the port 80 request redirecting to https 443 port, so I put it in the vhost configuration.\n\nI also want an autoconfig (Mozilla thunderbird use) for my mailserver. However I need to put a config-v1.1.xml accessible on port 80.\n\nThe problem is when I request http://example.com it's does not redirect to https://example.com like I want to but it redirects to the autoconfig.\n\nIs there a way to keep autoconfig and have a redirection to https://example.com ?\n\nI have setup a dns record for autoconfig.example.com and call it in vhost file but when I type mysite.com, it still goes in the autoconfig.\n\nAny clues ?\nThanks\n\nHere is the autoconfig.conf\n\nListen 80\nListen 443\n<VirtualHost 178.33.235.19:80>\n ServerName autoconfig.example.com\n DocumentRoot /var/www/html/autoconfig/\n <Directory /var/www/html/autoconfig>\n Order allow,deny\n allow from all\n </Directory>\n</VirtualHost>\n\n\nAnd the site vhost example.conf\n\n<VirtualHost *:80>\n ServerName example.com\n ServerAlias www.example.com\n RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]\n</VirtualHost>\n\n<VirtualHost _default_:443>\n ServerAdmin [email protected]\n DocumentRoot /var/www/html/example/\n DirectoryIndex index.php\n\n ServerName example.com\n ServerAlias www.example.com\n\n #SSL Config\n SSLCipherSuite RC4-SHA:AES128-SHA:HIGH:!aNULL:!MD5\n SSLHonorCipherOrder on\n SSLCertificateFile /etc/httpd/ssl/STAR_example_com.crt\n SSLCertificateKeyFile /etc/httpd/ssl/STAR_example_com.key\n SSLCertificateChainFile /etc/httpd/ssl/COMODORSADomainValidationSecureServerCA.crt\n\n <Directory /var/www/html/>\n Options FollowSymLinks Indexes MultiViews\n AllowOverride All\n LogLevel crit\n Require all granted\n </Directory>\n\n ErrorLog /var/log/apache/example-error_log\n CustomLog /var/log/apache/example-access_log common\n\n</VirtualHost>"
] | [
"apache"
] |
[
"Update background color around MediaPlayerElement",
"I have a MediaPlayerElement in a Grid and i want to change the black background to White when I resize the window. I horizontally stretched the MPE so I want to update the component color, not the grid one. \n\nHow can I do that ? I tryed to update the MPE style without success...\n\n<Page x:Class=\"ToDelete.MainPage\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\"\n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n mc:Ignorable=\"d\"\n Background=\"{ThemeResource ApplicationPageBackgroundThemeBrush}\">\n\n <Page.Resources>\n <Style x:Key=\"MediaPlayerElementStyle1\" TargetType=\"MediaPlayerElement\">\n <Setter Property=\"HorizontalAlignment\" Value=\"Stretch\"/>\n <Setter Property=\"VerticalAlignment\" Value=\"Stretch\"/>\n <Setter Property=\"IsTabStop\" Value=\"False\"/>\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"MediaPlayerElement\">\n <Grid x:Name=\"LayoutRoot\">\n <Border Background=\"Transparent\"/>\n <Image x:Name=\"PosterImage\" Stretch=\"{TemplateBinding Stretch}\" Source=\"{TemplateBinding PosterSource}\" Visibility=\"Collapsed\"/>\n <MediaPlayerPresenter x:Name=\"MediaPlayerPresenter\" IsFullWindow=\"{TemplateBinding IsFullWindow}\" MediaPlayer=\"{TemplateBinding MediaPlayer}\" Stretch=\"{TemplateBinding Stretch}\"/>\n <ContentPresenter x:Name=\"TransportControlsPresenter\" Visibility=\"{TemplateBinding AreTransportControlsEnabled}\" />\n <Grid x:Name=\"TimedTextSourcePresenter\"/>\n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n\n </Page.Resources>\n\n <Grid Background=\"White\">\n\n <MediaPlayerElement x:Name=\"mpe\" \n Style=\"{StaticResource MediaPlayerElementStyle1}\" \n Source=\"ms-appx:///Assets/nyancat.mp4\"\n AreTransportControlsEnabled=\"False\" \n HorizontalAlignment=\"Stretch\" />\n\n </Grid>\n </Page>"
] | [
"c#",
"xaml",
"uwp",
"uwp-xaml"
] |
[
"ENV variable in json",
"We have a xxx.json which describes which data access layer our app has to use:\n\n{\n \"service_base\": \"https://xxxx.com\",\n \"resource_base\": \"/build/resources\",\n \"template_base\": \"build/templates/dir\"\n}\n\n\nThe Gulp build will use this file to build the application. Now we are using different dal's so we want to use an environment variable to pass with the gulp build command. How do we have to obtain this?\n\nI read it's not possible to declare env vars in JSON. We tried something as this but didn't work:\n\n{\n \"service_base\": process.env.DAL_ENV,\n \"resource_base\": \"/build/resources\",\n \"template_base\": \"build/templates/dir\"\n}\n\n\nAnd trying to pass the env var DAL_ENV to our gulp build command."
] | [
"json",
"gulp"
] |
[
"Terminal path is not an actual place",
"When I opened terminal today, all commands (ls,touch, python ...) don't work. I look up online and find out it is because the path in terminal gets replaced. So I open the .bash_profile and find this below. I comment out the last line and terminal gets normal again.\n\nSo I have this question, where does the last line come from? And what are those special characters?\n\n(The day before, I installed pygames. Is it possible cause?)\n\n #added by Anaconda3 4.3.1 installer\nexport PATH=\"/Users/test/anaconda/bin:$PATH\"\nexport PATH=‚Äô/usr/local/bin:Äô"
] | [
"python",
"macos",
"terminal",
"path"
] |
[
"Inserting JavaScript giving errors in GoogleMaps",
"I have two json arrays with which I am trying to produce Markers on a Map.\nI'm getting the error:\n\nAttempted import error: 'find' is not exported from './data/geoData.json' (imported as 'geoData').\n\nwhile trying to find the zip in the geoData array within the JS for the position...\nAs noted, the console.log() returns the correct value.\nimport React from 'react';\nimport { GoogleMap, withScriptjs, withGoogleMap, Marker} from 'react-google-maps';\nimport styles from 'styled-components';\nimport * as zips from "./data/zips.json";\nimport * as geoData from "./data/geoData.json";\n\nfunction googleMap () {\n return (\n <GoogleMap\n defaultZoom={5.0}\n defaultCenter={{lat: 38.5, lng: -98.5556}}\n >\n { zips['zipCodes'].map(zip => {\n console.log(geoData.find(elm => elm.fields.zip === zip['Recipient_Postal_Code']).fields.latitude); // I get the number\n console.log(typeof geoData);\n console.log(typeof geoData[0].fields);\n console.log(typeof geoData[0].fields.latitude);\n <Marker\n key = {zip['Shipment_Tracking_Number']}\n position = {{\n lat: geoData.find(elm => elm.fields.zip === zip['Recipient_Postal_Code']).fields.latitude,\n lng: geoData.find(elm => elm.fields.zip === zip['Recipient_Postal_Code']).fields.longitude\n }} />\n })}\n </GoogleMap>\n )\n}\n\nConsole output:\n34.197737\nobject\nobject\nnumber"
] | [
"javascript",
"reactjs",
"google-map-react"
] |
[
"change text to image and back on button at runtime in Android",
"I want to change a button's text to an image, and back (instead the image I want the text back) on some user interactions, at RUNTIME.\nHow can I do this? Can anyone show me an example?\n\nAs far as I understood I can't use Image Button, because I can't add text on it.\nI tried to use\n\nsetCompoundDrawables\n\n\nbut this is not working for me (no visible change on button). Here is my code:\n\n Button button = (Button) findViewById(R.id.button1);\n\n Drawable myDrawable = this.getResources().getDrawable(R.drawable.ic_launcher);\n myDrawable.setBounds(0, 0, 0, 0);\n\n button.setCompoundDrawables(myDrawable, null, null, null);\n\n\nPlease help"
] | [
"android",
"button"
] |
[
"Normalizing values in SQL query",
"I have an data table I wish to perform some numeric analysis on for that I need all the values to be in the same range. 0..1.\n\nI have a somewhat slow and longhanded way of accomplishing this but would like a more straigt forward performant solution to my problem\n\nWhat I need to do is:\n\ngroup by projectid\nwith in each project take the average of each of the values and divide by the largest average for the entire set.\n\ncurrently I have\n\nselect avg(foo * 1.0)/ (Select MAX(IL) FROM (select avg(foo * 1.0) as IL from table group by \n ProjectID) tbl)\nfrom table\n\n\nso if the list is\n\nprojectid | foo\n-----------------\n1 | 1\n1 | 2\n2 | 4\n2 | 2\n\n\nthe largest average is 3 and the result should therefor be\n\n0.5,1\n\nwhere the first is the average for projectId 1 divided by 3 and the second is the average for projectId 2 divided by 3"
] | [
"sql",
"sql-server",
"sql-server-2008",
"tsql"
] |
[
"Rails 5 IntegrationTest with IP Geolocation",
"I'm making use of the geokit-rails gem to perform geolocation based on the IP address of the user who is logging in via #geocode_ip_address (https://github.com/geokit/geokit-rails#ip-geocoding-helper).\n\nHowever, I'm having a very hard time finding a way to test this via the Rails 5 IntegrationTest. I need a way to provide multiple remote IP addresses when simulating a login but I am stuck on the following issues:\n\n\nhow to spoof an IP address (that will vary based on the user logging in)\nhow to prevent making a ton of requests to the geolocation service \n\n\nMy original approach was to just skip it and place the :geo_location information in the session hash, however this seems to have gone away in Rails 5 per https://github.com/rails/rails/issues/23386.\n\nAnybody have experience with a similar set-up?"
] | [
"ruby-on-rails",
"geolocation",
"integration-testing",
"ruby-on-rails-5",
"geokit"
] |
[
"Methods Limit 65k - Google Play Services and ADT",
"I've seen some questions about it ( Question 1 and since I can't use gradle in eclipse, I don't know another option) but I don't have any idea to solve it.\n\nSo, here is the thing: I updated my ADT and my Play Services to implement the new way to get the user's location (I'm using ADT). Since I did it, I'm facing the problem that I have more than 65k methods in my project. I tried to change the proguard as Android Developers recomends, but nothing happens. So, maybe the proguard isn't enabled in my Android app! I tried to see it here, but I realized that I don't have the proguard.cfg file in any of my projects!\n\nHow can I solve it? I just use few things in Play Services (GCM and Location)."
] | [
"android",
"android-multidex"
] |
[
"Break li element content",
"I want to display li elements in ul element as one inline text, and on smaller screens I want the last li element to be displayed in the next line.\nThis is my example :\n\r\n\r\nul {\n list-style: none;\n padding: 0;\n margin: 0;\n display: flex;\n flex-wrap: wrap;\n}\n\nli {\n font-size: 16px;\n text-transform: uppercase;\n word-break: break-word;\n overflow-wrap: break-word;\n list-style: none;\n}\n\nli:not(:last-child)::after {\n content: \"\";\n display: inline-block;\n vertical-align: middle;\n width: 6px;\n height: 6px;\n border-radius: 50%;\n background: #9aa6c4;\n margin: 0 12px;\n}\r\n<ul>\n <li>Word</li>\n <li>26-OCT-20</li>\n <li>LOOOOOOOOOOOOOOOOOOOOOOOOOOONG TEEEEEEEEEEEEEEXT</li>\n <li><a href=\"#\">Link</a></li>\n</ul>\r\n\r\n\r\n\nSo here on smaller screen I want all the li elements except the last one to act line one line, so the text will break and not the li elements, but the last li element will always break to the next line if there is no space left.\nFor example I want this:\n\nInstead of this :\n\nHow can I solve this (without using media queries)?"
] | [
"css"
] |
[
"Indirect Population of Textarea in HTML Form Using PHP",
"I am working on an \"Update User Data\" form, which should reflect the initially entered information stored in the database into the textarea, and can be changed if the user wishes to. While I'm doing so, I have a concern - is directly writing value = <?php //some code ?> the safest bet? \n\nI was trying to invoke a function to place my PHP code in that instead, but apparently it's just displaying the function's name. \n\nHere's my code snippet: \n\n<div>Date of Birth: </div>\n <input id=\"dob\" type=\"date\" onFocus=\"emptyElement('status')\" value=\"reflect_data('dob');\">\n\n\nwhere the function reflect_data is defined as - \n\nfunction reflect_data(elem) {\n//query and some code to access the data and store into $member\n\nif (elem == \"dob\") {\n echo $member['DOB'];\n exit();\n}\n\n\nNOTE : A newbie to PHP, any advice would be welcome. Thanks. :)"
] | [
"javascript",
"php",
"html"
] |
[
"Getting null pointer exception while sending selected row data to servlet",
"I want to display selected Row data from jsp page to another jsp page.For taht i am passing selected row data to servlet using the hidden id. But I am getting the null pointer exception while sending data from jsp to Servlet.\n\nplease find my below code:\n\nIn jsp code:\n\n <tr > \n <form action=\"DisplayData\" method=\"get\">\n <TD ><%=item.getAPPLICATIONID()%></TD>\n <TD><%=item.getAPPLICATIONNAME()%></TD>\n <input type=\"hidden\" id=\"sid\" name=\"sid\" value=<%=item.getAPPLICATIONID() %>>\n\n <TD><input type=\"submit\" value=\"Submit\" ></TD>\n <%\n\n}\n\n\nServlet Code:\n\nprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {\n\n DBConnection db=new DBConnection();\n HttpSession hs = request.getSession();\n Integer pid =(Integer) request.getAttribute(\"sid\");\n List<ApplicationList> dbean=db.getAllaplicationsList(pid);\n hs.setAttribute(\"detbean\",dbean);\n response.sendRedirect(\"Output.jsp\");\n\n}\n\n\nI am getting null pointer Exception in Servlet page. The value is pid is showing null.Could you please suggest me how can resolve this issue."
] | [
"java"
] |
[
"How to design divider Textfield in flutter",
"I want to design textfield in flutter like this"
] | [
"android",
"flutter"
] |
[
"Would this simple code cause a memory leak?",
"Say you have the following C++ code snippet:\n\nclass base {};\nclass derived : public base {\npublic:\n std::string str;\n};\n\nint main() {\n base *b = new derived();\n delete b;\n}\n\n\nThis would leak, right? derived's string's destructor is never being called because base's destructor isn't marked as virtual. Or am I misunderstanding something?"
] | [
"c++",
"inheritance",
"memory-leaks",
"virtual",
"destructor"
] |
[
"Images uploaded from mobile are sideways",
"I have a site that's live and getting new signups. I am running into an issue. Most of my users come from mobile, and when you upload a profile picture from mobile, then it's sideways. It's weird because it doesn't do that in the desktop version. \n\nIs there a fix for this? I've been searching for hours and can't seem to find anything. \n\nI would like to check for the image direction and save it so it appears upright. \n\nEDIT: I am using lepozepo:s3 and uploading directly to amazon s3."
] | [
"javascript",
"jquery-mobile",
"mobile",
"meteor"
] |
[
"add new Project to existing github Repo",
"I am developing a Client-Server application and I want to store both projects (Client and Server) on github the same github repo.\nI am on macosx.\nI created a local repository for the client side project with Eclipse git plugin and then I committed it to github. It worked fine.\n\nNow I want to add to this Repo the server side project possibly inside a new subfolder. This part is developed on a different workspace than the client part. I tried to share the project using Eclipse, but it tells me there is no existing repo. I think this is because the two parts of the system are developed with different Eclipse IDEs.\n\nI tried to create a new repo under the first one, but it became a great mess because github couldn't understand which was the master.\nI am using the GitHub client application to manage commits to the remote repo.\n\nSomeone can help me?\n\nThanks"
] | [
"git",
"github",
"commit",
"repository"
] |
[
"It is possible to configure functions with subtype overloading?",
"When using CREATE TABLE it is possible to declare varchar(12), varchar(34) or varchar datatypes, and it will be different...\n\nBut when declaring a function, the \"subtype\" is ignored... No warning (!)... I see that to ignore is a good thing, the function signature is essential to manage function overloading, and \"subtype signatures\" will be a something chaotic to manage... But I not see in the Guide (also nothing at typeconv-func), no Guide's warning about it, no explanation. \n\nSo, in nowadays, 2018, after all PostgreSQL v10+ enhancements... Can I configure PostgreSQL to accept function overloading with subtypes? \n\n\n\nConcrete example\n\nCREATE TABLE foo ( x varchar(12), y varchar(34), z varchar );\n\\d foo\n-- not ignored, as expected \n\nCREATE OR REPLACE FUNCTION foo( p_x varchar ) RETURNS text AS \n$f$ SELECT 'hello1' $f$ LANGUAGE SQL IMMUTABLE;\nCREATE OR REPLACE FUNCTION foo( p_x varchar(12) ) RETURNS text AS \n$f$ SELECT 'hello10' $f$ LANGUAGE SQL IMMUTABLE;\n\n\\df foo\n List of functions\n Schema | Name | Result data type | Argument data types | Type \n--------+------+------------------+-----------------------+--------\n public | foo | text | p_x character varying | normal\n (1 row)\n\n\nSo it is impossible to declare foo(x) that not do the same tham foo(z)... \n\n SELECT pg_typeof(x),pg_typeof(y),pg_typeof(z) FROM foo;\n -- returns \"character varying\" for all\n\n\n\n\nOf course, sometimes we can use pg_typeof():\n\n\nWith VARCHAR(s) is impossible to check s.\nWith PostGIS's geometry is possible to check subtype (e.g. POINT subtype). It is an overload workaround, but not \"real overload\". \n\n\n\n\nNOTE: the parsing error with the commented foo('abc') will be solved with adequate \"orthogonal overloading function set\". In the example, with \n\nCREATE FUNCTION foo( p_x text ) RETURNS text AS $f$ SELECT 'hello-text' \n$f$ LANGUAGE SQL IMMUTABLE;\n\n\nthe \"automatic cast abc to text\" solve the problem select foo('abc') is working."
] | [
"postgresql",
"overloading"
] |
[
"Sails.js swig template not working",
"I installed Sails.js 0.9.4 and created an application that uses the swig template engine with the following command:\n\nsails new sailsproject--template=swig\n\n\nWhen I try to run the app via sails lift I get the following error:\n\nC:\\Users\\akis\\Desktop\\sailsproject>sails lift\n\nC:\\Users\\akis\\AppData\\Roaming\\npm\\node_modules\\sails\\node_modules\\express\\lib\\ap\nplication.js:174\n if ('function' != typeof fn) throw new Error('callback function required');\n ^\nError: callback function required\n at Function.app.engine (C:\\Users\\akis\\AppData\\Roaming\\npm\\node_modules\\sails\n\\node_modules\\express\\lib\\application.js:174:38)\n at Array.loadExpress [as 1] (C:\\Users\\akis\\AppData\\Roaming\\npm\\node_modules\\\nsails\\lib\\express\\index.js:70:7)\n at listener (C:\\Users\\akis\\AppData\\Roaming\\npm\\node_modules\\sails\\node_modul\nes\\async\\lib\\async.js:462:46)\n at C:\\Users\\akis\\AppData\\Roaming\\npm\\node_modules\\sails\\node_modules\\async\\l\nib\\async.js:416:17\n at Array.forEach (native)\n at _each (C:\\Users\\akis\\AppData\\Roaming\\npm\\node_modules\\sails\\node_modules\\\nasync\\lib\\async.js:32:24)\n at Object.taskComplete (C:\\Users\\akis\\AppData\\Roaming\\npm\\node_modules\\sails\n\\node_modules\\async\\lib\\async.js:415:13)\n at processImmediate [as _immediateCallback] (timers.js:330:15)\n\nC:\\Users\\akis\\Desktop\\sailsproject>\n\n\nDoes anyone know why? It works perfectly with jade or ejs and the docs in the /config/views.js file state that Sails supports other templates as well (including swig)."
] | [
"javascript",
"node.js",
"express",
"sails.js",
"swig-template"
] |
[
"F# Generics not so generic",
"I've come up against this a couple of times, but I'm really at a loss as to why it happens.\n\nI've got a discriminated union like:\n\ntype MStep<'A, 'B> =\n| Shuttle of Quotations.Expr<'B> * Quotations.Expr<'B>\n\n\nThere's more to the union, but this shows the basic problem.\n\nIf I do:\n\nlet s1 = Shuttle(<@ l.SomeIntProp @>, <@ r.SomeIntProp @>)\nlet s2 = Shuttle(<@ l.SomeStrProp @>, <@ r.SomeStrProp @>)\n\n\nI get a compiler error:\n\n\n This expression was expected to have type int, but here has type string\n\n\nLikewise, if I create them in the other order (string then int), I get the same error but the other way around.\n\nI can see that the compiler is likely inferring 'B based on my usage, but what if I want 'B to be truly generic?\n\n\n\nAs requested here is a more complete example:\n\ntype MStep<'A, 'B> =\n | Shuttle of Quotations.Expr<'B> * Quotations.Expr<'B>\n | Ident of Quotations.Expr<'B>\n | Trans of Quotations.Expr<'A> * Quotations.Expr<'B> * ('A -> 'B)\n\nlet doMig (f:Table<'A>, t:Table<'B>, s:('A * 'B -> MStep<'C, 'D> list)) =\n ignore()\n\nlet a = doMig(bpdb.Adjustments, ndb.Adjustments, (fun (l,r) ->\n [\n Shuttle(<@ l.Id @>, <@ r.Id @>)\n Shuttle(<@ l.Name @>, <@ r.Name @>)\n ]\n ))\n\n\nThis produces the compiler error as seen above.\n\nNOTE:\n\nbpdb and ndb are both database contexts provided by the SqlDataConnection type provider.\n\nThe open namespaces are:\n\nopen System\nopen System.Data\nopen System.Data.Linq\nopen Microsoft.FSharp.Data.TypeProviders\nopen Microsoft.FSharp.Linq\nopen System.Xml\nopen System.Xml.Linq\nopen Microsoft.FSharp.Quotations.Patterns\nopen System.Reflection\nopen System.Diagnostics"
] | [
"generics",
"f#",
"c#-to-f#"
] |
[
"Comparing two date vectors with function in R to avoid loop and dealing with NA",
"There is probably a very trivial workaround to this, but here goes... I am trying to compare two date vectors in R (not originally input as date vectors) to: return the first value if the second is NA and the first is not missing; to return the largest of the two dates if the second is not missing; or to return NA if both values are missing. For example, for data presented below, I'd like lastdate to compute as follows:\n\nv1 v2 lastdate\n1/2/2006 NA 1/2/2006\n1/2/2006 12/2/2006 12/2/2006\nNA NA NA\n\n\nI have written a formula to avoid looping over each row (85K in these data) as follows:\n\nlastdate <- function(lastdate1,lastdate2){\n if (is.na(lastdate1)==T & is.na(lastdate2)==T) {NA}\n else if (is.na(lastdate2)==T & !is.na(lastdate1)) {as.Date(lastdate1,format=\"%m/%d/%Y\")}\n else {max(as.Date(lastdate2,format=\"%m/%d/%Y\"),as.Date(lastdate1,format=\"%m/%d/%Y\"))}\n}\ndfbobs$leaveobsdate <- lastdate(as.Date(dfbobs$leavedate1,format=\"%m/%d/%Y\"),as.Date(dfbobs$leavedate2,format=\"%m/%d/%Y\"))\n\n\nThe last line is telling it to compare two vectors of dates, but is not quite right as I am getting the errors\n\nWarning messages:\n1: In if (is.na(lastdate1) == T & is.na(lastdate2) == T) { :\n the condition has length > 1 and only the first element will be used\n2: In if (is.na(lastdate2) == T & !is.na(lastdate1)) { :\n the condition has length > 1 and only the first element will be used\n\n\nI'm sure this is very silly and there's probably a much easier way to do this, but any help would be appreciated.\n\nEDIT: I have now attempted this with an ifelse function to deal with the vectors, as suggested, but the comparison, while working if I type in single values (e.g., lastdate(\"1/1/2006\",\"1/2/2006\")), produces NAs if I try it on the dataframe vectors. The code follows: \n\nlastdate <- function(lastdate1,lastdate2){\nifelse(is.na(lastdate1==T) & is.na(lastdate2==T), NA, \n ifelse(is.na(lastdate2)==T & !is.na(lastdate1), as.Date(lastdate1,format=\"%m/%d/%Y\"), \n ifelse(!is.na(lastdate2) & !is.na(lastdate1), max(as.Date(lastdate2,format=\"%m/%d/%Y\"),as.Date(lastdate1,format=\"%m/%d/%Y\")),NA)))\n}\ndfbobs$leaveobsdate <- as.Date(lastdate(as.Date(dfbobs$leavedate1,format=\"%m/%d/%Y\"),as.Date(dfbobs$leavedate2,format=\"%m/%d/%Y\")),origin=\"1970-01-01\")"
] | [
"r",
"date",
"vector"
] |
[
"Laravel: /resource gives 403 Forbidden",
"I want to create the url my-domain.dev/resources so I added this to my Route file:\n\nRoute::get('/resources', function(){\n dd('hi');\n});\n\n\nHowever, this is not working. I only get a 403 Forbidden error:\n\n\n\nAll other routes are working fine. Is it not possible to set this route in Laravel 5.5 ?"
] | [
"php",
"laravel-5"
] |
[
"Objective C Parse Query Results Using Two Classes Where Equals",
"I currently have a Parse query in objective c that uses one class (Photo) to retrieve data.\n\nPFQuery *photosFromUsersQuery = [PFQuery queryWithClassName:@\"photo\"];\n[photosFromUsersQuery whereKeyDoesNotExist:@\"type\"];\n[photosFromUsersQuery whereKeyExists:kESPhotoPictureKey];\n[photosFromUsersQuery whereKey:@\"createdAt\" greaterThanOrEqualTo:sevenDaysAgo];\n\nPFQuery *videosFromUserQuery = [PFQuery queryWithClassName:self.parseClassName];\n[videosFromUserQuery whereKeyExists:@\"type\"];\n[videosFromUserQuery whereKey:@\"createdAt\" greaterThanOrEqualTo:sevenDaysAgo];\n\nPFQuery *query = [PFQuery orQueryWithSubqueries:[NSArray arrayWithObjects:photosFromUsersQuery, videosFromUserQuery, nil]];\n\n[query includeKey:kESPhotoUserKey];\n[query orderByDescending:@\"createdAt\"];\n\n\nI now need to use a second class (user) which is a pointer in both classes.I want to filter the data from the query above to only display data where the user has a Public profile.In the user class, I have a column called privacy which either contains a value of Public or Private.\n\nI have tried many approaches but none have worked.Please help me accomplish this task.\n\nThank you"
] | [
"objective-c",
"xcode",
"parse-platform"
] |
[
"How to update lot of files with Github API?",
"I need in updating lot of files in my repo via php-script.\nI read api documentation and i can update any file with PUT request\n\n....\n$update = array(\"message\"=>\"COMMIT\", \"content\"=>base64_encode($test), \"sha\"=>$json[\"sha\"]);\nput(url, $data_string);\n....\n\n\nBut if i need to update 2000 files? It's too not convenient. Are there ways to manipulate with files by single request? And if yes, can smb give sample of such code?"
] | [
"php",
"github-api"
] |
[
"Receive Parameter in spring MVC controller",
"@RequestMapping(value = \"/Fin_AddCheckBook\", method = RequestMethod.POST)\npublic @ResponseBody\nJsonResponse addCoaCategory(\n @RequestParam(value=\"checkbookNumber\", required=true) String checkbookNumber,\n @RequestParam(value=\"checkbookName\", required=true) String checkbookName,\n @RequestParam(value=\"startNumber\", required=true) long startNumber,\n @RequestParam(value=\"bankId\", required=true) long bankId,\n @RequestParam(value=\"currencyId\", required=true) long currencyId,\n @RequestParam(value=\"noOfLeves\", required=true) int noOfLeves,\n @RequestParam(value=\"alertAt\", required=true) int alertAt,\n @RequestParam(value=\"isActive\", required=true) int isActive, Map map, Model model) {\n\n\nI have two table in one form ! I want to receive first table elements by name by specifying @RequestParam(value=\"startNumber\", required=true) long startNumber; \nbut\nsecond table elements in Map i.e Map map\n\nHow to receive some parameter with name and all other element in map ?"
] | [
"java",
"spring",
"parameters"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.