texts
sequence | tags
sequence |
---|---|
[
"login page without header/breadcrumb/footer",
"I using PrimeNG theme with Angular. I want create login component, which contains login form. I create component:\n\nng generate component login\n\n\nand add to app.routes.ts:\n\nimport {Routes, RouterModule} from '@angular/router';\nimport {ModuleWithProviders} from '@angular/core';\nimport {CampaignsOverviewComponent} from \"./campaigns/campaigns-overview/campaigns-overview.component\";\nimport {LoginComponent} from \"./login/login.component\";\n\nexport const routes: Routes = [\n {path: '', redirectTo: '/campaigns', pathMatch: 'full'},\n {path: 'campaigns', component: CampaignsOverviewComponent},\n {path: 'login', component: LoginComponent}\n];\n\nexport const AppRoutes: ModuleWithProviders = RouterModule.forRoot(routes, {\n useHash: true\n});\n\n\nWhen I follow to the 'login' page, I see:\n\n\n\nAs you can see, my component is embedded inside. But, I need to display my page on top of everything, so that the page has only the authorization form, without titles, menus and other things. How can this be done?"
] | [
"angular",
"angular6",
"primeng"
] |
[
"Implementing dynamic menu for Spring MVC/AOP application",
"I wish to implement dynamically changeable menu (updating whenever annotated method or controller added) for my Spring MVC application.\n\nWhat i want is to introduce new annotation (@RequestMenuMapping) which will go to @Controller beans and their methods (just like @RequestMapping works).\n\nHeres is what i want, User class, producing menu like\n\nUsers\n Index | List | Signup | Login\n\n\nwith following code:\n\n@Controller\n@RequestMapping(\"user\")\n@RequestMenuMapping(\"Users\")\npublic class User {\n\n @RequestMapping(\"\")\n @RequestMenuMapping(\"Index\")\n public String index(/* no model here - just show almost static page (yet with JSP checks for authority)*/) {\n return \"user/index.tile\";\n }\n\n @RequestMapping(\"list\")\n @RequestMenuMapping(\"List\")\n public String list(Model model) {\n\n model.addAttribute(\"userList\",/* get userlist from DAO/Service */);\n\n return \"user/list.tile\";\n }\n\n @RequestMapping(\"signup\")\n @RequestMenuMapping(\"Signup\")\n public String signup(Model model) {\n\n model.addAttribute(\"user\",/* create new UserModel instance to be populated by user via html form */);\n\n return \"user/signup.tile\";\n }\n\n @RequestMapping(\"login\")\n @RequestMenuMapping(\"Login\")\n public String login(Model model) {\n\n model.addAttribute(\"userCreds\",/* create new UserCreds instance to be populated via html form with login and pssword*/);\n\n return \"user/login.tile\";\n }\n}\n\n\nI think that Spring AOP may help me to pointcut methods with @RequestMenuMapping annotation and via @AfterReturning add something representing web-site menu to model.\n\nBut this raises two questions:\n\n\nHow do i get Model instance in @AfterReturning advice method in case it is missing in adviced method (as in .index())?\nHow do i get all methods (as in java reflection Method) and classes (as in java reflection Class) annotated with @RequestMenuMapping in order to build complete menu index?"
] | [
"java",
"spring",
"spring-mvc",
"aop",
"spring-aop"
] |
[
"Sort data in Axios response and set as useReducer payload",
"I'm calling data from an api into my react app using axios, like so:\nconst adapter = axios.create({\n baseURL: "http://localhost:4000",\n});\n\nconst getData = async () => {\n const response = await adapter.get("/test-api");\n return response.data;\n};\n\nThis runs in a context, and I have a basic reducer function that I pass to the context:\nconst initialState = {\n loading: true,\n error: false,\n data: [],\n errorMessage: "",\n};\n\nconst reducer = (state, action) => {\n switch (action.type) {\n case ACTIONS.FETCH_SUCCESS:\n return {\n ...state,\n loading: false,\n data: action.payload,\n };\n case ACTIONS.FETCH_ERROR:\n return {\n ...state,\n error: true,\n errorMessage: "Error loading data",\n };\n default:\n return state;\n }\n};\n\nThe data I'm returning from my api is shaped like this:\n{\n "data": [\n {\n "id": 1,\n "name": "Name 1",\n "items": [\n {\n "id": "klqo1gnh",\n "name": "Item 1",\n "date": "2019-05-12"\n }\n ]\n },\n {\n "id": 2,\n "name": "Name 2",\n "items": [\n {\n "id": "klqo2fho",\n "name": "Item 1",\n "date": "2021-05-05"\n },\n {\n "id": "klro8wip",\n "name": "Item 2",\n "date": "2012-05-05"\n }\n ]\n }\n ]\n}\n\nAnd I've written a simple function that finds the item whose nested array, items here, has the earliest date, using moment:\nconst sortDataByDate = (items) => {\n return items.sort((first, second) => {\n if (moment(first.items.date).isSame(second.items.date)) {\n return -1;\n } else if (moment(first.items.date).isBefore(second.items.date)) {\n return -1;\n } else {\n return 1;\n }\n });\n}; \n\nI then fetch everything in this function:\nconst fetchData = useCallback(async () => {\n try {\n await getData().then((response) => {\n dispatch({\n type: ACTIONS.FETCH_SUCCESS,\n payload: response,\n });\n });\n } catch (error) {\n dispatch({ type: ACTIONS.FETCH_ERROR });\n }\n }, []);\n\nI then run fetchData() inside a useEffect within my context:\nuseEffect(() => {\n fetchData();\n}, [fetchData]);\n\nAll this to say, here's the problem. My sortDataByDate function works sporadically; sometimes the data is ordered correctly, other times it's not. What I'd like to do is fetch my data, sort it with sortDataByDate, and then set the payload with that sorted data, so it's sorted globally rather than on a component level. Inside my App it seems to work consistently, so I think that I have missed something on a context level. Any suggestions?"
] | [
"reactjs",
"axios",
"react-hooks",
"reducers",
"use-context"
] |
[
"Custom ribbon Excel XML",
"I would like to create a custom item in MS Excel using XML. Within this item there will be several groups and within each groups a number of buttoms to callback vba macros. \n\nI am able to set up a single group many button XML (Code 1), but I am unable to set up several groups with a number of buttons (Code 2).\n\nI am not familiar with XML, so I would appreciate your insights where I am going wrong.\n\nCode 1\n\n<customUI xmlns=\"http://schemas.microsoft.com/office/2009/07/customui\">\n <ribbon startFromScratch=\"false\">\n <tabs>\n <tab id=\"customTab\" label=\"AA PAYMENTS APP\" insertAfterMso=\"TabView\">\n <group id=\"customGroup\" label=\"Group 1\">\n <button id=\"customButton\" label=\"Test1\" imageMso=\"HyperlinkInsert\" size=\"large\" onAction=\"Callback\" />\n <button id=\"customButton2\" label=\"JG Button 2\" imageMso=\"PictureBrightnessGallery\" size=\"large\" onAction=\"Callback2\" />\n <button id=\"customButton3\" label=\"Validate and Submit\" imageMso=\"PictureBrightnessGallery\" size=\"large\" onAction=\"Callback3\" />\n </group>\n </tab>\n </tabs>\n </ribbon>\n</customUI>\n\n\nCode 2\n\n<customUI xmlns=\"http://schemas.microsoft.com/office/2009/07/customui\">\n <ribbon startFromScratch=\"false\">\n <tabs>\n <tab id=\"customTab\" label=\"AA PAYMENTS APP\" insertAfterMso=\"TabView\">\n <group id=\"customGroup\" label=\"Group 1\">\n <button id=\"customButton\" label=\"Test1\" imageMso=\"HyperlinkInsert\" size=\"large\" onAction=\"Callback\" />\n <button id=\"customButton2\" label=\"JG Button 2\" imageMso=\"PictureBrightnessGallery\" size=\"large\" onAction=\"Callback2\" />\n <group id=\"customGroup2\" label=\"Group 2\">\n <button id=\"customButton3\" label=\"Validate and Submit\" imageMso=\"PictureBrightnessGallery\" size=\"large\" onAction=\"Callback3\" />\n </group>\n </tab>\n </tabs>\n </ribbon>\n</customUI>\n\n\nN.B I use Custom UI Editor."
] | [
"xml",
"excel",
"ribbon"
] |
[
"Forms authentication with requireSSL=true not returning cookie with Secure attribute",
"I'm seeing a strange response from our IIS site now that we've upgraded the host from Win2K3/IIS6 to Win2k8R2/IIS7.5. ASP.Net version 4.0\n\nWe have a significantly complex and mature web application that uses Forms Authentication with the following config:\n\n<authentication mode=\"Forms\">\n <forms loginUrl=\"~/Login\" timeout=\"2000\" domain=\"xx.xx.com\" requireSSL=\"true\" />\n</authentication>\n\n\nThe Login URL directs to an ASP.Net MVC 3 page properly configured for SSL.\n\nThe site behaved as expected in IIS6, but ever since the host migration, upon successful login the auth cookie in the response header is missing the Secure and HttpOnly attributes. This is problematic as we have a mixed content site with many HTTP pages. The auth cookie is now sent in every request, not just in requests over HTTPS and is now open to a session stealing vulnerability.\n\nOur Logoff link successfully sends a zero length cookie that does include the Secure and HttpOnly attributes.\n\nHere's the raw responses after successful login and logoff from Fiddler, edited to protect the innocent :)\n\nLogin Response:\n\nHTTP/1.1 200 OK\nCache-Control: private\nContent-Type: application/json; charset=utf-8\nSet-Cookie: .ASPXAUTH=83FCCA...102D; domain=xx.xx.com; path=/\nDate: Fri, 25 Jan 2013 22:53:31 GMT\nContent-Length: 84\n\n{...}\n\n\nLogoff Response:\n\nHTTP/1.1 302 Found\n\nCache-Control: private\nContent-Type: text/html; charset=utf-8\nLocation: http://xx.xx.com/?...\nSet-Cookie: .ASPXAUTH=; domain=xx.xx.com; expires=Tue, 12-Oct-1999 04:00:00 GMT; path=/; secure; HttpOnly\nSet-Cookie: logoff=; path=/\nSet-Cookie: ...\nDate: Fri, 25 Jan 2013 22:57:01 GMT\nContent-Length: 64053\n\n<html><head><title>...\n\n\nChanging the Integrated Pipeline setting of the app pool has no effect.\n\nHere are the important parts of the cookie creation code:\n\n var ctx = HttpContextFactory.Current;\n\n var cookie = new HttpCookie(\n FormsAuthentication.FormsCookieName,\n FormsAuthentication.Encrypt(\n new FormsAuthenticationTicket(\n SessionId,\n false,\n Convert.ToInt32(FormsAuthentication.Timeout.TotalMinutes)\n )\n )\n ) { Domain = domain };\n\n ctx.Response.Cookies.Add(cookie);\n\n\nAny thoughts on where to start looking for what's causing this?"
] | [
"asp.net",
"asp.net-mvc",
"iis",
"security"
] |
[
"Connecting neo4j database from Neo4j webadmin pane",
"I have created neo4j nodes and relationships from java code , i am trying to use Neo4j webadmin panel to display them as a graph.\nI have changed server config property \"org.neo4j.server.database.location\" to point to the DB folder i have created from java program.\nIs there any other changes i need to do in order to view the nodes and relationships? how to achieve the same?\n\nPlease guide."
] | [
"neo4j"
] |
[
"Gallery Images Ideas",
"Since multiple requests can slow down the speed at which a site loads, I was thinking that in the case of a gallery, would one large image containing all the thumbnails be better than loading individual thumbnails?\n\nThe large image would then use PHP to \"chop up\" the thumbnails and place them in the relevant locations on the page.\n\nMy main concern is would this have a negative impact on SEO? Since Google would only see one large image file, instead of many smaller ones. Would a way around this be to set the src of all thumbnails to redirect to the script that handles the thumbnail generation, where the image file name refers to a particular set of coordinates for that image?"
] | [
"php",
"http",
"seo"
] |
[
"reverse for ' with arguments '()' and keyword arguments not found. 1 pattern(s) tried:",
"I am trying to get a ListView for which get_absolute_url is defined in my template. But it raises an error:\n\n\n Reverse for 'accept_bid' with arguments '()' and keyword arguments '{'bid_id': 16}' not found. 1 pattern(s) tried: ['post/(?P[\\w-]+)/bid/(?P[\\w-]+)/$'].\n\n\nDo I need to define the the two integer id's in my view or is there some other problem?\n\nI would appreciate helping me in solve this.\n\nmodels.py:\n\nclass Bid(models.Model):\n\n post = models.ForeignKey(Post, related_name = \"bids\")\n user = models.OneToOneField(User, null=True, blank=True)\n amount = models.IntegerField()\n\n def get_absolute_url(self):\n return reverse(\"accept_bid\", kwargs={\"bid_id\": self.id})\n\n\nViews.py:\n\nclass LiveBids(LoginRequiredMixin, ListView, FormView ):\n template_name = 'live_bids.html'\n def get_queryset(self):\n\n return Post.objects.all().prefetch_related('bids').filter(user=self.request.user).order_by('id')\n\n\nurls.py:\n\nurl(r'^live_bids/$', LiveBids.as_view(model=Post), name='LiveBids'),\nurl(r'^post/(?P<post_id>[\\w-]+)/bid/(?P<bid_id>[\\w-]+)/$', views.accept_bid, name='accept_bid'),\n\n\nlive_bids.html:\n\n{% for bid in post.bids.all %}\n {{bid.amount}}\n <p><a href='{{ bid.get_absolute_url }}'>Accept</p>\n{% endfor %}"
] | [
"django",
"django-models",
"django-views",
"django-urls",
"django-generic-views"
] |
[
"How to obtain google + id from app engine user?",
"I'm migrating my data to google app engine from firebase.\nWhen I log in to the site using google auth I can retrieve the users google + id from firebase.\n\nbut when I am exporting the user data from app engine, the user_id() function does not give me the same value. \n\nI believe I've either got to find a way for firebase to get the email from the google oauth provider, or figure out a way to get google+ ID from a user's email when I'm exporting from app engine.\n\nTL;DR\nHow do i get the google+ ID from someone's gmail address?"
] | [
"google-app-engine",
"oauth-2.0",
"firebase"
] |
[
"Regex to validate a password",
"Possible Duplicate:\n Password validation regex \n\n\n\n\nbetween 8 and 16 characters, with at least 1 character from each of the 3 character classes -alphabetic upper and lower case, numeric, symbols.\n\nI have this code, but it doesn't work, when I write more than 16 characters, gives it as valid, but it should not; the it should to work ok with 3 character classes, but it works with 4, where's my mistake??\n\nhttp://jsbin.com/ugesow/1/edit\n\n<label for=\"pass\">Enter Pass: </label>\n<input type=\"text\" id=\"pass\" onkeyup=\"validate()\">\n\n\nScript\n\nfunction validate() {\n valor = document.getElementById('pass').value;\n if (!(/(?=.{8,16})(?=.*?[^\\w\\s])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*/.test(valor))) {\n\n document.getElementById('pass').style.backgroundColor = \"red\";\n } else {\n document.getElementById('pass').style.backgroundColor = \"#adff2f\";\n }\n}"
] | [
"javascript",
"html",
"regex"
] |
[
"Matlab: Change elements in 3D array using given conditions",
"I have a 3 dimensional array (10x3x3) in Matlab and I want to change any value greater than 999 to Inf. However, I only want this to apply to (:,:,2:3) of this array.\n\nAll the help I have found online seems to only apply to the whole array, or 1 column of a 2D array. I can't work out how to apply this to a 3D array.\n\nI have tried the following code, but it becomes a 69x3x3 array after I run it, and I don't really get why. I tried to copy the code from someone using a 2D array, so I just think I don't really understand what the code is doing.\n\nA(A(:,:,2)>999,2)=Inf;\nA(A(:,:,3)>999,3)=Inf;"
] | [
"arrays",
"matlab",
"multidimensional-array",
"matrix-indexing"
] |
[
"xml choice : single element should repeat",
"I want a document to consist only apples or oranges. I am creating an XML schema as follows:\n\n<element name=\"fruit\" type=\"myns:fruitType\"></element>\n\n<complexType name=\"fruitType\">\n <choice minOccurs=\"1\" maxOccurs=\"1\">\n <sequence>\n <element name=\"apple\" type=\"string\" minOccurs=\"0\" maxOccurs=\"unbounded\"></element>\n <element name=\"orange\" type=\"string\" minOccurs=\"0\" maxOccurs=\"0\"></element>\n </sequence>\n <sequence >\n <element name=\"orange\" type=\"string\" minOccurs=\"0\" maxOccurs=\"unbounded\"></element>\n <element name=\"apple\" type=\"string\" minOccurs=\"0\" maxOccurs=\"0\"></element>\n </sequence>\n </choice>\n</complexType>\n\n\nbut this accepts the following as a valid element.\n\n<fruit>\n <apple> apple1 </apple>\n <orange> orange1 </orange>\n <orange> orange2 </orange>\n <apple> apple2 </apple>\n</fruit>\n\n\nI want only the following to be valid:\n\n <fruit>\n <apple> apple1 </apple>\n <apple> apple2 </apple>\n .\n .\n <apple> appleN </apple>\n </fruit>\n\n\nOR\n\n<fruit>\n <orange> orange1 </orange>\n <orange> orange2 </orange>\n .\n .\n <orange> orangeN </orange>\n</fruit>\n\n\nAny idea how to do that?"
] | [
"xsd"
] |
[
"SESSION not remembered php",
"I came across the problem that my session vars aren't remembered when you are linked to another page. This might sound a bit strange. To clear it up a bit, I will explain my problem with some code:\n\nThis code is a snippet from 'Login.php'. Here I set the SESSION vars for Email and wachtwoord(Password).\n\n$query = \"SELECT * FROM user WHERE Email='$email' AND Wachtwoord='$Wachtwoord'\";\n\n$result = mysqli_query($connection, $query) or \ndie(mysqli_error($connection));\n$count = mysqli_num_rows($result);\nif ($count == 1){\n session_start();\n $_SESSION['email'] = $email;\n $_SESSION['wachtwoord'] = $Wachtwoord;\n\n\n$sql = \"UPDATE user SET Ingelogd = 1 WHERE Email='$email'\";\n$ressql = mysqli_query($connection, $sql) or \ndie(mysqli_error($connection));\n\n}else{\n echo \"Invalid Login Credentials.\";\n}\n\n\nInside this snippet, the email and wachtwoord session are correctly set(I believe, because I can echo these and get the right output)\n\nBut when the user gets redirected to chat.php which contains this php code(indirectly, this code is in 'LoginCheck.php'. Linked to as: Include('../Php/LoginCheck.php');):\n\nInclude('connect.php');\n//IF ((! $_SESSION['email']= NULL)&&(! $_SESSION['wachtwoord']=NULL)){\n $email = $_SESSION['email'];\n echo $_SESSION['email'];\n $Wachtwoord = $_SESSION['wachtwoord'];\n echo $_SESSION['wachtwoord'];\n echo 'something';\n\n$sql = \"SELECT * FROM user WHERE Email='$email' and Wachtwoord='$Wachtwoord' and Ingelogd=1\";\n$result = mysqli_query($connection,$sql) or die(mysqli_error($connection));\n$count = mysqli_num_rows($result);\nif (!$count == 1){\n //header('Location: Login.php'); \n}\n//}\n\n\nWhen php tries to do something with a SESSION var it gives this error: \nUndefined variable: _SESSION in F:\\xampp\\htdocs\\Chives-Functional\\Php\\LoginCheck.php on line 4\nThe line, in which $email is declared.\n\nWhat I want to check is whether the user is still logged in or not.\nHow can I get this to work? What am I doing wrong? And why isn't it remembered?\nThanks in advance, any help is appreciated!\n\nKind Regards,\n\nPs. If more information is required, feel free to ask!"
] | [
"php",
"mysql",
"session"
] |
[
"The value is incorrect when querying via jdbc driver. why?",
"I try to query data from Google BigQuery via JDBC driver, but some values seems to be incorrect.\n\nSteps:\n\n\nDownload Simba JDBC driver for googlebigquery freely from https://storage.googleapis.com/simba-bq-release/jdbc/SimbaJDBCDriverforGoogleBigQuery42_1.2.2.1004.zip\nLoading the driver to your Java App\nConnect the google query via jdbc\nThe sample codes are below:\n\n\n public static void main(String[] args) {\n\n Connection conn = null;\n String url =\"jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;\" +\n \"ProjectId=fedjdbc;OAuthType=0;DefaultDataset=jdbc;\" +\n \"[email protected];\" +\n \"OAuthPvtKeyPath=/Users/laptop/workspace/bigquery/accounts/fedjdbc-5cb29b8a02fb.json\";\n\n try {\n Class.forName(\"com.simba.googlebigquery.jdbc42.Driver\");\n conn = DriverManager.getConnection(url);\n\n query(conn);\n conn.close();\n\n\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }\n\n public static void query(Connection conn) {\n String sql = \"select * from numbers1\";\n sql = \"select * from numbers1\";\n sql = \"select timestamp(\\\"0001-01-01 00:00:00 UTC\\\") from jdbc.test_date\";\n try {\n PreparedStatement stmt = conn.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);\n System.out.println(\"query begin\");\n java.util.Date date = new java.util.Date();\n\n System.out.println(System.currentTimeMillis());\n\n ResultSet rs = stmt.executeQuery();\n System.out.println(System.currentTimeMillis());\n System.out.println(\"query end\");\n\n while (rs.next()) {\n System.out.println(rs.getString(1));\n //System.out.println(rs.getTimestamp(1));\n }\n rs.close();\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n }\n\n\nYou can find that the result is not \"0001-01-01 00:00:00.000000\" but \"0001-01-03 08:00:00.000000\".\n\nDo you know why?\n\nThe timezone convert the data locally?\n\nI test it in some hosts with different timezones, same issues."
] | [
"jdbc",
"google-bigquery",
"timestamp",
"timezone"
] |
[
"ng5-slider: Dragging pointers not moving when used in a Angular reactive form",
"When I use the slider in a reactive form with a component that has ChangeDetectionStrategy.OnPush the slider pointers do not move even though the numbers do update.\n\nThis is my code for the component:\n\nimport { Component, AfterContentChecked, ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core';\nimport { Options } from 'ng5-slider';\nimport { FormBuilder, FormGroup, FormControl } from '@angular/forms';\n\n\n@Component({\n selector: 'my-app',\n templateUrl: './app.component.html',\n styleUrls: [ './app.component.scss' ],\n changeDetection: ChangeDetectionStrategy.OnPush\n})\nexport class AppComponent {\n\n form: FormGroup = new FormGroup({\n sliderControl: new FormControl([20, 80])\n });\n\n options: Options = {\n floor: 0,\n ceil: 100,\n showOuterSelectionBars: true\n }\n\n minValue = 20;\n maxValue = 80;\n}\n\n\n\n<div class=\"custom-slider\" [formGroup]=\"form\">\n <ng5-slider \n formControlName=\"sliderControl\"\n [options]=\"options\" \n >\n </ng5-slider>\n</div>\n\n\n<div class=\"custom-slider\">\n <ng5-slider [(value)]=\"minValue\" [(highValue)]=\"maxValue\" [options]=\"options\"></ng5-slider>\n</div>\n\n\nAs you can see I have also tried with a template form as well where the slider does update. You can see the full example here on StackBlitz"
] | [
"angular"
] |
[
"Weird positioning of image view. Wrong content mode?",
"I want my image view to be displayed correctly at the bottom of the main view, but apparently the image is tilted to the top. I have tried to use every possible content mode of the image view, but none of them place the image view in the right position (bottom).\n\nThere's something wrong going on with the image, even though I set my layout constraints right. What am I doing wrong?\n\n\n\nimport UIKit\nimport PlaygroundSupport\n\nvar mainView = UIView(frame: CGRect(x: 0, y: 0, width: 1000, height: 1000))\n\nlet groundView = UIImageView(image: UIImage(named:\"GroundSkin.png\"))\nmainView.addSubview(groundView)\ngroundView.backgroundColor = .red\ngroundView.contentMode = .scaleAspectFit\ngroundView.translatesAutoresizingMaskIntoConstraints = false\ngroundView.leftAnchor.constraint(equalTo: mainView.leftAnchor).isActive = true\ngroundView.rightAnchor.constraint(equalTo: mainView.rightAnchor).isActive = true\ngroundView.heightAnchor.constraint(equalTo: mainView.heightAnchor, multiplier: 1).isActive = true\ngroundView.bottomAnchor.constraint(equalTo: mainView.bottomAnchor).isActive = true\n\nPlaygroundPage.current.liveView = mainView\nPlaygroundPage.current.needsIndefiniteExecution = true"
] | [
"ios",
"swift",
"uiimageview"
] |
[
"How to convert unsigned long to string",
"In the C language, how do I convert unsigned long value to a string (char *) and keep my source code portable or just recompile it to work on other platform (without rewriting code?\n\nFor example, if I have sprintf(buffer, format, value), how do I determine the size of buffer with platform-independent manner?"
] | [
"c"
] |
[
"How do I stop objects from being displayed as cursive in fira code iScript?",
"I am trying to switch to fira code iScript so I can get the keywords to be in cusrsive, var, const, class delete import, private, public ect... however it is making all objects cursive as well even though it is defined in the config not to do this, I've moved everything in to the exclude section and it continues to make objects cursive:\n "editor.tokenColorCustomizations": {\n "textMateRules": [\n {\n "scope": [\n //following will be in italic (=FlottFlott)\n ],\n "settings": {\n "fontStyle": "italic"\n }\n },\n {\n "scope": [\n //following will be excluded from italics (VSCode has some defaults for italics)\n "invalid",\n "storage.modifier", //static keyword\n "storage.type.class.js", //class keyword\n "entity.name.type.class", //class names\n "keyword.operator",\n "constant.numeric.css",\n "keyword.other.unit.px.css",\n "constant.numeric.decimal.js",\n "constant.numeric.json",\n "comment",\n "keyword", //import, export, return…\n "constant", //String, Number, Boolean…, this, super\n "entity.name.type.class", //class names\n "entity.other.attribute-name",\n "entity.name.method",\n "entity.name.tag",\n "variable.language",\n "meta.paragraph.markdown",\n "support.type.property-name.json",\n "string.other.link.title.markdown"\n ],\n "settings": {\n "fontStyle": ""\n }\n }\n ]\n}\n\nproduces this output:\nthe section in orange should not be in cursive. (italic)"
] | [
"visual-studio-code"
] |
[
"How to use async alternative for Promise.resolve().then()?",
"How to replace Promise.resolve().then() with async/await without blocking main thread?\nFirst snippet execute log('Synchronous 2') before the loop finishes which is expected.\nHowever log('Synchronous 2') is blocked in second snippet where I replace the function with async().\nHow to unblock log('Synchronous 2') in the second example?\n\r\n\r\nconst tick = Date.now();\nconst log = (v) => console.log(`${v} \\n Elapsed: ${Date.now() - tick}ms`);\n\nconst notBlocked = () => {\n return Promise.resolve().then(() => {\n let i = 0;\n while(i < 1000000000) { i++; } //runs asynchronically\n return ' billion loops done';\n })\n}\n\nlog(' Synchronous 1');\nnotBlocked().then(log);\nlog(' Synchronous 2');\r\n\r\n\r\n\nThe log('Synchronous 2') is blocked\n\r\n\r\nconst tick = Date.now();\nconst log = (v) => console.log(`${v} \\n Elapsed: ${Date.now() - tick}ms`);\n\nconst notBlocked = async() => {\n let i = 0;\n while(i < 100000000) { i++; } //runs synchronically and blocks main thread\n return ' billion loops done';\n}\n\nlog(' Synchronous 1');\nnotBlocked().then(log);\nlog(' Synchronous 2');"
] | [
"javascript",
"promise",
"es6-promise"
] |
[
"media images not being served up during production to heroku",
"So, I have a media folder with my profile photos in there for my users. It works fine during development locally and when debug=False on heroku, but as soon as debug=True it does not work anymore. I am not sure why. So my files are not being served up during the push and neither are they being uploaded when a user tries to upload. The image url path is there with the correct name of the image, but no photo appears and when clicking on the image url I get\n"The requested resource was not found on this server."\nMy actual website is working fine. And my static images , such as my Jumbotron and navbar logo are being served up, but my media folder seems to be the issue.\nAlso, I've set up WhiteNoise already. Should I move my media folder to my static folder?\nproject dir\n.\n├── 11_env\n│ ├── bin\n│ ├── lib\n│ └── pyvenv.cfg\n├── Procfile\n├── dating_app\n│ ├── __init__.py\n│ ├── __pycache__\n│ ├── admin.py\n│ ├── apps.py\n│ ├── chat.html\n│ ├── forms.py\n│ ├── media--profile_photo\n│ ├── migrations\n│ ├── models.py\n│ ├── static\n│ ├── tag.py\n│ ├── templates\n│ ├── templatetags\n│ ├── tests.py\n│ ├── urls.py\n│ └── views.py\n├── dating_project\n│ ├── __init__.py\n│ ├── __pycache__\n│ ├── asgi.py\n│ ├── settings.py\n│ ├── staticfiles\n│ ├── urls.py\n│ └── wsgi.py\n├── db.sqlite3\n├── manage.py\n├── requirements.txt\n└── static\n ├── css\n └── images\n\nsettings.py\nSTATIC_URL = '/static/'\n\nPROJECT_DIR = os.path.dirname(os.path.abspath(__file__))\nSTATIC_ROOT = os.path.join(PROJECT_DIR, 'staticfiles')\nSTATICFILES_DIRS = (\n os.path.join(BASE_DIR, 'static'),\n)\n\n\n\nMEDIA_URL = '/media/'\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\nmodels.py\nphoto = models.ImageField(upload_to='profile_photo',blank=False, height_field=None, width_field=None, max_length=100)\n\nurls.py root\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', include('dating_app.urls', namespace= 'dating_app')),\n\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)"
] | [
"django",
"heroku"
] |
[
"How to calculate Jaccard similarity between two data frame with in R",
"I have two binary dataframes c(0,1), and I didn't find any method which calculates the Jaccard similarity coefficient between both dataframes. I have seen methods that do this calculation between the columns of a single data frame.\nLets say DF1\n\nDF1 <- data.frame(a=c(0,0,1,0),\n b=c(1,0,1,0),\n c=c(1,1,1,1)) \n\n\nand DF2:\n\nDF2 <- data.frame(a=c(0,0,0,0),\n b=c(1,0,1,0),\n c=c(1,0,1,1)) \n\n\nWhat I am looking is a single Jaccard similarity coefficient between the two data frame (not column by column)\n\nCould you help me with this ?"
] | [
"r",
"dataframe",
"similarity"
] |
[
"ElasticSearch Delete Query - Filter with term and range",
"I have the following query that I am trying to use to delete data from an ElasticSearch index.\n\n{\n \"filter\": {\n \"and\": [\n {\n \"range\": {\n \"Time\": {\n \"from\": \"20120101T000000\",\n \"to\": \"20120331T000000\"\n }\n }\n },\n {\n \"term\": {\n \"Source\": 1\n }\n }\n ]\n }\n}\n\n\nI have tried to delete documents based on this query. This query returns results fine when I run it against the index. But when I try to run a delete command against the index, nothing happens.\n\nI am not sure if I am constructiing the query wrong or what else."
] | [
"elasticsearch"
] |
[
"How to configure which project to debug?",
"I want to run two different Android apps from Eclipse (in two different types of Emulators) simultaneously but step through one of them, in which I've set breakpoints.\n\nHow do I configure which of the two apps is the one being debugged? It's not possible to debug both simultaneously, is it (with breakpoints in each project)?"
] | [
"android",
"eclipse",
"android-emulator"
] |
[
"updating datatable using AJAX not working",
"I'm retrieving the list of files in a folder when a button is clicked. The function that retrieves the folder works, and if I load it before the table is rendered the values are shown as they should. However if I try to populate the table with a commandbutton calling a function initializing the list of values, no changes are made to the datatable. Here's my code:\n\n<h:form id=\"resultform\"> \n <p:dataTable id=\"resulttable\" value=\"#{ViewBean.resultList}\" var=\"result\">\n <p:column>\n <f:facet name=\"header\">\n <h:outputText value=\"GFEXP_NOM_BDOC\" />\n </f:facet>\n <h:outputText value=\"#{result.name}\" />\n </p:column>\n <p:column>\n <f:facet name=\"header\">\n <h:outputText value=\"GFEXP_DATE_MODIF\" />\n </f:facet>\n <h:outputText value=\"#{result.date}\" />\n </p:column>\n <p:column>\n <f:facet name=\"header\">\n <h:outputText value=\"GFEXP_PATH\" />\n </f:facet>\n <h:outputText value=\"#{result.path}\" />\n </p:column>\n <f:facet name=\"footer\">\n <p:commandButton value=\"REFRESH exploitation\" action=\"#{ViewBean.refresh}\" update=\":resultform:resulttable\" ajax=\"true\" />\n </f:facet>\n </p:dataTable>\n</h:form>\n\n\nHere's the backing bean code:\n\n@ManagedBean(name = \"ViewBean\")\n@ViewScoped\npublic class ViewBean implements Serializable {\n\n private static final long serialVersionUID = 9079938138666904422L;\n\n @ManagedProperty(value = \"#{LoginBean.database}\")\n private String database;\n\n @ManagedProperty(value = \"#{ConfigBean.envMap}\")\n private Map<String, String> envMap;\n\n private List<Result> resultList;\n\n public void initialize() {\n setResultList(Database.executeSelect(database));\n\n }\n\n public void refresh() {\n List<File> fileList = readDirectory();\n List<Result> tmpList = new ArrayList<Result>();\n for (File f : fileList) {\n Result result = new Result(f.getName().substring(0,\n f.getName().lastIndexOf(\".\")), String.valueOf(f\n .lastModified()), f.getPath().substring(0,\n f.getPath().lastIndexOf(\"\\\\\") + 1));\n tmpList.add(result);\n }\n setResultList(tmpList);\n }\n//GETTERS AND SETTERS"
] | [
"ajax",
"jsf",
"primefaces",
"datatable"
] |
[
"Deactivate a Customer in AX 2012",
"We are building an integration between CRM 2011 and AX 2012.\nThe connector works quite ok, but we don't want an inactive account to be modified in CRM when some updates are performed in AX.\n\nWe would like to make the status change to reflect in AX.\nIs there some inactive status in AX as well?"
] | [
"microsoft-dynamics",
"dynamics-ax-2012"
] |
[
"Help with C# - Silverlight - ToolKit - Dynamic Line Series",
"I need help with line chart in Silverlight Toolkit Line Series that updates dynamically having 3 lines updating itself every 5 seconds how do i do it?"
] | [
"c#",
"silverlight",
"silverlight-toolkit",
"toolkit",
"linechart"
] |
[
"Setting svg fill attribute in Javascript",
"Beginner's question. Why does the color variable color.svg not work when I try to change my svg attribute? Everything else works: the other colors (for circles added later), as well as the size of the svg (sizing taken from here).\n\nConstants:\n\n// colors\nvar color = {svg: \"black\", \n drop0: \"rgba(204, 204, 255, 1)\",\n drop1: \"orange\"};\n\n// margins\nvar margin = {top: 20, right: 10, bottom: 20, left: 10};\nvar width = 960 - margin.left - margin.right,\n height = 500 - margin.top - margin.bottom;\n\n\nNow I make an svg and try set attributes.\n\n// svg\nvar svg = d3.select(\"body\").append(\"svg\")\n .attr({width: width + margin.left + margin.right,\n height: height + margin.top + margin.bottom,\n fill: color.svg})\n .append(\"g\")\n .attr(\"transform\", \"translate(\" + margin.left + \",\" + margin.top + \")\");\n\n// followed by stuff about adding shapes, etc, which work\n\n\nI would prefer not to set it in CSS. No errors are thrown on the browser. I've commented out everything but these lines, and the svg is still not colored black."
] | [
"d3.js",
"svg",
"colors",
"fill"
] |
[
"Fire event from Async component in UI thread",
"I'm building a non-visual component in .Net 2.0. This component uses an asynchronous socket (BeginReceive, EndReceive etc). Asynchronous callbacks are called in the context of a worker thread created by the runtime. The component user shouldn't have to worry about multithreading (This is the main goal, what I want)\n\nThe component user can create my non-visual component in any thread (the UI thread is just a common thread for simple applications. More serious applications could create the component within an arbitrary worker thread). The component trigger events such as \"SessionConnected\" or \"DataAvailable\".\n\nThe issue: because of the Async Callbacks and the events raised therein the event handler is executed in the worker thread context. I want to use an intermediate layer which force\nthe event handler to execute in the context of the thread which created the\ncomponent at the first place.\n\nExample code (stripped from exception handling etc...)\n\n /// <summary>\n /// Occurs when the connection is ended\n /// </summary>\n /// <param name=\"ar\">The IAsyncResult to read the information from</param>\n private void EndConnect(IAsyncResult ar)\n {\n // pass connection status with event\n this.Socket.EndConnect(ar);\n\n this.Stream = new NetworkStream(this.Socket);\n\n // -- FIRE CONNECTED EVENT HERE --\n\n // Setup Receive Callback\n this.Receive();\n }\n\n\n /// <summary>\n /// Occurs when data receive is done; when 0 bytes were received we can assume the connection was closed so we should disconnect\n /// </summary>\n /// <param name=\"ar\">The IAsyncResult that was used by BeginRead</param>\n private void EndReceive(IAsyncResult ar)\n {\n int nBytes;\n nBytes = this.Stream.EndRead(ar);\n if (nBytes > 0)\n {\n // -- FIRE RECEIVED DATA EVENT HERE --\n\n // Setup next Receive Callback\n if (this.Connected)\n this.Receive();\n }\n else\n {\n this.Disconnect();\n }\n }\n\n\nBecause of the nature of the Async sockets all applications using my component are littered with \"If (this.InvokeRequired) { ...\" and all I want is the user to be able to use my component worry-free as sort of a drop-in.\n\nSo how would I go about raising the events without requiring the user to check InvokeRequired (or, put differently, how do I force the events raised in the same thread as the thread that initiated the event in the first place)?\n\nI have read stuff about AsyncOperation, BackgroundWorkers, SynchronizingObjects, AsyncCallbacks and tons of other stuff but it all makes my head spin.\n\nI did come up with this, surely clumsy, \"solution\" but it seems to fail in some situations (when my component is called from a WinForms project via a static class for example)\n\n /// <summary>\n /// Raises an event, ensuring BeginInvoke is called for controls that require invoke\n /// </summary>\n /// <param name=\"eventDelegate\"></param>\n /// <param name=\"args\"></param>\n /// <remarks>http://www.eggheadcafe.com/articles/20060727.asp</remarks>\n protected void RaiseEvent(Delegate eventDelegate, object[] args)\n {\n if (eventDelegate != null)\n {\n try\n {\n Control ed = eventDelegate.Target as Control;\n if ((ed != null) && (ed.InvokeRequired))\n ed.Invoke(eventDelegate, args);\n else\n eventDelegate.DynamicInvoke(args);\n }\n catch (Exception ex)\n {\n Console.WriteLine(ex.GetType());\n Console.WriteLine(ex.Message);\n //Swallow\n }\n }\n }\n\n\nAny help would be appreciated. Thanks in advance!\n\nEDIT:\nAccording to this thread my best bet would be to use SyncrhonizationContext.Post but I can't see how to apply it to my situation."
] | [
"c#",
"user-interface",
"asynchronous",
"sockets",
"invokerequired"
] |
[
"about the expression \"&anArray\" in c",
"First, I read that:\n\n\narray\n&array\n&array[0]\n\n\nwill all be the same as long as \"array\" is really an array.\nSo I tried:\n\nint main(){ \n char ar[]={'a','b','c','\\0'};\n printf(\"argument: &ar %s\\n\",&ar);\n printf(\"argument: &ar[1] %s\\n\",&ar[1]);\n}\n\n\nthe output:\n\nargument:&ar abc \nargument:&ar[1] bc\n\n\nIt seems that &ar is taken as a pointer to the first element instead of a pointer to \"ar\", which itself is a pointer to the first element if I am not mistaken.\n\n'cause that shouldn't be how &(pointer to a char) are treated, I tried:\n\nchar a='s';\nchar *pa=&a;\nprintf(\"argument: &pa %c\\n\",&pa);\n\n\nThe output for %c isn't even a character.\nNor shouldn't it be how a pointer to the first element of an array treated. I tried:\n\nchar *pa=&ar[0];\nchar **ppa= &pa;\nprintf(\"argument: &pa %s\\n\", ppa);\n\n\nThe output for %s is, not surprisingly, nonsense; but why hasn't &ar been nonsense? For if ar were a pointer, shouldn't &ar be as much a pointer to a pointer as is ppa?\n\nMy questions:\n\n\nIs simply \"&\" ignored when put before an array name?\nAre array names simply special on this?\nIf so, how does the compiler verify that the identifier following \"&\" is a reference to an array? Does it actually search for it in a list of arrays so for declared?"
] | [
"c"
] |
[
"Flow doesn't work when using `worker-loader` for importing web workers",
"I am using flow in my react app and started using web workers also using flow-immutable-models flow is working in main thread executed files but doesn't work in worker file.\nWhen webpack server restarts after save will get stuck at sail plugin.\nDid anyone face kinda issue in past?\n\nMy code as follows:\ncontroller file \n\nimport ImportWorker from 'worker-loader!./ImportWorker.js';\n\n....\n\nconst worker = new ImportWorker();\n worker.onmessage = this.handleMsg;\n this.worker = worker;\n\n\nworker file\n\n//@flow\nconst parseCSV = ({\n file,\n config = {}\n}): Promise<{\n file: File,\n parsedFile: {\n fileRows: Array<Object>,\n fileHeaders: Array<string>\n }\n}> => {\n return new Promise((resolve, reject) => {\n // some passing logic\n });\n};\n\n// some handelIncomingMsg handler logic\n\nonmessage = e => {\n try {\n handelIncomingMsg(e);\n } catch (err) {\n onError({ ...err, id: e.data.id });\n }\n};"
] | [
"webpack",
"sails.js",
"flowtype",
"web-worker",
"worker-loader"
] |
[
"Using C++, test existence of static member using SFINAE, return wrong value",
"I am learning template metaprogramming.\nWhen trying to test static member using following code, the second SFINAE always return wrong value:\n\n#include <cstdio>\n#include <type_traits>\n\n// ts_a\nstruct ts_a\n{\n static int a;\n};\n\n// ts_b\nstruct ts_b\n{\n static int b;\n};\n\n// has_a\ntemplate<typename T, typename = std::void_t<>>\nstruct has_a : std::false_type {};\ntemplate<typename T>\nstruct has_a<T, std::void_t<decltype( T::a )>> : std::true_type {};\n\n// has_b\ntemplate<typename T, typename = std::void_t<>>\nstruct has_b : std::false_type {};\ntemplate<typename T>\nstruct has_b<T, std::void_t<decltype( T::b )>> : std::true_type {};\n\nint main()\n{\n printf( \"%s\\n\", has_a<ts_a>::value ? \"true\" : \"false\" );\n printf( \"%s\\n\", has_b<ts_a>::value ? \"true\" : \"false\" );\n printf( \"%s\\n\", has_a<ts_b>::value ? \"true\" : \"false\" );\n printf( \"%s\\n\", has_b<ts_b>::value ? \"true\" : \"false\" ); \n\n return 0;\n}\n\n\nI am using Microsoft (R) C/C++ Optimizing Compiler Version 19.15.26732.1 for x64\n\ntrue\ntrue\nfalse\nfalse\n\n\nHowever when compile with GCC, it returns the expected value\n\ntrue\nfalse\nfalse\ntrue\n\n\nWhen define has_b before has_a ( CTRL-XV has_b before has_a ), MSVC returns\n\nfalse\nfalse\ntrue\ntrue\n\n\nSo, is it a compiler problem?\n\nThe following alternative works on both compilers, but it also return true to non-static member. Is there a way I can detect real static member ?\n\ntemplate <class T> \nstruct has_a_2\n{ \n template<typename U> \n static std::true_type check( decltype( U::a )* );\n template<typename U>\n static std::false_type check(...); \n\npublic: \n static constexpr const bool value = decltype( check<T>( 0 ) )::value;\n};"
] | [
"c++",
"template-meta-programming"
] |
[
"What dev environment should I use for data analysis on Mac?",
"I'm starting to develop an application and I'm not sure what environment (languages, tools, etc.) I should use. Here are some infos:\n\n\nThe app analyses a bunch of data that I have in a database. There is a lot of rolling, weighted averages - not too complicated, but probably too tricky to do in SQL. \nAt work, I'd probably end up with an OracleDB and a bunch of stored procedures. However, this is a private project and I've recently switched to a Mac.\nAfter the analysis is done, I might want to expose the results on the web. As my hosting package includes a MySQL database, I'd like to work with that as a database engine. I'm not sure how good the support for stored procs on MySQL is and what tools to use for writing and debugging - any equivalent to Toad on the Oracle side?\nWhen developing on Windows, I could write the analysis functionality as a C# or VB app - what would be a good equivalent on the Mac side?\n\n\nAny suggestions would be appreciated. I'd especially like to get a better understanding of some \"modern\" languages (such as Ruby or Python) if this makes sense for what I want to develop."
] | [
"macos",
"programming-languages"
] |
[
"Source control with SharePoint?",
"Have you tried to use SharePoint with version control such as Perforce (or Subversion), how did you do it?"
] | [
"svn",
"sharepoint",
"version-control",
"perforce"
] |
[
"How to run a firebase sample",
"I have cloned a firebase sample from here \n\nhttps://github.com/firebase/quickstart-js\n\nI want to run this sample, I have tried with itellij and gitbash but it doe not run"
] | [
"github",
"intellij-idea",
"firebase",
"firebase-realtime-database"
] |
[
"Unable to drag drop components on AEM new page",
"I am following AEM tutorial wknd tutorial. I have created the project using archetype and installed it on local AEM instance. Unlike the tutorial when i create a new page i do not get the option to drag and drop components and neither am i able to find any components in side rail.\n\nI went to the template to edit it in design mode and enable components but could not find design mode to edit it to enable components.\n\nI am not sure what to do to follow along with the tutorial. Any help is much appreciated."
] | [
"java",
"osgi",
"aem",
"sling",
"wcm"
] |
[
"Best syntax for a = (x == null) ? null : x.func()",
"Basic question here - I have many lines of code that look something like:\n\nvar a = (long_expression == null) ? null : long_expression.Method();\n\n\nSimilar lines repeat a lot in this function. long_expression is different every time. I am trying to find a way to avoid repeating long_expression, but keeping this compact. Something like the opposite of operator ??. For the moment I'm considering just giving in and putting it on multiple lines like:\n\nvar temp = long_expression;\nvar a = (temp == null) ? null : temp.Method();\n\n\nBut I was curious if there is some clever syntax I don't know about that would make this more concise."
] | [
"c#",
"syntax"
] |
[
"custom EditProfile in Django forms, submit button not working",
"I created EditProfile FORMs, in my forms.py file:\n from django.contrib.auth.forms import UserChangeForm\n from korisnici.models import CustomKorisnici\n from django import forms\n\n\n\nclass EditProfile(UserChangeForm):\n email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'}))\n first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))\n last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))\n phone_number = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))\n bio = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))\n phone_number = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'}))\n\n class Meta:\n model = CustomKorisnici\n fields = ('username', 'first_name', 'last_name', 'email','bio','phone_number','profile_image')\n\n def __init__(self, *args, **kwargs):\n super(EditProfile, self).__init__(*args, **kwargs)\n self.fields['username'].widget.attrs['class'] = 'form-control'\n self.fields['phone_number'].required = False\n self.fields['profile_image'].required = False\n self.fields['bio'].required = False\n\nAfter I run a default Django form in my HTML file(edit_profile.html):\n<div class="form-group">\n <div class="container">\n <div class="form">\n <form method="post" enctype="multipart/form-data">\n {% csrf_token %}\n {{ form.as_p }}\n <button id="btn" class="btn" type="submit">Edit Profile</button>\n </form>\n </div>\n </div>\n </div>\n\nWhen I click on submit button, it is working fine, my profile page was edit and data is change in base.\nBut when I customize my form in bootstrap, the submission button is not doing anything. Here is my bootstrap form:\n<form method="post" enctype="multipart/form-data">\n {% csrf_token %}\n <div class="form-group">\n <label >Username</label>\n <input type="text" class="form-control" name="username">\n </div>\n <div class="form-group">\n <label >First name</label>\n <input type="text" class="form-control" name="first_name">\n </div>\n <div class="form-group">\n <label >Last name</label>\n <input type="text" class="form-control" name="last_name">\n </div>\n <div class="form-group">\n <label >Email </label>\n <input type="email" class="form-control" name="email">\n </div>\n <div class="form-group">\n <label >Biography </label>\n <input type="text" class="form-control" name="bio">\n </div>\n <div class="form-group">\n <label >Phone number</label>\n <input type="text" class="form-control" name="phone_number">\n </div>\n <div class="form-group">\n <label >Profile image</label>\n <input type="file" class="form-control" name="profile_image">\n </div>\n\n <button id="btn" class="btn" type="submit">Edit Profile</button>\n</form>\n\nand view.py:\n class UserEditProfileView(generic.UpdateView):\n form_class = EditProfile\n template_name = 'registration/edit_profile.html'\n success_url = reverse_lazy('home')\n\n def get_object(self):\n return self.request.user"
] | [
"python",
"django",
"django-views",
"django-forms",
"django-bootstrap4"
] |
[
"View Controller with Embedded Navigation Controller linked to tableview",
"Mainly, my iphone application right now is a UIviewController with navigation buttons, logo, and title on the top of the screen. Inside this controller is a container view, which has an embedded navigation controller which leads to a series of table views that the user can navigate through. On the parent view, there is a back button that causes the inner navigaion controller to call popViewController and also updates the title of the screen on the outer view. This all works correctly, but when the user clicks the back button quickly, the naviagtion controller will already be in motion and “pop” again, but the title will update, causing the pages to become out of sync. \n\nI have tried to block the back button and even used completion handlers, but nothing seems to work. Is there really no way for me to be able to prevent the back button from being clicked while the inner navigation controller is busy?"
] | [
"ios",
"swift",
"popviewcontroller"
] |
[
"Bloom filter with bitwise operations in python",
"Consider the following Python implemetation for the bloom filter:\n\nclass BloomFilter(object):\n \"\"\"A simple bloom filter for lots of int/str\"\"\"\n\n def __init__(self, array_size=(1 * 1024), hashes=13):\n \"\"\"Initializes a BloomFilter() object:\n Expects:\n array_size (in bytes): 4 * 1024 for a 4KB filter\n hashes (int): for the number of hashes to perform\"\"\"\n\n self.filter = bytearray(array_size) # The filter itself\n self.bitcount = array_size * 8 # Bits in the filter\n self.hashes = hashes # The number of hashes to use\n\n def _hash(self, value):\n \"\"\"Creates a hash of an int and yields a generator of hash functions\n Expects:\n value: int()\n Yields:\n generator of ints()\"\"\"\n\n # Build an int() around the sha256 digest of int() -> value\n value = value.__str__() # Comment out line if you're filtering strings()\n digest = int(sha256(value).hexdigest(), 16)\n for _ in range(self.hashes):\n yield digest & (self.bitcount - 1)\n digest >>= (256 / self.hashes)\n\n def add(self, value):\n \"\"\"Bitwise OR to add value(s) into the self.filter\n Expects:\n value: generator of digest ints()\n \"\"\"\n for digest in self._hash(value):\n self.filter[(digest / 8)] |= (2 ** (digest % 8))\n\n\n def query(self, value):\n \"\"\"Bitwise AND to query values in self.filter\n Expects:\n value: value to check filter against (assumed int())\"\"\"\n return all(self.filter[(digest / 8)] & (2 ** (digest % 8)) \n for digest in self._hash(value))\n\n\nA simple use of this bloom filter would be:\n\nbf = BloomFilter()\n\nbf.add(30000)\nbf.add(1230213)\nbf.add(1)\n\nprint(\"Filter size {0} bytes\").format(bf.filter.__sizeof__())\nprint bf.query(1) # True\nprint bf.query(1230213) # True\nprint bf.query(12) # False\n\n\nCan you explain in detail how the hash functions are used? For example in the line:\n\nself.filter[(digest / 8)] |= (2 ** (digest % 8))\n\n\nit seems that the code is using OR and AND operations to write to the filter using the hash functions created using self._hash but I cannot understand how this bitwise operation works when adding and querying values to/from the filter.\n\n\nWhy the 2**(digest %8)?\nWhy the use of OR to write to the filter and AND to query?"
] | [
"python",
"bloom-filter"
] |
[
"Are there any tools for monitoring database during debugging in android?",
"I want to monitor the contents of my database during debugging, i.e, I want to see all the rows in the tables, and see the updates as and when they take place. Currently, I'm using android.util.Log. But, if there is a better way to do it, that would be nice. Thanks."
] | [
"android",
"database",
"sqlite"
] |
[
"MultiAutoCompleteTextView android restrict user from selecting same value multiple times",
"MultiAutoCompleteTextView android how to restrict user from selecting same value multiple times?"
] | [
"android",
"xamarin.android",
"multiautocompletetextview"
] |
[
"Visualization of continous availability of several URLs",
"I need to monitor several Sites (say around 300 Urls) for its availability continuously. I can understand that Checking for all the sites availability and populating it on a single dashboard with individual sites may not be a good Visualization solution.\n\nCan someone help me with what kind of visualization this use case can be achieved. I am using nodejs app for getting the data of the sites availability at regular intervals.\n\nLooking for suggestion with any opensource framework is also great.\n\nThank you."
] | [
"javascript",
"url",
"monitoring",
"visualization",
"availability"
] |
[
"Where to create session instances?",
"So I am creating C++ HTTP emulating via TCP server. I will have simple authentification service which will be created in C++. I will have sessions. I wonder which form shall I give them - real files on server or lines in SQL Lite db I use for my server? Or just keep them in RAM? Which way is better for performance / safety?"
] | [
"c++",
"session"
] |
[
"Matplotlib funcanimation with different size of data",
"I got some problems with using funcanimation.\nCodes are as below:\n graph = ax.scatter(x_data, y_data, z_data, c=c, cmap="jet", alpha=0)\n plt.colorbar(graph)\n\n\n def update_graph(num):\n up_time = t_stamp[threshold[num]]\n up_x = x_data[threshold[num]:threshold[num + 1]]\n up_y = y_data[threshold[num]:threshold[num + 1]]\n up_z = z_data[threshold[num]:threshold[num + 1]]\n\n graph._offsets3d = (up_x, up_y, up_z)\n title.set_text(f'{up_time}')\n\n ani = FuncAnimation(fig, update_graph, frames=2, interval=10, blit=False, repeat=False)\n\nI initialized the graph with the all data so that the colorbar could be set within proper range,\nand in update_graph, the size of up_x&up_y&up_z changes iteratively.\nBut I think _offsets3d doesn't allow the changes of the number of data, which throws an error:\nValueError: operands could not be broadcast together with remapped shapes [original->remapped]: (337899,4) and requested shape (1,4)\n\nThen how can I animate a scatter plot when the size of data continuously changes?\nAny hints or advices are welcomed.\nThanks in advance :)"
] | [
"python",
"matplotlib"
] |
[
"how to generate PNG/JPG of excel range?",
"how to generate PNG/JPG of excel range?\nI need to send letter which contains content from sheet in my excel file like picture. \n\nHow I can do this? \n\nThanks."
] | [
"java",
"excel"
] |
[
"How to get latest commit from development branch",
"I cloned the develop branch:\n\ngit clone --branch 1.1/develop --recursive git://github.com/fuel/fuel.git\n\n\nbut the files cloned do not show commits to the development branch like:\n\nhttps://github.com/fuel/core/commit/8d964dd62e017c5e45e4827f0f0c7d1df26dd395\n\n\nHow can I get the latest commits to the development branch?"
] | [
"git",
"github",
"fuelphp"
] |
[
"JMeter issues when running large number of threads",
"I'm testing using Apache's Jmeter, I'm simply accessing one page of my companies website and turning up the number of users until it reaches a threshold, the problem is that when I get to around 3000 threads JMeter doesn't run all of them. Looking at the Aggregate Graph \nit only runs about 2,536 (this number varies but is always around here) of them. \n\nThe partial run comes with the following exception in the logs:\n\n01:16 ERROR - jmeter.JMeter: Uncaught exception: \njava.lang.OutOfMemoryError: unable to create new native thread\n at java.lang.Thread.start0(Native Method)\n at java.lang.Thread.start(Unknown Source)\n at org.apache.jmeter.threads.ThreadGroup.start(ThreadGroup.java:293)\n at org.apache.jmeter.engine.StandardJMeterEngine.startThreadGroup(StandardJMeterEngine.java:476)\n at org.apache.jmeter.engine.StandardJMeterEngine.run(StandardJMeterEngine.java:395)\n at java.lang.Thread.run(Unknown Source)\n\n\nThis behavior is consistent. In addition one of the times JMeter crashed in the middle outputting a file that said:\n\n# There is insufficient memory for the Java Runtime Environment to continue.\n# Native memory allocation (malloc) failed to allocate 32756 bytes for ChunkPool::allocate\n# Possible reasons:\n# The system is out of physical RAM or swap space\n# In 32 bit mode, the process size limit was hit\n# Possible solutions:\n# Reduce memory load on the system\n# Increase physical memory or swap space\n# Check if swap backing store is full\n# Use 64 bit Java on a 64 bit OS\n# Decrease Java heap size (-Xmx/-Xms)\n# Decrease number of Java threads\n# Decrease Java thread stack sizes (-Xss)\n# Set larger code cache with -XX:ReservedCodeCacheSize=\n# This output file may be truncated or incomplete.\n#\n# Out of Memory Error (allocation.cpp:211), pid=10748, tid=11652\n#\n# JRE version: 6.0_31-b05\n# Java VM: Java HotSpot(TM) Client VM (20.6-b01 mixed mode, sharing windows-x86 )\n\n\nAny ideas?\nI tried changing the heap size in jmeter.bat, but that didn't seem to help at all."
] | [
"jmeter"
] |
[
"Configure Azure DevOps email template",
"I have configured Microsoft Azure DevOps to build our software and release it automatically. (With the Build and with the release Pipeline) \nAfter the succesful release I have set it up, to send an email to all project-members.\n\nMy question is: Can I somehow configure this email? \n\nE.g. I need to remove the \"Summary\" part. Is this somehow possible with Azure Devops?\n\nScreenshot of current email:"
] | [
"azure",
"azure-devops",
"azure-pipelines",
"pipeline",
"azure-pipelines-release-pipeline"
] |
[
"I keep getting 0 as the value of this variable",
"I'm trying to write this program to calculate simple interest on a deposit. It's supposed to add the interest money onto the original deposit. \n\nBut it keeps making variable \"rate\" 0 which is why when I run it, the result is 0. Any help is appreciated.\n\n #include <stdio.h>\n\nint main(void){\n\n double d;\n double rate;\n double y;\n double final;\n int x;\n\n printf(\"Enter the deposit: \");\n scanf(\"%d\", &d);\n\n printf(\"Enter the interest rate (0-100): \");\n scanf(\"%d\", &rate);\n\n printf(\"Enter the number of years: \");\n scanf(\"%i\", &x);\n\n rate = rate / 100;\n\n y = d * rate * x;\n\n final = d + y;\n\n\n printf(\"After %i number of years, the deposit in the savings account is now %d\", x, rate);\n\n}"
] | [
"c",
"calculator"
] |
[
"Spring Data JPA Repositories",
"I have a repository definition like\n\npublic interface UserRepository extends CrudRepository<User, Long> {}\n\n\nIn the Spring context file I have \n\n<jpa:repositories base-package=\"my.package\"/>\n\n\nThen I try to do something like\n\nnew Repositories(applicationContext).getRepositoryFor(User.class);\n\n\nbut I get the error\n\n\n Method \"getRepositoryFor\" with signature\n \"(Ljava/lang/Class;)Lorg/springframework/data/repository/CrudRepository;\"\n is not applicable on this object\n\n\nDoes anyone have any idea what could have I done wrong?"
] | [
"java",
"spring",
"jpa",
"spring-data",
"spring-data-jpa"
] |
[
"Xcode convert code of rest web service to swift",
"This button action below allows the user when logging with the two textfields emailLogin.text, passwordLogin.text to go to a web view and display login successful with the web servers data. Using a restful web service through a Post method.I want to convert this code to swift to allow me to do the same thing.\n\n- (IBAction)btnLogin:(id)sender {\n //if there is a connection going on just cancel it.\n [self.connection cancel];\n\n //initialize new mutable data\n NSMutableData *data = [[NSMutableData alloc] init];\n self.receivedData = data;\n [data release];\n\n //initialize url that is going to be fetched.\n NSURL *url = [NSURL URLWithString:@\"http://192.168.1.9/phploginws/index.php\"];\n //NSURL *url = [NSURL URLWithString:@\"http://192.168.1.9/MyWebService.php\"];\n\n //initialize a request from url\n NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];\n\n //set http method\n [request setHTTPMethod:@\"POST\"];\n //initialize a post data\n NSString *postData = [NSString stringWithFormat:@\"tag=login&email=%@&password=%@\", emailLogin.text, passwordLogin.text];\n\n\n //NSString *postData = [[NSString alloc] initWithString:@\"tag=login&[email protected]&password=12345\"];\n //NSString *postData = [[NSString alloc] initWithString:@\"rw_app_id=1&code=test&device_id=test\"];\n\n //set request content type we MUST set this value.\n\n [request setValue:@\"application/x-www-form-urlencoded; charset=utf-8\" forHTTPHeaderField:@\"Content-Type\"];\n\n //set post data of request\n [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];\n\n //initialize a connection from request\n NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];\n self.connection = connection;\n [connection release];\n\n //start the connection\n [connection start];\n\n}"
] | [
"xcode",
"rest",
"swift",
"post"
] |
[
"Relaunch browser via Selenium remote webdriver after remote VM reboot",
"I'm running selenium scripts on remote VM via selenium remote webdriver where for each test i will be rebooting the VM. Below is the sample program used where the browser launch fails for the second after VM reboot.\n\n WebDriver driver;\n DesiredCapabilities capabilities=new DesiredCapabilities();\n capabilities.setCapability(\"platformVersion\", \"40.0.2\");\n capabilities.setCapability(\"platformName\", \"WINDOWS\");\n capabilities.setCapability(\"browserName\", \"firefox\");\n driver= new RemoteWebDriver(new URL(\"http://10.86.101.217:4444/wd/hub\"), capabilities);\n driver.quit();\n// Rebooting the VM, Selenium server started after rebooting\n\n Thread.sleep(200000);\n System.out.println(\"end\");\n\n driver= new RemoteWebDriver(new URL(\"http://10.86.101.217:4444/wd/hub\"), capabilities);\n Thread.sleep(3000);\n System.out.println(\"end 2\");"
] | [
"selenium",
"virtual-machine",
"ui-automation",
"remotewebdriver"
] |
[
"\"File can not be opened\" compiler error in MPLABX /MPLAB IDE",
"I'm a newbie trying to lean PIC, I downloaded MPLAB and MPLAB X IDE. I have done this around 100 times and looked over web enough before asking this question, but my code does not compile and it always fails.\n\nHere is what I did:\n\n\nCreated a new project using the project wizard,\nEdited the code,\nCopied the 16F871.H library header in both folder (I created the project in) and added it to the header files in MPLAB IDE.\n\n\nHere's my code:\n\n// IFIN.C Tests an input\n#include \" 16F877A.h \"\nvoid main()\n{\n int x; // Declare variable\n output_D(0); // Clear all outputs\n while(1) //\n {\n x = input(PIN_C0); // Get input state\n if(x = = 1)\n output_high(PIN_D0); // Change output\n }\n}\n\n\nBut on compiling the code, I'm getting the following error:\n\nExecuting:\n\"C:\\Program Files\\PICC\\Ccsc.exe\" +FM \"NEW.c\" #__DEBUG=1 +ICD +DF +LN\n+T +A +M +Z +Y=9 +EA #__16F877A=TRUE\n\n*** Error 18 \"NEW.c\" Line 2(10,23): File can not be opened\n Not in project \"C:\\Users\\jatin\\Desktop\\DHAKKAN PIC\\ 16F877A.h \"\n Not in \"C:\\Program Files\\PICC\\devices\\ 16F877A.h \"\n Not in \"C:\\Program Files\\PICC\\drivers\\ 16F877A.h \"\n*** Error 128 \"NEW.c\" Line 2(10,17): A #DEVICE required before this line\n*** Error 12 \"NEW.c\" Line 6(9,10): Undefined identifier -- output_D\n*** Error 12 \"NEW.c\" Line 9(10,11): Undefined identifier -- input\n*** Error 51 \"NEW.c\" Line 10(8,9): A numeric expression must appear here\n\n 5 Errors, 0 Warnings. Build Failed. Halting build on first failure as requested. \nBUILD FAILED: Mon Jul 08 15:09:17 2013\n\n\nI would be grateful if you could help me."
] | [
"microcontroller",
"c"
] |
[
"Service returning generic observables of multiple types(potentialy) - can not subscribe",
"I'm building an app using Angular. I've looked for a solution but I couldn't figure out one.\nI've created an abstract service with generic type of T:\n export abstract class AbstractService<T>{\n\n public _url;\n\n abstract getRequest(): Observable<T> | Observable<T[]>;\n\n abstract postRequest(val: T| null): Observable<T>;\n\n }\n\nwhen I try to subscribe to the service, I get a compilation error:\nthis.service.getRequest().subscribe((data)=>{...})\n\nI want the component calling the service to behave differently depending on the observable.\nI tried typechecking as follow:\nlet observable = this.service.getRequest()\nif(typeof(observable) === typeof(Observable<T>)){...}\n\nThat didn't work either.\nIs it even possible to check the type? is there a mechanism to handle this?"
] | [
"angular",
"typescript",
"generics",
"rxjs"
] |
[
"Data binding within an object and to the DOM",
"This is an extreme simplification of what I want to build(loan interest calculator). I have three fields. Whenever one field is changed, I want the others to change in order to satisfy this algebraic equation:\n\nA = B * C\nB = A / C\nC = A / B\n\n\nI think I want to bind these values with an object, but I'm not sure how to go about this. Here is the set up i have so far:\n\nvar binder = {\n a: 2,\n b: 1,\n c: 1\n};\n\n$('input[type=number]').on('change', function() {\n var id = $(this).attr('id');\n var value = id.val();\n binder[id] = Number($(this).val()); \n});\n\n\nAt this point I've set the corresponding key in the object to the value of the currently active field. I could run through a bunch of case() statements like:\n\nswitch( id ) {\n case a :\n binder.b = $(this).val()/binder.c;\n binder.c = $(this).val()/binder.b;\n break; \n etc.\n}\n\n\nI also need to update the field values. This seems unsustainable, especially when the number of fields grow, and the computation becomes more complex. My question is then twofold:\n\nHow do I bind the fields' values to the object?\n\nHow do I bind the object's values to each other?"
] | [
"javascript",
"oop",
"data-binding"
] |
[
"Spark on Windows - \"The system cannot find the path specified.\"",
"This seems like a common problem with trying to use Spark on Windows from the research I've done so far, and usually has to do with the PATH being set incorrectly.\nI've triple checked the PATH however, and tried out many of the solutions I've come across online, and I still can't figure out what's causing the problem.\n\nTrying to run spark-shell from the command prompt in Windows 7 (64-bit) returns The system cannot find the path specified.\n\n\nHowever I can run that same command from within the directory where the spark-shell.exe is located (albeit with some errors), which leads me to believe that this is a PATH issue like most of the other posts regarding this problem on the internet. However...\nSpark-shell works when called from directory:\n\nShell appears to be working:\n\n\nFrom what I can tell, my PATH appears to be set correctly. Most of the solutions for this issue that I've come across involve fixing the %JAVA_HOME% system variable to point to the correct location and adding '%JAVA_HOME%/bin' to the PATH (along with the directory holding 'spark-shell.exe'), however both my JAVA_HOME variable and PATH variable appear to contain the required directories."
] | [
"java",
"apache-spark",
"path",
"windows-7-x64"
] |
[
"Resetting the model values",
"I have an ng-model=\"name\" in my html page. It is connected to the main controller. The model is used to submit the name in a form using ng-submit= formfilled(name). But after the form is submitted, I want the name input field to be blank again. How can I do this?\n\nI was trying to do $scope.name = \"\" on my controller after the form is submitted, but it's not working. \n\nIf I understand correctly, the ng-model creates the name you give it as a variable in the scope right?"
] | [
"angularjs",
"forms",
"reset",
"angular-ngmodel",
"ng-submit"
] |
[
"Changing Opacity With Reactive Extensions",
"<rant>Yes, I know this would be easier to implement in WPF. I hear that a lot. Sadly, It is not possible.\n </rant>\n\n\nI am writing a WinForms app, and I need to \"fade\" a Control in & out. Transparency is all but impossible in WinForms, so I am trying to use opacity: the idea is to change the Alpha channel of each child control's ForeColor property over a period of time. This seems like a perfect time to work on my Reactive Extensions! \n\nMy possible solution is:\n\nprivate void FadeOut()\n{\n // our list of values for the alpha channel (255 to 0)\n var range = Enumerable.Range(0,256).Reverse().ToList();\n\n // how long between each setting of the alpha (huge value for example only)\n var delay = Timespan.FromSeconds(0.5);\n\n // our \"trigger\" sequence, every half second\n Observable.Interval(delay)\n // paired with the values from the range - we just keep the range\n .Zip(range, (lhs, rhs) => rhs)\n // make OnNext changes on the UI thread\n .ObserveOn(SynchronizationContext.Current)\n // do this every time a value is rec'd from the sequence\n .Subscribe(\n // set the alpha value\n onNext:ChangeAlphaValues, \n // when we're done, really hide the control\n onCompleted: () => Visible = false, \n // good citizenry\n onError: FailGracefully);\n}\n\n// no need to iterate the controls more than once - store them here\nprivate IEnumerable<Control> _controls;\n\nprivate void ChangeAlphaValues(int alpha)\n{\n // get all the controls (via an extension method)\n var controls = _controls ?? this.GetAllChildControls(typeof (Control));\n\n // iterate all controls and change the alpha\n foreach (var control in controls)\n control.ForeColor = Color.FromArgb(alpha, control.ForeColor);\n}\n\n\n... which looks impressive, but it doesn't work. The really impressive part is that it doesn't work in two ways! Gonna get a \"Far Exceed\" on my next performance review if I keep this up. :-)\n\n\n(Not really the Rx part of the problem) The alpha values don't actually seem to make any difference. Despite setting the values, the display looks the same.\nIf I close the window before the sequence is complete, I get the following error: \n\n\n\n System.InvalidOperationException was unhandled\n Message: An unhandled exception of type 'System.InvalidOperationException' occurred in System.Reactive.Core.dll\n Additional information: Invoke or BeginInvoke cannot be called on a control until the window handle has been created.\n\n\nI assume this is where a cancellation token would come in handy - but I have no idea how to implement it. \n\nI need guidance on:\n\nHow to close the window gracefully (i.e. without throwing an error) if the sequence is still running, and how to get the alpha values for the colors to actually display after they're changed.\n\n... or maybe this is the wrong approach altogether.\n\nI'm open to other suggestions."
] | [
"c#",
"winforms",
"system.reactive",
"opacity"
] |
[
"constructor vs typeof to detect type in JavaScript",
"In this question I did not see suggestions to use constructor.\n\nSo instead of typeof callback == \"function\"\n\nI would use callback && (callback.constructor==Function).\n\nTo me it seems obvious that comparison to memory pointers is always better than comparison to strings in terms of both runtime performance and coding safety.\n\nWhy not use constructor to detect all types and forget about ugly typeof?\n\nIt works for all primitive types, functions and arrays:\n\nundefined === undefined\nnull === null\n[1,2,3].constructor == Array \n(1).constructor == Number\n(true).constructor == Boolean\n(()=>null).constructor == Function\n'abc'.constructor == String\n(new Date()).constructor == Date\nelse it's an object, where instanceof helps to detect it's parents if needed.\n\n\nIf string interning can be relied upon then runtime performance advantage goes away. But safe coding advantage still stays."
] | [
"javascript",
"types",
"constructor",
"detection",
"typeof"
] |
[
"Getting undefined value while returning json value from controller",
"Here I want to get all the values which I inserted into the json data in a table before getting submitted but unfortunately am not getting the results I want. So far I have done this. Please have a look.\n\n<script>\n $(\"#getdata\").on('click',function () {\n var form_data={ \n agent_name: $('#agent_name').val(),\n number: $('#number').val(),\n quantity: $('#quantity').val(),\n date: $('#date').val(),\n commision: $('#commision').val(),\n profit: $('#profit').val(),\n agent_amount: $('#agent_amount').val(),\n user_id: $('#user_id').val(),\n type: name_type.val(),\n }\n\n $.ajax({\n type: 'POST',\n url: '<?php echo base_url();?>admin_control/ajax_data',\n data: form_data,\n dataType:\"json\", //to parse string into JSON object,\n success: function(data){ \n if(data){\n var len = data.length;\n alert(len);\n var txt = \"\";\n if(len > 0){\n for(var i=0;i<len;i++){\n if(data[i].number && data[i].type){\n txt += $('#table').append('<tr><td>data[i].type</td><td>data[i].number</td><td>data[i].quantity</td><td>data[i].amount</td><td><input type=\"checkbox\" class=\"add_checkbox\" name=\"layout\" id=\"add_checkbox\" value=\"1\" checked></td></tr>');\n\n }\n }\n if(txt != \"\"){\n\n $(\"#table\").append(txt).removeClass(\"hidden\");\n }\n }\n }\n },\n error: function(jqXHR, textStatus, errorThrown){\n alert('error: ' + textStatus + ': ' + errorThrown);\n }\n});\nreturn false;\n });\n</script> \n\n\nHere I want to pass the values of json_data in to the table i had written and how can we pass that here am getting error like undefined.\n\nHere is my controller\n\npublic function ajax_data()\n {\n $array = array(\"agent_name\" => $_POST['agent_name'],\"number\"=>$_POST['number'],\"type\"=>$_POST['type'],\"quantity\"=>$_POST['quantity'],\"date\"=>$_POST['date'],\"commision\"=>$_POST['commision'],\"profit\"=>$_POST['profit'],\"agent_amount\"=>$_POST['agent_amount'],\"user_id\"=>$_POST['user_id']);\n $data['json'] = $array;\n echo json_encode($data);\n}\n\n\nhere is my json_data which looks like this \n\n{\"json\":{\"agent_name\":\"admin\",\"number\":\"444\",\"type\":\"super\",\"quantity\":\"4\",\"date\":\"2018-02-14 15:16:27\",\"commision\":\"10.00\",\"profit\":\"40.00\",\"agent_amount\":\"0.00\",\"user_id\":\"1\"}}"
] | [
"javascript",
"jquery",
"json",
"ajax",
"codeigniter-3"
] |
[
"XML file contents to text area and PHP: Remove character replacement",
"I have a xml file which I'm retrieving its data with this PHP function file_get_contents().\n\nMy intention is to provide an editor for this XML file, so the XML contents string are loaded in a textarea, then edited (if needed), and saved with file_put_contents()\n\nThe string that PHP returns contains replacement characters (the �). How can I remove this or find a better solution to this?\n\nMy xml file looks like this:\n\n<?xml version=\"1.0\"?>\n<BCPFORMAT xmlns=\"http://schemas.microsoft.com/sqlserver/2004/bulkload/format\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n <RECORD>\n <FIELD ID=\"1\" xsi:type=\"CharTerm\" TERMINATOR=\",\" MAX_LENGTH=\"100\" COLLATION=\"SQL_Latin1_General_CP1_CI_AS\"/>\n <FIELD ID=\"2\" xsi:type=\"CharTerm\" TERMINATOR=\",\" MAX_LENGTH=\"100\" COLLATION=\"SQL_Latin1_General_CP1_CI_AS\"/>\n <FIELD ID=\"3\" xsi:type=\"CharTerm\" TERMINATOR=\",\" MAX_LENGTH=\"100\" COLLATION=\"SQL_Latin1_General_CP1_CI_AS\"/>\n <FIELD ID=\"4\" xsi:type=\"CharTerm\" TERMINATOR=\",\" MAX_LENGTH=\"100\" COLLATION=\"SQL_Latin1_General_CP1_CI_AS\"/>\n\n\nand it's retrieved as this:\n\n<�?xml version=\"1.0\"?>\n<BCPFORMAT xmlns=\"http://schemas.microsoft.com/sqlserver/2004/bulkload/format\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n <RECORD>\n <FIELD ID=\"1\" xsi:type=\"CharTerm\" TERMINATOR=\",\" MAX_LENGTH=\"100\" COLLATION=\"SQL_Latin1_General_CP1_CI_AS\"/>\n <FIELD ID=\"2\" xsi:type=\"CharTerm\" TERMINATOR=\",\" MAX_LENGTH=\"100\" COLLATION=\"SQL_Latin1_General_CP1_CI_AS\"/>\n <FIELD ID=\"3\" xsi:type=\"CharTerm\" TERMINATOR=\",\" MAX_LENGTH=\"100\" COLLATION=\"SQL_Latin1_General_CP1_CI_AS\"/>\n <FIELD ID=\"4\" xsi:type=\"CharTerm\" TERMINATOR=\",\" MAX_LENGTH=\"100\" COLLATION=\"SQL_Latin1_General_CP1_CI_AS\"/>"
] | [
"php",
"xml"
] |
[
"How to observe state of related object in model?",
"How can I observe the state of the Session object for changes from my movie model? I need that method for determining if the current user is authenticated and the owner of each movie in order to allow editing. Property works but doesn't react to changes in the Session object. Observes won't work for now with an if clause in the handlebars template.\n\nCode so far:\n\nApp.Movie = Ember.Model.extend({\n title: Ember.attr(),\n year: Ember.attr(),\n\n owner: Ember.belongsTo('App.User', {\n key: 'owner',\n serializer: UserType\n }),\n\n canEdit: function() {\n var owner = this.get('owner');\n\n console.log(owner, App.Session.objectId, owner.get('objectId'));\n\n if (owner && App.Session.objectId === owner.get('objectId')) {\n return true;\n }\n\n return false;\n }.property('App.Session.objectId', 'owner')\n // }.observes('App.Session.objectId', 'owner')\n});\n\n{{#each movie in this}}\n <tr>\n <td>{{movie.year}}</td>\n <td>{{movie.title}}</td>\n {{#if movie.canEdit}}\n <td>\n <span class=\"clickable glyphicon glyphicon-remove pull-right\" {{action \"doDeleteMovie\" movie}}></span>\n <span class=\"clickable glyphicon glyphicon-pencil pull-right\" {{action \"doUpdateMovie\" movie}}></span>\n </td>\n {{else}}\n <td>\n <span class=\"glyphicon glyphicon-remove pull-right text-muted\"></span>\n <span class=\"glyphicon glyphicon-pencil pull-right text-muted\"></span>\n </td>\n {{/if}}\n {{/if}}\n </tr>\n{{/each}}"
] | [
"javascript",
"ember.js"
] |
[
"Different HTTP Response to Same Request on Dev/Prod machine phenomena",
"i have a service that is query data from a specific seller...\nit is requesting https://www.ace.co.il and parsing the html for the needed info...\nOn my PC at home, everything seem to work well.\nWhen i deploy it to google-cloud app-engine, it seems the response is different!\ni set up a Minimal example to show my issue:\nconst axios = require('axios');\n \n// Make a request for a user with a given ID\naxios.get('http://www.ace.co.il')\n .then(function (response) {\n // handle success\n console.log(`Got ${response.data.length} chars`);\n console.log(`First 100:`);\n console.log(response.data.slice(0, 100));\n })\n .catch(function (error) {\n // handle error\n console.log(error);\n })\n .then(function () {\n // always executed\n });\n\nit request the url ace.co.il and gets the length of the response,\nalso types the first 100 chars.\non my machine, the output is (which is good)\nGot 236345 chars\nFirst 100:\n<!DOCTYPE html>\n<html lang="he-il">\n <head>\n <meta charset="utf-8">\n<meta name="HandheldFriendly" c\n\nwhen i use Repl.it with the same code\nthe output is :\nGot 98475 chars\nFirst 100:\n<html><head><meta charset="utf-8"><script>X0ww.Y2B=function (){return typeof X0ww.E2B.C2B==='functio\n\nwhich looks like a Obfuscated Javascript to annoy the browser.\nI tried also to see how a snap-shot service will work, so i tried https://www.site-shot.com/\nand it got the html correctly...\nI Assume it is something to do with the Region, and timezone or smth\nBut failed to see how i fake it or check it.\n\nHow can that be?\nAny ideas what to look for?\nCan you try from your PC?"
] | [
"node.js",
"http",
"web",
"request",
"axios"
] |
[
"Router link changes the path but Router view doesn’t change",
"So i have a side navbar and some link in it. The entry point is the homepage. The problem is, when i'm trying to change router-view using router-link in my side navbar, the router-view doesn't change, but the path has change.\n\nSo here's my route path on my router.js: \n\n {\n path: '/',\n component: Home,\n children: [\n {\n path: ':name',\n name: 'theTask',\n props: true,\n component: TodoList\n }\n ]\n }, \n ],\n\n\nAnd here's my App.vue\n\n<div class=\"container\">\n <div class=\"main__content\">\n <div class=\"sidenav\">\n <aside class=\"menu\">\n <ul class=\"menu-list\">\n <li><router-link :to=\"{ name: 'theTask', params: {name: 'today'} }\">Today</router-link></li>\n <li><router-link :to=\"{ name: 'home' }\">Next 7 Days</router-link></li>\n </ul>\n </aside>\n </div>\n <div class=\"content\">\n <router-view></router-view>\n </div>\n </div>\n </div> \n\n\nIt rendered the homepage, but when i'm clicking router-link to the child route, it doesn't change the router-view, only the router link."
] | [
"javascript",
"vue.js",
"vuejs2",
"vue-router"
] |
[
"Can someone explain Artificial Neural Networks?",
"According to Wikipedia (which is a bad source, I know) A neural network is comprised of \n\n\nAn input layer of A neurons\nMultiple (B) Hidden layers each comprised of C neurons.\nAn output layer of \"D\" neurons.\n\n\nI understand what does input and output layers mean.\n\nMy question is how to determine an optimal amount of layers and neuron-per-layer?\n\n\nWhat is the advantage/disadvantage of a increasing \"B\"?\nWhat is the advantage/disadvantage of a increasing \"C\"?\nWhat is the difference between increasing \"B\" vs. \"C\"?\n\n\nIs it only the amount of time (limits of processing power) or will making the network deeper limit quality of results and should I focus more on depth (more layers) or on breadth (more neurons per layer)?"
] | [
"artificial-intelligence",
"machine-learning",
"neural-network"
] |
[
"How to take the log of all elements of a list",
"I have an array \n\nx = [1500, 1049.8, 34, 351, etc]\n\n\nHow can I take log_10() of the entire array?"
] | [
"python",
"arrays"
] |
[
"Connection to https://api.parse.com refused",
"I have an application which has a login screen, there are two options, 1 login with twitter and 2. username and password.\n\nThis application is live on the store, however, I am currently getting some reports of connection being refused to api.parse.com. I have tested here on multiple devices and it's connecting fine.\n\nAre there any reasons that parse may refuse connection other than there being an issue with their servers? Could device imei etc come into play? I just find this unusual that it's happening for some and not others. Plus, I'll end up losing a lot of users in this way.\n\nAny guidance is appreciated.\n\nI'd really appreciate any help on this if anyone knows anything about it, parse.com status says it's fully operational, there's no parse forum any more, if someone could give me some insight it would be great"
] | [
"android",
"parse-platform"
] |
[
"Not able to receive window message in c# .net",
"I want to send message to other process already running. What wrong...? why I am not able to receive messages\nMy sender code is as below\n\npublic partial class RegisterWindowMessage : Form\n {\n [DllImport(\"User32.dll\", EntryPoint = \"SendMessage\")]\n\n //private static extern int SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);\n private static extern int SendMessage(IntPtr hWnd, int Msg, string s, int i);\n\n const int WM_SETTEXT = 0X000C;\n public RegisterWindowMessage()\n {\n InitializeComponent();\n }\n\n\n private void button1_Click(object sender, EventArgs e)\n {\n Process[] procs = Process.GetProcesses();\n foreach (Process p in procs)\n {\n if (p.ProcessName.Equals(\"TaskScheduling\"))\n {\n\n IntPtr hWnd = p.MainWindowHandle;\n\n Thread.Sleep(1000);\n SendMessage(hWnd, WM_SETTEXT, \"This is the new Text!!!\", 0);\n\n MessageBox.Show(\"Inside\");\n }\n }\n }\n\n private void button2_Click(object sender, EventArgs e)\n {\n }\n\n }\n\n\nMy receiver code is\n\npublic partial class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n }\n\n private void Form1_KeyDown(object sender, KeyEventArgs e)\n {\n\n }\n private void frmReceiver_KeyDown(object sender, KeyEventArgs e)\n {\n // this.lsvMsgList.Items.Add(e.KeyValue.ToString());\n }\n\n\n protected override void WndProc(ref Message m)\n {\n MessageBox.Show(m.Msg.ToString());\n MessageBox.Show(m.LParam.ToString());\n MessageBox.Show(m.WParam.ToString());\n if (m.LParam.ToInt32() == 1)\n {\n\n }\n else\n {\n base.WndProc(ref m);\n }\n }\n }\n\n\nI want to know why i am not able to receive message. Let me know where I am wrong"
] | [
"c#",
".net",
"window"
] |
[
"How to change the message in buildRules [CakePHP 3]?",
"The function below is for being sure the e-mail from form is unique, if it's already in use a message is showed. I want to change this message.\n\npublic function buildRules(RulesChecker $rules)\n{\n $rules->add($rules->isUnique(['username']));\n $rules->add($rules->isUnique(['email']));\n return $rules;\n}\n\n\nI tried this way:\n\n public function buildRules(RulesChecker $rules)\n {\n $rules->add($rules->isUnique(['username']));\n $rules->add($rules->isUnique(['email']), \n ['errorField' => 'email', 'message' => 'Este email já encontra-se em uso.']\n );\n return $rules;\n}\n\n\nIt works but both messages are being showed, the default one and mine."
] | [
"validation",
"cakephp",
"cakephp-3.0"
] |
[
"Nested table formatting with simple_form, nested_form and twitter-bootstrap",
"Update: I updated this after doing some digging and realizing that this might be twitter-bootstrap causing the problem.\n\nHere is a rough version of my nested form:\n\n<%= simple_nested_form_for @user, :html => { :class => 'form-horizontal' } do |f| %>\n <fieldset>\n <%= f.input :email %>\n <%= f.input :name_first %>\n <%= f.input :name_last %>\n\n <table class=\"table table-striped\">\n <thead>\n <tr>\n <th>Active</th>\n <th>Company</th>\n <th>Role</th>\n <th>Actions</th>\n </tr>\n </thead>\n <tbody>\n <%= f.simple_fields_for :roles, :wrapper_tag => :tr do |role_form| %>\n <td><%= role_form.hidden_field :id %><%= role_form.input :active, :label => false, :wrapper => false %></td>\n <td><%= role_form.association :company, :label => false, :wrapper => false %></td>\n <td><%= role_form.input :role, :label => false, :collection => [ \"Guest\", \"User\", \"Inspector\", \"Owner\"], :wrapper => false %></td>\n <td><%= role_form.link_to_remove \"Delete\", :class => 'btn btn-mini btn-danger' %>\n </td>\n <% end %> \n </tbody>\n </table>\n <p><%= f.link_to_add \"Add a Role\", :roles %></p>\n </div>\n\n <div class=\"form-actions\">\n <%= f.submit nil, :class => 'btn btn-primary' %>\n <%= link_to 'Cancel', users_path, :class => 'btn' %>\n </div>\n </fieldset>\n<% end %>\n\n\nWhen it's rendered the fields in the table rows are indented the same as the parent form via the { :class => 'form-horizontal' }. I just want the fields with no wrapper divs etc. and can't seem to figure it out. I thought the :wrapper => false was the ticket but no luck so far.\n\nDan"
] | [
"ruby-on-rails-3",
"twitter-bootstrap",
"nested-forms",
"simple-form"
] |
[
"My SQL error Unknown column 'w' in 'field list'",
"Hello I am new in PhP and trying to learn some stuff. \nso I am trying to make a \"Simple\" registration to start learning the basics as adding and extracting information to the database .\nI have the following code but when ever I add information in to the fields and press submit I get this error in return Unknown column 'w' in 'field list'\n'w' was in the First Name field \n\n<?php\ninclude('db.php');\nif(isset($_POST['submit'])){\n //Perform Verifications\n\n $pass = $_POST['password'];\n $cpass = $_POST['confirmpassword'];\n\n if($pass == $cpass)\n {\n //carry on\n $name = mysql_escape_string($_POST['firstname']);\n $uname = mysql_escape_string($_POST['username']);\n $pass = mysql_escape_string($_POST['password']);\n $cpass = mysql_escape_string($_POST['password']);\n\n mysql_query(\"INSERT INTO `users`(`id`, `firstname` , `username` , `password` ) VALUES (NULL, `$name`, `$uname` ,`$pass`)\") or die(mysql_error());\n\n }\n else\n {\n echo \"Sorry your passwords do not Match.<br />\"; \n exit();\n }\n\n}else{\n $form = <<<EOT\n<form action=\"\" method=\"POST\" >\nFull Name <input type=\"text\" name=\"firstname\" /> <br />\nUsername: <input type=\"text\" name=\"username\" /> <br />\nPassword: <input type=\"password\" name=\"password\" /> <br />\nConfirm Password: <input type=\"password\" name=\"confirmpassword\" /> <br />\n<input type=\"submit\" value=\"Register\" name=\"submit\" />\n</form>\nEOT;\n\necho $form;\n}\n\n\n?>\n\n\nin the db.php I just have the code to connect to the database"
] | [
"php",
"mysql",
"database"
] |
[
"Declared a List, Implement as LinkedList, cannot use getLast() method",
"I'm tried to create a linkedlist like below\n\nList<Integer> list = new LinkedList<>();\nint i = list.getLast();\n\n\nBut when I use getLast() method from LinkedList class, it reports \"cannot find symbol \"method getLast()\"\". \n\nIt appears that, since getLast() only exists in LinkedList class, and I declared list as a List, so I cast it into a more general form and lost some function.\n\nBut I'm curious how Java find a method name? Since I instantiate it as a LinkedList, can't it find this method in instantiated class?\nIs there any documents I can read about"
] | [
"casting"
] |
[
"DAG & Graph: Simple path from s to t that goes via as many colored vertices as possible",
"I have two seperate problems both revolving around graphs and determining an approach to find a simple path from s to t that goes via as many blue vertices as possible. Additionally I have to determine which one of the two problems that is NP-Hard. \n\nThe graph in the first problem is an undirected graph where some of the vertices are blue and the graph in the other problem is a a directed acyclic graph also where some of the vertices are blue. \n\nI have got a hint that the second problem with the directed acyclic graph, can be solved using dynamic programming, but I have a very hard time grasping how the problem can be modelled as a dynamic programming problem, as I do not quite see the overlapping of subproblems. Maybe one could demonstrate or clarify how this can be done? \n\nAlso the first problem should be the NPHard one, that can be reduced to a Hamiltonian Path, I can partly see how this is correct, but then the question arises, can the second problem with the directed acyclic graph then also be reduced to a Hamiltonian Path, also making it NPHard? Why or why not?"
] | [
"algorithm",
"graph",
"dynamic-programming",
"np-hard"
] |
[
"jQuery DataTable rendering applying only on one target at a time",
"I have a DataTable which fills its data through an ajax call. I'm rendering two targets but only the second target is being rendered. Below is my code\n\ncolumnDefs: [\n { responsivePriority: 1, targets: 1 },\n { responsivePriority: 2, targets: 2 },\n { responsivePriority: 3, targets: 3 },\n { responsivePriority: 7, targets: 4 },\n { responsivePriority: 4, targets: 5 },\n { responsivePriority: 5, targets: 6 },\n { responsivePriority: 6, targets: 7 },\n {\n 'targets': 2,\n 'render': function (data, type, full, meta) {\n return type === 'display' && data.length > 10 ?\n data.substr(0, 10) + '…' :\n data;\n },\n 'targets': 7,\n 'render': function (data, type, full, meta) {\n // Something here\n },\n}],\n\n\nHere only targets : 7 is rendering but not 2."
] | [
"jquery",
"datatables"
] |
[
"Firestore read/write pricing; does .limit(25) counts as 25 reads or one?",
"I am a bit confused as to whether a query like the one below counts as one read or 25 reads for Firestore pricing ? \n\nqueryRef.limit(25).get().then(()=>{\n\n...\n\n});\n\n\nI understand that in the pricing chart a \"document read\" has been defined as the unit but I am a bit confused about a query like above and need a confirmation."
] | [
"firebase",
"google-cloud-firestore"
] |
[
"No resources found that matches at AndroidManifest.xml",
"I am trying to follow this solution Broadcast Receiver Not Working After Device Reboot in Android, but I get the following error:\n\n\n No resource found that matches the given name (at 'resource' with value '@xml/my_accessibility_service').\n\n\n\n\nWith my_accessibility_service.xml : \n\n<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<accessibility-service\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:packageNames=\"myapp\"\n android:accessibilityFeedbackType=\"feedbackSpoken\"\n android:description=\"@string/service_desc\"\n android:notificationTimeout=\"100\">\n</accessibility-service>\n\n\nWhy is it happening?\nThanks."
] | [
"xamarin.forms",
"android-manifest",
"accessibilityservice"
] |
[
"Import error in iPython after installing umfpack",
"After installing the umfpack package (which I needed) I can no longer import any packages in an iPython Notebook. Any import command e.g\n\nimport numpy as np\n\n\nresults in a stream of errors the last of which is \n\n/Users/murray/anaconda/lib/python2.7/site-packages/numpy/core/__init__.py in <module>()\n 12 os.environ[envkey] = '1'\n 13 env_added.append(envkey)\n---> 14 from . import multiarray\n 15 for envkey in env_added:\n 16 del os.environ[envkey]\n\nImportError: dlopen(/Users/murray/anaconda/lib/python2.7/site-packages/numpy/core/multiarray.so, 2): Library not loaded: @rpath/libopenblas-r0.2.18.dylib\nReferenced from: /Users/murray/anaconda/lib/python2.7/site-packages/numpy/core/multiarray.so\nReason: image not found\n\n\nI'm really out of my depth herem so if you can help, assume I am a total novice."
] | [
"python-2.7",
"importerror"
] |
[
"When stringifying an object, JSON turns element nodes into Objects?",
"So I'm working on a little personal project and I came upon a problem. \n\nI need each day object to hold various dom element objects. These object instances are stored in an array and then that array needs to be stored into localStorage to load later. \n\nThe problem is when I do JSON.stringify and then JSON.parse it converts the HTML nodes into objects. So when I try to append element it tells me that the first parameter is not a node.\n\nfunction save() {\n\n localStorage.days = JSON.stringify(global.days); \n localStorage.numberOfDays = global.numberOfDays;\n localStorage.totalCount = global.totalCount;\n\n }\n\n function load() {\n\n var parsedDays = JSON.parse(localStorage.days);\n parsedDays.forEach(function(day){\n\n document.getElementById(\"mainPage\").appendChild(day.textObject);\n\n });\n\n\nanyone know how I can put an array of objects which hold elements into localStorage while keeping their node type????"
] | [
"javascript",
"html",
"json",
"dom",
"stringify"
] |
[
"Multiple case insensitive like comparisons in mysql",
"I am trying to create a book store search field that matches keywords in a book's title, subtitle, and author columns. I can get a single case insensitive like statement to work, but it seems to not work when I try under multiple columns. Can anyone help me find what is wrong? Or is there an easier way to accomplish this?\n\n $getbooks= mysql_query(\"SELECT * FROM books WHERE (\n LOWER(title) LIKE LOWER('%,\".$_GET['search'].\",%') \n OR LOWER(author) LIKE LOWER('%,\".$_GET['search'].\",%') \n OR LOWER(subtitle) LIKE LOWER('%,\".$_GET['search'].\",%')\n ) \n AND status='1' \n ORDER BY id DESC\");"
] | [
"mysql",
"sql",
"sql-like",
"case-insensitive"
] |
[
"ruby: undefined method `>>' for \"\\x0F\":String (NoMethodError)",
"I get such error when accessing my Redmine installation using Apache with FastCGI. What can be the reason for that?\n\n/usr/local/rvm/rubies/ruby-1.9.3-p374/lib/ruby/gems/1.9.1/gems/fcgi-0.8.8/lib/fcgi.rb:454:in `read_length': undefined method `>>' for \"\\x0F\":String (NoMethodError)\n from /usr/local/rvm/rubies/ruby-1.9.3-p374/lib/ruby/gems/1.9.1/gems/fcgi-0.8.8/lib/fcgi.rb:448:in `read_pair'\n from /usr/local/rvm/rubies/ruby-1.9.3-p374/lib/ruby/gems/1.9.1/gems/fcgi-0.8.8/lib/fcgi.rb:441:in `parse_values'\n from /usr/local/rvm/rubies/ruby-1.9.3-p374/lib/ruby/gems/1.9.1/gems/fcgi-0.8.8/lib/fcgi.rb:435:in `parse'\n from /usr/local/rvm/rubies/ruby-1.9.3-p374/lib/ruby/gems/1.9.1/gems/fcgi-0.8.8/lib/fcgi.rb:195:in `read_record'\n from /usr/local/rvm/rubies/ruby-1.9.3-p374/lib/ruby/gems/1.9.1/gems/fcgi-0.8.8/lib/fcgi.rb:126:in `next_request'\n from /usr/local/rvm/rubies/ruby-1.9.3-p374/lib/ruby/gems/1.9.1/gems/fcgi-0.8.8/lib/fcgi.rb:116:in `session'\n from /usr/local/rvm/rubies/ruby-1.9.3-p374/lib/ruby/gems/1.9.1/gems/fcgi-0.8.8/lib/fcgi.rb:104:in `each_request'\n from /usr/local/rvm/rubies/ruby-1.9.3-p374/lib/ruby/gems/1.9.1/gems/fcgi-0.8.8/lib/fcgi.rb:36:in `each'\n from /usr/local/rvm/rubies/ruby-1.9.3-p374/lib/ruby/gems/1.9.1/gems/rack-1.4.4/lib/rack/handler/fastcgi.rb:27:in `run'\n from /var/www/redmine/public/dispatch.fcgi:21:in `<main>'\n\n\nthe line mentioned in the error look like following (with line numbers), it's a fragment of fcgi.rg file:\n\n453 def self::read_length(buf)\n454 if buf[0] >> 7 == 0\n455 then buf.slice!(0,1)[0]\n456 else buf.slice!(0,4).unpack('N')[0] & ((1<<31) - 1)\n457 end\n458 end\n\n\nThanks,\nMark"
] | [
"ruby",
"redmine",
"fastcgi"
] |
[
"ARCore support for newly released terminals",
"I did a search on ARCore-enabled devices.\n\nhttps://developers.google.com/ar/discover/supported-devices\n\nIt doesn't say whether it will support the Galaxy Tab S5E.\n\nWill ARCore work on the Galaxy Tab S5E?"
] | [
"augmented-reality",
"arcore"
] |
[
"Cannot call toString() on numeric constant in Javascript",
"toString() doesn't work on numeric literal like 5.toString(), but it works on string literal (\"str\".toString()) or after the numeric literal is assigned to var, like var a = 5;a.toString(). Wondering why it doesn't work for the first case?"
] | [
"javascript"
] |
[
"Insert line in to pattern on text file python",
"I have a text file that takes the form of:\n\nfirst thing: content 1\nsecond thing: content 2\nthird thing: content 3\nfourth thing: content 4\n\n\nThis pattern repeats throughout the entire text file. However, sometimes one of the rows is completely gone like so:\n\nfirst thing: content 1\nsecond thing: content 2\nfourth thing: content 4\n\n\nHow could I search the document for these missing rows and just add it back with a value of \"NA\" or some filler to produce a new text file like this:\n\n# 'third thing' was not there, so re-adding it with NA as content\nfirst thing: content 1\nsecond thing: content 2\nthird thing: NA \nfourth thing: content 4\n\n\nCurrent code boilerplate:\n\nwith open('original.txt, 'r') as in:\n with open('output.txt', 'wb') as out:\n #Search file for pattern (Maybe regex?)\n #If pattern does not exist, add the line\n\n\nThanks for any help you all can offer!"
] | [
"regex",
"python-2.7",
"io"
] |
[
"Duplicates In a String",
"I need to write a function that takes a string and returns it with duplicate characters removed in Lua. What I need help with is...\n\n\nMaking a hash with letters and the counts\nMaking each letter equal to only one, deleting more than one occurrence\nConverting hash into the new string with duplicates removed\n\n\nA simple function/algorithm would be appreciated!"
] | [
"string",
"hash",
"lua",
"duplicates",
"character"
] |
[
"Some letters of Google Fonts appear broken on Mac",
"Some letters of Google Fonts (Work Sans, Exo 2 tested) appear broken on Mac when used on a website and viewed in a browser (or printed).\nWhy is it that way and is there a solution?\nExample of an "A" of Work Sans in a website viewed in a browser on Mac.\n\nReference:\nWork sans on Google Fonts"
] | [
"macos",
"web",
"fonts",
"font-face"
] |
[
"Mac OS X 10.8 MySQL connection error: localhost does not work, 127.0.0.1 all OK",
"I have now a new MabBook with 10.8 and I am trying to set up all the Apache & MySQL etc.\nApache successfully runs including vhosts.\n\nIn my /etc/hosts I have all the local hosts set including 127.0.0.1 localhost etc.\n\nWhen I try to coennct to one of my local vhost, e.g. alpensonne, I can connect to MySQL without any troubles. If I try to have the MySQL host to be localhost, I get the follwoing error:\n\nDatabase connection error (2): Could not connect to MySQL.\n\n\nI know the error (2) means username or password incorrect, but they are fine.\nIf I connect with\n\nmysql -u root\nSELECT password,host FROM user where user='root';\n\n\nAlso I have just done to be double sure:\n\nSET PASSWORD FOR 'root'@'localhost' = '';\n\n\nIs it possible that localhost uses a different MySQL socket? Maybe it then tries to connect to a different MySQL?"
] | [
"php",
"mysqli",
"vhosts"
] |
[
"Awk replace entire line when match is found",
"I have the following code:\n\nfunction replaceappend() {\n awk -v old=\"^$2\" -v new=\"$3\" '\n sub(old,new) { replaced=1 }\n { print }\n END { if (!replaced) print new }\n ' \"$1\" > /tmp/tmp$$ &&\n mv /tmp/tmp$$ \"$1\"\n}\n\nreplaceappend \"/etc/ssh/sshd_config\" \"Port\" \"Port 222\"\n\n\nIt works perfectly but I am looking to modify it so it replaces the entire lines contents rather than just the matching text.\n\nAt the moment it would do this:\n\nPort 1234 -> Port 222 1234\n\n\nI want it to be work like this:\n\nPort 1234 -> Port 222\n\n\nI closest code I can find to do this is found here:\n\nawk 'NR==4 {$0=\"different\"} { print }' input_file.txt\n\n\nThis would replace the entire line of the match with the new content. How can I implement this into my existing code?"
] | [
"regex",
"bash",
"shell",
"awk",
"debian"
] |
[
"Getting SQLCODE and SQLSTATE from select query inside Procedure DB2",
"I have a procedure and all I want is the SQLSTATE and SQLCODE from a select query. I am NOT interested in the result itself.\n\n Create procedure select_test(IN query varchar(1024))\n Language sql\n BEGIN\nDECLARE SQLCODE INTEGER DEFAULT 0;\nDECLARE SQLSTATE CHAR(5) DEFAULT '00000';\nDECLARE V_QUERY VARCHAR(24576);\nDECLARE V_ERRORMSG VARCHAR(2048) DEFAULT '';\nDECLARE V_SQLCODE INTEGER DEFAULT 0;\nDECLARE V_SQLSTATE CHAR(5) DEFAULT '00000';\nDECLARE STMT STATEMENT;\nDECLARE C1 CURSOR FOR STMT;\nDECLARE CONTINUE HANDLER FOR SQLEXCEPTION, SQLWARNING,NOT FOUND\nBEGIN\nGET DIAGNOSTICS\nEXCEPTION\n1 V_ERRORMSG = MESSAGE_TEXT;\nVALUES(SQLSTATE,SQLCODE)INTO V_SQLSTATE, V_SQLCODE;\nEND;\n\nSET V_QUERY = QUERY;\nPREPARE STMT FROM V_QUERY;\n\nOPEN C1; CLOSE C1;\n\n End@\n\n\nAll I need is the SQLCODE,SQLSTATE and MESSAGE_TEXT. The result of the select is not important. \nQuery is something like \n\n SELECT A,B,C from TAB_A;\n\n\nwith a wrong table in the query.\n\nThanks to @Mark Barinstein I got hinted to the cursor part so thank you for that lready.\n\nThe problem is that I get SQLCODE -504 and it should be -204. So it is not the SQLCODE of the select.\n\nI am running DB2 Windows v10.5\n\nAny idea?\n\nThanks"
] | [
"sql",
"stored-procedures",
"error-handling",
"db2",
"execute"
] |
[
"React useState hook: object property remains unchanged",
"I have recently started learning react and I have a component that has a login form:\nimport Joi from "joi";\nimport { useState } from "react";\n\nconst Login = () => {\n const [username, setUsername] = useState("");\n const [password, setPassword] = useState("");\n const loginSchema = Joi.object().keys({\n username: Joi.string().required(),\n password: Joi.string().required(),\n });\n const [errors, setErrors] = useState({ username: null, password: null });\n\n const handleSubmit = (form) => {\n form.preventDefault();\n validate();\n };\n\n const validate = () => {\n const { error } = loginSchema.validate(\n { username, password },\n { abortEarly: false }\n );\n if (!error) return null;\n for (const item of error.details) {\n let key = item.path[0];\n let value = item.message;\n setErrors({ ...errors, [key]: value });\n }\n return errors;\n };\n\n return (\n <div className="container">\n <div>\n <h1>Login</h1>\n </div>\n <div className="card">\n <div className="card-body">\n <form onSubmit={handleSubmit}>\n <div className="form-group">\n <label htmlFor="username">Username</label>\n <input\n name="username"\n type="text"\n className="form-control"\n id="username"\n placeholder="Enter username"\n value={username}\n onChange={(username) => setUsername(username.target.value)}\n />\n {errors.username && (\n <div className="alert alert-danger">{errors.username}</div>\n )}\n </div>\n <div className="form-group">\n <label htmlFor="password">Password</label>\n <input\n name="password"\n type="password"\n className="form-control"\n id="password"\n placeholder="Password"\n value={password}\n onChange={(password) => setPassword(password.target.value)}\n />\n {errors.password && (\n <div className="alert alert-danger">{errors.password}</div>\n )}\n </div>\n <button type="submit" className="btn btn-primary">\n Submit\n </button>\n </form>\n {/* Delete later */}\n <h4>{JSON.stringify(errors)}</h4>\n </div>\n </div>\n </div>\n );\n};\n\nexport default Login;\n\nHere, I am trying to set the values of username and password in the errors object, but for some reason, only the password property gets set, the username property remains null. I have used object destructuring but it still doesn't set the value, please help."
] | [
"javascript",
"reactjs",
"use-state",
"object-destructuring"
] |
[
"Running subsets of Jest tests in parallel",
"We're using Jest to power our Node.js tests, these interact with a Postgres database to test CRUD operations. We're currently passing the --runInBand CLI option to ensure our tests operate in serial, this works fine but is obviously slower than we'd like.\n\nNow from reading around (and previous experience) I've found it useful to be able to mark groups of tests as parallelise-able. This is possible with nose in python but I cannot seem to find the syntax in Jest. Is this possible? Or is there another approach to speeding up database (or state constrained to generalise) tests that Jest advocates?\n\nThanks,\nAlex"
] | [
"node.js",
"postgresql",
"ecmascript-6"
] |
[
"Order of class initialization during java deserialization",
"During deserialization, are subclasses guaranteed to be initialized before any class instance objects are restored from the input stream? Specifically, I have a subclass with static fields that I'd like to access in the superclass readObject() method. Can I count on the subclass static fields being valid?"
] | [
"java",
"deserialization",
"static-initialization"
] |
[
"Android source code import in eclipse",
"I have downloaded the android source code from the android master branch. I followed the procedure given on the website to build it. When I run it from terminal everything builds fine without errors. When I followed the procedure to import this I eclipse it throws me about 2000 errors\nthe errors basically include \nIRemoteService cannot be resolved and \nIRemoteServiceCallback cannot be resolved. \nHas anyone encountered the same issues ?"
] | [
"java",
"android",
"eclipse"
] |
[
"how to save contents of a file as single string using java",
"I am trying to extract a specific content from text file by using delimiters. This is my code : \n\nFile file = new File(\"C:\\\\Inputfiles\\\\message.txt\"); \nBufferedReader br = new BufferedReader(new FileReader(file)); \nString st; \nwhile ((st=br.readLine()) != null) {\nString[] strings = StringUtils.split(st, \"------------\");\nSystem.out.println(strings);}\n\n\nBut as a result, each and everyline is getting splitted by delimiter and saved as array.\n\nCan anyone suggest how I can save the contents from file as a single string, so I can get limited number of lines only as Array."
] | [
"java",
"filereader"
] |
[
"Where to store connection string in a 3-tier winform application using C# 4.0",
"We are about to implement an application using winforms. I would like to have a 3 layer architecture (GUI, Business Logic and Data Access Layer. \n\nWe have one database per customer, so we must be able to access different databases (possible on different servers as well) using the application. E.g. Customer A is on server A and Customer B is on server B. \n\nEDIT: \nDeployment scenario: This application may be installed on ServerA, but the databases might be on ServerA, ServerB, ServerC, ServerX (I think you get the picture).\n\nReading the db connection from a database is then somewhat complicated since I don't know which db the user wants to connect to. And to top it off the user ids are only unique in the same db, so a user with the username e.g \"admin\" can exists in multiple databases:)\n\nWe would like to be able to log on the application providing a user name, password and connection string information. Now, how do you send the connection string information to the DAL, so that the GUI nor the Business Layer doesn't have to have a knowledge of the database connection string? I would not like to store the connection string in the GUI project and pass that as a parameter to the Business Layer that in turns passes the connection string to the DAL every time I need some data in the database.\n\nEDIT: The connection string information only need to be available while the user is logged in. As soon as he logs out this information should be deleted) \n\nI have implemented a class in an new project that inherits from ApplicationSettingsBase (Both the UI project and the DAL project have a reference to the new project). So I'm now able to persist the connection information (to a user.config file by default). So I can instantiate that class from the User interface and store the connection information by calling base.Save on my class and then in the DAL I can instantiate the same class and read the connection information there. Not sure if I like that solution because the user.config file is tied to the windows user (by storing the file in the C:\\Users...\\AppData\\ hierarchy and I'm not sure about the performance by doing it this way. Overkill maybe?\n\nEDIT: I have not been able to find a satisfactory solution yet, so I appreciate more answers from the community:) \n\nEDIT: \n\nI found a way to solve this. I have only testet the solution in a small test project, but here goes: \n\nThe user logs in and the UI methods responsible for retrieving the login information runs this method: \n\npublic void SetTempSetting()\n{\n // Get the configuration file.\n Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); \n\n // Add the connection string.\n ConnectionStringsSection csSection = config.ConnectionStrings;\n csSection.ConnectionStrings.Add(new ConnectionStringSettings(\"ConnectionStringName\", GetConnectionString()));\n\n // Save the configuration file.\n config.Save(ConfigurationSaveMode.Modified);\n\n}\n\n\nThe SetTempingSetting() method will write the connectionstring to the ProjectName.dll.config \n\nAnd in the DAL project I can get the connectionstring from the ConfiguraionManager like this: \n\nvar connectionstring = ConfigurationManager.ConnectionStrings[\"ConnectionStringName\"].ConnectionString;\n\n\nAnd when the user logs out of the application the logout method can execute this method to delete the connectionstring from the Project.dll.config\n\npublic void RemoveTempSetting()\n {\n // Get the configuration file.\n Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); \n // Add the connection string.\n ConnectionStringsSection csSection = config.ConnectionStrings;\n csSection.ConnectionStrings.Remove(\"ConnectionStringName\");\n // Save the configuration file.\n config.Save(ConfigurationSaveMode.Modified); \n }\n\n\nAny thoughts on this solution? Pros? Cons? Overengineered? Bad design?"
] | [
"c#",
"winforms",
"3-tier"
] |
[
"How can I access the title or text of an \"a\" nested within a \"td\" using JavaScript?",
"I have a calendar where the day cells are clickable \"td\" elements. Inside each is an \"a\" that has a title. I need to use this title in a JavaScript function that is called when any of the \"td\" elements are clicked. I had to disable the PostBack for all \"a\" elements\n\nHere is code for one of the cells:\n\n<td align=\"center\" style=\"width:14%;\"><a href=\"javascript:__doPostBack('ctl00$MainContent$Calendar2','6314')\" style=\"color:Black\" title=\"April 15\">15</a></td>\n\n\nI just need to access the 15 text technically. I can get the month elsewhere.\n\nIs this possible using JavaScript?"
] | [
"javascript",
"html",
".net"
] |
[
"Iterating with ggsave and ggplot2",
"I have a folder containing csv files. I am iterating over these csv files and creating one plot per csv file. I can do this via:\n\nsetwd(\"/myfiles/folder\")\nfilenames = dir(pattern=\"*.csv\")\nfor (i in 1:length(filenames)) { \n tmp <-read.csv(filenames[i]); \n print(ggplot(aes(x = count, y = time), data = tmp) + geom_point(aes(color = id)) \n + geom_smooth(aes(color = id), method= \"lm\", se = F, formula=y ~ poly(x, 3, raw=TRUE)) \n + ggtitle(\"Title\") + labs(x=\"Count)\",y=\"Time\")+ggsave(file=\"ID_.jpeg\"))\n}\n\n\nHowever, as you would expect this only creates one .jpeg file and thus it is overwritten each time and I am left with the final plot saved. \n\nI have tried:\n\nfor (i in 1:length(filenames)) { \n tmp <-read.csv(filenames[i]); \n print(ggplot(aes(x = count, y = time), data = tmp) + geom_point(aes(color = id)) \n + geom_smooth(aes(color = id), method= \"lm\", se = F, formula=y ~ poly(x, 3, raw=TRUE)) \n + ggtitle(\"Title\") + labs(x=\"Count)\",y=\"Time\")+ggsave(file=\"ID\"+id+\".jpeg\"))\n}\n\n\nBut this results in:\n\n\n Error in regexpr(\"\\.([[:alnum:]]+)$\", x) : object 'id' not found \n\n\nWhy is the id not recognised by ggsave when it is previously (for the geom_plot item)?"
] | [
"r",
"csv",
"ggplot2"
] |
[
"Sort a string of Roman Numerals",
"The input will be a string of Roman numerals that have to be sorted by their value. Also this task has to be completed using classes in c++\n\nSo far I've created my class \n\n#include<iostream>\n#include<string>\nusing namespace std;\n\nclass RomanNumbers\n{\npublic:\n RomanNumbers(string = \"\");\n\n void setRoman(string);\n\n int convertToDecimal();\n\n void printDecimal();\n\n void printRoman();\n\n\nprivate:\n\n string roman;\n\n int decimal;\n\n};\n\n\nAnd the functions to convert a number from Roman numeral to integer form but my question is : How shall I sort them because I can't create a new string that will contain the converted Roman numerals and sort the string. Any help will be appreciated.\n\n#include<iostream>\n#include<string>\n#include \"RomanNumbers.h\"\nusing namespace std;\n\nRomanNumbers::RomanNumbers(string myRoman)\n{\n roman = myRoman;\n decimal = 0;\n}\n\nvoid RomanNumbers::setRoman(string myRoman)\n{\n roman = myRoman;\n decimal = 0;\n}\n\nint RomanNumbers::convertToDecimal()\n{\n enum romans { I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1000 };\n\n for (int i = 0; i < roman.size(); i++)\n {\n switch (roman[i])\n {\n\n case 'M': decimal += M; break;\n case 'D': decimal += D; break;\n case 'C': decimal += C; break;\n case 'L': decimal += L; break;\n case 'X': decimal += X; break;\n case 'V': decimal += V; break;\n\n case 'I':\n if (roman[i + 1] != 'I' && i + 1 != roman.size())\n {\n decimal -= 1;\n }\n else\n {\n decimal += 1;\n }\n break;\n\n }\n }\n\n return decimal;\n}\n\nvoid RomanNumbers::printRoman()\n{\n cout << \"Number in Roman form : \" << roman;\n cout << endl;\n}\n\nvoid RomanNumbers::printDecimal()\n{\n cout << \"Number converted in integer form : \" << decimal;\n\n cout << endl;\n}"
] | [
"c++",
"string",
"sorting",
"roman-numerals"
] |
[
"When simulation on true device, database error: SQLiteDB - failed to copy writable version of DB",
"I`m using databases in my swift project.\nEveryting was fine when I did simulation on simulator, but when i tried to run my app on my truth ios device, the error showed below\n\n\n Database path:\n /var/mobile/Containers/Data/Application/7751C273-D7B4-4AE1-9593-775755C0F0D2/Documents/data.db\n \n SQLiteDB - failed to copy writable version of DB! \n \n Error - the file “data.db” couldn’t be opened because there is no\n such file.\n\n\nanyone has any solution?"
] | [
"ios",
"xcode"
] |
[
"Should I use log_level :debug in production on my Rails app",
"The default for production.rb is:\n\n\nconfig.log_level = :info\n\n\nHowever, I really like to see the SQL queries and extra logging in my production environment.\n\nChanging the log level to:\n\n\nconfig.log_level = :debug\n\n\nIs this a terribly bad practice? How much overhead does this add to my application to have Rails do this extra logging?"
] | [
"ruby-on-rails",
"ruby-on-rails-3",
"ruby-on-rails-4"
] |
[
"Google CALDAV XML request using curl (php)",
"I'm trying to do a CalDAV XML request to the google caldav server with PHP.\n\nFor some reason the google calDAV is very poorly documented.\n\nThe purpose is to get a list of all events, including the event-specific data. (eg. Begin, End, Summary, ...).\nThe goal is to do this as efficiently as possible.(all event data in one request).\n\nI figured out that this can be accomplished by a REPORT request.\n\nI'm using code found in this post.\n\nMy exact code : \n\n $xml= '<c:calendar-query xmlns:d=\"DAV:\" xmlns:c=\"urn:ietf:params:xml:ns:caldav\"><d:prop><c:calendar-data /></d:prop></c:calendar-query>';\n $url = \"https://apidata.googleusercontent.com/caldav/v2/*email*/events\";\n $user = \"**********@gmail.com\";\n $pw = \"*********\";\n\n $data = $this->doRequest($user, $pw, $url, $xml);\n print_r($data);\n\n}\n\npublic function doRequest($user, $pw, $url, $xml)\n{\n $c=curl_init();\n $url = preg_replace('{^https?://[^/]+}', '', $url);\n curl_setopt($c, CURLOPT_URL, $url);\n curl_setopt($c, CURLOPT_HTTPHEADER, array(\"Depth: 1\", \"Content-Type: text/xml; charset='UTF-8'\", \"Prefer: return-minimal\"));\n curl_setopt($c, CURLOPT_HEADER, 0);\n curl_setopt($c, CURLOPT_SSL_VERIFYHOST, false);\n curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);\n curl_setopt($c, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);\n curl_setopt($c, CURLOPT_USERPWD, $user.\":\".$pw);\n curl_setopt($c, CURLOPT_CUSTOMREQUEST, \"REPORT\");\n curl_setopt($c, CURLOPT_POSTFIELDS, $xml);\n curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);\n $data=curl_exec($c);\n\n curl_close($c);\n\n return $data;\n} \n\n\nThe xml request is copy-pasted from the SabreDAV wiki.\n\nWhat google returns on this code is \"Unknown Error\".\nI know the credentials from the google are working, since i successfully tried some request using SabreDAV's built-in requests (eg. propfind). But a report request cannot be generated by SabreDAV.\n\nSo i think there must be something in the xml request that google caldav cannot handle properly.\n\nI have been fiddling around with this for several days, but i can't seem to figure out a proper solution."
] | [
"php",
"xml",
"curl",
"caldav",
"sabredav"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.