texts
sequence | tags
sequence |
---|---|
[
"delete specific edges in R",
"I'm new to programming in R and not very good so now I've got a question about my progect. I spend a lot of time in searching a specific code about \"delete.edges\". I want to delete specific edges from my graph, those with weight 0. I have make a txt in which i have 3 columns. the first and the second are the vertices kai the third is the weight. I wrote 0 in order to define no connection, 1,2,3 etc for connection. My graph is weighted. the plot gave me all of the posible edges including those with weight=0 and now i have to delete them and make a new plot."
] | [
"r",
"igraph"
] |
[
"Getting the value an Http Post Method returns",
"I have a post method in my web api that returns a string and i am calling the method from a client. How do i get the value that is being returned.\n\nPost Method\n\n public String Post(Models.SQNotificationDataAccessRepository.NotificationEntry notificationEntry)\n {\n String externalReferenceID = String.Empty;\n if (notificationEntry == null)\n {\n throw new HttpResponseException(HttpStatusCode.BadRequest);\n }\n\n externalReferenceID= dbTransactionLayer.PopulateEsiTable(notification);\n\n return externalReferenceID;\n }\n\n\nClient \n\n using (var client = new HttpClient())\n {\n client.BaseAddress = new Uri(\"http://localhost:12819/\");\n client.DefaultRequestHeaders.Accept.Clear();\n client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(\"application/json\"));\n\n\n Notification notification = new Notification()\n {\n id = 102,\n To = new String[] { \"[email protected]\", \"[email protected]\" },\n Title = \"Notification WebService Client Test\",\n MessageBody = \"The message body will go there\",\n DelieveryType = \"Email\",\n Response = true\n };\n\n\n\n HttpResponseMessage response = await client.PostAsJsonAsync(\"api/NotificationEntry/Post\",notification);\n var result = response;\n\n Console.WriteLine(\"Successfully delivered:\" + result.ToString);\n }"
] | [
"c#",
"asp.net-mvc"
] |
[
"Angular get ElementRef from router-outlet component",
"To get the component instance from a router-outlet I can use\n<router-outlet (activate)="onRouterActivate($event)"></router-outlet>\n\nand I can capture this in my method:\n public onRouterActivate(componentRef) {\n this.componentRef = componentRef;\n }\n\nbut how do I get the nativeElement/ElementRef for the underlying componentRef? The nativeElement property doesn't appear to exist on what gets passed via (activate)"
] | [
"angular"
] |
[
"Git: Check programmatically if anything is staged",
"For a Git script I'm writing, I'd like to have a programmatic way to check whether there is anything at all staged. i.e. I want a positive result if anything at all is staged, and negative if nothing is staged.\n\nBonus points: A way to programmatically check whether there is anything new in the working tree that can be staged."
] | [
"git"
] |
[
"Cannot source RVM files because of PowerPC architecture",
"I ran the railsinstaller from railsinstaller.org on my OS X 10.7.5, then ran into a few issues with RVM:\n\n1) First, I got \"RVM: command not found\". So I created the .bash_profile and added\n\n[[ -s \"$HOME/.rvm/scripts/rvm\" ]] && source \"$HOME/.rvm/scripts/rvm\"\n\n\n2) Restarted the terminal, but still getting the same error message. I checked the .rvm folder to see if it's properly installed; it seems to be missing the \"scripts\" folder. So I ran \n\n\\curl -L https://get.rvm.io | bash -s stable\n\n\n3) Then I get this:\n\nLaunch of \"gtar\" failed: the PowerPC architecture is no longer supported. Could not extract RVM sources.\n\n\nBase on my research, this means that I need an Intel 64-bit machine. But I double checked and that is indeed what I have (Intel Core Duo 2). I've been spending hours trying to find more relevant documentations but to no avail, so I'm really stuck as I need the RVM for my projects.\n\nI would really appreciate any help! Thank you!"
] | [
"ruby-on-rails",
"rvm",
"powerpc"
] |
[
"vectorization of a single loop in matlab (multiplication and then addition)",
"I have a nX2 matrix A and a 3D matrix K. I would like to take element-wise multiplication specifying 2 indices in 3rd dimension of K designated by each row vector in A and take summation of them. \n\nFor instance of a simplified example when n=2,\n\nA=[1 2;3 4];%2X2 matrix\nK=unifrnd(0.1,0.1,2,2,4);%just random 3D matrix\nL=zeros(2,2);%save result to here\nfor t=1:2\n L=L+prod(K(:,:,A(t,:)),3);\nend\n\n\nCan I get rid of the for loop in this case?"
] | [
"performance",
"matlab",
"vectorization"
] |
[
"Deploying Jersey 1.3 Web Service on Weblogic 9.2 or 10.1",
"I am having issues deploying my Jersey RESTful web service to weblogic 9.2\n\nI followed a tutorial at http://www.vogella.de/articles/REST/article.html.\n\nThe tutorial is for java 6 and tomcat 6 which it works fine for. However, I need to convert this to java 5 and tomcat 5.5 so that I can successfully deploy it on weblogic which uses java 1.5\n\nWhen I use jre 5 and build the project, I get the following stack: java.lang.reflect.InvocationTargetException\n at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)\n at java.lang.reflect.Method.invoke(Method.java:585)\n at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:295)\n at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:433)\nCaused by: java.lang.UnsupportedClassVersionError: Bad version number in .class file (unable to load class com.sun.jersey.spi.container.servlet.ServletContainer)\n at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1884)\n at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:889)\n at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1353)\n at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1232)\n at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1068)\n at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:966)\n at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:3996)\n at org.apache.catalina.core.StandardContext.start(StandardContext.java:4266)\n at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)\n at org.apache.catalina.core.StandardHost.start(StandardHost.java:736)\n at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1014)\n at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)\n at org.apache.catalina.core.StandardService.start(StandardService.java:448)\n at org.apache.catalina.core.StandardServer.start(StandardServer.java:700)\n at org.apache.catalina.startup.Catalina.start(Catalina.java:552)\n ... 6 more\n\nAny help would be greatly appreciated."
] | [
"java",
"tomcat",
"jaxb",
"weblogic",
"jersey"
] |
[
"How do I prevent running out of memory when inserting a million rows in mysql with php",
"I have built a script in Laravel that reads a JSON file line by line and imports the contents into my database.\n\nHowever, when running the script, I get an out of memory error after inserting about 80K records.\n\nmmap() failed: [12] Cannot allocate memory\n\nmmap() failed: [12] Cannot allocate memory\nPHP Fatal error: Out of memory (allocated 421527552) (tried to allocate 12288 bytes) in /home/vagrant/Code/sandbox/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php on line 1758\n\nmmap() failed: [12] Cannot allocate memory\nPHP Fatal error: Out of memory (allocated 421527552) (tried to allocate 32768 bytes) in /home/vagrant/Code/sandbox/vendor/symfony/debug/Exception/FatalErrorException.php on line 1\n\n\nI have built a sort of makeshift queue to only commit the collected items every 100, but this made no difference.\n\nThis is what the part of my code that does the inserts looks like:\n\npublic function callback($json) {\n\n if($json) {\n\n $this->queue[] = [\n\n 'type' => serialize($json['type']),\n 'properties' => serialize($json['properties']),\n 'geometry' => serialize($json['geometry'])\n ];\n\n if ( count($this->queue) == $this->queueLength ) {\n\n DB::table('features')->insert( $this->queue );\n\n $this->queue = [];\n }\n }\n}\n\n\nIt's the actual inserts (DB::table('features')->insert( $this->queue );) that are causing the error, if I leave those out I can perfectly iterate over all lines and echo them out without any performance issues.\n\nI guess I could allocate more memory, but doubt this would be a solution because I'm trying to insert 3 million records and it's currently already failing after 80K with 512Mb memory allocated. Furthermore, I actually want to run this script on a low budget server.\n\nThe time it takes for this script to run is not of any concern, so if I could somehow slow the insertion of records down that would be a solution I could settle for."
] | [
"php",
"mysql",
"laravel"
] |
[
"Postfix AS an SMTP relay with auth config issues",
"Im trying to put together a postfix container to act as a smart host/relay in my environment. The plan being all our applications/service will send email to the container, the container will then deliver forward on the email directly.\nI've set up the usual SPF configuration and so on but i'm getting stuck configuring postfix to require authentication for mail submission.\nEvery time I follow a guide of find some sample configuration which supposedly do this, it seems that in actual fact they are specifying credentials for their postfix instance to authenticate with a upstream relay/smart host like an ISP or similar.\nI know Relay and Smart Host are two different things, but ive been through that many discussions that use them interchangeably i'm going to draw a diagram.\n[SERVICE X] ---25/tcp [user:pass] ---> [POSTFIX CONTAINER] }-----> direct to [email protected]\n /\\ this bit doesnt work\n\nDoes anyone know how I can configure postfix AS an SMTP smart host/relay with basic SMTP Auth, rather than postfix to send TO a smart host/relay with Auth?\nI've been through so many permutations of this not working my postfix config is currently a mess otherwise I would post my existing state. Im somewhat sure I need to implement SASL for this but theres a lot of conflicting methods."
] | [
"smtp",
"postfix-mta",
"smarthost"
] |
[
"Code execution stops on connection.Open() statement",
"i am working in unity engine and trying to connect my MySql database on my server with my unity game the connection string seems to be working fine and does not throw any exception but my code execution stops at connection.Open() line i have tried everything debug line to line but there is no error or exception here is my code\n\n void Initialize()\n{\n try\n {\n Debug.Log(\"Initilized\");\n server = \"localhost\";\n database = \"test\";\n uid = \"root\";\n password = \"\";\n string connectionString;\n connectionString = \"server=\" + server + \";\" + \"database=\" +\n database + \";\" + \"uid=\" + uid + \";\" + \"password=\" + password + \";\";\n\n connection = new MySqlConnection();\n connection.ConnectionString = connectionString;\n }\n catch(MySqlException ex)\n {\n Debug.Log(ex.Message);\n }\n}\n private bool OpenConnection()\n{ \n try\n {\n connection.Open(); //at this line the code wont execute furthur \n return true;\n }\n catch (MySqlException ex)\n {\n Debug.Log(ex.Message + ex.Number);\n switch (ex.Number)\n {\n case 0:\n SSTools.ShowMessage(\"Cannot connect to server\", SSTools.Position.bottom, SSTools.Time.twoSecond);\n break;\n\n case 1045:\n SSTools.ShowMessage(\"Invalid username or password\", SSTools.Position.bottom, SSTools.Time.twoSecond);\n break;\n }\n return false;\n }\n}\n public void RegisterUser(string username, string password, string email)\n{\n string query =\n \"INSERT INTO Users (Username, Password, Email) VALUES('\" + username + \"','\" + password + \"','\" + email +\"')\";\n\n\n if (this.OpenConnection() == true)\n {\n\n MySqlCommand cmd = new MySqlCommand(query, connection);\n\n\n cmd.ExecuteNonQuery();\n\n\n this.CloseConnection();\n }\n}"
] | [
"mysql",
"visual-studio",
"unity3d"
] |
[
"continual update html display of js variable",
"So here is what I have by way of HTML\n\n<div class=\"circle\" >2000</div>\n<div class=\"circle\" >20</div>\n\n\nand here is the CSS\n\n.circle {\n width:50px;\n height:50px;\n border:3px solid green;\n border-radius:250px;\n line-height:50px;\n text-align:center;\n display:inline-block;\n}\n\n\nI have a .js page that is a total list of all may variables for this game I am making.\n\nWhat i am looking for is the ability to have each variable assigned a circle with a real-time/rapidly updating view of what the variables value is from the globalvars.js.\n\nI read that it was possibly to do by including an id in the div like this\n<div class=\"circle\" id=XXXXX></div>\nhowever I was unable to make this work and wanted to know if it was just me being stupid or something else. I am relatively new to programming so any and all constructive criticism is appreciated!"
] | [
"javascript",
"html",
"css"
] |
[
"Varying content of an SQL update statement in java",
"I need to write an update function where its content is different based on what parameters are passed, e.g. if I have updateBook(int id, String title, String author, int pages), I have to do something like:\nString sql;\nif((!title.equals("null"))&&(!author.equals("null"))&&(pages>0)))\n sql = "UPDATE book SET title='"+title+"', author='"+author+"', pages="+pages;\nelse if(((!title.equals("null"))&&(!author.equals("null")))\n sql = "UPDATE book SET title='"+title+"', author='"+author+"'";\nelse if(((!title.equals("null"))&&(pages>0)))\n sql = "UPDATE book SET title='"+title+"', pages="+pages;\n... //and so on\n\nsql = sql + " WHERE bookid="+id+";";\n\nThe more fields I have in my table, the more checks I have to do, which is uncomfortable, and requires me to write a lot of code.\nAlso, doing something like:\nsql = "UPDATE book SET ";\nif(!title.equals("null"))\n sql = sql +"title='"+title+"',";\nif(!author.equals("null"))\n sql = sql+"author='"+author+"',";\nif(pages>0)\n sql = sql+"pages="+pages";\nsql = sql + ";";\n\ncan't work since the unwanted commas cause statement errors.\nYou can see as well that if I have something like 6, 7, 8 etc field the checks start to get too many, and I can't also do more separated update statements as if something goes wrong I would need to rollback any query that has been done in that function.\nIs there any way round to get a custom update statement having to write few code?"
] | [
"java",
"sql",
"jdbc",
"sql-update"
] |
[
"AJAX sporadically fails, and apparently request was never sent?",
"$.ajax({\n url : baseUrl,\n data : {\n \"query\" : query,\n \"num\" : tracksRequested\n },\n dataType : \"text\",\n success : received,\n error : function(a,b,c) { alert(\"ERROR!\"); console.log(a); },\n type : \"GET\"\n});\n\n\nI am using jQuery to send AJAX requests. The code I am using is above. Usually, this works just fine. However, on occasion, the request fails and the error message appears. Upon inspection, both the ajax status code and the readyState appear to be 0, which AFAIK means the request was not sent. I was under the impression that this only happens if you try to request a page from a different domain. I am not doing that; the baseUrl variable above never changes, and yet I am getting this error on some (but not all!) of my requests. I have observed this using Chrome 13 and IE9."
] | [
"jquery",
"ajax"
] |
[
"opening another instance of powershell with a script while passing the arguments to the new instance",
"So I have two scripts, Main_Script.ps1 and Loki.ps1. I am trying to get the main script to call the Loki script in a new window while passing the variables from the main to the new window. So far I have gotten the script to open the second script and pass the variables but am unable to open a new instance. I have been through countless other posts to no avail. Below is the code for main and Loki. The Loki Scanner can be downloaded from https://github.com/Neo23x0/Loki. The variables are Scan_Drive which is the drive I want to scan. Machine_id which is what I want to name the output. Output_dir the output directory. Resource_Drive the drive where I put Loki. If there are any questions please let me know. It functions now just not how I want and I do not know how to get there. Assistance is greatly appreciated. I will adapt the answer to run other tools simultaneously.\nMain_Script.ps1\n[CmdletBinding()]\nparam(\n [Parameter(Mandatory=$true)][string] $Scan_drive,\n [Parameter(Mandatory=$true)][string] $Machine_id,\n [Parameter(Mandatory=$true)][string] $Output_dir,\n [Parameter(Mandatory=$true)][string] $Resource_drive\n)\n\n$Main_ScriptSplat = @{\n"Resource_drive" = $Resource_drive\n"Scan_drive" = $Scan_drive\n"Machine_id" = $Machine_id\n"wp_dir" = $Output_dir\n}\n \nmkdir ${Output_dir}:\\${Machine_id}\\\n\nmkdir ${Output_dir}:\\${Machine_id}\\AV\\\n\nWrite-Host "============================="\nWrite-Host "= Loki ="\nWrite-Host "============================="\nWrite-Host ""\n\n& "$PSScriptRoot\\Loki.ps1" @Main_ScriptSplat \n\nLoki.ps1\nparam(\n $Scan_drive, $Machine_id, $Output_dir, $Resource_drive\n\n)\n\n\n$loki_folder = "${Resource_drive}:\\loki"\n$loki_bin = "${loki_folder}\\loki.exe"\n\n\nWrite-Host "============================="\nWrite-Host "= Loki ="\nWrite-Host "============================="\nWrite-Host ""\n& "${loki_bin}" -p ${Scan_drive}: --noprocscan --dontwait --intense -l \n"${Output_dir}:\\${Machine_id}\\AV\\${Machine_id}.${Scan_drive}.loki.txt""
] | [
"powershell",
"powershell-4.0"
] |
[
"Not able to install the TensorFlow version 1.15 or earlier version",
"I am trying to install 1.15 version of Tensorflow in my windows and mac machine as the examples in the book doesn't work with latest version of the Tensorflow.\n\nC:\\Users\\kaushikchoudhury>pip install tensorflow==1.15\n\nI am getting the below error message and not sure the way to install 1.15 or previous version of it.\nERROR: Could not find a version that satisfies the requirement tensorflow==1.15 (from versions: 2.2.0rc1, 2.2.0rc2, 2.2.0rc3, 2.2.0rc4, 2.2.0, 2.3.0rc0, 2.3.0rc1, 2.3.0rc2, 2.3.0)\nERROR: No matching distribution found for tensorflow==1.15\nPlease suggest"
] | [
"python",
"tensorflow"
] |
[
"phoneGap database creation example",
"I am trying to create a database using phonegap's api: \nIn order to do this I have used the following html: \n\n<!DOCTYPE HTML>\n<html>\n<head>\n<title>Cordova</title>\n<script type=\"text/javascript\" charset=\"utf-8\" src=\"cordova-2.0.0.js\"></script>\n<script type=\"text/javascript\" charset=\"utf-8\">\n\n // Wait for Cordova to load\n //\n document.addEventListener(\"deviceready\", onDeviceReady, false);\n\n // Cordova is ready\n //\n function onDeviceReady() {\n var db = window.openDatabase(\"test\", \"1.0\", \"Test DB\", 1000000);\n alert(\"database created\");\n }\n\n </script>\n\n</head>\n<body>\n <form name=\"input\" action=\"html_form_action.asp\" method=\"get\">\n <input type=\"submit\" value=\"Create Db\" />\n </form>\n\n</body>\n</html>\n\n\nThe buttone doesnt do anyting. The idea is that when the app starts I'm supposed to get confirmation that a database has been created. However this is not happening. Please help..."
] | [
"android",
"cordova"
] |
[
"Umbraco SurfaceController model state / model validation issues",
"In Umbraco I can hook up MVC partials with a SurfaceController that either looses model state on re-rendering after a post back, or validates the model prematurely and so displays validation errors for @Html.ValidationMessageFor helpers on the initial page rendering. What I really want is behaviour consistent with vanilla MVC partials and models.\n\nI'm creating MVC partials for use in Umbraco supported by a SurfaceController to handle rendering and post-back.\n\nI then wrap these partials in \"Macros\" so they can be dropped into page content alongside other content, rather than creating a special Document Type for each special page required (there would be a lot).\n\nPartial:\n\n@using SomeProject.Web.Controllers\n@model SomeProject.Web.Models.Identity.UserModel\n\n@using (Html.BeginUmbracoForm<IdentitySurfaceController>(\"RegisterDetailsSubmit\", null, new { @class = \"form-horizontal\" }))\n{\n @Html.AntiForgeryToken()\n\n @Html.EditorFor(model => Model)\n\n <div class=\"form-group\">\n <div class=\"col-md-offset-2 col-md-10\">\n <input type=\"submit\" class=\"btn btn-primary\" value=\"Register\" />\n </div>\n </div>\n}\n\n\nMacro:\n\n@inherits Umbraco.Web.Macros.PartialViewMacroPage\[email protected](\"RegisterDetails\", \"IdentitySurface\")\n\n\nSurfaceController:\n\nusing SomeProject.Web.Models.Identity;\nusing System;\nusing System.Web.Mvc;\n\nnamespace SomeProject.Web.Controllers\n{\n public class IdentitySurfaceController : Umbraco.Web.Mvc.SurfaceController\n {\n\n [ChildActionOnly]\n public ActionResult RegisterDetails(UserModel model)\n {\n if (model == null || model.Id == Guid.Empty) model = new UserModel(GetUser());\n\n return View(model);\n }\n\n [HttpPost]\n [ValidateAntiForgeryToken]\n public ActionResult RegisterDetailsSubmit(UserModel model)\n {\n if (ModelState.IsValid)\n {\n ...\n }\n\n return CurrentUmbracoPage();\n }\n\n }\n}\n\n\nWhen I use:\n\n[ChildActionOnly]\npublic ActionResult RegisterDetails()\n\n\nI loose model state when rendering after a post back. User edits are lost.\n\nWhen I use:\n\n[ChildActionOnly]\npublic ActionResult RegisterDetails(UserModel model)\n\n\nValidation occurs early so I see validation errors everywhere as if a post back has already occurred. When setting break points in the code I can see the SurfaceController code is called first before hitting the partial view. In the partial view the model is populated, but for some reason all the validation messages get displayed as if the model is empty. If I do a post back, model state is preserved and everything displays as expected - validation messages for bad model properties, no messages for good model properties.\n\nI see validation messages for all @Html.ValidationMessageFor items, and also valid model properties in all @Html.EditorFor items that accompany them.\n\nAny idea what I might be doing wrong?"
] | [
"c#",
"asp.net-mvc",
"validation",
"state",
"umbraco7"
] |
[
"ASP.NET : the connection is closed",
"I want to execute a query but we are facing the problem of connection string\n\nThis is my code:\n\nOracleCommand _commandInvoice = new OracleCommand();\n_commandInvoice.CommandType = CommandType.StoredProcedure;\n\n_commandInvoice.Parameters.AddWithValue(\"I_INVOICE_ID\", strInvoiceID);\n_commandInvoice.Parameters.AddWithValue(\"I_ORG_ID\", ORG_ID);\n_commandInvoice.Parameters.AddWithValue(\"I_ORG_NAME\", strOrg_name);\n_commandInvoice.Parameters.AddWithValue(\"I_PROJECT\", strProject);\n_commandInvoice.Parameters.AddWithValue(\"I_VENDOR_NAME\", strVendor_name);\n_commandInvoice.Parameters.AddWithValue(\"I_VENDOR_TYPE_LOOKUP_CODE\", strVendorType_lookup_Code);\n_commandInvoice.Parameters.AddWithValue(\"I_INVOICE_NUMBER\", strInvoice_number);\n_commandInvoice.Parameters.AddWithValue(\"I_INVOICE_DATE\", strInvoice_date);\n_commandInvoice.Parameters.AddWithValue(\"I_INVOICE_AMT\", strInvoice_Amt);\n_commandInvoice.Parameters.AddWithValue(\"I_OUTSTANDING_AMT\", strOutstanding_Amt);\n_commandInvoice.Parameters.AddWithValue(\"I_OUTSTANDING_REQ_AMT\", strOutstanding_req_amt);\n\nif (obj_Conn.State == ConnectionState.Closed)\n{\n obj_Conn.Open();\n _commandInvoice.ExecuteNonQuery();\n}\n\n\nWe are getting am error:\n\n\n Invalid operation. The connection is closed."
] | [
"c#",
"asp.net",
"oracle"
] |
[
"Ambiguity in overloaded function: how is it resolved?",
"I have overloaded << to print the contents of a pair, in two different forms (see code below). The first form is specific for the pair type defined. The second is templated, for any pair. Any of the two is ok for my pair type. When both prototypes precede the definition of main, the first one (specific) is used, regardless of the order of the prototypes. Only when the prototype for the first is commented, is the second used.\n\nWhy is the ambiguity resolved in this way, deciding which is the appropriate function to use?\n\n#include <iostream>\n#include <map>\n\nusing namespace std;\n\ntypedef pair<string, char> pair_t;\n\nostream& operator<<(ostream& os, const pair_t& p); // First form, specific\n\ntemplate<class first_class, class second_class>\nostream& operator<<(ostream& os, const pair<first_class, second_class>& p); // Second form, generic\n\nint main(void) {\n pair_t p2;\n p2 = make_pair(\"Fer\", 'C');\n cout << p2 << endl;\n return 0;\n}\n\nostream& operator<<(ostream& os, const pair_t& p)\n{\n os << p.first << \" obtained \\'\" << p.second << \"\\'\";\n return os;\n}\n\ntemplate<class first_class, class second_class>\nostream& operator<<(ostream& os, const pair<first_class, second_class>& p)\n{\n os << \"(\" << p.first << \", \" << p.second << \")\";\n return os;\n}"
] | [
"c++",
"operator-overloading",
"ambiguity"
] |
[
"shopify how to search for a value in a tag that is stored as \"key:value\"",
"A company that i'm doing work with has added custom tags to each of my products. The problem i'm having is trying to find a meaningful way to work with this data.\nproduct.tags give me this.\nvalue1:abc\nvalue2:def\nvalue3:ghi\nvalue4:jkl\nMy problem is that each of these tags is a complete string.\ni need to figure out a way to say -- if value1 == "something" do "this" end --\nI've tried seeing if i can make something happen with product.tags | json, but as you can imagine that doesn't really help either. I've looked up working with the products API and how to achieve what i want-- but it seems like there might be an easier way to achieve this.\nCan anyone provide any insight?\nThe end result is i need to display specific copy on my product page depending on what those tags values (after the : ) are.\nThank you in advance."
] | [
"tags",
"shopify",
"liquid-layout"
] |
[
"dependency injection provide activity",
"I want to add an activity as a dependency for one of my classes\n\nclass ViewHandler{\n @inject public ViewHandler(Myactivity myactivity){\n this.activity = myactivity;\n }\n}\n\n\nhow can I do this without being obstructed by the Activity life cycle"
] | [
"android",
"dependency-injection",
"dagger-2"
] |
[
"awk: if pattern is found, count lines until the first empty line",
"In a large document, once a pattern is found, count all the lines, from the next line of the pattern, until the first empty one:\n\n...\nPATTERN \nBBBB\nCCCC\n\n...\n\n\nIt should print: 2\n\nWhat I have tried:\n\nawk '/PATTERN/{print $0}' file | wc-l"
] | [
"regex",
"awk"
] |
[
"Getting all visible Nodes from Infragistics UltraTree",
"I have 1 root node and many child nodes of that root node.\n\nI want to get all of the visible nodes key. \n\nThe recursive code block like below;\n\npublic void PrintNodesRecursive(UltraTreeNode oParentNode)\n{ \n foreach (UltraTreeNode oSubNode in ultraTree1.Nodes[0].Nodes)\n {\n MessageBox.Show(oSubNode.Key.ToString());\n PrintNodesRecursive(oSubNode);\n } \n}\n\nprivate void ultraButton3_Click(object sender, EventArgs e)\n{\n PrintNodesRecursive(ultraTree1.Nodes[0]);\n}\n\n\nHowever messagebox always show me '1' value. It doesn't count and endless loop happens.\n\nHow can I make it happen?"
] | [
"c#",
"winforms",
"infragistics",
"ultratree"
] |
[
"Find whether a string matches another string",
"I'd like to parse a string in order to see if it matches the entire string or a substring.\nI tried this:\n\nString [] array = {\"Example\",\"hi\",\"EXAMPLE\",\"example\",\"eXamPLe\"};\nString word;\n...\nif ( array[j].toUpperCase().contains(word) || array[j].toLowerCase().contains(word) )\nSystem.out.print(word + \" \");\n\n\nBut my problem is:\n\nWhen user enter the word \"Example\" (case sensitive) and in my array there is \"Example\" it doesn't print it, it only prints \"EXAMPLE\" and \"example\" that's because when my program compares the two strings it converts my array[j] string to uppercase or lowercase so it won't match words with both upper and lower cases like the word \"Example\".\n\nSo in this case if user enters \"Examp\" I want it to print:\n\nExample EXAMPLE example eXamPLe"
] | [
"java",
"string",
"string-comparison"
] |
[
"Receive only sms of a particular format by my application",
"I am using Brodcast Receiver class to receive sms by my application. I have also given priority to my application in manifest file. I have coded in my application that if a sms is in a particular format then it should load a second screen. It runs fine when sms is of particular format but when i send in any other format since my application has been given higher priority it receives sms first(my assumption) then it generates force close dialog box but the message shows in the notification bar. \n\nWhat i want is if a sms is of particular format then it should be handled by my application else it should be handled by system ?\n\nMy main file is :\n\npackage com.example.smsapp;\n\nimport android.content.BroadcastReceiver;\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.telephony.SmsMessage;\n\n\n\n\npublic class SMSApp extends BroadcastReceiver\n{\n@Override\npublic void onReceive(Context context, Intent intent) \n{\n //---get the SMS message passed in---\n Bundle bundle = intent.getExtras(); \n SmsMessage[] msgs = null;\n String str = \"\"; \n if (bundle != null)\n {\n //---retrieve the SMS message received---\n Object[] pdus = (Object[]) bundle.get(\"pdus\");\n msgs = new SmsMessage[pdus.length]; \n for (int i=0; i<msgs.length; i++){\n msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); \n // str += \"SMS from \" + msgs[i].getOriginatingAddress(); \n // str += \" :\";\n str += msgs[i].getMessageBody().toString();\n // str += \"\\n\"; \n }\n //---display the new SMS message---\n //Toast.makeText(context, str, Toast.LENGTH_SHORT).show();\n String[] msgText;\n msgText=str.split(\",\");\n if(msgText[0].equals(\"second\"))\n { \n Intent i = new Intent(context,Second.class);\n i.putExtra(\"msg\",msgText[1]);\n i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); \n context.startActivity(i);\n }\n\n }\n this.abortBroadcast();\n}\n\n\n\n }\n\n\nManifest file:\n\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\npackage=\"com.demo.smsapp\" android:versionCode=\"1\"\nandroid:versionName=\"1.0\">\n<uses-sdk android:minSdkVersion=\"8\" />\n\n<application android:icon=\"@drawable/icon\" android:label=\"@string/app_name\">\n <activity android:name=\"Second\" class=\".second\"\n android:label=\"SMSApp\">\n </activity>\n <receiver android:name=\".SMSApp\">\n <intent-filter android:priority=\"100\">\n <action android:name=\"android.provider.Telephony.SMS_RECEIVED\" />\n </intent-filter>\n </receiver>\n</application>\n<uses-permission android:name=\"android.permission.SEND_SMS\">\n</uses-permission>\n<uses-permission android:name=\"android.permission.RECEIVE_SMS\">\n</uses-permission>\n</manifest>"
] | [
"android"
] |
[
"How to compute SHA-1 of a big file (>50MB) in google apps script?",
"I'm trying to use Box chunked-upload API from google apps script for a big file (>50MB). I could create session and uploaded part files, but I got stuck to commit upload.\n\nThis API requires \"Digest\" header mandatorily, but I cannot compute the digest of the file since it's more than 50MB.\n\nWhen I run the following code, apps script says \"File big_file.bin exceeds the maximum file size.\"\n\n\r\n\r\nfunction test_compute_digest() {\r\n var big_file = DriveApp.getFileById(\"XXXXXXXXXXXXX-XXX-XXXXXXXXXXXXXXX\"); // >50MB file\r\n var sha1 = Utilities.base64Encode(Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_1, big_file.getBlob().getBytes()));\r\n Logger.log(sha1);\r\n}\r\n\r\n\r\n\n\nIs there any way to compute SHA-1 of a big file (>50MB) in google apps script?"
] | [
"google-apps-script",
"box"
] |
[
"how to handle a post collection zf2 rest",
"Everywhere I read that the POST method in ZF2 RestController is builded to support create Collections of data\n\nBut I can't find a tutorial on internet that shows a create collection method, I only found alone enitity been created in POST create method.\n\nSo, how handle the POST (create) method to accept only one Entity post or a Collection of Entities\n\nsorry for my English, I'm Brazilian"
] | [
"php",
"rest",
"zend-framework2"
] |
[
"parsing out the last number of the post",
"Ok so i have a post that looks kind of this\n\n[optional_premium_1] => Array\n (\n [0] => 61\n )\n[optional_premium_2] => Array\n (\n [0] => 55\n )\n[optional_premium_3] => Array\n (\n [0] => 55\n )\n[premium_1] => Array\n (\n [0] => 33\n )\n[premium_2] => Array\n (\n [0] => 36 )\n[premium_3] => Array\n (\n [0] => 88 )\n\n[premium_4] => Array\n (\n [0] => 51\n )\n\n\nhow do i get the highest number out of the that. So for example, the optional \"optional_premium_\" highest is 3 and the \"premium_\" optional the highest is 4. How do i find the highest in this $_POST"
] | [
"php",
"regex",
"parsing",
"post"
] |
[
"Python reshaping a np 4D array into a 2D array. Kaggle Image data",
"I am trying to convert a 4D array into a 2D array for the use of sklearn SVM model but it gives me issues when I try to use the data in the model. \nSo i get the data split into the train and test data and then convert it into a np array like so.\n\n#Train data\nnpXt = np.array(x_train)\nnpYt = np.array(y_train)\n#Eval test data\nnpXT = np.array(x_test)\nnpYT = np.array(y_test)\n\n\nThen I look at the shape like so\n\nnpXt.shape\n\n\nWhich gives me this,\n\n(28709, 48, 48, 1)\n\n\nI try to change it by doing this;\n\nnpXt.transpose((28709, 48, 48, 1)).reshape(np.prod(npXt.shape[:2]),-1)\n\n\nBut gives this error.\n\nAxisError Traceback (most recent call last)\n<ipython-input-8-2682876229f4> in <module>()\n----> 1 npXt.transpose((28709, 48, 48, 1)).reshape(np.prod(npXt.shape[:2]),-1)\n\nAxisError: axis 28709 is out of bounds for array of dimension 4\n\n\nWhat am I doing wrong here?\n\nThanks for any help with this\n\nUPDATE:\nThank you for all the suggestions:\nI tried it and there is a error like this:\n\nValueError: bad input shape (28709, 7)\n\n\nSo here is what I have fixed to get to this. What I think is the problem is that I am not reshaping the array right currently.\nSo I download the data like this and this works fine:\n\nx_train, y_train, x_test, y_test = aiu.getKaggleData(file,numClass)\n\n\nWhich gives this as the result:\n\nCreating Testing and Training datasets\nFilling datasets\nTransforming data to fit model's needs\nNormalizing traing/testing datasets\nReshaping data\n28709 train samples\n3589 test samples\n\n\nI expect this and this worked with another model that I built.\nNext I build the SVM model like so:\n\nclf = SVC(C=0.01, kernel='linear', decision_function_shape='ovo', probability=True) \n\n\nThen convert the train and test data into np arrays like this\n\n#Train data\nnpXt = np.array(x_train)\nnpYt = np.array(y_train)\n#Eval test data\nnpXT = np.array(x_test)\nnpYT = np.array(y_test)\n\n\nThen using what has been suggested \n\nmy_array = np.ones((28709, 48, 48, 1))\nnewXTrain = np.transpose( my_array ).reshape(np.prod(npXt.shape[:2]),-1)\nprint(newXTrain.shape)\nprint(npYt.shape)\n\n\nWhich gives me this:\n\n(1378032, 48) #for data\n(28709, 7) #for lables\n\n\nThen I try to train the model like so\n\nclf.fit(newXTrain,npYt)\n\n\nWhich gives me this\n\n raise ValueError(\"bad input shape {0}\".format(shape))\n ValueError: bad input shape (28709, 7)\n\n\nThank you for all your help so far\n\nI have even tried this but still gives an error:\n\nnewXTrain = np.transpose( my_array ).reshape(np.prod(npXt.shape[:1]),-1)\n\n\nThat gives me this which looked promising.\n\n(28709, 2304)\n(28709, 7)\n\n\nbut gave the same error as ValueError: bad input shape (28709, 7)"
] | [
"python",
"numpy",
"scikit-learn",
"kaggle"
] |
[
"UnhandledErrorDetected: Unspecified error COMException",
"Struggling with an error that freezes the app and only occurs on the tablet (never on my laptop). Seems to be related to quickly switching the hamburger menu. I got one stack trace that incriminated a 3rd party control, but 9 of 10 times all I get is the following. There are only a couple of \"async void\"s where I can't avoid them (overriding events) and from other logging, I believe the issue is in the XAML (methods are logging entry/exit):\n\n\n Unspecified error\n : System.Runtime.InteropServices.COMException (0x80004005): Unspecified error\n \n Unspecified error\n at Windows.ApplicationModel.Core.UnhandledError.Propagate()\n at Oceaneering.Commons.Utilities.Logger.CoreApplication_UnhandledErrorDetected(Object sender, UnhandledErrorDetectedEventArgs e)\n\n\nSetting up like this:\n\nCoreApplication.UnhandledErrorDetected += CoreApplication_UnhandledErrorDetected;\n\n\nAnd the receiving method is:\n\ntry { \n e.UnhandledError.Propagate();\n}\ncatch (Exception ex){\n logChannel.LogMessage(string.Format(\"Unhandled Exception: {0}:{1}\", ex.Message, ex.ToString()));\n SaveToFileAsync().Wait();\n} \n\n\nAnything else I can do to gather more info? Thanks!"
] | [
"win-universal-app",
"uwp",
"windows-10-universal",
"windows-10-mobile"
] |
[
"htaccess allow from 127.0.0.1 not working",
"I am using XAMPP on windows 7. I put this htaccess file in my htdocs folder and I'm getting access denied when I try to open http://localhost/.\n\nOrder allow,deny\nAllow from 127.0.0.1\nAllow from ::1\nDeny from all\n\n\nI want to deny access to any computers other than this one. How can I do this?"
] | [
"apache",
".htaccess"
] |
[
"How to read an Excel spreadsheet and convert units?",
"I've got an excel spreadsheet that I would like to use python to convert the measurements from cm3/day to just cm3/year.\n\nis there a way to do this?\nI've looked into openpyxl mostly as this module seems to come up the most for excel editing but I guess I'm mostly confused about how to edit the units so they are all the same... I can't seem to find a module that supports what I'm trying to do."
] | [
"python",
"excel",
"converters"
] |
[
"Three.js error with multiple canvases and JSON loaded geometry",
"I'm attempting to create multiple views and have copied the example code found here exactly and it works perfectly.\n\nHowever as soon as I replace the geometries with one that i've built in blender it throws an error:\n\nCannot read property 'length' of undefined - three.js 21532\n\n\nIn the animate / render loop it renders the first canvases first frame, then the second canvases first frame it throws the error.\n\nI know it has something to do with object.__webglInit being undefined for the second object."
] | [
"javascript",
"three.js"
] |
[
"retrieve href attributes from url with php",
"i want to retrieve the href attributes within all the anchor tags on the homepage url provided by the website1, crawl the website by one level depth, and retrieve the href attributes within all the anchor tags found on the crawled page, but it doesn't show anything. the function i used is findAndCompare.\n\n<html>\n<body>\n\n<form action=\"<?php echo htmlspecialchars($_SERVER[\"PHP_SELF\"]);?>\" method=\"post\">\nwebsite: <input type=\"text\" name=\"website1\"><br>\nwebsite: <input type=\"text\" name=\"website2\"><br>\n<input type=\"submit\" name=\"submit\">\n</form>\n\n</body>\n</html> \n\n<?php\n if(isset($_POST['submit']))\n {\n // form has been submitted\n $form_data = $_POST['website1'];\n findAndCompare($form_data);\n\n }\n else\n {}\n\nfunction findAndCompare($url){\n\n// Create a DOM parser object\n$dom = new DOMDocument();\n\n$dom->loadHTML($url);\n\n// Iterate over all the <a> tags\nforeach($dom->getElementsByTagName('a') as $link) {\n // Show the <a href>\n echo $link->getAttribute('href');\n echo \"<br />\";\n}\n}\n\n?>"
] | [
"php",
"url",
"dom",
"href"
] |
[
"Flask REST API record sender's IP address",
"I have created a minimal REST API using Flask, SQLAlchemy, and Marshmallow. here is app.py file:\nfrom flask import Flask, request, jsonify\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_marshmallow import Marshmallow\nimport os\n\n# Initialize App\napp = Flask(__name__)\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\n# Database Setup\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'db.sqlite')\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n# Init db\ndb = SQLAlchemy(app)\n# Init marshmallow\nma = Marshmallow(app)\n\n\n# Product Class/Model\nclass Product(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(100), unique=True)\n description = db.Column(db.String(200))\n price = db.Column(db.Float)\n qty = db.Column(db.Integer)\n\n def __init__(self, name, description, price, qty):\n self.name = name\n self.description = description\n self.price = price\n self.qty = qty\n\n\n# Product Schema\nclass ProductSchema(ma.Schema):\n class Meta:\n fields = ('id', 'name', 'description', 'price', 'qty')\n\n\n# Init Schema\nproduct_schema = ProductSchema()\nproducts_schema = ProductSchema(many=True)\n\n\n# Create Product\[email protected]('/product', methods=['POST'])\ndef add_product():\n name = request.json['name']\n description = request.json['description']\n price = request.json['price']\n qty = request.json['qty']\n\n new_product = Product(name, description, price, qty)\n\n db.session.add(new_product)\n db.session.commit()\n\n return product_schema.jsonify(new_product)\n\n\n# Get All Products\[email protected]('/receive', methods=['GET'])\ndef get_products():\n all_products = Product.query.all()\n result = products_schema.dump(all_products)\n return jsonify(result)\n\n\n# Run the Server\nif __name__ == '__main__':\n app.run(debug=True)\n\nI want to extract the sender's IP address through the GET method. However, the sender's IP doesn't need to be part of the JSON payload.\nExample: POST\n{\n "name": "Product 1",\n "description": "This is product 1",\n "price": 120.00,\n "qty": 100\n}\n\nGET\n{\n "ip": "<whatever-the-ip>"\n "name": "Product 1",\n "description": "This is product 1",\n "price": 120.00,\n "qty": 100\n}\n\nHow do I implement this functionality in my code? I tried using request.remote_addr, but I am not getting what I expected."
] | [
"rest",
"flask",
"sqlalchemy",
"flask-sqlalchemy",
"flask-restful"
] |
[
"32-bit MAPI app with 64-bit Outlook",
"The 32-bit version of our app is unable to send email using MAPISendMail with 64-bit Outlook installed. It returns an error 0x80004005, about which I can find little information beyond the fact that it seems to be a MAPI initialization error.\n\nAccording to this MSDN document, MAPISendMail is the one exception to the rule that 32-bit apps can't use 64-bit MAPI. And yet it doesn't work (at least with XP and Vista--we haven't tested Win7/8 yet).\n\nCan anyone shed any light on this?\n\nTIA"
] | [
"windows",
"outlook",
"mapi",
"mapisendmail"
] |
[
"Restrict from moving to X axis (C# Unity)",
"I have this example data\n\n\n Data: P, B, B, T, P\n\n\nSo it will be outputted like this\n\n\n\nBut what is happening to me is this\n\n\n\nWhat I want here is that every tie must not increment to the X axis . How can I obtain that?\n\nHere's what I've tried so far:\n\nstring[] scoreboardWinner = new string[] \n{\n \"P \",\"B \",\"T \",\n \"BP \",\"B P\",\"B B\",\"BB \",\n \"PB \",\"P B\",\"P P\",\"PP \",\n \"TP \",\"TB \",\"T P\",\"T B\",\n \"TTT\",\n \"BBP\",\"BPB\",\"BPP\",\"BBB\",\n \"PPB\",\"PBP\",\"PBB\",\"PPP\"\n};\n\nprivate void XandYaxis() {\n\n string[,] table = new string[104, 6];\n string newPreviousValue = \"placeholder\";\n int xIndex = -1;\n int yIndex = 0;\n\n if (gametable_no == 1)\n {\n for (int i = 0; i < list.Count; i++)\n {\n newString[0] += list[i].r;\n }\n\n string[] newChars = newString[0].Split(',');\n\n if (table.GetLength(0) < xIndex)\n {\n break;\n }\n\n if (result.Equals(newPreviousValue) && yIndex < table.GetLength(1) - 1)\n {\n yIndex += 1;\n table[xIndex, yIndex] = result;\n }\n else\n {\n xIndex += 1;\n yIndex = 0;\n table[xIndex, yIndex] = result;\n }\n }\n}\n\n\nI also tried putting an if else statement inside of the \n\nif (result.Equals(newPreviousValue) && yIndex < table.GetLength(1) - 1)\n {\n string newResult = scoreboardWinner[2];\n if (previousValue.Contains(newResult))\n {\n yIndex += 1;\n table[xIndex, yIndex] = result;\n }\n }\n}\n\n\nBut it didn't work.\n\nBy the way the scoreboardWinner[2] = \"T \"; which is the TIE"
] | [
"c#",
"android",
"unity3d"
] |
[
"Implementing Parallel Algorithm for Longest Common Subsequence",
"I am trying to implement the Parallel Algorithm for Longest Common Subsequence Problem described in http://www.iaeng.org/publication/WCE2010/WCE2010_pp499-504.pdf\n\nBut i am having a problem with the variable C in Equation 6 on page 4\n\n\n\nThe paper refered to C on at the end of page 3 as\n\n\n C as Let C[1 : l] bethe finite alphabet\n\n\nI am not sure what is ment by this, as i guess it would it with the 2 strings ABCDEF and ABQXYEF be ABCDEFQXY. But what if my 2 stings is a list of objects (Where my match test for an example is obj1.Name = obj2.Name), what would my C be here? just a union on the 2 arrays?"
] | [
"algorithm",
"parallel-processing",
"lcs"
] |
[
"How to resolve this error : spawn yarn ENOENT?",
"Yarn Install successful:\nC:\\Users\\Yael\\Downloads\\metamask-extension-8.0.9\\metamask-extension-8.0.9>yarn\nyarn install v1.22.10\n[1/5] Validating package.json...\n[2/5] Resolving packages...\nsuccess Already up-to-date.\nDone in 2.77s.\n\nYarn dist error:\nC:\\Users\\Yael\\Downloads\\metamask-extension-8.0.9\\metamask-extension-8.0.9>yarn dist\nyarn run v1.22.10\n$ yarn build prod\n$ node development/build/index.js prod\nrunning task "prod"...\nStarting 'prod'...\nStarting 'clean'...\n(node:12548) ExperimentalWarning: The fs.promises API is experimental\nFinished 'clean'\nStarting 'styles:prod'...\nFinished 'styles:prod'\nStarting 'scripts:deps:background'...\nStarting 'scripts:deps:ui'...\nStarting 'scripts:core:prod:background'...\nStarting 'scripts:core:prod:ui'...\nStarting 'scripts:core:prod:phishing-detect'...\nStarting 'scripts:core:prod:contentscript'...\nStarting 'static:prod'...\nStarting 'manifest:prod'...\nevents.js:174\nthrow er; // Unhandled 'error' event\n^\nError: spawn yarn ENOENT\n at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)\n at onErrorNT (internal/child_process.js:415:16)\n at process._tickCallback (internal/process/next_tick.js:63:19)\nEmitted 'error' event at:\n at Process.ChildProcess._handle.onexit (internal/child_process.js:246:12)\n at onErrorNT (internal/child_process.js:415:16)\n at process._tickCallback (internal/process/next_tick.js:63:19)\nerror Command failed with exit code 1.\ninfo Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\nerror Command failed with exit code 1.\ninfo Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.\n\nC:\\Users\\Yael\\Downloads\\metamask-extension-8.0.9\\metamask-extension-8.0.9>"
] | [
"yarnpkg"
] |
[
"ios app: How to efficiently use an existing database",
"I have a single table database which is stored as an MSAccess database. It served us greatly as a desktop app for a long time, but I want to convert it to an ios app.\nThe table contains several hundred recordings, a key, and 20 properties. It serves us as a reference \"book\", and therefore some of the properties are short text, some are just words, and some are long texts containing multiple lines with indentations. As a database, it works for us flawlessly.\n\nThe question is - if I am going to build an app, what is the most efficient way of reusing this existing database and still remain the original text format?\nI would like to include a search by keyword, and it should then go to a new view controller showing all the properties, as a list, something like this: \n\nhttps://www.sketchappsources.com/resources/source-image/dictionary-app.png\n\nIt should be read-only, and the user could use it offline."
] | [
"ios",
"database"
] |
[
"\"Invalid IAP credentials: Base64 decode failed on token:\" while accessing APIs on Google Cloud[.NET]",
"I'm trying to get access token to Authenticate Google Service Account using below code. This code is returning a token. I tried to access the APIs from Postman with the token I received, however getting error as "Invalid IAP credentials: Base64 decode failed on token:". Just FYI, I'm using Google's OAuth library for .NET.\nThis is the token I received\nya29.c.Ko4B4Act579buZYyeoPgvOwuKREoi981lSLUQxA03SzAPGQuPY9Z3CXSnkouFdO4wj1lRwhGJxCLlnLlVsmLBySYf1VWQIbtSf8wMbIzW5b7n6mXeQgb-xk8SXwNZsLqxHprGlj-Zr35YrvoBzQPE6_OEQSD7g90g3Y-3DDnkCqs1m_K-udBVIVVYJ3lDQ\n\nCode\nclass Program\n{\n public const string SCOPE_READONLY = "https://www.googleapis.com/auth/userinfo.profile";\n public const string KEYFILE_PATH_READONLY = @"../../keys/XXXjson";\n public const string CLIENT_EMAIL_READONLY = "[email protected]";\n static void Main(string[] args)\n {\n var token = GoogleServiceAccount.GetAccessTokenFromJSONKey(\n KEYFILE_PATH_READONLY,\n SCOPE_READONLY);\n\n Console.WriteLine(token);\n } \n}\n\n.\npublic class GoogleServiceAccount\n {\n /// <summary>\n /// Get Access Token From JSON Key Async\n /// </summary>\n /// <param name="jsonKeyFilePath">Path to your JSON Key file</param>\n /// <param name="scopes">Scopes required in access token</param>\n /// <returns>Access token as string Task</returns>\n public static async Task<string> GetAccessTokenFromJSONKeyAsync(string jsonKeyFilePath, params string[] scopes)\n {\n using (var stream = new FileStream(jsonKeyFilePath, FileMode.Open, FileAccess.Read))\n {\n return await GoogleCredential\n .FromStream(stream) // Loads key file\n .CreateScoped(scopes) // Gathers scopes requested\n .UnderlyingCredential // Gets the credentials\n .GetAccessTokenForRequestAsync("https://accounts.google.com/o/oauth2/auth"); // Gets the Access Token\n }\n }\n\n /// <summary>\n /// Get Access Token From JSON Key\n /// </summary>\n /// <param name="jsonKeyFilePath">Path to your JSON Key file</param>\n /// <param name="scopes">Scopes required in access token</param>\n /// <returns>Access token as string</returns>\n public static string GetAccessTokenFromJSONKey(string jsonKeyFilePath, params string[] scopes)\n {\n return GetAccessTokenFromJSONKeyAsync(jsonKeyFilePath, scopes).Result;\n }\n\n }"
] | [
"c#",
"oauth-2.0",
"jwt",
"google-oauth",
"service-accounts"
] |
[
"Getting the class of a Java generic, and interface implementation of generics",
"I'd like to make a class that looks basically like this:\n\npublic class MyClass<T implements Serializable) {\n\n void function() {\n Class c = T.class;\n }\n}\n\n\nTwo errors:\n- I cannot call T.class, even though I can do that with any other object type\n- I cannot enforce that T implements Serializable in this way\n\nHow do I solve my two generics problems?\n\nCheers\n\nNik"
] | [
"java",
"generics"
] |
[
"PolarSSL PKI encrypt/sign",
"I need to encrypt data with asymmetric key. Not sure whether PolarSSL (v1.2) has common API for this. The key in certificate can be RSA or DHM (or EC) and I expect to have universal API like \"init/encrypt/decrypt/free\" without separate calls to rsa_encrypt, dh_encrypt, etc."
] | [
"pki",
"polarssl"
] |
[
"Swift: Modifying one element in Array of Dictionaries",
"I have an Array of dictionaries like this:\n\n{\nPlace = \"somewhere\";\nType = Any;\ntimeRegisted = \"2017-04-24T16:15:00\";\n},\n\n\nI'm modifying the timeRegisted from UTC to local time. Like this:\n\nlet newJsonContent = jsonContent { (contents:Any) -> String in\n\n let dict:NSDictionary = contents as! NSDictionary\n let time:String = dict.object(forKey: \"SchedDepTime\") as! String\n print(time)\n\n let dateFormatter = DateFormatter()\n dateFormatter.dateFormat = \"yyyy-MM-dd'T'HH:mm:ss\"\n dateFormatter.timeZone = NSTimeZone(name: \"UTC\")! as TimeZone\n let date = dateFormatter.date(from: time)\n dateFormatter.dateFormat = \"MM-dd-yyyy HH:mm\"\n dateFormatter.timeZone = NSTimeZone.local\n let timeStamp = dateFormatter.string(from: date!)\n return time\n } \n\n\nThe conversion of UTC to local time works great but my question to guys. How can just modify the time and keep the contents of the dictionary and not just the times?\n\nAny of you knows how can I do this?\nI'll really appreciate your help."
] | [
"swift3",
"nsarray",
"nsdictionary"
] |
[
"Growl Notification - Won't fire notification using framework (Mist)",
"I'm working on a small wrapper for the Growl 1.3.1 SDK. More specifically, I'd like to package Growl in my application so that even if the user doesn't have Growl, they will still be able to get notifications. I previously had Growl installed and my code would fire a notification. I have since uninstalled Growl and am using just the framework; Mist, I believe it is called. However, when I launch the code now (that Growl is uninstalled), no notification is fired! Below is the code I am currently working with:\n\n#import \"growlwrapper.h\"\n\nvoid showGrowlMessage(std::string title, std::string desc) {\n std::cout << \"[Growl] showGrowlMessage() called.\" << std::endl;\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n [GrowlApplicationBridge setGrowlDelegate: @\"\"];\n [GrowlApplicationBridge\n notifyWithTitle: [NSString stringWithUTF8String:title.c_str()]\n description: [NSString stringWithUTF8String:desc.c_str()]\n notificationName: @\"Upload\"\n iconData: nil\n priority: 0\n isSticky: NO\n clickContext: nil\n ];\n [pool drain];\n}\n\nint main() {\n showGrowlMessage(\"Hello World!\", \"This is a test of the growl system\");\n return 0;\n}\n\n\nI also have the appropriate Growl Registration dictionary, and am compiling with:\n\ng++ growlwrapper.mm -framework Growl -framework Foundation -o growltest\n\n\nIs there anything wrong with this code? Any ideas why it wouldn't be firing?\n\n\n\nEdit: Seems the code above is working just fine. Just needed to be in a run loop, with the appropriate Growl dictionary stuff."
] | [
"c++",
"objective-c",
"macos",
"objective-c++",
"growl"
] |
[
"postgresql - is it possible to run different SELECT functions based on a filter?",
"I have a Postgresql function that collects data (data is the same) from tree different postgresql functions. But, it should be possible to only run some of the three functions based on a filter. Example\n\nFROM (SELECT events.id,\n events.slug,\n events.picture_url,\n events.lat,\n events.lng,\n events.user_id,\n events.inserted_at,\n events.updated_at,\n events.geom,\n events.address,\n events.place\n FROM (\n -- DO FILTERING CASE WHEN (filter = 'global' OR filter = 'self') THEN\n SELECT * from my_events(param_user_id)\n END\n UNION\n -- DO FILTERING CASE WHEN (filter = 'global' OR filter = 'friends') THEN\n --by starting from follows table\n SELECT * FROM follows(param_user_id)\n END\n UNION\n -- DO FILTERING CASE WHEN (filter = 'global' OR filter = 'friends') THEN\n SELECT * FROM friends_events(param_user_id)\n END\n\n ) AS events ORDER BY events.inserted_at DESC LIMIT limit_count OFFSET limit_count * page\n ) AS e; END; $function$\n\n\nA filter is a text string for example filter = \"function 1\". \nIf filter = \"function 1\" then only execute SELECT and ignore the other two. \n\nIf filter = \"all\" then run all of them. Lambda example\nSELECT (<fields>) FROM(\nIF filter = \"function1\" OR filter = \"all\" then\nSELECT <function 1>\nIF filter = \"function 2\" OR filter = \"all\" THEN\n\nSELECT <function2>\n\n\nAnd so on."
] | [
"postgresql"
] |
[
"Editing form by double clicking element",
"I have a form, and I want to be able to edit any part of that form by double clicking it. So going from this:\n\n\r\n\r\n<table>\r\n <tr>\r\n <th>Name</th>\r\n <th>Email</th>\r\n <th>Phone</th>\r\n </tr>\r\n <tr>\r\n <td>John Smith</td>\r\n <td>[email protected]</td>\r\n <td>+12345678</td>\r\n </tr>\r\n</table>\r\n\r\n\r\n\n\nHow can I by double-clicking an element, transform it to an input element?\nFor example: if I double click on John Smith, the HTML changes into this:\n\n\r\n\r\n<table>\r\n <tr>\r\n <th>Name</th>\r\n <th>Email</th>\r\n <th>Phone</th>\r\n </tr>\r\n <tr>\r\n <form action=\"index.php\" method=\"post\">\r\n <td><input type=\"text\" value=\"John Smith\" name=\"name\" /></td>\r\n <td>[email protected]</td>\r\n <td>+12345678</td>\r\n </form>\r\n </tr>\r\n</table>\r\n\r\n\r\n\nSo now I can change John's name.\n\nDoes someone know how to do it?"
] | [
"javascript",
"jquery",
"html"
] |
[
"autocomplete jquery depend on five first characters",
"How can I use the autocomplete plugin on an input field depending on the 5 first characters typed dynamically. for exemple i have typed : \n\n12345 \n\n\nAnd I get : \n\n12345 New York. \n\n\nWhat i tried is : \n\n var availableTags = [\n \"12345 New Yord\",\n \"12378 Paris\",\n \"45687 Barcelon\"\n];\n\n $( \"#tags\" ).autocomplete({\n source: availableTags,\n minLength: 5\n });\n\n\nThe problem is : \nI have to complete the available tags depending on the first 5 charachters using a function"
] | [
"javascript",
"jquery",
"autocomplete"
] |
[
"preg_match_all: Warning: preg_match_all(): Unknown modifier '(' in",
"Possible Duplicate:\n preg_match() Unknown modifier '[' help \n\n\n\n\nI am trying to match this pattern \n\n $regex_pattern = '<td id=\"(\\w+)\" class=\"(\\w+)\">(\\w+).com<\\/td>';\n preg_match_all($regex_pattern, $result, $matches);\n print_r($matches);\n\n\nBut I am getting this error: Warning: preg_match_all(): Unknown modifier '(' in\n\nWhat's wrong in my regex pattern?"
] | [
"php",
"regex",
"preg-match",
"preg-match-all"
] |
[
"Capital letter with android:keyOutputText?",
"I am developing a language specific softkeyboard in android. My language has two letter characters such as 'ch' and 'ng'. I am using the following xml code to display and output the required characters\n\n<Key android:keyOutputText=\"ng\" android:keyLabel=\"ng\"/>\n\n\nBut the output is only in small letters even if its the first letter in a sentence or when using the SHIFT key. How can i fix this? The required output would be to make only the first letter capital when its the first letter of a sentence or using shift key (eg. Ngaiteh), but to make it appear all capital when using capslock (eg. NGAITEH)\n\nI know its quite easy to use the normal english keyboard and just type the required characters one by one, but this will really improve the typing speed for my language. Thanks."
] | [
"android",
"keyboard",
"android-softkeyboard",
"ime"
] |
[
"PHP PDO : fetchColumn() does not work when row count = 1",
"I have a query that count a number of rows :\n\n$query = \"SELECT COUNT (D.grouper) FROM (Select Distinct grouper FROM Operateurs WHERE \".implode(' AND ',$where).\" ) D\";\n\n\nIt work fine when the number of rows is more than one, and return nothing when number of rows = 1 !!\n\n$stmt1->execute();\n$count = $stmt1->fetchColumn();\n\n\nThe data of the WHEN Clause is from a form, and i'm using SQL Server 2008."
] | [
"php",
"sql-server-2008",
"pdo"
] |
[
"The connection string for a local SQL 2012 Express Server Instance",
"So I've been wanting to learn a little more about SQL but I'm having some trouble connecting to a local SQL server database in the ASP.NET project I'm working on. Though I'm able to connect using Visual Studio and SQL Server Management Studio, I just can't get the connection string right. I've been looking at connectionstrings.com but I get exceptions when using alot of the keywords it suggests (server, initial catalog, database, etc.).\n\n*Edit - Added Web.config\n\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<configuration>\n <system.web>\n <compilation debug=\"true\" targetFramework=\"4.5\" />\n <httpRuntime targetFramework=\"4.5\" />\n </system.web>\n\n <connectionStrings>\n <add name=\"StarterSite\" connectionString=\"Data Source=|DataDirectory|\\StarterSite.sdf\" providerName=\"System.Data.SqlServerCe.4.0\" />\n <add name=\"AdventureWorks\" connectionString=\"Data Source=ROBERT-PC;Initial Catalog=AdventureWorks2012;Integrated Security=True\" />\n <add name=\"DefaultConnnection\" connectionString=\"Data Source=ROBERT-PC\\MSSQLSERVER;Initial Catalog=AdventureWorks2012;Persist Security Info=True;User ID=USERNAME;Password=PASSWORD\"\n providerName=\"System.Data.SqlClient\" />\n </connectionStrings>\n\n <runtime>\n <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <dependentAssembly>\n <assemblyIdentity name=\"DotNetOpenAuth.Core\" publicKeyToken=\"2780ccd10d57b246\" />\n <bindingRedirect oldVersion=\"1.0.0.0-4.1.0.0\" newVersion=\"4.1.0.0\" />\n </dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name=\"DotNetOpenAuth.AspNet\" publicKeyToken=\"2780ccd10d57b246\" />\n <bindingRedirect oldVersion=\"1.0.0.0-4.1.0.0\" newVersion=\"4.1.0.0\" />\n </dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name=\"System.Web.Optimization\" publicKeyToken=\"31bf3856ad364e35\" />\n <bindingRedirect oldVersion=\"1.0.0.0-1.1.0.0\" newVersion=\"1.1.0.0\" />\n </dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name=\"WebGrease\" publicKeyToken=\"31bf3856ad364e35\" />\n <bindingRedirect oldVersion=\"1.0.0.0-1.5.2.14234.0.0\" newVersion=\"1.5.2.14234.0.0\" />\n </dependentAssembly>\n </assemblyBinding>\n </runtime>\n<system.data> \n <DbProviderFactories>\n <remove invariant=\"System.Data.SqlServerCe.4.0\" />\n <add name=\"Microsoft SQL Server Compact Data Provider 4.0\" invariant=\"System.Data.SqlServerCe.4.0\" description=\".NET Framework Data Provider for Microsoft SQL Server Compact\" type=\"System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91\" />\n </DbProviderFactories>\n </system.data></configuration>"
] | [
"c#",
"asp.net",
"sql",
"sql-server"
] |
[
"Submit form with text and images to Laravel Controller via Ajax",
"Using Laravel 7\njQuery v3.4.1\nI'm trying to send the content of a form via Ajax to a Laravel Controller. The form contains a text field and a file field . I wanted to find a way to send both types of fields in one request.\nIt looks like the content gets send but Laravel can't read it and returns an error.\nMy Ajax Code\n$.ajaxSetup({\n headers: {\n 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')\n }\n}); \n \nvar form = $('form')[0]; \nvar formData = new FormData(form);\n\n \n \n$.ajax({\n url: form.attr('action'),\n data: formData,\n cache: false,\n method:'POST',\n contentType: false,\n processData: false,\n success: function (data) {\n\n console.log(data);\n \n },\n error: function (error,jqXHR, textStatus, errorThrown) {\n \n \n console.log(data.error); \n \n }\n });\n \n\nThe Form\n<form id="newProduct" action="{{route('Product.store',app()->getLocale())}}" method="POST" enctype="multipart/form-data">\n @csrf\n <input name="title" maxlength="10" length="10" placeholder="Product Title" type="text" id="title" class="form-control>\n <input type="file" name="files" id="files" class="files">\n</form> \n\nThe Laravel function\npublic function store(Request $request)\n{\n dd($request->input->all());\n}\n\nThe Data gets send via ajax , but somehow Laravel can't access it all. I get the following error message from Laravel Call to a member function all() on null with a 500 Http Return code.\nThis is an extract from the http request send to Larval via ajax\n-----------------------------23552347725043592001228805073\nContent-Disposition: form-data; name="title"\nsdf\nWhat has to be changed so Laravel can read the data ? Thanks in advance."
] | [
"jquery",
"ajax",
"laravel"
] |
[
"R: Create a new data frame from an existing data frame to study changes in one variable (column)",
"For example, let's say I have a data frame that looks like this:\n1 0.00038 0.75053 0.50 35 6000 0.75346\n2 0.00038 0.75053 0.50 35 6050 0.72079\n3 0.00038 0.75053 0.50 35 6100 0.69229\n4 0.00038 0.75053 0.50 35 6150 0.66689\n5 0.00038 0.75053 0.50 35 6200 0.64382\n6 0.00038 0.75053 0.50 35 6250 0.62269\n7 0.00038 0.75053 0.50 35 6300 0.60313\n# and so on\n\nIn this data frame, I want find out whenever the value in column 6 equals 6550, column 2 = 0.00030, column 3 = 0.75000, and column 4 = 0.50 (perhaps to study how a dependent variable changes when the value in column 5 changes). If it does, I want to create a new data frame using all the rows that satisfy this condition. Any suggestions?"
] | [
"r"
] |
[
"Simple Boolean Logic",
"I'm trying to determine the conditions under which the following expression, where a and b are properly declared boolean variables, evaluates to false:\n(a && (b || !a)) == a && b\n\nTo me, it seems that this expression will always evaluate to true. If either a or b is false, both sides of the equality operator will evaluate to false. If a and b are both true, then both sides will evaluate to true. That's all the options, and it's the correct answer for my online homework. However, when I run this in IntelliJ CE with the Java 11 JVM, it seems like it prints false whenever b is false:\nwhen a and b are both false, IntelliJ outputs false\nI get the same output when b is false and a is true. Can someone explain where the fault in my logic is? Thank you very much."
] | [
"java",
"boolean",
"boolean-logic",
"boolean-operations"
] |
[
"can we use string function in replace function in sql while updating a record",
"I want to update my record on certain conditions. \n\neg. I've a column ResidenceAddress1, which has email id along with the address.\n\nSample data:\n\[email protected],Rourkela \[email protected] 2nd street,7 hills \n2nd street, [email protected]\n\n\nI am finding the email from ResidenceAddress1 this way:\n\nselect (concat(trim(substring_index(substring_index(Residence_Address1, '@', '1'), ' ', -1)),'','@gmail.com') as mail,Residence_Address1\nfrom mytable\nwhere Residence_Address1 like '%gmail%' and Email_Personal1=\"\" \n\n\nWhen I update it this way:\n\nupdate mytable\nset email_Personal1=concat(trim(substring_index(substring_index(Residence_Address1, '@', '1'), ' ', -1)), '','@gmail.com') , \n Residence_Address1=replace(residence_address1,\"'concat(trim(substring_index(substring_index(Residence_Address1, '@', '1'), ' ', -1)), '','@gmail.com')'\",'')\nwhere Residence_Address1 like '%gmail%' and Email_Personal1=\"\"\n\n\nThis way, it updates email_personal1 but didn't update residence_address1 with replaced empty value instead of gmail id value in that row. Where am I mistaking here?"
] | [
"mysql",
"sql",
"replace",
"concat"
] |
[
"How can I \"simulate\" directories on a server?",
"Say I go to example.com/testing/1/2/3. I don't want it to request the directory \"/testing/1/2/3\", I want it to pass that part of that URL to a script (presumably example.com/index.php).\n\nI don't know if it works exactly as I described, but the reason I ask is because in Wordpress, in \"Permalink Settings\", you have the option to change the URL scheme to something like http://example.com/2013/08/sample-post/, so that when you navigate to that URL it shows you that post. However, it doesn't create any of those directories, or any directories for that matter. I'm wondering how that works because I'd like to use it in other places. It seems fairly commonplace (I doubt URL shorteners have hundreds of thousands of directories at the root of their domain and probably use this instead), but I'm just not sure what it is called or how to find more information about it and was hoping someone could point me in the right direction. Thanks."
] | [
"html",
"wordpress",
"web",
"server-side"
] |
[
"Adding database results to array of objects in React Native",
"I have been working on this for a while now and I cannot seems to find a good/proper way to add objects coming from a DB query to an array holding objects. Please note I am developing a React Native Expo application.\n\nThis is basically the code that I have\n\n var arr = [];\n\nfirebase.firestore().collection('Something').where(\"text\", \"==\" , \"text\").get().then((querySnapshot) =>{\n querySnapshot.forEach((doc) =>{\n arr += doc.data();\n })\n})\n\n\nThe idea here is to have arr populated with the object result of doc.data(). I have looked at a million (if felt like it) tutorials, but I cannot seems to figure out the proper and correct way to populate my array.\n\nThank you for the help"
] | [
"reactjs",
"react-native"
] |
[
"How to rescale pixel value array to any resolution in JavaScript?",
"I am working on a machine learning project in which I want the model to predict what has been drawn on the screen. I am using p5 to implement the drawing part of the project, in which I can just create an ellipse trail by dragging the mouse in the canvas. The problem is that I need the canvas to be at least 400x400 but the ML model only takes in 28x28 images. I want a way to downscale whatever is on the canvas to 28x28. I can generate a list of all the pixel values by using the get(x,y) function in p5. But I have no idea what should I do in order to downscale the drawn image.\nIs there any method I can do this, without needing to code the down-scaler from scratch?"
] | [
"javascript",
"image-processing",
"image-resizing",
"p5.js"
] |
[
"Read and Write to current editor pane from IntelliJ plugin (plugin-dev)",
"Is it possible to get the current editor pane and edit the contents from an IntelliJ (IDEA) plugin?\n\nI'd like to for example, select some text in the current editor and overwrite it with my own.\n\nI've got this far;\n\nEditor editor = FileEditorManager.getInstance(event.getProject()).getSelectedTextEditor();\nVisualPosition position = editor.getCaretModel().getVisualPosition();\nDocument document = editor.getDocument();\ndocument.insertString(position.column, Character.toString(text.charAt(offset)));\n\n\nwhere event is AnActionEvent coming in from the AnAction class.\n\nbut it doesn't update the editor panel.\n\nAny pointers much appreciated."
] | [
"java",
"intellij-idea",
"intellij-plugin"
] |
[
"How to resolve error with fileentry.copyTo(), Cordova 1.6.1",
"I'm trying to execute the copyTo method on a FileEntry and it's failing with an error code of 1. I suspect I'm not giving it what it needs. Here is the input I'm providing to the method, which one of these values is incorrect? Running on android but also getting the error on iOS. I'm attempting to follow the instructions from the API docs, but the expected input is not clear.\n\nvar imageUri = 'file:///mnt/sdcard/Android/data/com.test.app/cache/resize.jpg?1337214925787';\nvar newFileName = 'test.jpg';\nvar directoryFullPath = 'file:///mnt/sdcard/App/Job';\n\nwindow.resolveLocalFileSystemURI(\n imageUri,\n function (entry) {\n console.log(\"Get file entry success, copy file\");\n var parentEntry = new DirectoryEntry({ fullPath: directoryFullPath});\n entry.copyTo(\n parentEntry,\n newFileName,\n function (newEntry) {\n console.log(\"FileEntry copy to done. New Path: \" + newEntry.fullPath);\n },\n function (error) {\n console.log(\"FileEntry copy to fail. Error code: \" + error.code);\n }\n..."
] | [
"cordova"
] |
[
"How to clear collection associations in JPQL?",
"Consider the following JPQL query:\n\nUPATE FOO f SET f.bars = NULL\n\n\nRunning this statement will yield the exception:\n\njava.lang.IllegalArgumentException: org.hibernate.QueryException: collections not assignable in update statements [UPATE FOO f SET f.bars = NULL ]\n\n\nWhat I'm trying to do is to sever in one statement all associations between FOO and BAR. Instead of iterating over each FOO to set the bars collections to null. That's much faster.\n\nUnfortunately the association is unidirectional - so there's no foo attribute in a Bar entity. Hence JPQL can clear the other side of the association.\n\nInvoking NEW does not work either:\n\nUPATE FOO f SET f.bars = NEW java.util.ArrayList()\n\n\nThis results in a different exception:\n\njava.lang.IllegalArgumentException: node to traverse cannot be null!\n\n\nIt's clear JPA/Hibernate won't allow a collection association to be set to null. But maybe somebody in here knows a workaround ?"
] | [
"hibernate",
"jpa-2.0"
] |
[
"Symfony 3 + FOS REST Bundle: Normalize values before validation",
"I'm working on a FOS REST API. In the underlying models I'd like to be able to define Constraints representing the form appropriate for the datastore, for example, a US Phone Number should be exactly 10 digits.\n\n/**\n * @var string\n *\n * @Assert\\NotBlank(message=\"Phone is required.\")\n * @Assert\\Regex(message=\"Exactly 10 digits are required.\", pattern=\"/^\\d{10}$/\")\n */\nprivate $phone;\n\n\nOn the other hand I'd like to be able to accept liberal values, for example a phone number formatted as:\n\n{\n \"phone\": \"603-988-6521\"\n}\n\n\nThe ideal way to implement this would be to have some type of \"conversion\" or \"normalization\" phase where select fields could be converted to all digits etc. prior to validation.\n\nWhat would be the best way to accomplish this in the FOST REST paradigm and Symfony 3?"
] | [
"php",
"symfony",
"fosrestbundle"
] |
[
"Android - Get an Image from the Gallery App?",
"I need to be able to get an image from the gallery when the user clicks on a button. \n\nSince there are heaps of answers to this, my question is how can I do this, set the selected image to a RelativeLayout and this RelativeLayout is in another Class.\n\nMy project is set out like this: I have my SettingsActivity which is where the button is, and my MainActivity where the wallpaper is located. I need the image to set to the RelativeLayout when the user navigates back to the MainActivity.\n\nCode I have tried:\n\nSettingsActivity:\n\nchangeWallpaper.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view1)\n {\n Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);\n startActivityForResult(i, RESULT_LOAD_IMAGE);\n }\n });\n....\nprotected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {\n Uri selectedImage = data.getData();\n String[] filePathColumn = { MediaStore.Images.Media.DATA };\n Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);\n cursor.moveToFirst();\n int columnIndex = cursor.getColumnIndex(filePathColumn[0]);\n String picturePath = cursor.getString(columnIndex);\n cursor.close();\n\n editor.putBoolean(SETWALLPAPER, wallpaperSelection);\n editor.commit();\n }\n}\n\n\nMainActivity:\n\nisWallpaper = prefs.getBoolean(SETWALLPAPER, false);\n...\nif(isWallpaper == true)\n {\n Toast.makeText(MainActivity.this, \"Setting BG\", Toast.LENGTH_LONG).show();\n wallpaperView.setBackgroundDrawable(new BitmapDrawable(bitmap));\n }\n\n\nThanks"
] | [
"android",
"android-layout",
"android-relativelayout"
] |
[
"boost::lockfree::spsc_queue and boost::asio",
"I'm would like to receive directly into a boost::lockfree:spsc_queue (or, alternatively, a boost::circular_buffer) from a boost::asio::async_read call. Looks like I need to write a wrapper to make the spsc_queue a MutableBuffer.\n\nCan anyone share some guidance on if this is possible, and how to achieve this?\n\nMany thanks"
] | [
"c++",
"boost",
"boost-asio",
"boost-circularbuffer"
] |
[
"PHP script detect that it is an include",
"I have a PHP class file that is used as an include both through a web server and by a cron process. I am looking for a way to add some code to the head of the script so that I can detect if the script is being launched directly from the command line instead of being included in another script. This way I can make testing a bit easier by calling the script directly and having a function instantiate the object and execute some code on it without needing to create a wrapper script for it.\n\nI tried using if (php_sapi_name() == 'cli') { but that tests true even if the script is being included in another script that was called from the command line."
] | [
"include",
"php"
] |
[
"Double/nested for loop in R",
"I've encountered a particular problem: What I want to do is to get values in my matrix basing on other values in the matrix, e.g\n\n [,1] [,2] [,3]\n[1,] 110 0.0000 0.0000\n[2,] 0 300.3475 0.0000\n[3,] 0 0.0000 820.0785\n\n\nAnd now, I want to have in first column down to last row values of: \n\n[1,1] = 110\n[2,1] = [1,1] * const\n[3,1] = [2,1] * const\n\n\nIn second column:\n\n[2,1] = 0\n[2,2] = 300.3475\n[3,2] = [2,2] * const\n\n\nAnd the same thing for every column. So the point is to get value from [i, i], multiply it by a const and put into [i+1, i], then this value multiply by a const and put into [i+2, i]. And the same procedure for each column. So the matrix shown above will like this (const = 0.36624):\n\n [,1] [,2] [,3]\n[1,] 110.00000 0.0000 0.0000\n[2,] 40.28666 300.3475 0.0000\n[3,] 14.75468 110.0000 820.0785\n\n\nI've come up with something like this:\n\nN <- 2\nM.dim <- N+1\nd <- 0.36624 #const\nS0 <- c(110, 320, 820.075) #but length of this vector equals M.dim it's just example)\nbin.mat <- matrix(rep(0), M.dim, M.dim)\n\nfor(i in 1:M.dim){\n for(j in i:N){\n bin.mat[i,i] <- S0[i]\n bin.mat[j + 1, i] <- bin.mat[j, i] * d\n }\n}\n\n\nAnd now, it is working - but it shows an error:\n\nError in `[<-`(`*tmp*`, j + 1, i, value = bin.mat[j, i] * d) : \n subscript out of bounds\n\n\nAnd being honest, I have no idea why. Probably beacuse I don't really get how this loop is working, I just tried maaaaaany variations of it and this is the only one actually doing what I want :D And while other calculations based on this matrix are incorrect, I suspect that as long as it works for low numbers of columns or rows it may not work properly for big ones."
] | [
"r",
"loops",
"for-loop",
"matrix",
"nested"
] |
[
"UPDATE n records for each user",
"I have to update n oldest orders per each user. For now I use following code to update 1 oldest record per user, but can't figure out how to update n records...\n\nUPDATE orders\n INNER JOIN (\n SELECT id, MIN(created) AS created\n FROM orders \n WHERE status=\"queue\" AND type=\"order\"\n GROUP BY user_id\n ) m ON orders.id = m.id\n SET orders.status = \"process\",\n orders.lock_id =\"somehash\"\n\n\nI found anserw:\n\nset @num := 0, @type := \"\";\n\nUPDATE orders INNER JOIN(\n\nSELECT id, user_id, created, row_number FROM (\n SELECT id, user_id, created,\n @num := if(@type = user_id, @num + 1, 1) AS row_number,\n @type := user_id AS dummy\n FROM orders\n WHERE status = \"queue\"\n ORDER BY user_id, created asc ) AS grouped_orders \nWHERE grouped_orders.row_number <= 2\n\n) m ON orders.id = m.id SET orders.status = \"process\", orders.lock_id = \"somehash\";"
] | [
"mysql",
"sql"
] |
[
"Two variables concatenated inside single quotes",
"I have went through many samples to have a variable inside quotes..But that doesnt help my case..it is strange in my case..have a look at it..\n\nVar x='http://www.xyzftp/myservice/service1.svc'\n\nVar y='/logincheck'\n\n\nNow i want to have it inside a single quoted string like \n\n'http://www.xyzftp/myservice/service1.svc/logincheck'\n\n\nUPDATE:\n\nI have a file named domainname.xml\n\nI get the value http://www.xyzftp/myservice/service1.svc from that file.Now i need to concatenate /logincheck with it and pass as an URL to an ajax call...\n\nThats my specific need guys !!\n\nAny ideas friends ???"
] | [
"javascript",
"jquery",
"html"
] |
[
"Correct placement of the stubs in Junit test class for wiremock",
"I found below code from here. All the stubs are created in @Before section.\n\n@Rule\npublic WireMockRule wireMockRule = new WireMockRule(18089);\n\nprivate HttpFetcher instance;\n\n@Before\npublic void init() {\n instance = new HttpFetcher();\n\n // all the stubs\n stubFor(get(urlEqualTo(\"/hoge.txt\")).willReturn(\n aResponse().withStatus(200).withHeader(\"Content-Type\", \"text/plain\").withBody(\"hoge\")));\n stubFor(get(urlEqualTo(\"/500.txt\")).willReturn(\n aResponse().withStatus(500).withHeader(\"Content-Type\", \"text/plain\").withBody(\"hoge\")));\n stubFor(get(urlEqualTo(\"/503.txt\")).willReturn(\n aResponse().withStatus(503).withHeader(\"Content-Type\", \"text/plain\").withBody(\"hoge\")));\n}\n\n@Test\npublic void ok() throws Exception {\n String actual = instance.fetchAsString(\"http://localhost:18089/hoge.txt\");\n String expected = \"hoge\";\n assertThat(actual, is(expected));\n}\n\n@Test(expected = HttpResponseException.class)\npublic void notFound() throws Exception {\n instance.fetchAsString(\"http://localhost:18089/NOT_FOUND\");\n}\n\n@Test(expected = HttpResponseException.class)\npublic void internalServerError() throws Exception {\n instance.fetchAsString(\"http://localhost:18089/500.txt\");\n}\n\n@Test(expected = HttpResponseException.class)\npublic void serviceUnavailable() throws Exception {\n instance.fetchAsString(\"http://localhost:18089/503.txt\");\n}\n}\n\n\nIs that the correct approach. Wouldn't it be better if we create the stub in @Test method itself (so the stubs related to that test can be identified easily)."
] | [
"java",
"junit",
"wiremock"
] |
[
"Strech To Fit Volley NetworkImageView",
"I'm using NetworkImageView to display images , the problem is the width and the height of the image is not fitting with the NetworkImageView , and the image will take it's original size and a white space will appear in the NetworkImageView . I don't wan't to change the image size as well ..\n\n <com.android.volley.toolbox.NetworkImageView\n android:layout_gravity=\"top\"\n android:id=\"@+id/thumb2\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"170dp\" />"
] | [
"android",
"image",
"android-volley",
"networkimageview"
] |
[
"I wasn't able to use the get['id'] on header[Location...]",
"Why can I use this to pass the id \n\n<a href='detail.php?id=\".$row['posts_id'].\n$sql = \"SELECT * FROM posts WHERE posts_id=\".$_GET['id'];\n\n\nBut not on this which gives me a blank id\n\nheader(\"Location: ../detail.php?id=\".$_GET['id']);"
] | [
"php",
"html",
"mysql"
] |
[
"Make Func for a generic type",
"I have this architecture.\n\npublic void Init()\n {\n PropertyInfo[] infos = typeof(Transform).GetProperties(BindingFlags.Public | BindingFlags.Instance);\n foreach (PropertyInfo info in infos)\n {\n // Save getter\n MethodInfo method = info.GetGetMethod();\n System.Type returnType = method.ReturnType;\n\n\n System.Func<Transform, Vector3> fact = GetFactory<Transform, Vector3>(method);\n\n Vector3 v = fact(this.Value);\n Debug.Log(\"Test123 \" + v);\n\n //_getters.Add(info.Name, newMethod);\n }\n }\n\n static System.Func<T, T1> GetFactory<T, T1>(MethodInfo info)\n {\n return (System.Func<T, T1>)GetFactory(typeof(T), typeof(T1), info);\n }\n\n static object GetFactory(System.Type type, System.Type type1, MethodInfo info)\n {\n System.Type funcType = typeof(System.Func<,>).MakeGenericType(type, type1);\n return System.Delegate.CreateDelegate(funcType, info);\n }\n\n\nIt even works if method.ReturnType is Vector3.\nBut I want the func<Transform, Vector3> to be func<Transform, ReturnType>.\nI have no idea doing this.\n\nDoes someone of you know how I can do this?\n\nAnd I also have no idea how to save the result in a dictionary.\nWhich type can the dictionary be of?\n\n public Dictionary<string, System.Func<object, object>> _getters = new Dictionary<string, System.Func<object, object>>();\n\n\n\n\nEdit: No ideas?"
] | [
"c#",
"reflection"
] |
[
"how to align marker to center of the image lists HTML",
"i have this code.\n\n <ul style=\"list-style-type:square\">\n <li><img src=\"Files/Images/001.png\"></li>\n <li><img src=\"Files/Images/002.png\"></li>\n <li><img src=\"Files/Images/003.png\"></li>\n </ul> \n\n\nthe marker seems to be at the align at the bottom of the image, how can align it to the center?"
] | [
"html",
"css"
] |
[
"Streaming data from Neo4j to Gephi - \"Invalid UTF-8 start byte 0xfc\"",
"I have recently started working with Neo4j and I am interested in visualizing my graph in Gephi. To do that, I am trying to use the apoc procedure \n\nCALL apoc.gephi.add(null,'workspace1', paths) yield nodes, relationships, time\nRETURN nodes, relationships, time\n\n\nSome of my nodes have accented characters such as ö or å and that seems to be giving me trouble because I obtain the following error: \n\nNeo.ClientError.Procedure.ProcedureCallFailed: Failed to invoke procedure 'apoc.gephi.add': Caused by: org.codehaus.jackson.JsonParseException: Invalid UTF-8 start byte 0xfc at [Source: apoc.export.util.CountingInputStream@599da1f9; line: 19, column: 125] \n\n\nOn Gephi I obtain some of the nodes but not all of them or the relationships. This doesn't happen when I work with a database without special characters (like the movie database).\n\nI am using \n\n\nWindows 7\nNeo4j Desktop 1.1.9\nNeo4j 3.4.1\nAPOC 3.4.0.1\nGephi 0.9.2\nSpanish locale\n\n\nThis is a similar problem to this one but it remains unsolved. Does anyone have any ideas?"
] | [
"neo4j",
"gephi",
"neo4j-apoc"
] |
[
"Firebird SQL Script command string limitation",
"Does anybody know, if there is a command string size limitation in Firebird?\n\nWhen executing a small \"insert\" script it works perfectly, but when the script has a lot of lines it returns the following errer: \"Unexpected end of command - line X, column Y\".\n\nInteressting, the line and column number varies dependanding on the actual script size.\n\nI'm using Firebird 2.5\n\nHere is the executing script:\n\nset term ^ ;\nEXECUTE BLOCK AS BEGIN\ninsert into TABLE (COLUMNA) values (13);\n...\ninsert into TABLE (COLUMNA) values (14);\nEND^\nset term ; ^"
] | [
"delphi",
"firebird"
] |
[
"multi select spinner clearAll button android",
"I'm creating multi select spinner and got problem with Clear All button\nhttp://postimg.org/image/eoyq5jpib/ but \"Select all\" work pretty good but when clicked on \"Clear all\" nothing happens. Why I'm getting problem with \"Clear All\"? \n\nprotected CharSequence[] _options = { \"One\", \"Two\", \"Three\", \"Four\", \"Five\" };\nprotected boolean[] _selections = new boolean[ _options.length ];\nprotected Button _optionsButton;\n\n public class ButtonClickHandler implements View.OnClickListener {\n public void onClick( View view ) {\n showDialog( 0 );\n }\n}\n\n@Override\nprotected Dialog onCreateDialog( int id )\n{\n return\n new AlertDialog.Builder( this )\n .setTitle( \"Students\" )\n .setMultiChoiceItems(_options, _selections, new DialogSelectionClickHandler())\n .setPositiveButton(\"OK\", new DialogButtonClickHandler())\n .setNeutralButton(\"Select All\",\n new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n selectAllStudents();\n }\n })\n .setNegativeButton(\"Clear All\",\n new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialog, int which) {\n clearAllStudents();\n }\n })\n .create();\n\n}\n\n\npublic class DialogSelectionClickHandler implements DialogInterface.OnMultiChoiceClickListener\n{\n public void onClick( DialogInterface dialog, int clicked, boolean selected )\n {\n Log.i(\"ME\", _options[clicked] + \" selected: \" + selected);\n }\n}\n\n\npublic class DialogButtonClickHandler implements DialogInterface.OnClickListener\n{\n public void onClick( DialogInterface dialog, int clicked )\n {\n checkAllStudents();\n switch( clicked )\n {\n case DialogInterface.BUTTON_POSITIVE:\n printSelectedStudents();\n break;\n case DialogInterface.BUTTON_NEUTRAL:\n printSelectedStudents();\n break;\n case DialogInterface.BUTTON_NEGATIVE:\n printSelectedStudents();\n break;\n }\n }\n}\n\nprotected void clearAllStudents(){\n for (int i = 0; i<_options.length; i++) {\n _selections[i] = false;\n }\n}\n\nprotected void selectAllStudents(){\n for (int i = 0; i<_options.length; i++) {\n _selections[i] = true;\n }\n}\nprotected void printSelectedStudents(){\n for( int i = 0; i < _options.length; i++ ){\n Log.i( \"ME\", _options[ i ] + \" selected: \" + _selections[i] );"
] | [
"android"
] |
[
"How to send websocket event asynchronously using ws-rs?",
"Using the ws-rs library, how do I send a websocket message asynchronously?\n\nIn the examples I see on_message being used to reply to a message but how would a server send a message out of the blue?\n\nFor example:\n\n\nClient sends request to start processing data\nServer responds using on_message with \"yes I am starting to process your data\"\nEvery 1% change server responds with an update\n\n\nIn my case processing takes a long time and should report data in the meantime the user is going to be playing with while data is being processed so I really want the server to report the progress data while processing.\n\nIf I do that in the on_message, it simply responds with a message at the end of processing which defeats the purpose of using websockets. See related issue on github.\n\nI am open to switching the websocket library if there is another one that is simpler to use."
] | [
"rust"
] |
[
"How to use Google map styles on a My Map",
"I am new to playing around with the Google maps API and have what should be a simple question yet I can't find a simple answer after hours of Googling. I am a fiction writer and a hypertext project I'm writing is set in a fictionalized version of Milwaukee, WI. I want to embed a styled Google map with links to a wiki based on the fictional world.\n\nSo I can create a My Places map with markers and links:\nhttp://trenthergenrader.com/calypsis/rivertown%20googlemap/mymap.html\n\nAnd I can create a styled Google map of Milwaukee:\nhttp://trenthergenrader.com/calypsis/rivertown%20googlemap/styled.html\n\nBut I don't see how to create a styled version of the My Places map. Everywhere I look for instructions on how to do this, it simply says to use the link and embed feature in Google maps but I don't how/where to add the styling when all I get is a long link within an iframe tag.\n\nThis has got to be possible, right?\n\nThanks in advance."
] | [
"google-maps",
"styles"
] |
[
"get milliseconds since 1970 from string",
"I got a string like this:\n\n\"2016-08-12 06:13:24 UTC\"\n\n\nHow can I convert this date time string to milliseconds since January 1, 1970 UTC ?"
] | [
"ruby"
] |
[
"Simple form that redirects with query string from field",
"I am brushing up on my HTML while in the process of learning django and am wanting to create a form (single field and button). The button, when pushed should redirect to a page with the value in the form as a query string. For example, if the user types in \"test\", then pushes the button, they should be redirected to \"webpage.com?test\".\n\nAm I correct in thinking the best way to do this is with javascript? If so, would anyone mind providing an example?\n\nThanks!"
] | [
"javascript",
"django",
"forms",
"redirect",
"query-string"
] |
[
"Unit-testing a functional core of value objects: how to verify contracts without mocking?",
"I wanted to give the Functional Core/Imperative Shell approach a shot, especially since Swift's structs are so easy to create.\n\nNow they drive me nuts in unit tests.\n\nHow do you unit test a net of value objects?\n\n\n\nMaybe I'm too stupid to search for the right terms, but in the end, the more unit tests I write, the more I think I should delete all the old ones. In other words my tests seem to bubble up the call chain as long as I don't provide mock objects. Which is impossible for (struct) value objects, because there's no way to replace them with a fake double unless I introduce a protocol, which doesn't work well in production code when methods return Self or have associated types.\n\nHere's a very simple example:\n\nstruct Foo {\n func obtainBar() -> Bar? { \n // ... \n }\n}\n\nstruct FooManager {\n let foos: [Foo]\n\n func obtainFirstBar() -> Bar {\n // try to get a `Bar` from every `Foo` in `foos`; pass the first\n // one which isn't nil down\n }\n}\n\n\nThis works well with a concrete Foo class or struct. Now how am I supposed to test what obtainFirstBar() does? -- I plug in one and two and zero Foo instances and see what happens.\n\nBut then I'm replicating my knowledge and assertions about Foo's obtainBar(). Well, either I move the few FooTests into FooManagerTests, which sounds stupid, or I use mocks to verify the incoming call instead of merely asserting a certain return value. But you can't subclass a struct, so you create a protocol:\n\nprotocol FooType {\n func obtainBar() -> Bar\n}\n\nstruct Foo: FooType { /* ... */ }\n\nclass TestFoo: FooType { /* do some mocking/stubbing */}\n\n\nWhen Bar is complex enough to warrant its own unit tests and it seems it should be mocked, you end up with this instead:\n\nprotocol FooType {\n typealias B: BarType\n\n func obtainBar() -> B\n}\n\n\nBut then the compiler will complain that FooManager's collection of foos doesn't work this way. Thanks, generics. \n\nstruct FooManager<F: FooType where F.B == Bar> {\n let foos: [F] // ^^^^^^^^^^^^^^^^ added for clarity \n\n func obtainFirstBar() -> Bar { /* ... */ }\n}\n\n\nYou can't pass in different kinds of Foo, though. Only one concrete FooType is allowed, no weird mixes of BlueFoo and RedFoo, even if both return the same Bar and seem to realize the FooType protocol in the same way. This isn't Objective-C and duck typing isn't possible. Protocols don't seem to add much benefit in terms of abstraction here anyway unless they're not depending on anything else which is a protocol or Self.\n\nIf protocols lead to confusion and not much benefit at all, I'd rather stop using them. But how do I write unit tests if one object is mostly a convoluted net of dependent objects, all being value types, seldomly optional, without moving all tests for every permutation in the test suite of the root object(s)?"
] | [
"swift",
"unit-testing",
"value-type",
"value-objects"
] |
[
"Form loads with the minimal size (which displays only the title bar) rather than the size corresponding to the value set to its properties",
"I have a form which contains a Menu Strip docked to the top, a Status Strip docked to the bottom, and a Panel docked to fill the entire space between the aforementioned controls. I have set the attributes to the following values for the form:\n\nDuring the design phase:\n\nAutoScaleMode: Dpi\nAutoSize: false\nAutoSizeMode: GrowOnly\nDoubleBuffered: true\nSizeGripStyle: Show\n\n\nDuring runtime (in the form's constructor):\n\n// Calculate the default size of the window on the basis of the ratio of the dimensions of the window to the dimension of the screen resolution of the machine used in development as the default dimensions of the window is aligned to that of the machine used to design it \nthis.Size = new Size(Screen.GetWorkingArea(this.Location).Size.Width * (widthOfWindowInDesignPhase /horizontalResolutionOfTheDisplayInDesignPhase), Screen.GetWorkingArea(this.Location).Size.Height * (heightOfWindowInDesignPhase / verticalResolutionOfTheDisplayInDesignPhase)); \nthis.MinimumSize = new Size(this.Size.Width, this.Size.Height);\n\n\nMy first attempt to resolve this issue was to tinker around with the AutoSize and AutoSizeMode properties, but I require this to be set to the aforestated values as changing them would not allow the user to resize the form. The other approach I tried, which also failed, was by setting the AutoSize properties of the aforementioned controls to false as to force the child containers of the form to not resize.\n\nThanks in advance.\n\nPS Screenshot of the concerned form:"
] | [
"c#",
".net",
"windows",
"winforms",
"size"
] |
[
"How to make item accessible in class method",
"I have the following model class:\n\nclass ItemInstance(models.Model):\n\n TITLE = 0\n COLLECTION = 1\n TVSERIES = 2\n\n\nThis allows me to do:\n\nitem = ItemInstance.objects.all()[0]\nitem.TITLE ==> 0\n\n\nBut not this:\n\ncls = ItemInstance\ncls.TITLE ==> error\n\n\nHow would I enable these vars to be available for a @classmethod?"
] | [
"python",
"django"
] |
[
"Shopify look for upcoming items in .json?",
"I know for a shopify website you can do:\nxxx.com/products.json\nOR\nxxx.com/collections/new-arrivals/products.json\nto see the products that are in store or the new arrivals\nBUT\nhow do I check for upcoming items that will be dropped at a certain time before the actual drop?\nthe above references will be updated on the drop, but how do I check something before the drop for upcoming items?"
] | [
"shopify"
] |
[
"moving / scrolling up and down on three JTable simultanously.",
"I have three different jtable on three diffenernt jscrollpane - one next to the other.\nI successfuly written some code that makes them all scroll together when I scroll the mouse wheel.\nI inherrited JScrollpane and overriden its processMouseWheelEvent methos as follows: \n\n public void processMouseWheelEvent(MouseWheelEvent e) {\n ...\n if (e.getSource() == this) {\n for (BTSJScrollPane other : effected) {\n other.processMouseWheelEvent(e);\n }\n }\n}\n\n\nI have canelled the pageup pagedown using \n\n final InputMap inputMap = \n comp.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);\n inputMap.put(KeyStroke.getKeyStroke(\"PAGE_DOWN\"), EMPTY);\n inputMap.put(KeyStroke.getKeyStroke(\"PAGE_UP\"), EMPTY);\n\n comp.getActionMap().put(EMPTY, emptyAction);\n\n\nBut,\nmy only problem now is that when the user clicks up and down, they dont go together but rather scroll indipently.\nAny suggestions ?\nSo far I wrote in my scrollpane something like \n\n KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {\n @Override public boolean dispatchKeyEvent(KeyEvent e) {\n if (thisIsThesourceTable) {\n if (e.getKeyCode() == 38 || e.getKeyCode() == 40) {\n\n }\n }\n return false;\n }\n });\n\n\nBut :\n1. is there a better way?\n2. maybe I should do it somehow in the actionMap?\n3. how do I pass the key up/down event to the other scrollpane?\n4. can I know if I am near the end of the viewing part in the scroll pane? is it needed"
] | [
"java",
"swing",
"listener",
"jscrollpane",
"jscrollbar"
] |
[
"Press Print Screen on keyboard with JavaScript?",
"Is there a way to click a JavaScript button and that cause your computer to click the Print Screen button on the keyboard?"
] | [
"javascript",
"keyboard"
] |
[
"How to hide the Week numbers in the CalendarView (DatePicker)",
"I am new to Android (and Java), please help me with this problem.\n\nI am trying to hide the week numbers in the CalendarView in the DatePicker, found a Boolean set to true called:\n\nmShowWeekNumber\n\n\ninside \n\nmCalendarView\n\n\nin the DatePicker, but how can I set this value to false....??\n\nAny help will be appreciated."
] | [
"java",
"android",
"android-calendar"
] |
[
"check a text file written has completed",
"My script has two part. first, it will execute a 2 java class and write the output to 2 different text file and the output per file is large (10000 lines). second, after executing this command, it will start to read both of those file simultaneously and process it.\n\n java -cp ./weka.jar weka.classifiers.functions.SMO -t /Users/mainulquraishi/Documents/sentiment_directory/2014/Books/training/representation${i}_by_${i}.arff -no-cv -T /Users/mainulquraishi/Documents/sentiment_directory/2014/Books/representations/representation2014_by_${i}.arff -v -o >>test1.txt \n\n java -cp ./weka.jar weka.classifiers.functions.SMO -t /Users/mainulquraishi/Documents/sentiment_directory/2014/Books/training/representation${i}_by_${i}.arff -no-cv -T /Users/mainulquraishi/Documents/sentiment_directory/2014/Books/representations/representation2014_by_${i}.arff -v -o >>test2.txt \n\n while read compareFile1 <&3 && read compareFile2 <&4; do\n #Here the processing goes \n done 3<test1.txt 4<test2.txt\n\n\nNow, my question is, is there any possibility that before completing the writing of the both file, the second part of the program may start(both part is in the same program file)?\n if the answer is yes, how can i signal my program that the writing of both file has completed? or any other technique is highly appreciated."
] | [
"bash",
"shell"
] |
[
"How to fix Django DetailView Missing query set exception error",
"When I try to use DetailView to view my posts I keep getting an exception error.\n\n\n ImproperlyConfigured at /post/1/\n BlogDetailView is missing a QuerySet. Define BlogDetailView.model, BlogDetailView.queryset, or override BlogDetailView.get_queryset().\n Request Method: GET\n Request URL: http://127.0.0.1:8000/post/1/\n Django Version: 2.2\n Exception Type: ImproperlyConfigured\n Exception Value:\n BlogDetailView is missing a QuerySet. Define BlogDetailView.model, BlogDetailView.queryset, or override BlogDetailView.get_queryset().\n Exception Location: C:\\Users\\julia.virtualenvs\\Documents-SYi_ANcG\\lib\\site-packages\\django\\views\\generic\\detail.py in get_queryset, line 73\n Python Executable: C:\\Users\\julia.virtualenvs\\Documents-SYi_ANcG\\Scripts\\python.exe\n Python Version: 3.7.3\n\n\nI have reviewed my code against the book Django For Beginners by Will Vicent Still I can't find any problems\n\nmodels.py\n\nfrom django.db import models\n\n# Create your models here.\n\nclass Post(models.Model):\n\n title = models.CharField(max_length=200)\n\n author = models.ForeignKey(\n\n 'auth.User',\n\n on_delete=models.CASCADE,\n\n )\n body = models.TextField()\n\n def __str__(self):\n\n return self.title\n\n\nviews.py \n\nfrom django.views.generic import ListView, DetailView # new\nfrom .models import Post\n\n# Create your views here.\n\nclass BlogListView(ListView):\n\n model = Post\n\n template_name = 'home.html'\n\nclass BlogDetailView(DetailView): # new\n\n Model = Post\n\n template_name = 'post_detail.html'\n\n\nurls.py\n\n# blog/urls.py\nfrom django.urls import path\nfrom .views import BlogListView, BlogDetailView # new\n\nurlpatterns = [\n\n path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'), # new\n\n path('', BlogListView.as_view(), name='home'),\n\n]\n\n\npost_detail.html\n\n<!-- templates/post_detail.html-->\n{% extends 'base.html' %}\n\n{% block content %}\n <div class=\"post-entry\">\n <h2>{{ post.title }}</h2>\n <p>{{ post.body }}</p>\n </div>\n\n{% endblock content %}\n\n\nThis code is supposed to allow me to see my posts when I browse to http://127.0.0.1/posts/1 or post/2"
] | [
"django",
"detailview"
] |
[
"C++ Program to connect with MySQL",
"I am new to C++ (although I have some experience with C) and MySQL and I am trying to make a program that reads a database from MySQL, I have been following this tutorial but I get an error when I try to 'build' the solution. (I am using Visual C++ 2008 just like they do in the tutorial.\n\nCompiling...\ntest2.cpp\nc:\\users\\rafael\\documents\\visual studio 2008\\projects\\test2\\test2\\test2.cpp(43) : warning C4244: 'initializing' : conversion from 'my_ulonglong' to 'unsigned int', possible loss of data\nCompiling manifest to resources...\nMicrosoft (R) Windows (R) Resource Compiler Version 6.0.5724.0\nCopyright (C) Microsoft Corporation. All rights reserved.\nLinking...\ntest2.obj : error LNK2019: unresolved external symbol _mysql_close@4 referenced in function _main\ntest2.obj : error LNK2019: unresolved external symbol _mysql_fetch_row@4 referenced in function _main\ntest2.obj : error LNK2019: unresolved external symbol _mysql_num_rows@4 referenced in function _main\ntest2.obj : error LNK2019: unresolved external symbol _mysql_store_result@4 referenced in function _main\ntest2.obj : error LNK2019: unresolved external symbol _mysql_query@8 referenced in function _main\ntest2.obj : error LNK2019: unresolved external symbol _mysql_real_connect@32 referenced in function _main\ntest2.obj : error LNK2019: unresolved external symbol _mysql_init@4 referenced in function _main\nC:\\Users\\*****\\Documents\\Visual Studio 2008\\Projects\\test2\\Debug\\test2.exe : fatal error LNK1120: 7 unresolved externals\n\n\nI followed the tutorial and I cannot figure out what's going on, I guess it's something to do with the linkers, but I do not know what could I do.\n\nThis is the code I am using (source):\n\n\n#include \"stdafx.h\"\n#include \"my_global.h\" // Include this file first to avoid problems\n#include \"mysql.h\" // MySQL Include File\n#define SERVER \"localhost\"\n#define USER \"root\"\n#define PASSWORD \"********\"\n#define DATABASE \"test\"\n\n\nint main()\n{\n MYSQL *connect; // Create a pointer to the MySQL instance\n connect=mysql_init(NULL); // Initialise the instance\n /* This If is irrelevant and you don't need to show it. I kept it in for Fault Testing.*/\n if(!connect) /* If instance didn't initialize say so and exit with fault.*/\n {\n fprintf(stderr,\"MySQL Initialization Failed\");\n return 1;\n }\n /* Now we will actually connect to the specific database.*/\n\n connect=mysql_real_connect(connect,SERVER,USER,PASSWORD,DATABASE,0,NULL,0);\n /* Following if statements are unneeded too, but it's worth it to show on your\n first app, so that if your database is empty or the query didn't return anything it\n will at least let you know that the connection to the mysql server was established. */\n\n if(connect){\n printf(\"Connection Succeeded\\n\");\n }\n else{\n printf(\"Connection Failed!\\n\");\n }\n MYSQL_RES *res_set; /* Create a pointer to recieve the return value.*/\n MYSQL_ROW row; /* Assign variable for rows. */\n mysql_query(connect,\"SELECT * FROM TABLE\");\n /* Send a query to the database. */\n unsigned int i = 0; /* Create a counter for the rows */\n\n res_set = mysql_store_result(connect); /* Receive the result and store it in res_set */\n\n unsigned int numrows = mysql_num_rows(res_set); /* Create the count to print all rows */\n\n /* This while is to print all rows and not just the first row found, */\n\n while ((row = mysql_fetch_row(res_set)) != NULL){\n printf(\"%s\\n\",row[i] != NULL ?\n row[i] : \"NULL\"); /* Print the row data */\n }\n mysql_close(connect); /* Close and shutdown */\n return 0;\n}"
] | [
"c++",
"mysql",
"sql",
"database",
"database-connection"
] |
[
"Python pandas: Iterate over several dataframes",
"I have dozens of fairly similar df to which I would like to apply the same manipulations.\n\nFor example, I would like to rename cols:\n\ndf.rename(columns={\"oldname\": \"newname\"}, inplace=True)\n\n\nThe dataframes have all the same column names. I thought of automating like this:\n\nfor one_df in list_of_df:\n command = one_df + \".rename(columns={'name': 'newname'}, inplace=True)\"\n exec(command)\n\n\nIs there a more decent, panda-ish solution?"
] | [
"python",
"pandas"
] |
[
"How to edit the expandable List CSS",
"This is the actual code, but only changes the style of the button and not the expandable list.\n\nSo, how can I edit the list style witch CSS? Also want to quit the blue frameborder...\n\nHTML:\n\n <table>\n <input class=\"select\" type=\"hidden\" value=\"COLOR DE FONDO:\" placeholder=\"COLOR DE FONDO DEL DISEÑO\">\n <tr>\n <td><select class=\"select\">\n <option value=\"\" disabled selected>Color de fondo</option>\n <option value=\"Blanco\">Blanco </option>\n <option value=\"Negro\">Negro </option>\n <option value=\"Rojo\">Rojo </option>\n <option value=\"Verde\">Verde </option>\n <option value=\"Azul\">Azul </option>\n <option value=\"Amarillo\">Amarillo </option>\n <option value=\"Naranja\">Naranja </option>\n <option value=\"Rosa\">Rosa </option>\n <option value=\"Cian\">Cian </option>\n </select></td>\n </tr>\n </table>\n\n\nCSS:\n\n.select{\nborder-radius: 30px;\noutline: none;\nbox-shadow: 0px;\nborder: 0px solid #F0F0F0;\nbackground: #f0f0f0;\nwidth: 400px;\nheight: 45px;\ndisplay: inline-block;\nresize: none;\nmargin: 8px 0;\npadding: 12px 20px;\n}\n\n\nImage of how appears"
] | [
"javascript",
"html",
"css"
] |
[
"Aggregating data in Python using more than one measure from a formula",
"Suppose I have a series of data that I want to aggregate by Cat\n\nCat Volume Result\n\nA 45 4\nA 57 3\nB 56 3\nC 45 1\nC 55 2\n\n\nI would like to aggregate variance, Skewness and Kurtosis of volume and maximum of Result by cat. I know how to do it one by one by calculating the variance, skewness and Kurtosis of volume but I would like to it neatly with something like this\n\ndef f(row):\n row['ResultM']=row['Result'].max()\n row['Variance'] = pd.DataFrame(scipy.stats.moment(row['Volume'], moment=[2,3,4]))\nreturn \n\nTestData=OrgData.groupby('Id').apply(f)\n\n\nBut it does not work . Can anyone offer suggestions how I can correct my code? Thanks"
] | [
"python",
"aggregation"
] |
[
"PHP, MYSQL, AJAX - filter multiple select's",
"There are tons of questions about this, but none of them really deal with Select Options.\n\nMy question: I have 4 selects all with multiple values pulled from the database. I want to database information to display, and as the user selects each item it only shows what the user has selected.\n\nFor example: Box 1 - A (Show all A) box 2 - year (Show all A with year, if none then display \"Nothing matches your search\" box 3 ect...\n\nMy Code: \n\nif(isset($_POST[\"action\"]))\n{\n $query = \"\n SELECT * FROM DB\";\n\n if(isset($_POST[\"producer\"]))\n {\n $producer_filter = implode(\"','\", $_POST[\"producer\"]);\n $query .= \"\n WHERE producer=('\".$producer_filter.\"')\n \";\n }\n if(isset($_POST[\"size\"]))\n {\n $size_filter = implode(\"','\", $_POST[\"size\"]);\n $query .= \" OR size=('\".$size_filter.\"')\n \";\n }\n if(isset($_POST[\"model\"]))\n {\n $model_filter = implode(\"','\", $_POST[\"model\"]);\n $query .= \"OR model=('\".$model_filter.\"')\";\n }\n if(isset($_POST[\"year\"]))\n {\n $year_filter = implode(\"','\", $_POST[\"year\"]);\n $query .= \"OR year=('\".$year_filter.\"')\";\n }\n\n $statement = $conn->prepare($query);\n $statement->execute();\n $result = $statement->fetchAll();\n $total_row = $statement->rowCount();\n $output = '';\n if($total_row > 0)\n {\n foreach($result as $row)\n {\n $output .= '\n <tr><td>'.$row['producer'].'</td>\n <td>'.$row['size'].'</td>\n <td>'.$row['model'].'</td>\n <td>'.$row['year'].'</td>\n <td>'.$row['salesman'].'</td>\n <td>'.$row['country'].'</td></tr>\n\n ';\n }\n }\n else\n {\n $output = 'Please User Filters to Search for Parts';\n }\n echo $output;\n}\n\n\nAnd then my Jquery:\n\n$(document).ready(function() {\n\n filter_data();\n\n\n function filter_data() {\n\n const action = 'fetch_data';\n let producer = get_filter('producer');\n let size = get_filter('size')\n let model = get_filter('model')\n let year = get_filter('year')\n\n $.ajax({\n url: \"search.php\",\n method: \"POST\",\n data: {\n action: action,\n producer: producer,\n size: size,\n model: model,\n year: year\n },\n\n success: function(data) {\n $('.prod').html(data);\n },\n });\n }\n\n function get_filter(class_name) {\n var filter = [];\n $('.' + class_name).each(function() {\n filterData = $(this).val();\n filter.push(filterData)\n\n });\n console.log(filter)\n return filter;\n }\n\n $('.form-control').change(function() {\n filter_data();\n });\n\n });\n\n\nThis works, however, it displays everything regardless if it matches my filters or not. Is there something I can add in the Jquery?\n\nI appreciate all the help."
] | [
"php",
"jquery"
] |
[
"WooCommerce save customer earlier during the checkout",
"Good evening.\n\nWe have split up the checkout in the following steps:\n\n\nLogin / register\nCustomer information (checkout form)\nPayment\nThank you page\n\n\nWe want to store the customer details / register the user after step 2, so that abandoned cart can pick up the information even before the client starts entering the payment info. Based on the customers billing country we want to show one of two options for step 3, strip or Klarna Checkout. If possible without refreshing the page.\n\nSo the question is, how can we register the user using jQuery Ajax (on click of the proceed to step 3 button)?\n\nCan anyone point me in the right direction?"
] | [
"jquery",
"ajax",
"woocommerce"
] |
[
"ElasticSearch hits have no fields",
"I am having a problem where when I run a search on elastic using the java api I get back results... but when I try and extract values from the results there are no fields.\n\nElasticSearch v5.3.1\n\nElastic API: org.elasticsearch.client:transport v5.3.0\n\nMy code:\n\nSearchRequestBuilder srb = client.prepareSearch(\"documents\").setTypes(\"documents\").setSearchType(SearchType.QUERY_THEN_FETCH).setQuery(qb).setFrom(0).setSize((10)).setExplain(false);\n\nsrb.addDocValueField(\"title.raw\");\nSearchResponse response = srb.get();\n\nresponse.getHits().forEach(new Consumer<SearchHit>() {\n\n @Override\n public void accept(SearchHit hit) {\n System.out.println(hit);\n Map<String, SearchHitField> fields = hit.getFields();\n\n Object obj = fields.get(\"title.raw\").getValue();\n\n }\n\n });\n\n\nWhen the forEach runs the obj is always coming back null. Fields has an item in it with the key of title.raw and it has a SearchHitField."
] | [
"java",
"elasticsearch"
] |
[
"Displaying white screen when opening React-Native from existing native android App",
"In Android, integrating react native to an existing app. Basically, my android app was originally developed in Java. From the java side, I click on the button to go to another screen that is using React Native.\n\nThen, there is a problem, every time I click the button that opens the App.js (which contains stack navigation), it takes 2 or 3 seconds in a white screen (loading the bundle). so how to avoid this white screen?\n\nUpdated Code\n\nconst Navigation = StackNavigator({\nhome:{\n screen: HomeScreen,\n}\n})\nclass MyApp extends Component {\nrender() {\n return (\n <Navigation/>\n );\n }\n}\n\nexport default MyApp;\nAppRegistry.registerComponent('MyApp', () => Navigation);"
] | [
"reactjs",
"react-native",
"screen",
"native"
] |
[
"How to transpose dataset more simply",
"I'd like to make the dataset like the below. I got it, but it’s a long program.\nI think it would become more simple. If you have a good idea, please give me some advice.\n\nThis is the data.\ndata test;\ninput ID $ NO DAT1 $ TIM1 $ DAT2 $ TIM2 $;\ncards;\n1 1 2020/8/4 8:30 2020/8/5 8:30\n1 2 2020/8/18 8:30 2020/8/19 8:30\n1 3 2020/9/1 8:30 2020/9/2 8:30\n1 4 2020/9/15 8:30 2020/9/16 8:30\n2 1 2020/8/4 8:34 2020/8/5 8:34\n2 2 2020/8/18 8:34 2020/8/19 8:34\n2 3 2020/9/1 8:34 2020/9/2 8:34\n2 4 2020/9/15 8:34 2020/9/16 8:34\n3 1 2020/8/4 8:46 2020/8/5 8:46\n3 2 2020/8/18 8:46 2020/8/19 8:46\n3 3 2020/9/1 8:46 2020/9/2 8:46\n3 4 2020/9/15 8:46 2020/9/16 8:46\n;\nrun;\n\nThis is my program.\n data\n t1(keep = ID A1 A2 A3 A4)\n t2(keep = ID B1 B2 B3 B4)\n t3(keep = ID C1 C2 C3 C4)\n t4(keep = ID D1 D2 D3 D4);\n set test;\n if NO = 1 then do;\n A1 = DAT1;\n A2 = TIM1;\n A3 = DAT2;\n A4 = TIM2;\n end;\n *--- cut (NO = 2, 3, 4 are same as NO = 1)--- ;\n end;\n if NO = 1 then output t1;\n if NO = 2 then output t2;\n if NO = 3 then output t3;\n if NO = 4 then output t4;\nrun;\n\nproc sort data = t1;by ID; run;\nproc sort data = t2;by ID; run;\nproc sort data = t3;by ID; run;\nproc sort data = t4;by ID; run;\ndata test2;\n merge t1 t2 t3 t4;\n by ID;\nrun;"
] | [
"sas",
"dataset",
"transpose"
] |
[
"Sending Multipart Email in vbscript",
"I wrote a script that sends HTML emails. It worked well in Gmail, but I opened it in Outlook, it was all Chinese.\n\nI learned about MIME emails - Sending 2 versions of the email, one with HTML and one plain text, but didn't understand how to create one. I saw somewhere that you need a certificate with a private key.\n\nCan someone explain how to make it work?\n\nThis is my email-sending code:\n\n'Send an email\nstrSMTPFrom = \"[email protected]\"\nstrSMTPTo = email 'Email taken from array\nstrSMTPRelay = \"smtp1.hp.com\" \nstrTextBody = strContent 'Content taken from the template\n\nSet oMessage = CreateObject(\"CDO.Message\")\noMessage.Configuration.Fields.Item(\"http://schemas.microsoft.com/cdo/configuration/sendusing\") = 2 \noMessage.Configuration.Fields.Item(\"http://schemas.microsoft.com/cdo/configuration/smtpserver\") = strSMTPRelay\noMessage.Configuration.Fields.Item(\"http://schemas.microsoft.com/cdo/configuration/smtpserverport\") = 25 \noMessage.Configuration.Fields.Update\n\noMessage.Subject = strSubject\noMessage.From = strSMTPFrom\noMessage.To = strSMTPTo\noMessage.HTMLBody = strTextBody\noMessage.Send"
] | [
"email",
"vbscript",
"mime",
"multipart"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.