texts
sequence | tags
sequence |
---|---|
[
"Redshift COPY failing to read tar.gz from S3. Error code 1216. Missing newline: Unexpected character 0x2f found at location 1",
"tar --list\n\nWhen I list the contents of the tar.gz file I get the following:\n\n$ tar --list --verbose --file /tmp/tmp.tar.gz | head -5\ndrwxrwxr-x user/user 0 2015-07-22 19:51 ./\n-rw-rw-r-- user/user 113376 2015-07-13 06:29 ./NASDAQ_20140324.txt\n-rw-rw-r-- user/user 116101 2015-07-13 06:29 ./NASDAQ_20140602.txt\n-rw-rw-r-- user/user 120710 2015-07-13 06:30 ./NASDAQ_20140822.txt\n-rw-rw-r-- user/user 123969 2015-07-13 06:31 ./NASDAQ_20141104.txt\n\n\n\n\nzcat\n\nWhen I zcat the file I get:\n\n$ zcat /tmp/tmp.tar.gz | head -5\n./0000775000175000017500000000000012553663674010514 5ustar useruser./NASDAQ_20140324.txt0000664000175000017500000033534012550547030013173 0ustar useruserAAIT,D,20140324,31.1,31.29,30.97,31.11,14600\nAAL,D,20140324,36.25,36.86,36.03,36.8,6514500\nAAME,D,20140324,3.71,3.75,3.71,3.73,5900\nAAOI,D,20140324,25.76,26.15,24.84,25.81,213300\nAAON,D,20140324,19.2267,19.2933,18.8667,19.1667,149700\n\n\n\n\nstl_load_errors\n\nThe issue from stl_load_errors (listing pertinent columns only) for the <files> found in the s3://<bucket>/<key> are:\n\nfilename => <file>.tar.gz\nline_number => 1\ncolname => (empty)\ntype => (empty)\ncol_length => (empty)\nposition => 0\nraw_line => ./\nraw_field_value => (empty)\nerr_code => 1216\nerr_reason => Missing newline: Unexpected character 0x2f found at location 1\n\n\nBreaking this down further:\n\n\nerror_code of 1216 is Invalid input line.\nerror_reason has 0x2f which is the forward slash UTF-8 character\n\n\n\n Note: On line_number = 1, at the position of 0, the\n raw_line has ./, which apart from the period (.) is the forward\n slash character mentioned in the error_reason\n\n\nThis seems to be consistent with what the zcat output provides, which has a malformed first line. Whether this is a red herring or not, I do not know.\n\n\n\nBut wait, there's more...\n\n\n The text files originally come zipped, so I convert the zip archive\n files into tar.gz archive files in this manner ...\n\n\n\nzip files are unziped into a temp dir\ntext files in the temp dir are transformed\n2.1. sed removes a header line from the file and pipes into ...\n2.2. awk prepends a column to the output and saves to a temp text file\n2.3. mv just renames the temp file to the original file name within the temp working directory\ntar.gz file is create from the transformed temp files\n\n\n1.\n\nunzip -q \"${in_archive_file_path}\" -d \"${tmp_working_dir}\"\n\n\n2.\n\nfor in_file_path in `find \"${tmp_working_dir}\" -type f -iname \"*_????????.txt\" | sort -n`;\ndo \n sed -e \"1{/^${quote_header_mask}/d;}\" \"${in_file_path}\" |\n awk -v in_var=\"${exchange}\" '{print in_var,$0}' OFS=, > \"${tmp_working_dir}/tmp.txt\"\n mv -f \"${tmp_working_dir}/tmp.txt\" \"${in_file_path}\"\ndone\n\n\nand quote_header_mask=\"<ticker>,<date>,<open>,<high>,<low>,<close>,<vol>\"\n\n3.\n\ntar c -C \"${tmp_working_dir}/\" . | pigz --best -p4 > \"${working_dir}/tmp.tar.gz\"\nmv -f \"${working_dir}/tmp.tar.gz\" \"${out_file_path}\"\n\n\nworking_dir is the parent to tmp_working_dir\n\n\n\nCOPY\n\ncopy source.quote_daily\n(\n exchange_code\n ,ticker_code \n ,date_key_local\n ,price_open \n ,price_high \n ,price_low \n ,price_close \n ,volume\n)\nfrom 's3://<bucket>/<key>' \ncredentials 'aws_access_key_id=<key value>;aws_secret_access_key=<secret key value>' \ndelimiter ','\ngzip\ntrimblanks\ncompupdate off\nstatupdate off\n; \n\n\n\n\nQuestion(s)\n\n\nIs zcat pointing me in the right direction with respect to what Redshift will \"see\" when decompressing the archive ... ?\n... which might mean my tar.gz creation script is screwing things up?"
] | [
"bash",
"awk",
"sed",
"amazon-redshift"
] |
[
"JPA Hibernate Split data between two tables",
"I have a REST API that will receive some customer data on the following format:\n\n{\n \"customer_Id\": 50,\n \"name\": \"name\",\n \"company_name\": \"company_name\",\n \"email\": \"[email protected]\",\n \"business_phone\": \"(00) 1111-2222\",\n \"mobile_phone\": \"(00) 1111-2222\",\n \"document\": \"123456789\",\n \"state_registration_number\": \"ISENTO\",\n \"state_registration_type\": \"NO_CONTRIBUTOR\",\n \"city_registration_number\": \"ISENTO\",\n \"classification\": \"AUTO\",\n \"address\": {\n \"street\": \"STREET NAME XXX\",\n \"number\": \"NUMBER XX\",\n \"complement\": \"COMPLEMENT\",\n \"zip_code\": \"ZIP_CODE\",\n \"neighborhood\": \"NEIGHBORHOOD\",\n \"city\": \"CITY\",\n \"state\": \"STATE\"\n }\n}\n\n\nI'd like to save this data on two tables: One table should contains the \"main\" customer data, and the other one should contais the customer's \"address\" data.\n\nSo, I defined the Customer entity as below:\n\n@Data\n@Entity(name = \"X_CUSTOMERS\")\npublic class Customer {\n\n @Id\n private int customer_Id;\n\n @NotNull\n private String name;\n\n private String company_name;\n\n private String email;\n\n private String business_phone;\n\n private String mobile_phone;\n\n @NotNull\n private String document;\n\n private String state_registration_number;\n\n private String state_registration_type;\n\n private String city_registration_number;\n\n @NotNull\n private String classification;\n\n @OneToOne(cascade = CascadeType.ALL)\n private Address address;\n\n}\n\n\nAnd the Address entity as\n\n@Data\n@Entity(name = \"X_ADDRESS\")\npublic class Address {\n\n @NotNull\n private String street;\n\n private String number;\n\n private String complement;\n\n private String zip_code;\n\n private String neighborhood;\n\n private String city;\n\n private String state;\n\n}\n\n\nBut, I couldn't realize how to create a relationship between them. Should I create a customer_id attribute on the Address entity? Should I define some additional Tags on Customer's address attribute? Note that I don't have a customer on the JSON data that is posted by the REST Client and, if a Customer is Update ou Deleted, the Address data should be Updated / Deleted also.\n\nSorry if this is a such trivial question. I'm learning the basics of JPA/Hibernate these days and your answer will guides me to the right direction to avoid things such 'reinventing the wheel'.\n\nThanks a lot!"
] | [
"spring",
"hibernate",
"spring-boot",
"jpa"
] |
[
"Is there a way to pass parameters through an update query to a select query in Microsoft Access VBA using the execute command?",
"I'm trying to use the Execute command in Access VBA code to run a saved update query (that changes some information in a select query) but I keep getting: \"Runtime Error 3061 - Too few parameters, expected 3\".\n\nThe update query has no criteria but the select query that it is editing does have a few criteria that are based on some TempVars.\nHere is the first criteria the select query uses:\n\nLike IIf([TempVars]![VarAccessLevel] Between 3 And 4,\"*\",[TempVars]![VarLoginID])\n\nThe second criteria used is:\n[TempVars]![VarClassBlockChosen]\n\nI'm assuming the TempVars are the 3 parameters it is looking for, but I have no clue how to go about providing them.\n\nHere is the VBA code I have written.\n\nCurrentDb.Execute \"qupdMarkAllAsPresent\", dbFailOnError\n\nNotably, I started out with Do.Cmd OpenQuery \"qupdMarkAllAsPresent\" and it worked fine but after I attempted to switch to the Execute command (to prevent warning messages) it began asking for parameters."
] | [
"ms-access",
"vba"
] |
[
"Storing Data With Same Primary Key Dynamodb",
"I am trying to store data in a way such as:\n\nTheir are 100 different types of fruits each fruit has a primary key of type \"Fruit\" so that when I query for \"Fruit\" all of the fruits are returned.\n\nHowever, Dynamodb requires primary keys to be Unique.\n\nSo I am wondering how I would design my database scheme in order to achieve these results or is there another solution I should use in AWS?"
] | [
"database",
"amazon-web-services",
"amazon-dynamodb"
] |
[
"(GNU) Make: How does one set up a basic system?",
"I would like to try to establish a very small system of Makefiles. I have the following set up, but something is not quite right (this has been pieced together from reading a few SO posts about the topic, though somewhat project-specific, and some websites. I must not be catching something fundamental in having a \"Makefile\" call sub-makefiles.\n\nThis is even simpler than having the main Makefile call files in different subdirectories. Here are the following files I have prepared:\n\nMakefile:\n\nall:\n $(MAKE) -f ./make_system.mk\n $(MAKE) -f ./make_crc.mk\n\n\nmake_system.mk:\n\nG = -g ## debug option\nCC = gcc ## compiler\nSRCS = source.c sink.c gateway.c\nEXES = source sink gateway\nOBJS = source.o sink.o gateway.o\nCFLG = \nLFLG =\nLIB = #-lsocket -lnsl -lpthread\n\nall: $(EXES)\n\n%.o: %.c %.h\n $(CC) -c $G $(CFLG) $<\n\nsource: source.o\n $(CC) -o source source.o $(LIB) $(LFLG)\n\nsink: sink.o\n $(CC) -o sink sink.o $(LIB) $(LFLG)\n\ngateway: gateway.o\n $(CC) -o gateway gateway.o $(LIB) $(LFLG)\n\nclean:\n /bin/rm -f core *.o $(EXES) *~\n\n\nmake_crc.mk:\n\n\nCC = gcc\nCFLAGS = -g\nLFLAGS =\nHDR = crcmode.h\nSRC = crcmodel.c crctest.c\nOBJ = crcmodel.o crctest.o\nEXE = crctest\n\nall: $(EXE)\n\n%.o: %.c %.h\n $(CC) -c $(CLFAGS) $<\n\n$(EXE): $(OBJ)\n $(CC) $(LFLAGS) $(OBJ) -o $(EXE)\n\nclean:\n /bin/rm -f *.o *~ core $(EXE)\n\n\nHow would I set up Makefile to call the smaller sub-makefiles (of type *.mk)? This is a basic but important first step towards working with larger scale makefile systems (there is the manual to consult, though I do not think it has explicit basic examples). If someone who has done this could show me a small Makefile vignette, this would be greatly appreciated (again, this makefile system can exist within the same local directory).\n\nNote: The individual makefiles \"make_system\" and \"make_crc\" work fine when they are themselves named \"Makefile\", but I want to try to call them as separate sub-makefiles with one single overall Makefile.\n\nADDENDUM (to solution below):\nOnce I implemented Carl's solution shown below, I realized that you need to always include some form of \"make clean\" or at least enter at in the command line before calling your Makefile. Otherwise, you see the appropriate output \"nothing to be done\". This was something I knew before, but neglected to do this time around (easy check: just look at your directory and you will see you have executables in the environment/directory)."
] | [
"build",
"makefile",
"gnu-make"
] |
[
"How do I return JSON in a DooPHP Controller?",
"I'm setting up an AJAX system and I have a controller that I need to return JSON data. In the examples so far, all of the controllers end with a call to the view:\n\n $this->renderc( 'interest', $data );\n\n\nI'd like to return straight JSON for use with jQuery, but the code below is not quite working right:\n\nreturn json_encode($data);\n\n\nbecause the return comes through as the header, not the content in Firebug. Heeeelp!"
] | [
"php",
"jquery",
"ajax",
"doophp"
] |
[
"Difference between setTranslationY() and translationYBy()?",
"I am trying to achieve the following functionality :-\nWhen Someone taps on my image view it should show the image appearing with an animation i.e. entering from screen top. To get this I am following the following approach\n\n\nTranslate the image view out of view\nAttach the image to view\nTranslate it back with animation\n\n\nI have two set of codes where animating the view out of screen does not work but just calling setTranslationY() on view works\nRefer to code segment attached\n\nimageView.setTranslationY(-2000);\nimageView.setImageResource(R.drawable.red);\nimageView.animate().translationYBy(2000).setDuration(300);\n\n\nThis works but following doesn't.\n\nimageView.animate().translationYBy(-2000);\nimageView.setImageResource(R.drawable.red);\nimageView.animate().translationYBy(2000).setDuration(300);\n\n\nCan you please explain about the behaviour and maybe difference between setTranslateY() vs translationYby()."
] | [
"android",
"animation",
"android-animation"
] |
[
"Only one product available for In App Purchase - why?",
"Cheers,\n\nI am currently developing my first app featuring In App Purchases. Everything is set up and working (in sandbox mode, app has not yet been submitted), except for one issue:\n\nOf the three products I created, only one will be retrieved by the SKProductsRequest. I double and triple-checked the IDs, everything seems to be fine. The one product which could be retrieved is the first one I created, in case that matters. I was able to purchase it without any problems.\n\nWhat could be the trouble with the other two?\n\nThanks!!\n\nEdit:\nI forgot to mention - i checked the invalidProductIdentifiers array that comes with the response, and it contains the missing products. Seems like something is wrong with the way I set the products up, although I couldn't imagine what that would be. The products are almost identical and the IDs are only slightly different... I'm clueless..\n\nEdit2:\nAfter I added a few more products for testing purposes, some (not all) of them where actually available for purchase. Although further testing is necessary, it appears like only those products are available which are cheaper than the original one (or are below some magical limit..). Can you guys make anything out of this?\n\nEdit3:\nAfter quite some time and even more testing, still no success. I am pretty sure now that this is connected to the product price. Products below a certain pricing do appear, while those above that price don't. I haven't bothered finding the exact price tier demarking the border, but the scheme is quite obvious anyway. The question that remains is - why?? Why should a price tier that I may freely select be inappropriate for sale? And we're still talking about the sandbox here, so the products didn't even go through review (thus no opportunity to get rejected). I'm puzzled. Any help greatly appreciated.\n\nUpdate:\n\nIssue resolved. See update to my own answer."
] | [
"ios",
"app-store",
"in-app-purchase"
] |
[
"How to install Ruby on Red hat",
"I'm trying to install ruby on Red Hat, via an ssh-connection, but it won't work.\n\nI can't use yum install ruby, because I don't have the needed repositories."
] | [
"ruby",
"linux",
"rhel"
] |
[
"Restarting a persisted workflow using a self-hosted WorkflowServiceHost",
"I'm trying to work out how to resume a persisted workflow that I'm self-hosting with a WorkflowServiceHost. Currently my host wires up persistence and idling behaviour like so:\n\n // Persistence\n var connStr = @\"\";\n var behavior = new SqlWorkflowInstanceStoreBehavior(connStr);\n behavior.InstanceCompletionAction = InstanceCompletionAction.DeleteNothing;\n behavior.InstanceLockedExceptionAction = InstanceLockedExceptionAction.AggressiveRetry;\n behavior.InstanceEncodingOption = InstanceEncodingOption.None;\n host.Description.Behaviors.Add(behavior);\n\n // Idle behaviour\n var idleBehavior = new WorkflowIdleBehavior();\n idleBehavior.TimeToPersist = TimeSpan.FromMinutes(2);\n idleBehavior.TimeToUnload = TimeSpan.FromMinutes(2);\n host.Description.Behaviors.Add(behavior);\n\n\nI am storing the workflow instance GUID against a ProductID in my database inside a custom activity contained in the workflow, so I am able to easily trace a specific workflow instance to a product ID. I want to be able to somehow pass this Product ID to my ServiceHost and have it resume the correct persisted workflow for me.\n\nCan anyone point me in the right direction on how to do this?\n\nMany thanks in advance\nIan"
] | [
"wcf",
"workflow",
"workflow-foundation-4",
"workflowservice"
] |
[
"Limit For each output AFTER if statement",
"Good morning,\n\nI try to get a top-10 of countries, but want to exclude a few countries from the output. I realize the following code is filtering the 10 results, so when one of the countries is in it will be filtered. the result is only a top 6 for example. But I need a top-10. Can anybody tell me how to limit the For Each statement to 10 without taking the 4 countries into account?\n\nThank you very much!\n\n<table class=\"table\" >\n <thead>\n <tr>\n <th><?=l('Top 10 landen')?></th>\n <th><?=l('Bezoek')?></th>\n </tr>\n </thead>\n <tbody>\n <?php foreach(array_slice($countries, 0, 10) as $country => $cdata)\n if($country != 'United States' && $country != 'Canada' && $country != 'China' && $country != 'Mexico') {\n ?>\n <tr>\n <td><?=$country?></td>\n <td><?=$cdata['views']?></td>\n </tr> \n <?php } ?>\n </tbody>\n</table>"
] | [
"php"
] |
[
"I can't make my player move forward and backward! What is the problem?",
"I have been trying to create a video game but I stuck in this tutorial, in the tutorial it shows us to use input actions addon (What that does is it makes W-A-S-D or joystick type of keys easy to use) but even I watched the video after 3rd time I couldn't find the mistake! the problem is that I am not able to move my player forward or backward, I can only move it right and left. Please help I have tried so many things, like restarting the program or changing some code but it's not working can you help me to fix it?\nHere is the first code to take the WASD commands from the addon script:\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class InputManager : MonoBehaviour\n{\n //Takes the wasd controls from addon\n InputWASD playerControls;\n\n public Vector2 movementInput;\n public float verticalInput;\n public float horizontalInput;\n\n private void OnEnable()\n {\n if (playerControls == null)\n {\n playerControls = new InputWASD();\n\n playerControls.PlayerMovement.Movement.performed += i => movementInput = i.ReadValue<Vector2>();\n }\n\n playerControls.Enable();\n }\n private void OnDisable()\n {\n playerControls.Disable();\n }\n\n public void HandleAllInputs()\n {\n HandleMovementInput();\n //TODO: HandleJumpInput\n // HandleAttackInput\n // HandleDashInput\n // HandleAbilityInput\n }\n\n private void HandleMovementInput()\n {\n verticalInput = movementInput.y;\n horizontalInput = movementInput.x;\n }\n}\n\nHere is the second code to use keys in movement:\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class PlayerAct : MonoBehaviour\n{\nInputManager inputManager;\nVector3 moveDirection;\nTransform cameraObject;\nRigidbody playersRB;\n\npublic float moveSpeed = 6f;\npublic float rotationSpeed = 15f;\n\nprivate void Awake()\n{\n inputManager = GetComponent<InputManager>();\n playersRB = GetComponent<Rigidbody>();\n cameraObject = Camera.main.transform;\n}\n\npublic void HandleAllAction()\n{\n HandleMovement();\n HandleRotation();\n}\n\nprivate void HandleMovement()\n{\n moveDirection = cameraObject.forward * inputManager.verticalInput;\n moveDirection = moveDirection + cameraObject.right * inputManager.horizontalInput;\n moveDirection.Normalize();\n moveDirection.y = 0;\n moveDirection = moveDirection * moveSpeed;\n\n Vector2 movementVelocity = moveDirection;\n playersRB.velocity = movementVelocity;\n}\n\nprivate void HandleRotation()\n{\n Vector3 targetDirection = Vector3.zero;\n\n targetDirection = cameraObject.forward * inputManager.verticalInput;\n targetDirection = targetDirection + cameraObject.right * inputManager.horizontalInput;\n targetDirection.Normalize();\n targetDirection.y = 0;\n\n if (targetDirection == Vector3.zero)\n {\n targetDirection = transform.forward;\n }\n\n Quaternion targetRotation = Quaternion.LookRotation(targetDirection);\n Quaternion playerRotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);\n\n transform.rotation = playerRotation;\n}\n}\n\nHere is the third and last code to use first 2 codes:\nusing System.Collections;\nusing System.Collections.Generic;\nusing UnityEngine;\n\npublic class PlayerMain : MonoBehaviour\n{\n //Calling scripts\n InputManager inputManager;\n PlayerAct playerAct;\n\n private void Awake()\n {\n inputManager = GetComponent<InputManager>();\n playerAct = GetComponent<PlayerAct>();\n }\n private void Update()\n {\n inputManager.HandleAllInputs();\n }\n private void FixedUpdate()\n {\n playerAct.HandleAllAction();\n }\n}\n\nI did what the man told me (in the tutorial) but mine is not working!"
] | [
"c#",
"unity3d"
] |
[
"CSS styles for text links also affecting image links",
"I've been working on this one for about an hour now, and I'm about ready to pull my hair out. What seems like it should be a simple one or two lines of CSS apparently isn't. I have a Posterous blog with a custom theme I designed for a client, viewable here: http://phar-ma.com/\n\nI obviously use CSS to style the text links in the posts. My problem is, the same styles are also being applied to images that have a larger version to view, since Posterous automatically turns them into links to the larger versions (the smaller images aren't turned into links). So basically I need to figure out how the return the styling of the link images to the same as the non-link images. Right now they have weird spacing and borders around them (because of the styles for the text links) and those change when you hover over them. They're also not centered correctly. I've tried just about every piece of CSS code I know, and I've had absolutely no luck. I also searched on Google and found this: http://perishablepress.com/press/2008/10/14/css-remove-link-underlines-borders-linked-images/ but still no luck with that either.\n\nSo, if anyone has any ideas, I'd appreciate it. Thanks!"
] | [
"html",
"css"
] |
[
"Upload image use intervention package laravel 5.2",
"I select 3 images to upload. Once image crop with 3 size [1903 x 793, 960 x 600, 446 x 446]. But image upload success not full 9 images.\n\nPlease help me!\n\nMy code:\n\njQuery:\n\n$(\"#inputImage\").change(function () {\n var files = this.files,\n formData = new FormData();\n if (!files.length) {\n return;\n }\n formData.append('_token', $('input[name=_token]').val());\n formData.append('category', 'category');\n for (var i = 0; i < files.length; i++) {\n formData.append('images[]', files[i]);\n }\n console.log(formData);\n $.ajax({\n type: 'POST',\n url: '{{ route('images.upload') }}',\n cache: false,\n contentType: false,\n processData: false,\n data: formData,\n success: function (result) {\n console.log(result)\n }\n });\n });\n\n\nUploadController:\n\n public $sizeCrop = array(array('width' => '1903', 'height' => '793'), array('width' => ' 960', 'height' => '600'), array('width' => '446', 'height' => '446'));\n\npublic function upload(Request $request)\n{\n $files = $request->file('images');\n $category = $request->get('category');\n\n $destinationPath = storage_path('app/public/images/' . ((isset($category)) ? $category : ''));\n if (!is_dir($destinationPath)) {\n Storage::disk('public')->makeDirectory('images/' . ((isset($category)) ? $category : ''));\n }\n\n foreach ($files as $file) {\n $img = Image::make($file->getRealPath());\n\n foreach($this->sizeCrop as $key => $size) {\n $filename = (time() + $key) . '_' . $size['width'] . '_' . $size['height'] . '.' . $file->getClientOriginalExtension();\n $img->crop($size['width'], $size['height'])->save($destinationPath . '/' . $filename);\n }\n }\n}"
] | [
"php",
"laravel-5.2",
"intervention"
] |
[
"Mapping Domain with String ID",
"I'm trying to map a domain with a table that is part of a legacy database that doesn't have an id column so I've opted for using a String id with one of the existing columns however I'm getting this error message when I try to create a new instance.\n\norg.codehaus.groovy.grails.web.servlet.mvc.exceptions.CannotRedirectException\nCannot redirect for object [PlanType : (unsaved)] it is not a domain or has no identifier. Use an explicit redirect instead\n\nHere is the domain:\n\nclass PlanType {\n\nstatic hasMany = [template:Template]\n\nString id\nString name\nString description\nString emailId\nString initialPhase\nString productType\n\nstatic mapping = {\n\nversion false\ntable 'PLAN_TYPES'\n\nid generator:'assigned', name:'name', type: 'string'\n\nname column: 'PLAN_TYPE' \nemailId column: 'EMAIL_ID'\ninitialPhase column: 'INITAL_PHASE'\nproductType column: 'PRODUCT_TYPE'\n\n}\n\nstatic constraints = {\n id (bindable:true)\n description (maxSize:100, blank:true, nullable:true)\n emailId (maxSize:50, blank:true, nullable:true)\n initialPhase (maxSize:250, blank:true, nullable:true)\n productType (maxSize:20, blank:true, nullable:true)\n} \n}\n\n\nHere is the controller\n\nimport static org.springframework.http.HttpStatus.*\nimport grails.transaction.Transactional\n\n@Transactional(readOnly = true)\nclass PlanTypeController {\n\nstatic allowedMethods = [save: \"POST\", update: \"PUT\", delete: \"DELETE\"]\n\ndef index(Integer max) {\n params.max = Math.min(max ?: 10, 100)\n respond PlanType.list(params), model:[planTypeInstanceCount: PlanType.count()]\n}\n\ndef show(PlanType planTypeInstance) {\n respond planTypeInstance\n}\n\ndef create() {\n respond new PlanType(params)\n}\n\n@Transactional\ndef save(PlanType planTypeInstance) {\n if (planTypeInstance == null) {\n notFound()\n return\n }\n\n if (planTypeInstance.hasErrors()) {\n respond planTypeInstance.errors, view:'create'\n return\n }\n\n planTypeInstance.save flush:true\n\n request.withFormat {\n form multipartForm {\n flash.message = message(code: 'default.created.message', args: [message(code: 'planTypeInstance.label', default: 'PlanType'), planTypeInstance.id])\n redirect planTypeInstance\n }\n '*' { respond planTypeInstance, [status: CREATED] }\n }\n}\n\ndef edit(PlanType planTypeInstance) {\n respond planTypeInstance\n}\n\n@Transactional\ndef update(PlanType planTypeInstance) {\n if (planTypeInstance == null) {\n notFound()\n return\n }\n\n if (planTypeInstance.hasErrors()) {\n respond planTypeInstance.errors, view:'edit'\n return\n }\n\n planTypeInstance.save flush:true\n\n request.withFormat {\n form multipartForm {\n flash.message = message(code: 'default.updated.message', args: [message(code: 'PlanType.label', default: 'PlanType'), planTypeInstance.id])\n redirect planTypeInstance\n }\n '*'{ respond planTypeInstance, [status: OK] }\n }\n}\n\n@Transactional\ndef delete(PlanType planTypeInstance) {\n\n if (planTypeInstance == null) {\n notFound()\n return\n }\n\n planTypeInstance.delete flush:true\n\n request.withFormat {\n form multipartForm {\n flash.message = message(code: 'default.deleted.message', args: [message(code: 'PlanType.label', default: 'PlanType'), planTypeInstance.id])\n redirect action:\"index\", method:\"GET\"\n }\n '*'{ render status: NO_CONTENT }\n }\n}\n\nprotected void notFound() {\n request.withFormat {\n form multipartForm {\n flash.message = message(code: 'default.not.found.message', args: [message(code: 'planTypeInstance.label', default: 'PlanType'), params.id])\n redirect action: \"index\", method: \"GET\"\n }\n '*'{ render status: NOT_FOUND }\n }\n}\n}\n\n\nAny ideas how to solve this?"
] | [
"spring",
"hibernate",
"grails",
"mapping"
] |
[
"Using MouseListener to begin or end an otherwise infinite loop",
"I want to have a mouseclick begin a loop that reports the location of the mouse and until the mouse is clicked. I had no problem beginning the loop and reporting the location, but even though the MouseClicked method ends the loop if the mouse is clicked twice, or should, the program continues the loop infinitely. \n\npublic JFramethingy() {\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setBounds(100, 100, 450, 300);\n contentPane = new JPanel();\n contentPane.addMouseListener(new MouseAdapter() {\n int numClicked;\n public void mouseClicked(MouseEvent arg0) {\n numClicked++;\n for (int i = 0; i > -1;) {\n if(i % 1002000 == 0){\n PointerInfo a = MouseInfo.getPointerInfo();\n Point b = a.getLocation();\n int x = (int) b.getX();\n int y = (int) b.getY();\n System.out.println(x + \",\" + y); \n\n\n }\n if (numClicked > 1){\n numClicked = 0;\n i = -3;\n }\n i++;\n } \n } \n });"
] | [
"java",
"eclipse",
"swing",
"jframe",
"awt"
] |
[
"Create a new column based on other columns and a dictionary",
"let's suppose I have a dataframe with at least two columns col1 and col2. Also I have a dictionary of dictionaries, whose keys consist of the values in col1 resp. col2.\n\nimport pandas as pd\ndict_of_dicts = {'x0': {'y0':1, 'y1':2, 'y2':3}, 'x1': {'y0':0, 'y1':0, 'y2':1}, 'x2': {'y0':2, 'y1':1, 'y2':3}} \ndf = pd.DataFrame( {'col1': ['x1', 'x2', 'x2'], 'col2': ['y0', 'y1', 'y0']} )\nprint(df)\n col1 col2\n0 x1 y0\n1 x2 y1\n2 x2 y0\n\n\nNow I want to create a third column that contains the value of my dictionary with the keys given by col1 and col2 in the respective line. Something like\n\ndf['col3'] = dict_of_dicts[df['col1']][df['col2']].\n\n\nThe result should look like this:\n\n col1 col2 col3\n0 x1 y0 0\n1 x2 y1 1\n2 x2 y0 2\n\n\nIt should be similar to \"map\", as explained here Adding a new pandas column with mapped value from a dictionary\n\nBut I rely on two columns. Could anybody help me with that, please?\n\nBy the way: I actually don't have to use a dictionary of dictionaries (as just described). I could also use a table (dataframe) with the one set of keys as index set of the dataframe and the other set of keys as the column names. But also here I don't know how to access a specific \"cell\" which would be specified by the values in col1 and col2.\n\nI hope my problem is clear.\n\nThank you, Nadja"
] | [
"python",
"pandas",
"dictionary",
"dataframe"
] |
[
"Why are braces allowed in this Python code?",
"Python has never used braces to define code blocks, it relies on indentation instead; this is one of the defining features of the language. There's even a little cookie that CPython gives you to show how strongly they feel about this:\n\n>>> from __future__ import braces\nSyntaxError: not a chance\n\n\nWhen I saw this little snippet posted to a forum (since deleted) I thought it cannot possibly work. But it does!\n\n>>> def hi(): {\n print('Hello')\n }\n\n>>> hi()\nHello\n\n\nWhy does this code work, when it appears to violate the language syntax?"
] | [
"python",
"curly-braces"
] |
[
"How to limit regex's findall() method",
"Is there a regex equivalent of BeautifulSoup's limit=X argument for the findall method? I mean, how to find the first X words in question and then break the code execution? thank you"
] | [
"python",
"regex",
"python-2.7"
] |
[
"Knockout: Unable to bind to a button's click event when using Bootstrap popover",
"I am having trouble with Knockout executing Javascript when a user clicks on a button. Unfortunately this is quite a complex page, and I cannot show the full content, but hopefully the small snippet below is enough.\n\nI have tried to simplify this by not even calling the actual view model in the Knockout binding of data-bind, and instead I just simply alert.\n\n<div data-bind=\"foreach: MyComputedStuff()\">\n...\n <div class=\"popover-content\">\n <button onclick=\"alert('bar')\">\n This works!\n </button>\n <button data-bind=\"click: function(data, event){alert('foo')}\">\n THIS DOES NOT WORK\n </button>\n </div>\n...\n</div>\n\n\nIs there something obvious that I am doing wrong here?\n\nWhy is it impossible for alert('foo') to be executed?\n\nIt might help to know that we use Bootstrap and this particular button is within a popover div.\n\nEdit:\n\nI see nothing in the console, and the rest of the page's Javascript continues to work as normal. I have tried this in Chrome and IE9.\n\nI should have said that I am able to bind the click event on another element within the same foreach, to a function in the view model. This works, and this is what I expected to be able to duplicate. (If I replace the call to a function with alert('blah') then I see alert as expected here.) So why not on my button??\n\n<a rel=\"tooltip\" \n title=\"Favourite App\"\n data-bind=\"click: function(data, event){$root.ToggleFavorite(data)}\">"
] | [
"javascript",
"twitter-bootstrap",
"knockout.js"
] |
[
"Finding all references of a common method name in Visual Studio 2010 for a C# solution",
"In Visual Studio 2010, if I right-click a method and choose \"Find All References\", it simply displays use of all methods with the same name rather than use of the method of that actual class.\n\nThe solution is C# rather than C++, so I can't find a way to switch to accuracy mode. Also, I cannot simply make the method private or comment it out to generate errors as the method is an override:\n\npublic override string ToString() { ... }\n\n\nIs there any way of finding all uses of a particular class method in a solution without trawling through every single name match (in this case every instance of ToString() in the solution)?"
] | [
"c#",
"visual-studio-2010"
] |
[
"Andoid app Sync failed Gradle sync issues start up failed",
"Opened my app and ran into gradle sync problems. I am so sure that I didn't touch the gradle files.\n\n\n\nThis is what I am getting - \n\n\n ERROR: startup failed:\n build file 'C:\\Users\\Ibrahim\\AndroidStudioProjects\\Misnap\\app\\build.gradle': 1: unexpected char: 0x0 @ line 1, column 8.\n � � � � 5 V � 1 2 3 � � � � � � � � � � % * + -\n ^ 1 error\n\n\nI tried \n\n\nDelete iml file and .idea directory - didnt work \nI also did a clean and rebuild project - didnt work, infact the clean project is not showing anymore, just rebuild."
] | [
"java",
"android",
"xml",
"gradle",
"synchronization"
] |
[
"java.lang.NullPointerException on explicit wait",
"I am trying to loop through and click on a number of buttons on a web page. My code first checks for the number of the elements on the page, then loops through and clicks each one. \n\nThis worked for the first loop, but then I got an Element Not Found exception on the second loop. This is because when the button is clicked the element disappears from the page and the DOM changes. I then read that an explicit wait will force Selenium to repoll the DOM. So I added the explicit wait. \n\nBut now I get a java.lang.NullPointerException on the very first loop at the wait.Until line. \n\nThe driver is a RemoteWebDriver if that makes any difference.\n\nvar elements = new List<IWebElement>();\ndriver.Manage().Timeouts().ImplicitWait=TimeSpan.FromSeconds(0);\nelements.AddRange(driver.FindElements(By.XPath(\"//button[contains(@data-cancelref,'outgoing_requests')]\")));\n\nif(!elements.Any()) {\n return;\n}\n\nint loop = elements.Count-1;\nfor(int i = 0; i<loop; i++) {\n WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));\n wait.Until(ExpectedConditions.ElementIsVisible(By.XPath(\"//button[contains(@data-cancelref,'outgoing_requests')]\")));\n var button = driver.FindElement(By.XPath(\"//button[contains(@data-cancelref,'outgoing_requests')]\"));\n button.Click();\n Thread.Sleep(rnd.Next(2000, 4000));\n}\n\ndriver.Manage().Timeouts().ImplicitWait=TimeSpan.FromSeconds(60);\n\n\nStack Trace: \n\nat OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)\nat OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)\nat OpenQA.Selenium.Remote.RemoteWebElement.get_Displayed()\nat OpenQA.Selenium.Support.UI.ExpectedConditions.<>c__DisplayClass7_0.<ElementIsVisible>b__0(IWebDriver driver)\nat OpenQA.Selenium.Support.UI.DefaultWait`1.Until[TResult](Func`2 condition)\nat _Common.FDriver.Clean(IWebDriver driver, String prox, Int32 timeout, Boolean& success) in C:\\_Common\\FDriver.cs:line 727\n\n\nLine 727 is the For statement"
] | [
"c#",
"selenium",
"remotewebdriver"
] |
[
"boost thread pool bind errors",
"I'm using boost::asio and boost::filesystem to perform some simple asynchronous filesystem operations.\nThe following code snippet is supposed to spawn a new thread for every directory it finds in the first level that recurses such directory, and so on, as long as there are threads to use from the thread pool.\n\nIt seems that the compiler does not recognize that I am passing the boost::asio::io_service by reference, and complains:\n\nmain.cpp:51:51: Call to implicitly-deleted copy constructor of 'boost::asio::io_service'\n\nI tried #define BOOST_ASIO_HAS_MOVE so it would think it is allowed to move the boost::asio::io_service even though it is really being passed by const &, but to no avail.\n\nIncludes:\n\n#include <iostream>\n#include <thread>\n// Threadpool\n#define BOOST_ASIO_HAS_MOVE\n#include <boost/asio/io_service.hpp>\n#include <boost/bind.hpp>\n#include <boost/thread/thread.hpp>\n// Filesystem\n#include <boost/filesystem.hpp>\n\n\nMain:\n\nint main(int argc, const char * argv[]) {\n boost::asio::io_service ioservice;\n boost::thread_group threadpool;\n boost::asio::io_service::work work(ioservice);\n unsigned int threads = std::thread::hardware_concurrency();\n for(unsigned int i = 0; i < threads; ++i)\n threadpool.create_thread(boost::bind(&boost::asio::io_service::run,\n &ioservice));\n\n\n ioservice.post(boost::bind(parallel_found_file,\n ioservice, // Call to implicitly-deleted copy constructor of 'boost::asio::io_service'\n APPS_DIR,\n FILE_NAME));\n threadpool.join_all();\n ioservice.stop();\n\n return 0;\n}\n\n\nFunction:\n\nstatic bool parallel_found_file(boost::asio::io_service & ioservice,\n const boost::filesystem::path & dir_path,\n const std::string & file_name)\n{\n if(!exists(dir_path))\n return true;\n\n boost::filesystem::directory_iterator end_itr;\n for(boost::filesystem::directory_iterator itr(dir_path);\n itr != end_itr;\n ++itr )\n {\n if(is_directory(itr->status()))\n {\n ioservice.post(boost::bind(parallel_found_file,\n ioservice, // Call to implicitly-deleted copy constructor of 'boost::asio::io_service'\n itr->path(),\n file_name));\n }\n else\n {\n if(itr->path().filename().string().find(file_name)\n != std::string::npos)\n {\n return true;\n }\n }\n }\n return false;\n}\n\n\nEdit:\n\nioservice.post(boost::bind(parallel_remove_file,\n boost::ref(ioservice),\n boost::ref(APPS_DIR),\n boost::ref(FILE_NAME)));\n\n\nio_service.hpp:102:3: Static_assert failed \"CompletionHandler type requirements not met\"\n\nboost::asio::io_service::post says:\nThe function signature of the handler must be:\nvoid handler();\n\nDoes this mean there's no way for me to pass or return values from the function? Since the required signature of the handler takes no parameters and has no return?\n\nThis works now, but I would really like to know why I can't pass parameters or a return value, only captured variables, or variables from outside the scope :/\n\nauto ioref = std::ref(ioservice);\nioservice.post([ioref]()\n -> void\n { parallel_remove_file(ioref, APPS_DIR, FILE_NAME); });"
] | [
"c++",
"multithreading",
"boost"
] |
[
"Accessing an HttpServletRequest from inside an AXIS2 module",
"I am implementing AXIS2 services in my web application. Our client's production boxes are a bit flaky, so I want a heads up when performance degraded. Specifically:\n\n\nrequest comes into my AXIS2 service\nmeasure the time that the request takes\nif the time is greater than X, log an error\n\n\nSo I wrote an AXIS2 module like this:\n\npublic class PerformanceHandler extends AbstractHandler implements Handler {\nprotected Logger logger = null;\n\npublic PerformanceHandler() {\n logger = LoggerFactory.getLogger( this.getClass() );\n}\n\npublic InvocationResponse invoke( MessageContext msgContext ) throws AxisFault {\n HttpServletRequest r = ( HttpServletRequest )msgContext.getProperty( HTTPConstants.MC_HTTP_SERVLETREQUEST );\n if( msgContext.getFLOW() == MessageContext.IN_FLOW || msgContext.getFLOW() == MessageContext.IN_FAULT_FLOW ) {\n // incoming request\n Date timeIn = new Date( System.currentTimeMillis() );\n r.setAttribute( this.getClass().getName() + \".timeIn\", timeIn );\n if( logger.isDebugEnabled() ) {\n logger.debug( \"Request \" + r.toString() + \" started processing at \" + timeIn );\n }\n } else {\n // outgoing response\n Date timeIn = ( Date )r.getAttribute( this.getClass().getName() + \".timeIn\" );\n Date timeOut = new Date( System.currentTimeMillis() );\n if( logger.isDebugEnabled() ) {\n logger.debug( \"Request \" + r.toString() + \" finished processing at \" + timeOut );\n }\n long delta = timeOut.getTime() - timeIn.getTime();\n if( delta > 300 ) { // todo: parameterize the delta threshold\n logger.error( \"Request \" + r.toString() + \" took \" + delta + \"ms to process.\" );\n }\n }\n\n return InvocationResponse.CONTINUE;\n}\n}\n\n\nAfter that, I edited the module.xml, axis2.xml appropriately, created the *.mar file and ran the app.\n\nHowever, it seems that \n\nHttpServletRequest r = ( HttpServletRequest )msgContext.getProperty( HTTPConstants.MC_HTTP_SERVLETREQUEST )\n\n\nis null. That was unexpected.\n\nSo my questions are:\n\n\nHow can I access the servlet request in an AXIS2 module?\nIf this is not allowed, what's the alternative for me to track the time between request starting processing and ending processing?\nI should be using some other existing AXIS2 functionality that can give me the same kind of result?\n\n\nMany thanks in advance,\nDave C."
] | [
"axis2",
"axis"
] |
[
"How to form another colum in a pd.DataFrame out of different variables",
"I'm trying to make a new boolean variable by an if-statement with multiple conditions in other variables. But so far my many tries do not even work with variable as parameter.\n\nhead of used columns in data frame\n\nI would really appreciate if anyone of you can see the Problem, I already searched for two days the whole World Wide Web. But as beginner I couldn't find the solution yet.\n\namount = df4['AnzZahlungIDAD']\ntime = df4['DLZ_SCHDATSCHL']\nErstr = df4['Schadenwert']\nZahlges = df4['zahlgesbrut']\ntimequantil = time.quantile(.2)\ndiff = (Erstr-Zahlges)/Erstr*100\ndiffrange = [(diff <=15) & (diff >= -15)]\nspecial = df4[['Taxatoreneinsatz', 'Belegpruefereinsatz_rel', 'IntSVKZ', 'ExtTechSVKZ']]\n\n\nFirst Method with list comprehension\n\nlabel = []\nlabel = [True if (amount[i] <= 1) & (time[i] <= timequantil) & (diff == diffrange) & (special == 'N') else False for i in label]\nlabel\n\n\nSecond Method with iterrows() \n\ndf4['label'] = pd.Series([])\ndf4['label'] = [True if (row[amount] <= 1) & (row[time] <= timequantil) & (row[diff] == diffrange) & (row[special] == 'N') else False for row in df4.iterrows()]\ndf4['label']\n\n\n3rd Method with Lambda function\n\ndf4.loc[:,'label'] = '1'\ndf4['label'] = df4['label'].apply([lambda c: True if (c[amount] <= 1) & (c[time] <= timequantil) & (c[diff] == diffrange) & (c[special]) == 'N' else False for c in df4['label']], axis = 0)\ndf4['label'].value_counts()\n\n\nI expected that I get a varialbe \"Label\" in my dataframe df4 that is whether True or False.\n\nFewer tries gave me only all values = False or all = True even if I used only a single Parameter, which is impossible by the data.\n\nFirst Method runs fine but Outputs: []\n\nSecond Method gives me following error: TypeError: tuple indices must be integers or slices, not Series\n\nThird Method does not load at all."
] | [
"python",
"pandas",
"dataframe",
"if-statement",
"boolean"
] |
[
"Identifying test projects from solution file",
"Assume that I have a visual studio solution file. I want to know how can i identify the test projects from that solution file.\nIs there any way to identify that.?"
] | [
"visual-studio",
"unit-testing",
"project",
"solution"
] |
[
"Can you create a new SQL buffer in Emacs if one already exists?",
"Let's say you have a *SQL* buffer already open in Emacs that is connected to a specific server and database. Now, your intention is to connect to a different server and database while keeping your other SQL buffer process active. \n\nHow exactly can you create a new *SQL* buffer process without killing your original SQL buffer? Can this be done? Is there a way to instead change your connection info for the existing buffer?"
] | [
"sql",
"emacs",
"sql-mode"
] |
[
"Select a data frame using string values and change its column name",
"I am trying to change the column name in a data frame. I would like to select the data frame using string values in combination with eval(as.name(paste())). \n\nHere is my code:\n\nlist <-c(\"a\",\"b\",\"c\",\"d\")\n\nfor (i in 1: length(list) )\n{\nassign(paste(\"tf_\", list[i], \"_0\", sep=\"\"), as.data.frame( ifelse ( !is.na( Data[[list[i]]] ),1,0 ) ) )\n\nnames(eval(as.name(paste(\"tf_\", list[i], \"_0\", sep=\"\"))))<-\"blablabla\"\n\n}\n\n\nWhen I am using the part names(eval(as.name(paste(\"tf_\", list[i], \"_0\", sep=\"\")))), it returns me the expected name but when I want to assign a different name string value it shows me the error: target of assignment expands to non-language object"
] | [
"r",
"string",
"dataframe"
] |
[
"Structural help - rails if statement",
"Please could you help me to think about how best to layout a form.\n\nI have a series of checklist boolean questions (for example, do you want data?). If the answer is yes, I want to show questions further relating to data.\n\nI have a form with the series of boolean questions and another form with the follow up questions to be shown if the answer is true at the top level. \n\nHow do I go about revealing the detailed follow up questions if the answer at the top is true?\n\nI tried if true then -- a link to the follow up form, but I'm either expressing it incorrectly or approaching the layout all wrong. I've seen some questions in this post describing methods to help with the reveal, but I don't follow the reasoning behind why.\n\nThank you."
] | [
"ruby-on-rails",
"ruby-on-rails-4",
"simple-form"
] |
[
"Unable to return the perl Hash into the template toolkit file",
"Thanks in advance.\n I am trying to display the list of files using the Template Toolkit file.Before this i am returning the hash from perl file into the .tt(template toolkit file) file.\n But the condition is not executing and also i am unable to display the list of files.\n For your reference i am providing the files.\n\nPerl file (Example.pm):\n\nsub example{ \n my $path = \"/sa2/tools/jayaram_delete\";\n if (chdir($path)) {\n @files = glob \"*\";//I am getting the list of files\n } else {\n @files = ();\n }\n\n $run{'files'} = \\@files;\n $run{'testing'}= 'files';\n\n return 'site/screen/screen.tt',\\%run;\n}\n\n\nTemplate toolkit file:(Example.tt)\n\n//This is The condition to display the Upload functionality in the .tt file\n [% IF screenName == 'Resource Management' %]\n//This is the code given in Stackoverflow,for displaying the list of files getting from perl file to .tt file.But this functionality is not working in this .tt file.\n[% files %]\n[% FOREACH n IN files %]\n [% n %]\n [% END %]\n//This is the Table format to display the Upload functionality in the .tt file.\n<table id='dataTableExample' class=dataTable cellpadding=01 cellspacing=01>\n\n <tr class=verification style=\"text-align:left;\">\n <th colspan=\"2\">Instrumentation Configuration</th>\n </tr>\n <tr class=controlTableDataRow>\n <td class=controlTableCommandCell>\n <form action='/sa/site/screen/testresults/ajaxTab/test/[% parentid %]/[% id %]' method='post' enctype=\"multipart/form-data\" target='file_upload'>\n <input type=\"file\" name=\"uploadFile\" size=30>\n <input type=\"submit\" name=\"submit\" value=\"Upload\">\n <iframe id='file_upload' name='file_upload' style=\"display:none\" src='about:blank' onload=\"if (file_upload.location.href != 'about:blank') uploadStatus(this)\" >\n </iframe>\n </form>\n </td>\n </tr>\n//This is the sample code to display in the .tt file\n <table class=propertyTable cellpadding=5 cellspacing=0>\n <tr class=propertyTableHeaderRow>\n <th>FileName</th>\n <th>Last Modified Date</th>\n </tr>\n </table>\n[% END %]\n\nFor your reference i am providing the complete file,please help to solve this problem for displaying the list of files in .tt file."
] | [
"perl",
"template-toolkit"
] |
[
"Telegram bot: customise buttons position on keyboard",
"Is there a way to customise buttons position on keyboard?\n\nExample: we have\n\nimport telegram\n\ndef start(bot, update):\n\n kb = [[telegram.KeyboardButton('/command1')],\n [telegram.KeyboardButton('/command2')],\n [telegram.KeyboardButton('/command3')]]\n kb_markup = telegram.ReplyKeyboardMarkup(kb, resize_keyboard=True)\n\n bot.send_message(chat_id=update.message.chat_id,\n text=\"Welcome!\",\n reply_markup=kb_markup)\n\n\nAs the result we have keyboard with 3 buttons, each button on its own row.\n\nI would like to have 2 button on the first row and 1 button on the second row. Is it possible?"
] | [
"python",
"telegram",
"telegram-bot",
"python-telegram-bot"
] |
[
"Bundled binary files with Pyinstaller (--onefile) are present but still not found at runtime?",
"Good day,\n\nWhile trying to make a standalone (--onefile) exe with Pyinstaller, I ran into a strange error. The execution does not find two .dll even though they were properly packed into the exe and are properly placed into a temp/_MEIPASSxxxxx folder at runtime, as the screenshots below show. This does not happen on the development computer.\n\n\n\n.\n\n\nI added my data (icon & readme) in this folder too thanks to this thread and the program has no problem with finding them, so the issue is only with binaries and not data apparently. Also there is no problem at all in --onedir mode, only --onefile.\n\nHere is my .spec:\n\n# -*- mode: python -*-\n\nblock_cipher = None\nimport sys\nsys.setrecursionlimit(5000)\n\nadded_binaries = [\n (\"python36.dll\", \".\"),\n (\"api-ms-win-crt-runtime-l1-1-0.dll\", \".\")\n ] \n\nadded_data = [\n (\"PilotageIcon.png\", \".\"),\n (\"PilotageREADME.pdf\", \".\")\n ]\n\na = Analysis(['Pilotage.py'],\n pathex=['C:\\\\Users\\\\local-adm\\\\Desktop\\\\Lucas\\\\Keithley\\\\2018 07 18'],\n binaries=added_binaries,\n datas=added_data,\n hiddenimports=[],\n hookspath=[],\n runtime_hooks=[],\n excludes=[],\n win_no_prefer_redirects=False,\n win_private_assemblies=False,\n cipher=block_cipher)\npyz = PYZ(a.pure, a.zipped_data,\n cipher=block_cipher)\nexe = EXE(pyz,\n a.scripts,\n a.binaries,\n a.zipfiles,\n a.datas,\n name='Pilotage',\n debug=True,\n strip=False,\n upx=True,\n runtime_tmpdir=None,\n console=True,\n icon='PilotageIcon.ico'\n )\n\n\nI read many other threads here but they do not match my situation as clearly the files are there, so I don't understand why the errors. Thank you in advance.\n\nPython version: 3.6.3\n\nPyinstaller version: 3.3.1"
] | [
"python-3.x",
"pyinstaller"
] |
[
"How can I pre-populate a hidden form field in grails?",
"I have just gotten started with Grails and I have a very basic application running. I want to pre-populate a hidden form field with a random string.\n\nWhat is the best way to do this? I have looked at the taglib but I am not sure what the best practice is for this sort of thing. Should I create a class in the src/java or src/groovy folder or is there a better way to get this done?\n\nLastly, and I know this is a very basic question, but if I do create a class or taglib, how exactly is that called from within the .gsp page?\n\nThanks!"
] | [
"grails"
] |
[
"How can I get an input in specific function and then use it in another function from the same class in python?",
"I have developed a class which gets an array as input and sort it with quicksort algorithm. the algorithm is based on divide and conquer method, so it is recursive.I am trying to set global value and then pass the parameters to partition function as default value, but it doesn't work.\nafter asking for input, the error below appears.\nthis is the error: \n\ndef partition(self, start = gl_start , end = gl_end):\nNameError: name 'gl_start' is not defined\n\n\nhere is the code\n\nclass quick:\n def __init__(self,text = input(' Please insert an array: ')):\n global gl_start\n global gl_end\n array = text.split(',')\n gl_start = 0\n gl_end = len(array) - 1\n self.array = array\n self.start = gl_start\n self.end = gl_end\n def partition(self, start = gl_start , end = gl_end):\n pivot = self.array[start]\n left = start + 1\n right = end\n done = False\n while not done:\n while left <= right and self.array[left] <= pivot:\n left += left\n while self.array[right] >= pivot and right >=left:\n right -= right\n if right < left:\n done = True\n else:\n # swap places\n print( \"Items swapped: {\" + str( self.array[left] ) + ' , ' + str(self.array[right]) + '} ' )\n temp=self.array[left]\n self.array[left]=self.array[right]\n self.array[right]=temp\n # swap start with myList[right]\n print( \"Pivotpoint swap : [\" + str( self.array[start] ) + '] ----> [' + str(self.array[right]) + '] ' )\n temp=self.array[start]\n self.array[start]=self.array[right]\n self.array[right]=temp\n print( \" Updated array is : \" + str(myList))\n return right\n def quicksort(self, start = gl_start , end = gl_end):\n if start < end:\n # partition the list\n pivot = self.partition(start, end)\n # sort both halves\n self.quicksort( start, pivot-1)\n self.quicksort(pivot+1,end)\n return self.array\n\n\nmyList = quick()\nmyList = quick.quicksort()\n\n\nI know I'm stuck with a simple answer. any help would be appreciated\nthanks guys!"
] | [
"python-3.x"
] |
[
"Outlook HTMLBody refuses to output the font size I specified, no matter the value",
"I have this code that send email with outlook\nMicrosoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application(); \nMicrosoft.Office.Interop.Outlook.MailItem oMsg = (Microsoft.Office.Interop.Outlook.MailItem)oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem); \noMsg.To = "[email protected]";\noMsg.CC = "[email protected]";\noMsg.Subject = "Fiche De Non-Confoemité N°: " + txtOrderNumber.Text+"/"+ txtCreationDate.DateTime.Year; \noMsg.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatHTML; \noMsg.Display(false); \noMsg.HTMLBody = "<font size='18px'>"+"Un nouveau fiche de non-confoemité a été ajouté: "+ \n "<br />" + "N°: " + txtOrderNumber.Text + "/" + txtCreationDate.DateTime.Year +\n "<br />" + "Détecteur: " + cmbDetecteurStructure.Text +\n "<br />" + "Personne Concernée: " + cmbRelevantEmployee.Text +\n "<br />" + "Date: " + txtCreationDate.Text +\n "<br />" + "Crée par « Smart Industrial Management »" +"</font>"+ oMsg.HTMLBody ;\n\nI tried different values for the font-size (14, 16, 18, 20) but it always end up with the same size (10) in outlook."
] | [
"c#",
"html",
"winforms",
"outlook"
] |
[
"Is it possible to query a comma separated column for a specific value?",
"I have (and don't own, so I can't change) a table with a layout similar to this. \n\nID | CATEGORIES\n---------------\n1 | c1\n2 | c2,c3\n3 | c3,c2\n4 | c3\n5 | c4,c8,c5,c100\n\n\nI need to return the rows that contain a specific category id. I starting by writing the queries with LIKE statements, because the values can be anywhere in the string\n\nSELECT id FROM table WHERE categories LIKE '%c2%';\nWould return rows 2 and 3\n\nSELECT id FROM table WHERE categories LIKE '%c3%' and categories LIKE '%c2%'; Would again get me rows 2 and 3, but not row 4\n\nSELECT id FROM table WHERE categories LIKE '%c3%' or categories LIKE '%c2%'; Would again get me rows 2, 3, and 4\n\nI don't like all the LIKE statements. I've found FIND_IN_SET() in the Oracle documentation but it doesn't seem to work in 10g. I get the following error: \n\nORA-00904: \"FIND_IN_SET\": invalid identifier\n00904. 00000 - \"%s: invalid identifier\"\n\n\nwhen running this query: SELECT id FROM table WHERE FIND_IN_SET('c2', categories); (example from the docs) or this query: SELECT id FROM table WHERE FIND_IN_SET('c2', categories) <> 0; (example from Google)\n\nI would expect it to return rows 2 and 3.\n\nIs there a better way to write these queries instead of using a ton of LIKE statements?"
] | [
"sql",
"oracle",
"csv",
"ora-00904",
"denormalized"
] |
[
"(c++11) reading a file while simultaneously saving each each word in the file to a given vector",
"So to start off, the goal of this function below is to read each line in the text file (TitanData.txt). Each line has 3 pieces of information: Age, Passenger Class, and if the passenger survived (saved as "TRUE" or "FALSE") in order. I've created 3 vectors: vector Age, vector PassengerClass, vector Survived. The issue seems to be that the push_back functions aren't working properly. I've been looking for solutions for hours and I have yet to come across one so hopefully I can get an answer here.\nThe function is below:\nvoid ReadFromFile(vector<int> Age, vector<string> PassengerClass, vector<bool> Survived)\n{\n bool survived;\n int age;\n string Passenger_Class;\n\n string val1, val2, val3;\n ifstream infile;\n infile.open("TitanicData.txt");\n if (infile)\n {\n while (infile >> val1 >> val2 >> val3)\n {\n age = stoi(val1);\n Age.push_back(age);\n\n\n Passenger_Class = val2;\n PassengerClass.push_back(val2);\n\n\n if (val3 == "TRUE")\n {\n survived = true;\n Survived.push_back(true);\n }\n if (val3 == "FALSE")\n {\n survived = false;\n Survived.push_back(false);\n }\n }\n infile.close();\n }\n}"
] | [
"c++"
] |
[
"Python: Comparing two JSON objects in pytest",
"I have an API that returns this JSON response\n\n{\n \"message\": \"Staff name and password pair not match\",\n \"errors\": {\n \"resource\": \"Login\",\n \"field\": \"staff_authentication\",\n \"code\": \"invalid\",\n \"stack_trace\": null\n }\n}\n\n\nUsing pytest, I want to build a copy of the JSON object and make sure it is exactly the same\n\nimport pytest\nimport json\nfrom collections import namedtuple\nfrom flask import url_for\nfrom myapp import create_app\n\[email protected]('client_class')\nclass TestAuth:\n\n def test_login(self, client):\n assert client.get(url_for('stafflogin')).status_code == 405\n res = self._login(client, 'no_such_user', '123456')\n assert res.status_code == 422\n response_object = self._json2obj(res.data)\n assert response_object.message == 'Staff name and password pair not match'\n invalid_password_json = dict(message=\"Staff name and password pair not match\",\n errors=dict(\n resource=\"Login\",\n code=\"invalid\",\n field=\"staff_authentication\",\n stack_trace=None,)\n )\n assert self._ordered(response_object) == self._ordered(invalid_password_json)\n\n def _login(self, client, staff_name, staff_password):\n return client.post('/login',\n data=json.dumps(dict(staff_name=staff_name, staff_password=staff_password)),\n content_type='application/json',\n follow_redirects=True)\n\n def _json_object_hook(self, d): return namedtuple('X', d.keys())(*d.values())\n def _json2obj(self, data): return json.loads(data, object_hook=self._json_object_hook)\n\n def _ordered(self, obj):\n if isinstance(obj, dict):\n return sorted((k, self._ordered(v)) for k, v in obj.items())\n if isinstance(obj, list):\n return sorted(self._ordered(x) for x in obj)\n else:\n return obj\n\n\npytest shows that the 2 objects are unequal. \n\n> assert self._ordered(response_object) == self._ordered(invalid_password_json)\nE AssertionError: assert X(message='St...k_trace=None)) == [('errors', [(...r not match')]\nE At index 0 diff: 'Staff name and password pair not match' != ('errors', [('code', 'invalid'), ('field', 'staff_authentication'), ('resource', 'Login'), ('stack_trace', None)])\nE Full diff:\nE - X(message='Staff name and password pair not match', errors=X(resource='Login', field='staff_authentication', code='invalid', stack_trace=None))\nE + [('errors',\nE + [('code', 'invalid'),\nE + ('field', 'staff_authentication'),\nE + ('resource', 'Login'),\nE + ('stack_trace', None)]),\nE + ('message', 'Staff name and password pair not match')]\n\ntests/test_app.py:31: AssertionError\n=========================== 1 failed in 0.22 seconds ===========================\n\n\nHow do I make the newly created JSON object to the same as the response?"
] | [
"python",
"json",
"pytest",
"object-comparison"
] |
[
"How run Express Js/MongoDB in command line and close the terminal",
"I wanna know how can I run an express project but hide or close the terminal.\n\nif I close the terminal my server fall, but I wanna hide it or something I'm doing a project in a local pc and me don't wanna that the user watches or close that and the app fall."
] | [
"javascript",
"node.js",
"express"
] |
[
"Do I need to provide images with different size if I retrieve it using Picasso or Glide or Volley?",
"Usually, it's better if we provide image in different densities (sdpi, mdpi,hdpi, xhdpi, etc). Do I need to provide the same thing if I retrieve it from the server using some kind of library (Picasso, Glide, Volley, etc) or should I just provide the original image and the library will convert it to the appropriate size and density to my app?\n\nNote: If I provide images with different size or densities, I don't retrieve all of it. I just retrieve all the images url and just download once of them. Is it better this way, or is it better to provide one original image url and retrieve it and re-size it to the appropriate size?"
] | [
"android",
"android-volley",
"picasso",
"android-glide"
] |
[
"How would I achieve a download button?",
"On my website index, I'm currently displaying 18 random images, here's the code I currently use to display these images:\n\nHere's my website I want to implement this feature on:\nhttp://www.freevatars.co.uk\n\nHTML:\n\n<script type=\"text/javascript\">\ndocument.write(getImageTag());\n</script>\n\n\nJS: \n\nvar imageURLs = [\n\"css/images/avatars/1.png\"\n , \"css/images/avatars/2.jpg\"\n , \"css/images/avatars/3.png\"\n , \"css/images/avatars/4.png\"\n , \"css/images/avatars/5.png\"\n , \"css/images/avatars/6.png\"\n , \"css/images/avatars/7.png\" \n , \"css/images/avatars/8.jpg\"\n , \"css/images/avatars/9.jpg\"\n , \"css/images/avatars/10.png\"\n , \"css/images/avatars/11.jpg\"\n , \"css/images/avatars/12.jpg\"\n , \"css/images/avatars/13.jpg\"\n , \"css/images/avatars/14.png\"\n , \"css/images/avatars/15.jpg\"\n , \"css/images/avatars/16.png\"\n , \"css/images/avatars/17.jpg\"\n , \"css/images/avatars/18.jpg\"\n ];\n function getImageTag() {\nvar img = '<img src=\\\"';\nvar randomIndex = Math.floor(Math.random() * imageURLs.length);\nimg += imageURLs[randomIndex];\nimg += '\\\" alt=\\\"Oh no, the image is broken!\\\"/>';\nreturn img;\n}\n// Images in JS code go up to 410, so I have only placed 18 here to shorten it.\n\n\nI was hoping to achieve a download button or a like system on the hover, however, with the image being displayed randomly with JS, I'm not able to use the standard HTML ahref download code because I would need an absolute path to the image.\n\nDoes anybody know how I could achieve this and keep the random images?\n\nThanks in advance!"
] | [
"javascript",
"html",
"css",
"image",
"download"
] |
[
"How to disable direct access to a view from url?",
"I have two views in my asp net core application. The first view is called customer and the second view is called payment. I want to disable that users can get direct acces by typing the url \"https://mywebsite/Payment\" in the browser. \n\nI want the users to be redirected to view which is called customer If users are trying to get direct access to view called payment.\n\nHow can I do that. I don't have any idea."
] | [
"asp.net-core"
] |
[
"Failed to load platform plugin in cross compiling of a Qt5.1 application for an ARM based target",
"I'm working with AM1808 based processing unit that has a Linux port on. I use Qt creator 3.0 with compiler version qt5.1.0 to build an application and install to this ARM processor as an App by cross-compiling it using the arm-2012.03 toolchain. Previously I develop the application using Qtcreator 2.4 with a qt4.7.4 compiler and it works fine in this processing unit.\n\nThe issue is faced when I cross compile the app and generate the binary and try to load into the ARM that gives me an error \n\"Failed to load platform plugin \".\n\nWhat is the issue with this? I run the same binary with my old compiler and I made the necessary changes required to run the same app in qt5.1.0 still it gives the error that I've never seen before. My binary is successfully generated without an error but when I run this binary, it generated this error.\n\nPlease share any solution to this..."
] | [
"linux-kernel",
"arm",
"qt5",
"embedded-linux",
"gnu-toolchain"
] |
[
"Updating/generating new .p12/.jks from .der",
"Current situation:\n\nWe do a POST to a certain url using HTTPS/SSL. For this to work my (former) colleague posted this question: Java HTTPS client certificate authentication\n\nSo basicly we have a keystore in .p12 format and the truststore is a .jks file.\n\nWe have no control over the server that receives our POST request.\n\nIssue:\n\nThe server admins have provided us with some new .der files because their old certificate was about to expire.\n\nAs I'm fairly new to SSL certificates and keytool- and openssl-commands I have no idea how to proceed from here.\n\n1) Is it necessary to generate new .p12 and .jks files? Or do I only need to generate a new .jks file?\n\n2) How do I generate these files from a .der certificate? I have found some websites with the most keytool/openssl commands but I haven't been able to successfully generate what I need.\n\nThe last command I tried (to no avail) was: \n\nkeytool -storepass dsmserver -keystore c:\\temp\\newkeystore.jks -importcert -alias \"c:\\temp\\newcert.der\" -trustcacerts"
] | [
"java",
"openssl",
"certificate",
"keytool"
] |
[
"How do I get a macro to run the same operation but with 2 seperate workbooks, not the same ones I used to record the macro?",
"I hope this is a clearer description of what I want to achieve.\n\nI just did a copy and paste values only and it did the operation for me. I was hoping a macro might speed the process up a bit. \n\nEssentially I want to copy cells 2,4,6,8,10....48 from column D in a particular workbook and paste the values into cells 23,24,25....46 in column J in a second workbook. The next step is to copy cells 3,5,7,9.....49 from column D in the first workbook and paste the values only into cells 23,24,25....46 in column X in the second workbook. \n\nObviously I could copy and paste these but I have thousands of these to do and was hoping a macro could help."
] | [
"vba"
] |
[
"Encryption result of java and php differ from each other",
"I'm trying to make an encrypt example in php and java. But the encryption result of java and php differ from each other.\n\nI think the result of Java is correct.\n\nWhich part of my PHP code is wrong?\nNeed your help, Thanks.\n\nThis is what I have\n\njava\n\npublic String enrollmentKeyId(String data, String key) {\n byte[] keyData = java.util.Base64.getUrlDecoder().decode(key);\n\n SecretKeySpec secureKey = new SecretKeySpec(keyData, \"AES\");\n String result = null;\n\n try {\n Cipher cipher = Cipher.getInstance(\"AES/ECB/PKCS5Padding\");\n cipher.init(Cipher.ENCRYPT_MODE, secureKey);\n byte[] encryptedData = cipher.doFinal(data.getBytes());\n result = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(encryptedData);\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return result;\n}\n\n\nphp\n\n$keyData = base64_decode($enrmtKey);\n\n$ivlen = openssl_cipher_iv_length('aes-128-ecb');\n$iv = openssl_random_pseudo_bytes($ivlen);\n\n$encryptedData = openssl_encrypt($this->pkcs5Pad($shortUuid, 16), 'aes-128-ecb', $keyData, OPENSSL_RAW_DATA, $iv);\n$result = base64_encode($encryptedData);\n\necho $result;\n\npublic function pkcs5Pad($text, $blockSize)\n{\n $pad = $blockSize - (strlen($text) % $blockSize);\n\n return $text . str_repeat(chr($pad), $pad);\n}"
] | [
"java",
"php"
] |
[
"Developer permissions by default for the members of GitLab",
"We have a wiki for documentation for all the members of the company. Because of LDAP authentication, anyone in my company can sign in to GitLab and a new GitLab user account associated with this user is created. \n\nThe wiki is located in a project inside a group like this:\n\nhttps://gitlab.com/somegroup/nameoftheproject/\n\nGroup visibility: internal\nProject visibility: internal\n\nWhen a user logs into GitLab, he can see the wiki pages but he cannot edit them unless I manually invite him through the members tab and give him developer permission. \n\nI would like that all the users from the company (hundreds) have developer permissions by default (instead of guest) when accessing the wiki so that they can edit it. Is that possible?\n\nThanks."
] | [
"permissions",
"gitlab"
] |
[
"Retrieve updated url in selenium using python",
"How to get the updated url from firefox browser using selenium and Python? The below code is a very good working example of what I am trying to do. The script opens up a url, looks for the search bar in the webpage, pastes a particular product and then executes the search. \n\nI am trying to extract the updated url after the search is completed which should be https://www.myntra.com/avene-unisex-thermal-spring-water-50-ml but I am getting https://www.myntra.com/. How can I get the required url?\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nfirefoxOptions = webdriver.FirefoxOptions()\nfirefoxOptions.set_preference(\"dom.webnotifications.enabled\", False)\n\ndriver = webdriver.Firefox(firefox_options = firefoxOptions)\n\ndriver.implicitly_wait(5)\n\n# Maximize the browser window\ndriver.maximize_window()\n\n# navigate to the home page\ndriver.get(\"https://www.myntra.com/\")\n\n# Locate the text field to update values\ntext_field = driver.find_element_by_class_name(\"desktop-searchBar\")\n\n# Clears any value already present in text field\ntext_field.clear()\n\n# Updates the string in search bar\ntext_field.send_keys(\"Avene Unisex Thermal Spring Water 50 ml\")\ntext_field.send_keys(Keys.ENTER)\n\nnew_page = driver.current_url\nprint(new_page)\n\ndriver.close()"
] | [
"python",
"python-3.x",
"selenium",
"selenium-webdriver",
"webdriverwait"
] |
[
"Beautifulsoup: How can I parse the next ?",
"I have this HTML code:\n\n<div class=\"card big_card\">\n <h3><a href=\"\"></a></h3>\n <div class=\"clogo\">\n <img src=\"\"><span class=\"site\"><a href=\"\" target=\"_blank\" title=\"\"></a></span>\n</div><p>telephone</b></p>\n<p>address</p> \n</div> \n\n\nand i coded this with beautifulsoup:\n\nsoup = BeautifulSoup(page.text, 'lxml')\nfor prov in soup.find_all('div', class_=\"card\"):\ntry:\ncur.execute(\"INSERT INTO provs (name,site,tel,address) VALUES (%s,%s,%s,%s)\", (prov.a.get_text(),prov.p.get_text(),prov.b.get_text(),))\nprint prov.get_text()\n\n\nThe first \"p\" tag is parsed, but I can't parse the second \"p\" tag with address. \n\nHow can I parse the next \"p\" tag as well as the first one?\n\nThanks for your help!"
] | [
"python"
] |
[
"Dart:JS: Get a context for a javascript object stored in a bundle generated by browserify",
"if I want to integrate some javascript code into Dart I do something like the following:\n\nJavascript Code:\n\nfunction JavaScriptCode()\n{\n this['init'] = init;\n function init()\n {\n console.log('init');\n }\n}\n\n\nDart Code:\n\nvoid main()\n{\n JsObject jsObject = new JsObject(['JavaScriptCode']);\n jsObject.callMethod('init', []);\n}\n\n\nHTML markup:\n\n<!-- Html File -->\n<!DOCTYPE html>\n<html>\n<body>\n <script src=\"main.js\">\n <script src=\"main.dart\">\n</body>\n</html>\n\n\nThis works fine if main.js is a normal JavaScript file. However, if I run browserfiy over main.js (browserify main.js -o main-bundle.js) to create a bundle, I can no longer get access to the JavaScriptCode object in my Dart code. Is it possible to get access to JavaScript objects that have been bundled using browserify from Dart? And if so how would I go about doing this? Please let me know if the question is unclear.\n\nMy aim with this was twofold:\n1) I want to manage my JavaScript dependencies better.\n2) I want to minimise the amount of JavaScript files that I am loading.\n\nAt the moment I have quite a few JavaScript files that my Dart app is working with. Ideally I would have a way to minimise these all into one file."
] | [
"dart",
"browserify",
"dart-js-interop"
] |
[
"How to make a synchronous call in Angular 9? | geolocation",
"The accepted solution here didn't work for me. I am making a call to a location service that needs to be synchronous because an api call is executed on it immediately thereafter.\n\nMy logging indicates that the location service is still returning undefined despite the await clause.\n\nservice that makes api call\n\n...\n@Injectable({providedIn: 'root'})\nclass PrepopulateService {\n constructor(private locationService: LocationService,\n private log: LoggerService) { }\n\n async prepopulate(): Promise<boolean> {\n const coords: string[] = await this.locationService.getLocation();\n console.log(coords)\n if(coords == null) {\n return false;\n }\n console.log(coords)\n // api call here\n return true;\n }\n}\n\nexport { PrepopulateService }\n\n\nservice that gets location for it\n\n...\n@Injectable({providedIn: 'root'})\nclass LocationService {\n\n constructor(private log: LoggerService) { }\n\n getLocation(): Promise<string[]> {\n if (navigator.geolocation) {\n navigator.geolocation.getCurrentPosition((position) => {\n const longitude = position.coords.longitude;\n const latitude = position.coords.latitude;\n console.log([String(latitude), String(longitude)])\n return [String(latitude), String(longitude)];\n });\n } else {\n this.log.warn('No support for geolocation');\n return null;\n }\n }\n}\n\nexport { LocationService }\n\n\nWhat's wrong with my implementation of async/await?"
] | [
"angular",
"typescript",
"promise",
"async-await",
"geolocation"
] |
[
"Insert Space After (x) characters in a string pulled from DataGridView",
"I've imported a CSV file and am populating a DataGridView. One of the columns has a set of numbers from the CSV that all have spaces in the numbers, I'm trying to allow a user to search that field but the spaces are causing issues.\n\nI've been able to target the specific column but I don't know how to allow a user to search and omit those spaces.\n\n if (numberradioButton.Checked == true)\n {\n\n foreach (DataGridViewRow row in dataGridView1.Rows)\n {\n if (row.Cells[11].Value.ToString().Equals(textBox1.Text))\n {\n row.Visible = true;\n row.Cells[11].Style.ForeColor = Color.Red;\n }\n else\n {\n row.Visible = false;\n }\n }\n\n\nThe numbers are always in the format of XX XXXXXX XXXXXX X. The string that the user will type into the textbox is XXXXXXXXXXXXXXX. My thinking is that I'll have to parse what the user enters and insert a space in the correct places. Any help would be greatly appreciated."
] | [
"c#",
"regex",
"datagridview"
] |
[
"Parser: Instruction expected Error while compiling Intel assembly with NASM",
"Can anyone tell me why are these errors happening? I am quite new to the assembly and I have some problems compiling the file. \n\nI tried compiling it in NASM,with following code in Debian:\n\nnasm -f elf codeasm.asm -o codeasm.o\n\n\nand I get the following errors:\n\ncodeasm.asm:2: error: parser: instruction expected\ncodeasm.asm:3: error: parser: instruction expected\ncodeasm.asm:5: error: label or instruction expected at start of line\ncodeasm.asm:6: warning: Unknown section attribute 'public' ignored on declaration of section `para'\ncodeasm.asm:6: warning: Unknown section attribute ''data'' ignored on declaration of section `para' \ncodeasm.asm:10: error: parser: instruction expected\ncodeasm.asm:11: error: parser: instruction expected\ncodeasm.asm:12: error: parser: instruction expected\ncodeasm.asm:13: error: parser: instruction expected\ncodeasm.asm:14: error: parser: instruction expected\ncodeasm.asm:15: error: parser: instruction expected\ncodeasm.asm:16: error: parser: instruction expected\ncodeasm.asm:20: error: parser: instruction expected\ncodeasm.asm:21: error: parser: instruction expected\ncodeasm.asm:23: error: symbol `dseg' redefined\ncodeasm.asm:23: error: parser: instruction expected\ncodeasm.asm:28: warning: Unknown section attribute 'public' ignored on declaration of section `para'\ncodeasm.asm:28: warning: Unknown section attribute ''indata'' ignored on declaration of section `para'\n\n\nFor the following code in assembly Intel syntax (Just the first couple of lines):\n\n xlist\n include stdlib.a\n includelib stdlib.lib\n list\n 286\ndseg segment para public 'data'\n\nh word ?\ni word ?\nj word ?\nk word ?\nl word ?\nsum word ?\niterations word ?\n\nInName byte \"file1.raw\",0\nOutName byte \"file2.raw\",0\n\ndseg ends\n\nInSeg segment para public 'indata'\n\nDataIn byte 251 dup (256 dup (?))\n\nInSeg ends\n\nOutSeg segment para public 'outdata'\n\nDataOut byte 251 dup (256 dup (?))\n\nOutSeg ends\n\n\nI was told that this code is working properly."
] | [
"assembly",
"debian",
"nasm",
"intel-syntax"
] |
[
"How to fit a website on windows mobile web browser through code + c#",
"hey in my application i use web browser component on a windows form and display any website that user types in say \"google.com\"\n\nbut that website does not fit in properly with the screen size\n\nhow can i do that through code?\n\ni cant find any property of windows mobile...\n\ncan somebody help!"
] | [
"c#",
"windows",
"mobile"
] |
[
"AngularJs tooltip directive - Add style",
"I have defined a tooltip:\n\n window.myApp.directive 'atooltip', ->\n\n restrict: 'A'\n link: (scope, element, attrs) ->\n\n on_enter = ->\n $(element).tooltip('show')\n on_leave = ->\n $(element).tooltip('hide')\n\n $(element).hover(on_enter, on_leave)\n\n\nUse it in my html file like this -->\n\n<span toolipt atooltip data-tooltip=\"tooltip\" data-placement=\"top\" title=\"CLICK TO ADJUST PRICING\">\n {{ something }}\n </span>\n\n\nHow can I change background-color, font etc., also I have more text to add in tooltip, how to format text, can I use html?"
] | [
"javascript",
"html",
"css",
"angularjs",
"tooltip"
] |
[
"Image edited and saved in C# can not be read by ffmpeg",
"I have template image (template.jpg) on which I draw some text (13.07.2017.) and than I save it to another location (temp/intro.jpg).\n\nThan I want to convert that and some other images into video with ffmpeg.\n\nIf I run command\n\nffmpeg.exe -f concat -safe 0 -i input.txt -c:v libx264 -vf \"fps=25,format=yuv420p\" out.mp4\n\n\nThose images gets concentrated into one video file. Problem is that this image edited through C# is black in final video.\n\nIf I for example open that C# created image in Adobe Fireworks and just save it (CTRL+S) without changing anything, and re run ffmpeg command everything is fine.\n\nThis is code which I use to add text to template image\n\n//INTRO IMAGE CREATION\nBitmap image = new Bitmap(1280, 720);\nimage.SetResolution(image.HorizontalResolution, image.VerticalResolution);\nGraphics g = Graphics.FromImage(image);\ng.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;\ng.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;\ng.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;\ng.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;\nStringFormat format = new StringFormat()\n{\n Alignment = StringAlignment.Near,\n LineAlignment = StringAlignment.Near\n};\n\n//template\nBitmap back = new Bitmap(Application.StartupPath + @\"\\Templates\\template.jpg\");\ng.DrawImage(back, 0, 0, image.Width, image.Height);\n\n//date\nstring Date = dateIntro.Value.ToString(\"dd.MM.yyyy.\");\nvar brush = new SolidBrush(Color.FromArgb(255, 206, 33, 39));\nFont font = new Font(\"Ubuntu\", 97, FontStyle.Bold, GraphicsUnit.Pixel);\nfloat x = 617;\nfloat y = 530;\n\ng.DrawString(Date, font, brush, x, y, format);\ng.Flush();\nimage.Save(Application.StartupPath + @\"\\temp\\intro.jpg\", ImageFormat.Jpeg);\nimage.Dispose();\n\n\nImage created this way can be opened and viewed in any program except converted to video with ffmpeg.\n\nIs there anything I'm missing while adding text and saving image in C#?"
] | [
"c#",
"image",
"video",
"ffmpeg"
] |
[
"possible resulting values of shared variable x",
"If we have two different processes with shared variable x, what are the possible values of x when both processes have completed?\n\nProcess A is running the following for-loop:\n\nfor (i = 0; i < 5; i++)\n x++\n\n\nProcess B is running:\n\nfor (j = 0; j < 5; j++)\n x--\n\n\nI want to say x can be anywhere from -5 to 5, assuming x is initialized to 0. Is this true? Please include an explanation."
] | [
"race-condition"
] |
[
"Adding additional property to $.ajax() callback with promise",
"I need to make 2 calls to an API which each contain some of the total data, that then needs to be iterated over. Call 1 gets two jsonp objects:\n\n[{\n \"id\": 17,\n \"name\": \"A\",\n \"campaign_code\": \"CAP20481\"\n},{\n \"id\": 18,\n \"name\": \"B\",\n \"campaign_code\": \"CAP20481\"\n}]\n\n\nCall 2 uses the ID from the first call to get an integer. I then need the corresponding \"name\" and integer. So far I have:\n\nfunction getStoreCounts() {\n var campaignID = $(\"input[title='Campaign ID']\").val();\n var storeLists = $.ajax({\n type: \"GET\",\n dataType: \"jsonp\",\n url: \"/apiIndex?callback=?&campaign_code=\" + campaignID.toString(),\n }),\n storeCount = storeLists.then(function(data) { \n $.each(data,function(i,storeList){\n $.extend(storeList,{stores:''});\n var getCount = $.ajax({\n type: \"GET\",\n dataType: \"jsonp\",\n url: \"/apiStoreCount?callback=?&list_id=\" + storeList.id.toString(),\n });\n\n getCount.done(function(count) {\n storeList.stores = count;\n });\n\n });\n return data;\n });\n\n storeCount.done(function(data) {\n console.log(data);\n $.each(data,function(i,tierCount){\n console.log(\"Tier: \"+tierCount.name);\n console.log(\"Stores: \"+tierCount.stores);\n });\n });\n}\n\n\nAt the final done promise return when I log out the whole data array, I get the stores values for each object intact. But when I try to iterate over each object in the array I'm missing the stores value. Attached output from Chrome."
] | [
"jquery",
"ajax"
] |
[
"Cloudflare 524 w/ nodejs + express",
"I'm running a nodejs webserver on azure using the express library for http handling. We've been attempting to enable cloudflare protection on the domains pointing to this box, but when we turn cloudflare proxying on, we see cycling periods of requests succeeding, and requests failing with a 524 error. I understand this error is returned when the server fails to respond to the connection with an HTTP response in time, but I'm having a hard time figuring out why it is\n\nA. Only failing sometimes as opposed to all the time\n\nB. Immediately fixed when we turn cloudflare proxying off.\n\nI've been attempting to confirm the TCP connection using \ntcpdump -i eth0 port 443 | grep cloudflare (the request come over https) and have seen curl requests fail seemingly without any traffic hitting the box, while others do arrive. For further reference, these requests should be and are quite quick when they succeed, so I'm having a hard time believe the issue is due to a long running process stalling the response. \n\nI do not believe we have any sort of IP based throttling or firewall (at least not intentionally?)\nAny ideas greatly appreciated, thanks"
] | [
"node.js",
"azure",
"express",
"tcp",
"cloudflare"
] |
[
"Way to include pom.xml with runtime dependencies within a gradle built and published jar",
"Is there a simple way to have gradle automatically generated a pom file listing the jar dependencies (both to published jars of other sibling projects and external) and have it included in the jar and published to a maven repo?\n\nThere is a lot of documentation on this subject but I am either missing something or it is as complicated as it seems. Can this not be done automatically?"
] | [
"gradle"
] |
[
"Javascript - if with asynchronous case",
"My question is a bit regards concept.\n\nA lot of times there is this such situation:\n\nif(something){\n someAsyncAction();\n}else{\n someSyncAction();\n}\n\n// Continue with the rest of code..\nvar a = 5;\n\n\nThe problem with this such case is clear, i don't want the var a = 5 to be call unless someAsyncAction() or someSyncAction() will done, now, cause soAsyncAction() is asynchronous the only way (i can think of) to solve this situation is something like that:\n\nvar after = function(){\n // Continue with the rest of code..\n var a = 5;\n}\n\nif(something){\n someAsyncAction(after);\n}else{\n someSyncAction();\n after ();\n}\n\n\nBUT, this code is ugly, hard to read and looks like anti-pattern and problematic.\n\nI trying to think maybe i can find some solution for that with Promises (using Bluebird at the backend) but can't find something.\n\nIs anyone faced this before and can help me figure it out?\n\nThanks!"
] | [
"javascript",
"design-patterns",
"asynchronous",
"promise",
"anti-patterns"
] |
[
"Iterator, set, if-else tags of Struts2(Getting the value of s:radio and applying if-else )",
"I have a jsp page in which I have two radio buttons and a select tag. Now, if the first radio button is clicked than I want to make that select tag disable but I am fail to do this , I have tried using \"disabled\" property. Following is the code.\nJsp Page\n\n<table align=\"center\">\n<s:iterator value=\"FirstObjectList\" status=\"AuthorTypeStatus\">\n <tr>\n <td>\n <s:radio name=\"radio_SelectedValue\" list=\"{ObjectName}\" listKey=\"ObjectKey\" listValue=\"ObjectName\" value=\"DefaultObject\"/> \n </td>\n </tr> \n</s:iterator>\n<s:if test=\"%{#radio_SelectedValue == 'ObjectName1'}\">\n <s:set name=\"isSelectDisabled\" value=\"false\"/> \n</s:if>\n<s:else>\n <s:set name=\"isSelectDisabled\" value=\"True\"/>\n</s:else>\n\n<tr >\n <td colspan=\"2\">\n Select Parent Discover Lab\n </td> \n</tr> \n<tr> \n <td>\n <s:select name=\"select_SelectedValue\" headerKey=\"DefaultObject\" headerValue=\"ParentObject\" list=\"ObjectList\" listKey=\"ObjectListKey\" listValue=\"ObjectListValue\" disabled=\"%{isSelectDiabled}\">\n <s:iterator value=\"ObjectList\">\n </s:iterator>\n </s:select>\n\n <s:submit value=\"Continue\">\n </s:submit> \n </td>\n\n</tr> \n\n\n\n\nAll the getter and setter methods are fixed..is this possible without javascript?"
] | [
"struts2",
"iterator"
] |
[
"How to get the remaining size on C: with ansible?",
"I need to get the remaining size of the C: partition, and I have trooble to do it with the win_disk_fact module.\nThe final objective is to check if the remaining size is less than 4GB before processing a software installation but for now I'm just trying to print the value with a debug.\n\nI use the win_disk_facts module (https://docs.ansible.com/ansible/latest/modules/win_disk_facts_module.html) and I can display the right value with \n\n- debug:\n var: ansible_facts.disks[0].partitions[1].volumes[0].size_remaining\n\n\nBut depending on where this role will be used, the C: partition might not be on the first disk, partition 1, volume 0, It might be somewhere else I have no ideas of that (I'm developping a generic role that will be largelly used by other people)\n\nI tried to use a jinja filter, but when I display the var it returns empty:\n\nvar: \n disk_C: '{{ ansible_facts.disks|selectattr(\"drive_letter\", \"C\") }}'\n\n - debug:\n var: disk_C\n\n\n\n\nThere is also something I don't get, if I try to display the size in :\n\n- debug:\n var: ansible_facts.disks[0].partitions[1].volumes[0].size_remaining\n\n\nThe result is :\n\nok: [lab-win-01] => {\n \"ansible_facts.disks[0].partitions[1].volumes[0].size_remaining\": \"52275679232\"\n}\n\n\nBut if I try to store this value a new variable (to reuse it after in something else)\n\n vars:\n diskC: '{{ ansible_facts.disks[0].partitions[1].volumes[0].size_remaining }}'\n\n- debug:\n var: diskC\n\n\nThen the result is :\n\nok: [lab-bs-win-01] => {\n \"diskC\": \"VARIABLE IS NOT DEFINED!\"\n}\n\n\nPlease, could someone enlight me on these two questions?"
] | [
"windows",
"ansible",
"ansible-facts"
] |
[
"IOS / Safari: CSS Content overlapping issue",
"Currently a strange content overlapping error for IOS / Safari on an iphone 11. Safari on desktop (With Iphone view) seems to be working fine, so it seems like some kind of issue IOS is causing.\nZIndex is set correctly on all elements. I don't know what else to do. Thanks!\n\nHere's the code for the page itself. (Notice the zIndex is set, but, in our picture on the right, this entire page is behind the foreground.)\n<div\n style={{\n display: "flex",\n justifyContent: "center",\n // alignItems: "center"\n }}\n >\n <div\n style={{\n width: "100vw",\n borderRadius: 5,\n minHeight: "100vh",\n top: 0,\n backgroundColor: "#f5f5f5",\n zIndex: 220,\n opacity: 1,\n }}\n >\n <div style={{ display: "flex", flexDirection: "column" }}>\n <div\n style={{\n width: "100%",\n display: "flex",\n flexDirection: "row",\n justifyContent: "flex-end",\n }}\n >\n <img\n id="close"\n onClick={() => this.closeModal()}\n src={Close}\n style={{\n width: "10vw",\n height: "10vw",\n marginTop: 40,\n marginRight: 40,\n }}\n />\n </div>\n <div\n id="bar"\n style={{\n display: "flex",\n flexDirection: "column",\n justifyContent: "center",\n alignItems: "center",\n paddingTop: 10,\n paddingBottom: 10,\n }}\n >\n {/* <div\n style={{\n display: "flex",\n justifyContent: "center",\n alignItems: "center",\n }}\n >\n Filters\n </div> */}\n <PriceDialogMobile\n minPrice={this.props.minPrice}\n maxPrice={this.props.maxPrice}\n clearContent={() => this.changePrice("$", "$")}\n changePrice={(min, max) => this.changePrice(min, max)}\n />\n <CategoryDialogMobile\n categories={this.props.categories}\n clearContent={() =>\n this.changeCategory([\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n true,\n ])\n }\n changeCategory={(categories) => this.changeCategory(categories)}\n />\n </div>\n </div>\n </div>\n </div>"
] | [
"css",
"ios",
"iphone",
"safari"
] |
[
"Drawing a fractal tree in Python, not sure how to proceed",
"I have this so far in python \n\nimport turtle\nimport math\nt = turtle.Turtle()\nt.shape(\"turtle\")\nt.lt(90)\n\nlv = 11\nl = 100\ns = 17\n\nt.penup()\nt.bk(l)\nt.pendown()\nt.fd(l)\n\ndef draw_tree(l, level):\n l = 3.0/4.0*l\n t.lt(s)\n t.fd(l)\n level +=1\n if level<lv:\n draw_tree(l, level)\n\n t.bk(l)\n t.rt(2*s)\n t.fd(l)\n if level<=lv:\n draw_tree(l, level)\n t.bk(l)\n t.lt(s)\n level -=1\n\nt.speed(100) \ndraw_tree(l, 2)\n\n\nBut I'm kind of stuck on how to proges, because I need to reach for building this tree. This is what I'm trying to produce:\n\n\n\nCan any one tell me what I am doing wrong?"
] | [
"python",
"turtle-graphics",
"fractals"
] |
[
"Function returning undefined after calling in string",
"I'm trying to make a shopping cart using JS and one of my tasks is to create a placeOrder function.\n\n\nThe placeOrder() function accepts one argument, a credit card number. \nIf no argument is received, the function should print out Sorry, we don't have a credit card on file for you.\nIf a card number is received, the function should print out Your total cost is $71, which will be charged to the card 83296759. Then, it should empty the cart array.\n\n\nHowever, when I call in the total function into the string keeps returning undefined.\n\n\r\n\r\nvar cart = [];\r\n\r\nfunction getCart() {\r\n return cart;\r\n}\r\n\r\nfunction setCart(c) {\r\n cart = c;\r\n return cart;\r\n}\r\n\r\nfunction addToCart(itemName) {\r\n var object = {\r\n [itemName]: Math.floor(Math.random(1, 100) * 100)\r\n };\r\n cart.push(object);\r\n console.log(`${itemName} has been added to your cart`);\r\n return cart;\r\n}\r\n\r\nfunction total() {\r\n if (cart.length !== 0) {\r\n var totalValue = [];\r\n for (var i = 0; i < cart.length; i++) {\r\n for (var item in cart[i]) {\r\n totalValue.push(cart[i][item]);\r\n var sum = totalValue.reduce(function(a, b) {\r\n return a + b;\r\n }, 0);\r\n console.log(`The total value is ${sum}`);\r\n }\r\n }\r\n } else {\r\n return (\"Your shopping cart is empty.\")\r\n }\r\n}\r\n\r\nfunction placeOrder(cardNumber) {\r\n if (cardNumber === undefined) {\r\n return (\"Sorry, we don't have a credit card on file for you.\");\r\n } else {\r\n console.log(`Your total cost is $${total()}, which will be charged to the card ${cardNumber}`);\r\n cart = [];\r\n return cart;\r\n }\r\n}\r\n\r\naddToCart(\"a\");\r\naddToCart(\"be\");\r\naddToCart(\"cart\");\r\nplaceOrder(14564);\r\n\r\n\r\n\n\nOutput:\n\nYour total cost is $undefined, which will be charged to the card 14564"
] | [
"javascript",
"arrays",
"oop"
] |
[
"ssh to list of nodes in bash",
"I need to ssh several nodes in a list.\nMy code, when I run each command manually, works, but in a bash script, it does not. \n\nsjc_nodes=$(kubectl get nodes -l nodeGroup=gpu --no-headers -o wide | awk '{print $1}' | sed -n -e 1,3p)\n\nfor sjc_node in \"${sjc_nodes}\"\ndo\necho $sjc_nodes;\nssh -F $HOME/.ssh/ssh_config userme@\"$sjc_node.ssh-server.net\" \"nvidia-smi\"\ndone;\n\n\nExpected: \n\nnode1 node2 node3\n\nnvidia-smi tests\n\n\nActual:\n\nnode1 node2 node3\nusage: nc [-46CDdFhklNnrStUuvZz] [-I length] [-i interval] [-M ttl]\n [-m minttl] [-O length] [-P proxy_username] [-p source_port]\n [-q seconds] [-s source] [-T keyword] [-V rtable] [-W recvlimit] [-w timeout]\n [-X proxy_protocol] [-x proxy_address[:port]] [destination] [port]\nssh_exchange_identification: Connection closed by remote host\n\n\nMy config file is below\n\ncat ~/.ssh/ssh_config\n\nHashKnownHosts no\n ServerAliveInterval 60\nCanonicalizeHostname yes\nCanonicalDomains server-ssh.net\nConnectionAttempts 100\nForwardAgent yes\nStrictHostKeyChecking no\nUserKnownHostsFile /dev/null\nuser userme\nHost *.server-ssh.net 10.*\n Compression yes\n ProxyCommand ssh -o \"StrictHostKeyChecking=No\" [email protected] nc %h %p"
] | [
"bash",
"ssh"
] |
[
"IText AllowAssembly and StandardEncryption",
"I am attempting to digitally sign a pdf document while still allowing for the modification of annotations and allowing the adding and removing of pages using itextsharp, Version=4.1.6.0. Below is my current code:\n\nvar signatureStamper = PdfStamper.CreateSignature(pdfReader, memoryStream, '\\0', null);\nsignatureStamper.SetEncryption(null, Encoding.UTF8.GetBytes(certificationBundle.Password), PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_MODIFY_ANNOTATIONS | PdfWriter.AllowAssembly, PdfWriter.STANDARD_ENCRYPTION_128);\n\n\nWith this configuration however, I am still unable to add and remove pages. Am I Using PdfWriter.AllowAssembly incorrectly?"
] | [
"c#",
"pdf",
"itext"
] |
[
"Issues with Spring cloud consul config while starting a Groovy app through Spring cloud cli",
"I am Exploring Consul for discovery and config server. I have added the required dependencies and yml file is set up. When i try to start the server using spring cloud cli (Spring run .) I am getting the below error which i am unable to resolve. Any help is appreciated.\n\n\n Error :\n \"A component required a bean named 'configServerRetryInterceptor' that could >not be found.\"\n\n\nI tried to define this bean but when i start the app through spring cloud cli it is not recognizing it.\n\n\n Please see the code below\n\n\nApp.groovy\n\n@Grab(\"spring-cloud-starter-consul-config\")\n@Grab(\"spring-cloud-starter-consul-discovery\")\n\n@EnableDiscoveryClient\n@EnableCircuitBreaker\n@RestController\n@Log\nclass Application{\n\n@Autowired\nGreeter greeter\n\nint counter = 0\n\n@RequestMapping(value = \"/counter\", produces = \"application/json\")\nString produce() {\n counter++\n log.info(\"Produced a value: ${counter}\")\n\n \"{\\\"value\\\": ${counter}}\"\n}\n\n@RequestMapping(\"/\")\nString home() {\n \"${greeter.greeting} World!\"\n}\n\n@RequestMapping(value = '/questions/{questionId}')\n@HystrixCommand(fallbackMethod = \"defaultQuestion\")\ndef question(@PathVariable String questionId) {\n if(Math.random() < 0.5) {\n throw new RuntimeException('random');\n }\n [questionId: questionId]\n}\n\ndef defaultQuestion(String questionId) {\n [questionId: 'defaultQuestion']\n}\n\n}\n\n@Component\n@RefreshScope\nclass Greeter {\n@Value('${greeting}')\nString greeting\n}\n\nbootstrap.yml\n\nconsul:\n host: localhost\n port: 8500\n config:\n enabled: true\n prefix: config\n defaultContext: master\n profileSeparator: '::'\n format: FILES\n discovery:\n instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}}\n health-check-url: http://127.0.0.1:${server.port}/health"
] | [
"spring",
"spring-cloud-config",
"spring-cloud-consul"
] |
[
"Tkinter: how to bind scale hotkeys?",
"I'd like to bind Control+MouseWheelUp combination.\nI tried to do so:\nimport tkinter as tk\n\nroot = tk.Tk()\nroot.bind('<Control-Button-4>',print)\n\nThis gives no reaction? Why?"
] | [
"python",
"tkinter"
] |
[
"Breeze.js - is there something like visualizer to examine local entity cache?",
"I am getting better with Chrome and Firefox debugging tools but I still have not found a way to easily examine the local entity cache managed by Breeze. I can see the data coming over the wire easily but once I am working against the local cache I would like something like the visualizers in VS C# debugging to examine the local data, see added objects, changed objects and the shape of objects when I have extended the metadata. \n\nI have Glimpse installed but that seems only good for the wire traffic. I have an eval of Hibernating Rhinos EF profiler and will install that if there is something in there that will do the trick.\n\nSurely somebody else has wanted this and figured out a visualizer or can just point to someplace in the Chrome or Firebug stuff that I am missing?"
] | [
"breeze",
"javascript-debugger",
"debuggervisualizer"
] |
[
"Making a list/vector of one column from different csv",
"I already loaded 20 csv files with function:\n\ntbl = list.files(pattern=\"*.csv\")\nfor (i in 1:length(tbl)) assign(tbl[i], read.csv(tbl[i]))\n\n\nThat how it looks like:\n\n> head(tbl)\n[1] \"F1.csv\" \"F10_noS3.csv\" \"F11.csv\" \"F12.csv\" \"F12_noS7_S8.csv\"\n[6] \"F13.csv\"\n\n\nIn all of those csv files is a column called \"Accession\". I would like to make a list of all \"names\" inside those columns from each csv file. One big list. \n\nTwo problems:\n\n\nSome of those \"names\" are the same and I don't want to duplicate them\nSome of those \"names\" are ALMOST the same. The difference is that there is name and after become the dot and the numer. \n\n\nLet me show you how it looks:\n\nAT3G26450.1 <--\nAT5G44520.2\nAT4G24770.1\nAT2G37220.2\nAT3G02520.1\nAT5G05270.1\nAT1G32060.1\nAT3G52380.1\nAT2G43910.2\nAT2G19760.1\nAT3G26450.2 <--\n\n\n<-- = Same sample, different names. Should be treated as one. So just ignore dot and a number after.\n\nIs it possible to do ? \n\nI couldn't do a dput(head) because it's even too big data set."
] | [
"r"
] |
[
"List - dictionary binding in java",
"I am building a library that has list of objects and dictionaries (maps) that relate objects from a list to objects in other list\n\ni.e. (in pseudo code):\n\n// list of buses\nbuses = [Bus1, Bus2, Bus3]\n\n// list of Loads\nloads = [Load1, Load2, Load3, Load4]\n\n// dictionary / map\nbus_loads = Bus1:{Load1, Load2}, Bus2:{Load3}, Bus3:{Load4}\n\n\nI am using Java to program this library.\nIs there any binding mechanism that allows me to delete an element in a list, delete the dictionary entry and the corresponding elements in the related list?\n\nFor example, if by deleting Bus1 in the buses list, I would delete the Bus1:{Load1, Load2} entry in the dictionary and also Load1 and Load2 in the loads list?\n\nThe straight forward solution is to create a method to delete the objects and take care of this, but I would like to know if there is a more efficient or straight forward manner.\n\nCode example:\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class List_dict_list_binding {\n\n public static void main(String[] args) {\n // Create the example\n Bus bus1 = new Bus(\"bus1\");\n Bus bus2 = new Bus(\"bus2\");\n Bus bus3 = new Bus(\"bus3\");\n\n ArrayList<Bus> buses = new ArrayList<>();\n buses.add(bus1);\n buses.add(bus2);\n buses.add(bus3);\n\n Load load1 = new Load(\"load1\");\n Load load2 = new Load(\"load2\");\n Load load3 = new Load(\"load3\");\n Load load4 = new Load(\"load4\");\n\n ArrayList<Load> loads = new ArrayList<>();\n loads.add(load1);\n loads.add(load2);\n loads.add(load3);\n loads.add(load4);\n\n Map<Bus, ArrayList<Load>> dict = new HashMap<>();\n dict.put(bus1, new ArrayList<>());\n dict.put(bus2, new ArrayList<>());\n dict.put(bus3, new ArrayList<>());\n\n dict.get(bus1).add(load1);\n dict.get(bus1).add(load2);\n\n dict.get(bus2).add(load3);\n\n dict.get(bus3).add(load4);\n\n System.out.println(\"Original\");\n System.out.println(buses);\n System.out.println(loads);\n System.out.println(dict);\n\n // DELETE bus1\n buses.remove(bus1);\n\n System.out.println(\"Deleted bus1\");\n System.out.println(buses);\n System.out.println(loads);\n System.out.println(dict);\n }\n\n}\n\nclass Bus {\n\n public String ID;\n\n Bus(String id) {\n ID = id;\n }\n\n @Override\n public String toString() {\n return ID;\n }\n}\n\nclass Load {\n\n public String ID;\n\n Load(String id) {\n ID = id;\n }\n\n @Override\n public String toString() {\n return ID;\n }\n}\n\n\nThe output is this:\n\nOriginal\n[bus1, bus2, bus3]\n[load1, load2, load3, load4]\n{bus3=[load4], bus1=[load1, load2], bus2=[load3]}\nDeleted bus1\n[bus2, bus3]\n[load1, load2, load3, load4]\n{bus3=[load4], bus1=[load1, load2], bus2=[load3]}"
] | [
"java",
"binding"
] |
[
"Python: return max column from a set of columns",
"Let's say i have a dataframe with columns A, B, C, D\n\nimport pandas as pd\nimport numpy as np\n## create dataframe 100 by 4\ndf = pd.DataFrame(np.random.randn(100,4), columns=list('ABCD'))\ndf.head(10)\n\n\nI would like to create a new column, \"max_bcd\", and this column will say 'b','c','d', indicating that for that particular row, one of those three columns contains the largest value.\n\nDoes anyone know how to accomplish that?"
] | [
"python",
"function",
"max"
] |
[
"While performing operations will the bookid's get changed?",
"I have made a program which is a small library operated via software. When I add two books and then delete the first book the second book gets the same bookid as the first book because of count-- in the del() function. I cannot rely on printing the count as the bookid. Is there a better option?\n\n#include<stdio.h>\n#include<conio.h>\n#include<stdlib.h>\nstatic int count;\nstruct book\n{\n int bookid;\n char name[30];\n char author[30];\n float price;\n};\nstruct book b[40];\nvoid add(void);\nvoid del(void);\nvoid sort(void);\nvoid price(void);\nvoid print(void);\nvoid main(void)\n{\n char choice;\n while(1)\n {\n clrscr();\n printf(\"Enter a choice:\\n 1.Add a book.\\n 2.Delete a book.\\n 3.Sort books by price.\\n 4.To print all books details.\\n 5.To print the names of the books whose price is less than 1000.\\n 6.Exit\\n\");\n choice=getche();//doing by getch() as getche makes the program rough as it is printed\n switch(choice)\n {\n case'1':add();break;\n case'2':del();break;\n case'3':sort();break;\n case'4':print();break;\n case'5':price();break;\n case'6':exit(0);\n default:printf(\"Enter a valid choice.\");break;\n }\n }/*switch ends*/\n}\nvoid add(void)\n{\n int i;\n char ch[30];\n clrscr();\n for(i=count;i<40;i++)\n {\n printf(\"Enter books name:\\n\");\n gets(b[i].name);\n printf(\"Enter author's name\\n\");\n gets(b[i].author);\n printf(\"Enter price:\\n\");\n gets(ch);\n b[i].price=atoi(ch);\n printf(\"Dear User,the book has succesfully been added.The book id is %d\",i);\n count++;\n break;\n } /* for ends*/\n getch();\n}\nvoid print(void)\n{\n int i;\n clrscr();\n for(i=0;i<count;i++)\n {\n printf(\"Bookid=%d,Name=%s,Author=%s,Price=%f\\n\",b[i].bookid,b[i].name,b[i].author,b[i].price);\n }\n getch();\n}\n\nvoid del(void)\n{\n int i,j;\n char ch[10];\n clrscr();\n printf(\"Enter book id:\");\n gets(ch); // how do i put it into the structure as i dont know that which structure it belongs to\n for(i=0;i<count;i++) //searching\n {\n if(b[i].bookid==atoi(ch))\n {\n for(j=i;j<count;j++)\n {\n b[j]=b[j+1];\n }//for j ends\n } //if ends\n } /* for of i ends */\n count--;\n getch();\n}\n//void del(void)\n//{\n\n // int i;\n // char ch[10];\n // clrscr();\n //printf(\"Enter book id:\");\n // gets(ch);\n // for(i=0;i<40;i++)\n // {\n // b[i]=b[i+1];\n //\n // }\n // count--;\n // printf(\"Dear user,delete succesful\");\n//getch();\n//}\nvoid sort(void)\n{\n int i;\n float temp;\n for(i=0;i<40;i++)\n {\n if(b[i].price>b[i+1].price)\n {\n temp=b[i].price;\n b[i].price=b[i+1].price;\n b[i+1].price=temp;\n }\n }/*for ends*/\n printf(\"Dear user,the books are sorted by price.\\n\");\n\n getch();\n}\n\nvoid price(void)\n{\n int i;\n clrscr();\n for(i=0;i<count;i++)\n {\n if(b[i].price<1000)\n {\n printf(\"%d.%s\\n\",i+1,b[i].name);\n }\n }\n getch();\n}"
] | [
"c"
] |
[
"SMS handling with regards to Priority settings and Ordered vs. Unordered Broadcast",
"I'd like to ask questions related to handling of android.provider.Telephony.SMS_RECEIVED.\n\nQ: \n\n\n Is android.provider.Telephony.SMS_RECEIVED an ordered or non-ordered\n broadcast? Where is the official documentation to identify whether is\n a non-ordered or ordered broadcast?\n\n\n<receiver android:name=\"com.nttdocomo.android.msg.chats.SmsReceiver\">\n <intent-filter android:priority=\"10\">\n <action android:name=\"android.provider.Telephony.SMS_RECEIVED\" />\n </intent-filter>\n </receiver>\n\n\nQ: \n\n\n With reference to the above code where the priority is set to \"10\". Is\n it possible for another SMS app to hijack my app, by setting to \"11\"\n or any higher value, to change the SMS message context or even delete\n it so it would never reach my app?\n\n\nQ: \n\n\n if I set to highest possible priority - ie.\n 'android:priority=\"2147483647\" ' - and what happens if yet another app\n also set to the same highest priority \"2147483647\"?\n\n\nThanks!"
] | [
"java",
"android",
"sms",
"telephony"
] |
[
"How can I organize angularjs factories/services/config/controllers files in different locations?",
"Currently I have this structure:\n\nindex.html\n>views\n login-view.html\n report-view.html\n>JS\n config.js\n >controllers\n loginCtrl.js\n reportCtrl.js\n >factories\n firebaseRefFactory.js\n\n\nIn config.js I have the routing of the templates, and the injection of firebase and such.\nI can use the controllers properly, but if I try to use a factory, I get the Uncaught Error: [$injector:modulerr]\n\nMy index.html\n\n<head>\n <!-- STYLES-->\n <link rel=\"stylesheet\" type=\"text/css\" href=\"CSS/modifier.css\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"CSS/base.css\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"CSS/skeleton.css\">\n <link rel=\"stylesheet\" type=\"text/css\" href=\"CSS/layout.css\">\n <!-- ANGULAR -->\n <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.18/angular.min.js\"></script>\n <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js\"></script>\n <script src=\"JS/angular-ui-router.min.js\"></script>\n <script src=\"https://cdn.firebase.com/js/simple-login/1.6.2/firebase-simple-login.js\"></script>\n <!-- FIREBASE -->\n <script src=\"https://cdn.firebase.com/js/client/1.0.17/firebase.js\"></script>\n <!-- ANGULARFIRE -->\n <script src=\"https://cdn.firebase.com/libs/angularfire/0.8.0/angularfire.js\"></script>\n <!-- CONFIG -->\n <script src=\"JS/config.js\"></script>\n <!-- FACTORIES -->\n <script src=\"JS/factories/firebaseRefFactory.js\"></script>\n <!-- CONTROLLERS -->\n <script src=\"JS/controllers/login.js\"></script>\n <script src=\"JS/controllers/reporte.js\"></script>\n\n</head>\n\n\nMy config.js\n\nangular.module('Demo', ['firebase','ui.router']).config(['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) {\n$urlRouterProvider.otherwise('login');\n\n$stateProvider.\nstate('login', {\n url: '/login',\n templateUrl: 'VIEWS/login-view.html',\n controller: 'loginCtrl'\n}).\nstate('report', {\n url: '/report',\n templateUrl: 'VIEWS/report-view.html',\n controller: 'reportCtrl',\n}); }]);\n\n\nMy loginCtrl where I want to use my factory\n\nangular.module('Demo').controller('loginCtrl', ['$scope', 'firebaseRefFactory', function($scope, firebaseRefFactory){\nalert(firebaseRefFactory.getRef()); }]);\n\n\nMy factory\n\nangular.module('Demo').factory('firebaseRefFactory', ['', function(){\nreturn function getRef(){\n var text = \"132\";\n return text;\n} }]);\n\n\nI tried changing the order of the scripts in the html file, and injecting the factory in the angular module in the config file."
] | [
"javascript",
"angularjs",
"factory"
] |
[
"How to get the object of Iframe at clientside(javascript) which placed inside Table in asp.net",
"I have iframe inside the column of <asp:table>. I want to get the object of an iframe in javascript. I tried like this in <body> section:\n\n<script type=\"text/javascript\">\n function resizeIframe()\n {\n var height = document.documentElement.clientHeight;\n height -= document.getElementById('frame').offsetTop;\n height -= 20; \n document.getElementById('frame').style.height = height + \"px\";\n };\n\n document.getElementById('frame').onload = resizeIframe;\n window.onresize = resizeIframe;\n</script>\n\n\nBut I'm getting error like \"object expected or null\"."
] | [
"javascript",
"asp.net"
] |
[
"I am unable to return all values using joins in my sql query, what am I doing wrong?",
"I have three tables - Assignment, Grades, Student and I am trying to make this query work so that it returns all assignments even if there is no grade entered for a student yet.\n\nThe tables are setup like this\n\nAssignment\n\nAssignmentId, AssignmentName, PointsPossible\n\n\nGrades (Junction table)\n\nStudentId, AssignmentId, PointsReceived\n\n\nStudent\n\n StudentId, StudentName\n\n\nMy query:\n\nselect \n s.StudentName, a.AssignmentName, g.PointsReceived, a.PointsPossible\nfrom \n student s \ncross join\n assignment a \nleft outer join\n grades g on s.StudentId = g.StudentId and g.AssignmentId = a.AssignmentId\norder by \n s.StudentName;\n\n\nWhen I run the query I get all the names I need, but I don't get all the assignments back. I should be getting all the names, all the assignments, and if the assignment hasn't been graded yet, there should be a null value returned.\n\nI need a little direction, maybe my tables are setup incorrectly."
] | [
"sql",
"sql-server",
"tsql"
] |
[
"SpriteKit: Uniform Circular Motion",
"I'm trying to move a sprite in a circular motion using a reusable function (that I need to use on different objects).\n\nThe first result is given by this function:\n\nfunc circularMotion(angle: CGFloat, radius: CGFloat, center: CGPoint) -> CGPoint{\n let x = radius * cos(angle) + center.x\n let y = radius * sin(angle) + center.y\n return CGPoint(x: x, y: y)\n}\n\n\nAnd then I update the position of my sprite like this:\n\noverride func update(currentTime: NSTimeInterval) {\nplayer.position = circularMotion(ang, radius: 200, center: CGPoint(x: size.width/2, y: size.height/2))\n\nang += speed\n}\n\n\nWhere ang (the angle) and speed (0.05) are two initialized properties.\n\nAnd this works pretty fine, but the actual problem is that I need to have the velocity of the sprite that rotates, since it has a PhysicBody.\n\nMy approach, though, changes only the position of the sprite. So I decided to do something like this:\n\noverride func update(currentTime: NSTimeInterval) {\n\nlet prevCirc = circularMotion(ang, radius: 200, center: CGPoint(x: size.width/2, y: size.height/2))\n\nlet Circ = circularMotion(ang + 0.05, radius: 200, center: CGPoint(x: size.width/2, y: size.height/2))\n\nlet v = CGVector(dx: Circ.x - prevCirc.x, dy: Circ.y - prevCirc.y )\n\nplayer.physicsBody!.velocity = v\n}\n\n\nI just calculated the difference of position, finding the perpendicular Vector respect to the position vector. This still \"works\", the body follows a circular motion, but it has not the radius and center given (it's a smaller circle). \n\nI know it's because of the length of the vector that it gives this result.\n\nSo the real question is, having the radius and the center of the circle I want (and the speed of how the angle changes) how can I calculate the perpendicular velocity so that it gives me a motion with those properties?"
] | [
"ios",
"iphone",
"sprite-kit",
"sprite",
"skspritenode"
] |
[
"WebStorm Auto import - \"require\" instead of \"import from\"",
"Working on a Node.js project I get suggestions (Alt + Enter) to import using ES6 when my Node.js does not support the import statement. Can I add suggestions that use require? Auto import saves so much time...\n\n\n\nThe manipulateName method definition:\n\nconst manipulateName = (layout, method) => {\n layout.name = method(layout.name);\n return layout;\n}\n\n\nand ...\n\nmodule.exports = {\n manipulateName,\n ...\n}"
] | [
"node.js",
"webstorm"
] |
[
"Why do I get two different Outputs, when merging two sorted lists (Python)",
"I am confused as to why i get two different outputs when I change the relational operator:\n\nHere is the incorrect version:\n\nlistOne = [1,3,6,9,11]\nlistTwo = [2,4,5,7,8,10,12]\n\ndef mergeTwo(l1,l2):\n output = []\n while l1 and l2:\n if l1[0] > l2[0]:\n output.append(l2.pop(0))\n output.append(l1.pop(0))\n\n if l1:\n output.extend(l1)\n elif l2:\n output.extend(l2)\n print output\n\n\nthe output is: \n[1, 2, 3, 4, 6, 5, 9, 7, 11, 8, 10, 12]\n\nbut it works when i do this:\n\nlistOne = [1,3,6,9,11]\nlistTwo = [2,4,5,7,8,10,12]\n\ndef mergeTwo(l1,l2):\n output = []\n while l1 and l2:\n if l1[0] < l2[0]:\n output.append(l1.pop(0))\n output.append(l2.pop(0))\n\n if l1:\n output.extend(l1)\n elif l2:\n output.extend(l2)\n print output\n\n\nI change the operator to < and the order of elements I pop off and I get this output:\n\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n\n\nwhy does the second version merge the two lists correctly unlike the first?"
] | [
"python",
"algorithm",
"merge",
"sorted"
] |
[
"UIActionsheet in Splitview crashing with iOS 5.1 update",
"After updating to iOS 5.1 from 5.0, an actionsheet presented from a button in the popover of a splitview controller is crashing the app. The error that its outputting is: * Assertion failure in -[UIActionSheet presentSheetInPopoverView:], /SourceCache/UIKit/UIKit-1914.84/UIActionSheet.m:1816\nSo in the Master View of the Splitview controller, I have a camera button that I attempt to present an actionsheet from asking to pick from camera roll or from camera. Any ideas?\n\nif(lpm != null) //Long Press Menu / Action Sheet\n lpm = null;\nlpm = new UIActionSheet(\"Select an action to perform on \" + Application.MO.CurrentList[indexPath.Row].Name);\nforeach(var button in buttonList)\n lpm.AddButton(button);\nlpm.CancelButtonIndex = buttonList.Count - 1;\nlpm.Style = UIActionSheetStyle.BlackTranslucent; \nlpm.ShowFrom(theList.RectForRowAtIndexPath(indexPath), this.View, true);\nlpm.Clicked += delegate(object sender, UIButtonEventArgs e2) {\n lpm.DismissWithClickedButtonIndex(e2.ButtonIndex, false);\n Application.MO.RespondToLongPressSelection(e2.ButtonIndex);\n };"
] | [
"ios",
"xamarin.ios",
"uisplitviewcontroller",
"uiactionsheet",
"ios5.1"
] |
[
"How to cache tab using jquery function for dynamic index number?",
"$('#operation_detail_main_tab').tabs({cache:true,show: function( event, ui ){\n if(ui.index!=6){\n $('#operation_detail_main_tab').tabs('load', ui.index);\n }\n}});\n\n\nI want the ui.index!=6 part, to have dynamic value. It should receive a value from somewhere.\n\nHow to do it as the value is from JSP. I know parameter in jsp is specified like ${my variable}, but is it possible to pass it to javascript function?"
] | [
"javascript",
"jquery",
"jsp"
] |
[
"How to access to controllers and retrieve data from the database while using vue-router?",
"What i want: Trying to build a simple SPA using vuejs and vue-router. Simply retrieve data from the database and display it to the user. I have adjusted the laravel routes to match the vue-router. But I don't know how to get data from database using vue-router.\n\nWhat I did and some description:\n\n\nmy vue-router\n\n\nconst routes = [\n {path:'/path', component: 'component},\n];\n\nconst router = new VueRouter({\n mode: 'history',\n routes \n});\n\n\n\nfile routes\n\n\nRoute::get('/{all}', 'Controller@methods')->where(['all' => '.*']);\n\n\nAdditional description: \nI was able to display the template of the components with the above code. However, I don't know how to retrieve data or how to manipulate multiple controllers like 'laravel's routes'."
] | [
"php",
"laravel",
"vue.js",
"vue-router"
] |
[
"Dynamically set Radio button from JSON using select option",
"I want to set questions from an pre-select question using Vue.js.\n\nI was able to get this working with an Radio button that once is checked it shows new set of questions.\n\nI´m trying to the same using drop-down selection, once value is set on the dropdown, will show the set of Radio button questions\n\nThis is my current test:\n\n<div id=\"app\">\n <select v-model=\"selectedL\">\n <option v-for=\"l in list\" v-bind:value=\"{ id: l.id, text: l.name }\">{{ l.name }}\n </option>\n </select>\n <div v-for=\"r in list.text\" :key=\"r.id\">\n <input type=\"radio\" :value=\"r\" v-model=\"selectedR\" :id=\"r.id\" :name=\"r.id\">\n <label class=\"label\" v-bind:for=\"r.id\">{{r.name}}</label>\n </div>\n</div>\n\n\n\n\nvar app = new Vue({\nel: '#app',\ndata: {\nselectedL: '',\nselectedR: '',\n\nlist: [\n {\n id: 1,\n name: 'A',\n text:[\n {\n text1: '123',\n text2: '456'\n }\n ]\n },\n {\n id: 2, \n name: 'B',\n text:[\n {\n text1: '678',\n text2: '908'\n }\n ]\n },\n {\n id: 3, \n name: 'C',\n text:[\n {\n text1: '143',\n text2: '786'\n }\n ]\n }\n]\n}\n})\n\n\nAbove is my working progress with Radio/Radio\n\nhttps://jsfiddle.net/bernlt/pvndg8jf/11/\n\nI need help to do the same using an Select-option to define Radio questions"
] | [
"javascript",
"json",
"vue.js"
] |
[
"Your Ruby version is 2.2.4, but your Gemfile specified 2.3.0?",
"I'm trying to bundle install a ruby project in Git Bash but I'm getting the above message.\n\nruby -v\n\n\n\n ruby 2.2.4p230 (2015-12-16 revision 53155) [i836-mingw32]\n\n\ngem -v\n\n\n\n 2.3.0\n\n\nNew to Ruby so its really frustrating. I'm trying to do the project below \nhttp://www.viralrails.com/?p=25"
] | [
"ruby-on-rails",
"ruby",
"rubygems"
] |
[
"Connection problems with the redis cluster",
"If I build a 3 master (port 6379) and 3 slave (port 6380) redis cluster, to which instance of redis does the program connect?\nSuppose I connect to any instance of redis, what happens if it goes down and master switches to another server?\nI've just started learning redis, please help me"
] | [
"redis"
] |
[
"Do I have to include segment.io snippet in each web page?",
"I have the snipped in the index.html but do I need to include it in all other pages? I've tried to work around it but nothing seems to work other than including it in the header of each html file."
] | [
"segment-io"
] |
[
"Correct way to import 3rd party js library cq-prolyfill in an angular 5 app",
"I'm trying to get the cq-prolyfill library to function when included through a typescript import statement E.G. import 'cq-prolyfill/cq-prolyfill.min.js'; in an angular module. I can see that it's being included in my vendor bundle, however the initial self invoking function within the library doesn't seem to be called. If I include the library via an html head import E.G. <script src=\"assets/js/cq-prolyfill.min.js\"></script> it works as expected. Any thoughts?"
] | [
"angular",
"typescript",
"angular5"
] |
[
"Sql and php if not set",
"I have a scrolling list with different names which i can choose from but if nothing is selected want all of them to be selected.\n\nhtml:\n\n<form action=\"\" method=\"POST\">\n <select name=\"names\">\n <option selected disabled value=\"\">Choose name</option>\n <option value=\"name1\">Name 1</option>\n <option value=\"name2\">Name 2</option>\n </select>\n <button type=\"submit\" name=\"submit\">OK</button>\n</form>\n\n\nphp:\n\nif(!isset($_POST['names'])) {\n*what to put here if i want all if not set*\n}\n\n\nSql:\n\nWHERE name = '\"($_POST['names'].'\""
] | [
"php",
"sql"
] |
[
"Donut Chart - arcTween transition with outer Radius",
"Donut Chart - arcTween transition with outer Radius\n\nHi, my intention is in the donuts when the data are updated the donuts can grow with transitions.\n\nI use this code for interpolate the arcs (works perfect) but i add the interpolate for the donut and don't worked good, the donut are growing with transition started in 0 and going to the new radius.\n\nArcs:\n\n//SET ARC RADIUS\nchart_vars_object.arc = d3.svg.arc()\n .outerRadius(chart_vars_object.general_radius)\n .innerRadius(0);\n\n\nPaths:\n\n//CREATE PATHS WITH ARC\n chart_vars_object.path = g.append(\"path\")\n .attr(\"class\",\"arc\")\n .style({'cursor': 'pointer', 'opacity': '0.9'})\n .attr(\"fill\", function(d) {\n return chart_vars_object.color(d.data.hash_taggeds_name);\n })\n .attr(\"d\", chart_vars_object.arc)\n .each(function(d) {\n this._current = d;\n });\n\n\nAnd when i update:\n\nchart_vars_object.arc_update = d3.select(\".pie_id_\"+ id_update).selectAll(\".arc_group\").select(\".arc\")\n .data(function(d) {\n return chart_vars_object.pie(data_update.hash_taggeds_update);\n })\n .transition()\n .duration(750)\n .attrTween(\"d\", arc_update_Tween);\n\nfunction arc_update_Tween(d) {\n this._current = this._current || d;\n var interpolate_arcs = d3.interpolate(this._current, d);\n var interpolate_donut = d3.interpolate(chart_vars_object.arc.outerRadius()(), newradius);\n this._current = interpolate_arcs(0);\n return function(t) {\n return chart_vars_object.arc.innerRadius(0).outerRadius(interpolate_donut(t))(interpolate_arcs(t));\n };\n }\n\n\nany suggestion?\n\nsorry for my english.-"
] | [
"d3.js"
] |
[
"WebSocket - Payload Length",
"The WebSocket RFC states the following in the [Data Frame Section] (https://tools.ietf.org/html/rfc6455#section-5.2) when describing the Payload Length:\n\n\n If 127, the following 8 bytes interpreted as a 64-bit unsigned integer (the most significant bit MUST be 0) are the payload length.\n\n\nI have two questions:\n\n\nIs there a particular reason why the most significant bit must be 0?\nDoes this makes the maximum size of a single frame 9223372036854775807 bytes?"
] | [
"websocket",
"size",
"rfc",
"payload"
] |
[
"What Type of Cast to Go from Parent to Child?",
"This question is about which C++ style cast should be used to make this conversion. I am aware that a C style cast can achieve this.\n\nFor the following class structure:\n\nclass Foo {};\n\nclass Bar : public Foo {};\n\n\nSay that I am given: Foo* ptr; and I want to cast it to a Bar* which type of cast should I be using? It seems like I must use dynamic_cast as it is:\n\n\n Used for conversion of polymorphic types\n\n\nI wanted to avoid dynamic_cast since it is a run time cast."
] | [
"c++",
"casting",
"parent-child",
"dynamic-cast",
"reinterpret-cast"
] |
[
"Rendering g-code coordinates in a WPF application?",
"I need to develop a g-code visualizer that will build lines according to g-code.\nThe task is quite simple. I need that in the WPF window, in the 3d component all the lines are displayed according to g-code. It should be possible to increase/decrease the size, rotate the camera.\nThere are no problems with the g-code processing module. I just need to decide which graphics engine to use for rendering.\nI faced such a task for the first time. \n\nAt the moment it seems to me that unity3d is suitable for this task. I integrate unity app in the WPF window. It use \"-parentHWND\" parameter and integrated in wpf window.\nPerhaps I am mistaken and there are simpler solutions. If so, then please suggest these solutions.\nenter image description here"
] | [
"c#",
"wpf",
"rendering",
"g-code"
] |
[
"how to load a UIView using a nib file?",
"I am new to objective C so I am bit confused on how to load another UIView. here is the code I have written to goto another UIView : \n\n [[NSBundle mainBundle] loadNibNamed:@\"NotificationsView\" owner:self options:nil];\n\n\nand in the header of this file I have included notifications.h and @class Notifications and in the .m file I have also included notifications.h\n\nnow in the notifications.h I have made an IBOutlet for the UIView and have linked the UIView to it\n\n@property (nonatomic, retain) IBOutlet UIView *NotificationsView;\n\nI have also @synthesize NotificationsView; in the .m file.\n\nwith all those things done, I still get an error when I try to load the nib using the code I shared at the top of this post, can someone tell me what it is that I am doing wrong?\n\nThanks"
] | [
"objective-c",
"ios",
"ios4"
] |
[
"Cordova with Angular 10 - Floating YouTube video",
"I'm developing a WebApp using Angular 10, and recently I published it to Android and iOS using Cordova.\nI want to add a new feature, that will be able the user to keep playing YouTube videos when minimizing the app, by providing a floating window (overlay).\nexample\nDoes Cordova provides any functionality to do so?\nThanks!"
] | [
"angular",
"cordova",
"android-overlay"
] |
[
"Setting the responseText field for html error codes",
"Using jquery AJAX to get data from a PHP script. The PHP script does some checking and will return html error codes like 403 or 400 when necessary. I would like to be able to set the reponseText to give a better description on the error for the 400 codes. Then allow my ajax fail function to handle it. \n\nI have research the different PHP command, I'm not finding anything that will allow the reponseText to be set.\n\nswitch($table) {\n case \"table1\": $tableID = \"table1\"; $table = \"table1\"; break;\n case \"table2\": $tableID = \"table2\"; $table = \"table2\"; break;\n case \"Table3\": $tableID = \"Table3\"; $table = \"Table3\"; break;\n case \"Table4\": $tableID = \"Table4\"; $table = \"Table4\"; break;\n default:\n header('HTTP/1.0 400 Bad Request, missing information');\n $level = 'Information';\n $errorMessage = \"[{$file}] [{$table}] table not found in list. line:\".__LINE__;\n error_log($errorMessage);\n die(); \n}\n\n\nI would like the responseText to return \"Table not found in list\""
] | [
"php",
"html"
] |
[
"What is the best way to get two parts of a Groovy string?",
"If I have a string in Groovy like so...\n\n'user.company.name'\n\n\n... and I want to get the the word \"company\" and \"name\" from that string, what is the best way to go about it?\n\nI was thinking of something like this, but I'm not sure if it's the most efficient/groovy way:\n\ndef items = 'user.company.name'.tokenize('.')\ndef company = items[-2]\ndef name = items[-1]\n\n\nIs there a better way to do this?"
] | [
"parsing",
"string",
"groovy"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.