texts
sequence
tags
sequence
[ "simulating rolling 2 dice in Python", "I have been asked to simulate rolling two fair dice with sides 1-6. So the possible outcomes are 2-12.\n\nmy code is as follows:\n\ndef dice(n):\n x=random.randint(1,6)\n y=random.randint(1,6)\n for i in range(n):\n z=x+y\n return z\n\n\nMy problem is that this is only returning the outcome of rolling the dice 1 time, so the outcome is always 2-12. I want it to return the sum of rolling the dice (n) times. \n\nDoes anyone have any suggestions for me?" ]
[ "python", "python-3.x", "random" ]
[ "Add FormGroup at Component level in Angular 2", "I have a component with a template like this:\n\n<td>\n <input type=\"text\" placeholder=\"Date: jour/mois/année\" formControlName=\"dateDebut\" >\n</td>\n<td>\n <input type=\"text\" placeholder=\"Date: jour/mois/année\" formControlName=\"dateFin\">\n</td>\n\n\nAs you might have guessed, the component will be applied (selector: '[app-xxx]') on tr elements.\n\nI need (and want) [formGroup] to be applied at this component level. How can it be done?\n\nI tried (I'm new at this) the following withouth success:\n\n @HostBinding('[formGroup]') formGroup: FormGroup;" ]
[ "angular" ]
[ "loading resource works locally but not on server", "First of all i've tried my code by extracting the war file (using maven) on both eclipse and on a tomcat 8.0.33 stand alone on my mac.\n\nI have also tried my code on a windows server 2008 with the same java version 1.8, and it works when i put some variable (which are username and password) hardcoded, but when i make the code to read them from a reousrce file, it is just working on my mac (both eclipse and tomcat stand alone), but not on the server\n\nthis is the code to read the resource\n\nprivate static String getUsername() {\n Properties prop = new Properties();\n InputStream input = null;\n\n try {\n\n input = new FileInputStream(MyConfiguration.class.getClassLoader()\n .getResource(\"configuration.properties\").getFile());\n\n // load a properties file\n prop.load(input);\n\n // get the property value and print it out\n return prop.getProperty(\"username\");\n\n } catch (IOException ex) {\n ex.printStackTrace();\n } finally {\n if (input != null) {\n try {\n input.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n return null;\n }\n\n\nwhere the location of the configuration.properties is in the src/main/resources and on the server, i can see that file is in the correct directory.\n\ni am using maven, i don't know what other information you need to help me, but if you say, i will give you" ]
[ "java", "eclipse", "maven", "tomcat", "windows-server-2008" ]
[ "IE9 - CKEdtor is being disabled after save when using knockout js", "I don't actualy know how to elaborate on this bug, but here is how it goes:\nI'm using CKEditor for multiple textareas on the same screen using knockout js \"foreach\".\n\nThe CKEditor is implemented along with knockout js like this:\n\nko.bindingHandlers.CKEDITOR = {\n init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {\n var ckEditorValue = valueAccessor();\n var id = $(element).attr('id');\n var allBindings = allBindings();\n var options = allBindings.EditorOptions;\n var visible = (typeof allBindings.visible == 'undefined' ? true : allBindings.visible);\n id = (typeof allBindings.id == 'undefined' ? id : allBindings.id);\n\n if (!visible || id == '') {\n $(element).hide();\n return;\n }\n\n $(element).attr('id', id).addClass(\"orb-ckeditor\");\n\n var ignoreChanges = false;\n\n var defaultConfig = {};\n defaultConfig.toolbar = [\n [\"Undo\", \"Redo\"],\n [\"Bold\", \"Italic\", \"Underline\", \"Strike\", \"RemoveFormat\", \"-\", \"TextColor\"],\n [\"NumberedList\", \"BulletedList\", \"Outdent\", \"Indent\"],\n [\"JustifyLeft\", \"JustifyCenter\", \"JustifyRight\", \"JustifyBlock\"],\n [\"Link\", \"Unlink\"]\n ];\n defaultConfig.defaultLanguage = 'en';\n defaultConfig.removePlugins = 'resize, wordcount, elementspath, magicline';\n defaultConfig.enterMode = CKEDITOR.ENTER_BR;\n\n defaultConfig.on = {\n change: function () {\n ignoreChanges = true;\n ckEditorValue(instance.getData());\n ignoreChanges = false;\n }\n };\n $.extend(defaultConfig, options);\n var instance = CKEDITOR.replace(id, defaultConfig);\n\n instance.setData(ckEditorValue());\n\n ckEditorValue.subscribe(function (newValue) {\n if (!ignoreChanges) {\n instance.setData(newValue);\n }\n });\n }\n};\n\n\nAnd here is the HTML:\n\n<div class=\"quiz-settings\" data-bind=\"foreach: items\">\n <textarea data-bind=\"CKEDITOR: PropertyObjectValue, visible: (PropertyType == 'MULTILINES' || PropertyType == 'EMAIL'), id: 'txtProp' + PropertyID\"></textarea>\n</div>\n\n\nI'm saving the data using an AJAX call and on the success method I'm re-binding the data to the editors.\nIt works fine in Chrome but in IE9 the editor is disabled after the save action when I click in it to edit but when I click on the font color button that opens the color palette the editor is enabled again\n\nI have no idea why this happens or how to fix it..." ]
[ "knockout.js", "ckeditor" ]
[ "SettingWithCopyWarning, while mapping with a dictionary", "I'm currently try to understand this warning:\n\nSettingWithCopyWarning: \nA value is trying to be set on a copy of a slice from a DataFrame.\nTry using .loc[row_indexer,col_indexer] = value instead\n\n\nI've seen this alot on SO, however my issue arises when trying to map.\n\nMy code is as such:\n\ndef merger(df):\n\n qdf = pd.read_csv('domains_only_df.csv')\n\n unfilt_rel_domains = qdf[['name', 'hits', 'owner', 'curated', 'domain']].copy()\n rel_domains = unfilt_rel_domains[unfilt_rel_domains['curated'] == 0]\n\n hits_dict= pd.Series(rel_domains.hits.values, index=rel_domains.owner).to_dict()\n\n name_dict = pd.Series(rel_domains.name.values, index=rel_domains.owner).to_dict()\n\n domain_dict = pd.Series(rel_domains.domain.values, index=rel_domains.owner).to_dict()\n\n df['Hits'] = df['eid'].map(hits_dict).fillna(0)\n df['Existing_domain'] = df['eid'].map(name_dict).fillna(0)\n df['idn'] = df['eid'].map(domain_dict).fillna(0)\n\nreturn df\n\n\nThe error occurs with .map(), my question is how would write a mapping using the warning's recommendation of using .loc[row_indexer,col_indexer] = value? I need .map() for speed and the lookup but I'm not quite sure how to avoid this warning." ]
[ "python", "python-3.x", "pandas", "dataframe" ]
[ "When is it ok to use a JS redirect?", "I am currently working on a site where an offer on a specific set of knife has just finished. I have therefore been asked to create a JS redirect and canonical link from this page to a page that lists all the knives that we sell for SEO purposes.\n\nI personally don't think think that this is the correct use of a JS redirect or canonical link, what does anyone else think?\n\nP.S. I am unable to create 301 or 302 redirects at the moment." ]
[ "javascript", "redirect", "seo" ]
[ "MFMessageComposeViewController slow to load", "i need use this to send msg but load slow at first time,even has 6,7 secs,So anyone know how to fix it?\nthanks a lot!\nbtw also show:“wait_fences: failed to receive reply: 10004003”?" ]
[ "performance" ]
[ "term by term division in python (division termino a termino en python )", "hello all, need to define a function that can be divided term by term matrix or in the worst cases, between arrays of lists so you get the result in a third matrix,\n\nthanks for any response" ]
[ "python" ]
[ "Error in console of AXIOS", "I am using axios in reactjs application. My code is like below\n\naxios.post('/api/addresses/upload/',formData,config)\n .then(function (response) {\n\n })\n .catch(error => {\n });\n\n\nI did not use any console.log() statement any where but I am getting below error in console.\n\n\n\nHow this error printed in console ?" ]
[ "javascript", "reactjs", "axios", "console.log" ]
[ "c# Printing a PDF with iTextSharp", "I have a problem with printing a pdf.\nSo my Document is being created by writing some values in a pdf document and saving it\n\npublic void CreateDocument(string name)\n {\n\n string oldreport = @\"..\\Resources\\FehlerReport.pdf\";\n string newreportpath = @\"..\\Resources\\\" + name;\n using (var newFileStream = new FileStream(newreportpath, FileMode.Create))\n {\n var pdfReader = new PdfReader(oldreport);\n\n var stamper = new PdfStamper(pdfReader, newFileStream);\n\n var form = stamper.AcroFields;\n\n var fieldKeys = form.Fields.Keys;\n\n form.SetField(\"Auftragsnummer\", Kundeninformation.Auftragsnummer.ToString());\n form.SetField(\"Kundensachnummer\", Kundeninformation.Kundensachnummer.ToString());\n form.SetField(\"Kundenname\", Kundeninformation.Kundenname.ToString());\n form.SetField(\"Kundenbestellnummer\", Kundeninformation.Kundenbestellnummer.ToString());\n form.SetField(\"Kundenrezepturnummer\", Kundeninformation.Kundenrezepturnummer.ToString());\n form.SetField(\"Spulennummer\", Kundeninformation.Spulennummer.ToString());\n\n form.SetField(\"Fertigungsdatum1\", System.DateTime.Today.ToString(\"dd.MM.yy\"));\n\n int i = 1;\n foreach (var item in _MeasurementReport.MeasurementReportItems)\n {\n form.SetField((\"UhrzeitRow\" + i).ToString(), item.Uhrzeit.ToString(\"HH:mm:ss\"));\n form.SetField((\"FehlerindexRow\" + i).ToString(), i.ToString());\n form.SetField((\"Position mmRow\" + i).ToString(), (item.Laufmeter * pixelSize).ToString(\"0.00\", System.Globalization.CultureInfo.InvariantCulture));\n form.SetField((\"HoeheRow\" + i).ToString(), (item.DefectCountours.H * pixelSize).ToString(\"0.00\", System.Globalization.CultureInfo.InvariantCulture));\n form.SetField((\"Breite mmRow\" + i).ToString(), (item.DefectCountours.W * pixelSize).ToString(\"0.00\", System.Globalization.CultureInfo.InvariantCulture));\n form.SetField((\"Flaeche Row\" + i).ToString(), (item.DefectCountours.W * pixelSize * pixelSize).ToString(\"0.00\", System.Globalization.CultureInfo.InvariantCulture));\n i++;\n }\n\n form.SetField(\"Datum\", System.DateTime.Today.ToString(\"dd.MM.yy\"));\n form.SetField(\"Uhrzeit\", System.DateTime.Now.ToString(\"HH:mm\"));\n\n stamper.FormFlattening = true;\n\n\n stamper.Close();\n pdfReader.Close();\n }\n\n }\n\n\nSo now i want to print the document with this function, which also calls the CreateDocument function. It prints, but the paper is white. I checked if the created pdf is being created, and it is being created but apparently not printed.\n\n public void Print()\n {\n\n string name = Kundeninformation.Auftragsnummer + \"_\" + Kundeninformation.Spulennummer+\".pdf\";\n CreateDocument(name);\n List<string> PrinterFound = new List<string>();\n PrinterSettings printer = new PrinterSettings();\n foreach (var item in PrinterSettings.InstalledPrinters)\n {\n PrinterFound.Add(item.ToString());\n }\n printer.PrinterName = PrinterFound[7];\n printer.PrintFileName = name;\n\n PrintDocument PrintDoc = new PrintDocument();\n\n PrintDoc.DocumentName = @\"..\\Resources\\\"+name;\n PrintDoc.PrinterSettings.PrinterName = PrinterFound[7];\n\n PrintDoc.Print();\n}" ]
[ "c#", "pdf", "printing", "itext" ]
[ "Pandas Basics using Square Brackets", "As seen by the code, I am trying to print out my table from the intervals of 0 to when hr1 in the column time is first equal to 1: 01 ( or 1:01 am). I am having a problem with how to implement when hr1 is equal to 1:01 in the square brackets. \n\nimport pandas as pd \n\ntable = pd.read_csv('2019-01-20.csv')\nspeed = table['speed_mph']\ntime = table['timestamp']\nx = 1\n\nfor hr1 in time: \n if x < 2: \n print(table[0:(hr1='1:01')])\n x += 1" ]
[ "python" ]
[ "Enable CORS when running AWS SAM CLI locally", "Whenever I try to access serverless lambda function via POST through the browser I get the error\n\n\n Response to preflight request doesn't pass access control check: No >'Access-Control-Allow-Origin' header is present on the requested resource.\n\n\nWhen it is a /GET it works fine I have read it is because it is not sending pre flight request. When I change it to POST this is when it fails.\n\nThe command I am running:\n\nsam local start-api\n\nAnd my template.yaml is:\n\n...\n\nResources:\n PropertiesFunction:\n Type: AWS::Serverless::Function\n Properties:\n CodeUri: target/service-0.0.1-SNAPSHOT.jar\n Handler: com.aws.PropertiesHandler::handleRequest\n Runtime: java8\n Events:\n PropertiesApi:\n Type: Api\n Properties:\n Path: /properties\n Method: post\n\n...\n\n\nHow can I enable CORS on these endpoints?" ]
[ "amazon-web-services", "aws-lambda", "aws-api-gateway", "serverless", "aws-sam-cli" ]
[ "Applying for an iphone developer certificate from scratch?", "Just got the iphone 4 and am eager to run my 'personally built' apps on it. Have looked everywhere on the apple website, but can't see where you 'sign up for a developer certificate'. Can someone explain to me how to do this, in baby steps?" ]
[ "iphone", "xcode", "certificate" ]
[ "Log4J2 - RollingFile Appender keeps on rolling", "I am developing a little REST Service which logs it's informations to a monthly rolling logfile. At least it should. But once the timebased rolling trigger kicks in, every logstatement that follows creates a new logroll.\n\nHere's my config file:\n\n{\n \"configuration\": {\n \"name\": \"Default\",\n \"properties\": {\n \"property\": {\n \"name\":\"FileName\",\n \"value\":\"restService.log\"\n }\n },\n \"appenders\": {\n \"Console\": {\n \"name\":\"stdout\",\n \"PatternLayout\": {\n \"pattern\":\"%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %m%n\"\n }\n },\n \"RollingFile\": {\n \"name\":\"File\",\n \"fileName\":\"./${FileName}\",\n \"filePattern\":\"./${date:yyyy-MM}/restService-%d{yyyy-MM-dd}-%i.log.gz\",\n \"PatternLayout\": {\n \"pattern\":\"%d %p %logger{36}.%M():%L [%t ThreadId:%T]: %m%n\"\n },\n \"Policies\": {\n \"CronTriggeringPolicy\": {\n \"schedule\":\"0 0 0 1 * ?\"\n }\n }\n }\n },\n \"loggers\": {\n \"root\": {\n \"level\":\"info\",\n \"appender-ref\": {\n \"ref\":\"File\"\n }\n }\n }\n }\n}\n\n\nThis creates a subdirectory every month where there should be exactly one logfile for the last month.\n\nE.g. if the month changes from 2016/12 to 2017/01 there is a directory called \"2017-01\" with the rolled logfile named \"restService-2017-01-01-1.log.gz\" which was copied from the file restService.log in the directory one level higher.\n\nThat works as it should ,but if the service logs a new message to its logfile it creates a new archived logfile in the subdirectory \"2017-01\" and names it \"restService-2017-01-01-2.log.gz\" and the basic logfile which should contain everything which was logged this ongoing month stays empty. \nThis happens with every log message after the trigger fired and with a default rolling max of 7, the whole log from last month would be deleted after 7 new log messages.\n\nDoes somebody know, what i am doing wrong or can point me in some direction?\n\nThank you in advance.\nubreckner" ]
[ "java", "log4j2" ]
[ "How to format string to date", "I trying to format string to date. String looks like that: 20200219 and I want to format it like 2020-02-19. Can some help me with this?" ]
[ "php", "laravel" ]
[ "PHPMailer with multiple html tables in mail body", "I am sending mails which contains data of\nText Content 1, HTML Table 1,Text Content 2, HTML Table 2 and so on..\nNote: number of rows and columns in HTML table are dynamic.\nMy PHPMailer:\n\n$mail = new PHPMailer ();\n$mail->isSMTP (); \n$mail->Host = '*******.net';\n$mail->SMTPAuth = true\n$mail->Username = '*****@*****.net'; \n$mail->Password = '*****';\n$mail->Port = ****;\n$mail->setFrom ( '********', '*********' );\n$mail->addAddress ($to , $name ); \n$mail->WordWrap = 50; \n$mail->isHTML ( true );\n$mail->Subject = $subject;\n$_body = $body;// contains mutiple HTML tables\n/*\n** $body = \"<div>Content1<table align='left'><tr>Table1 content<td></td></tr></table></div><br />\";\n** $body .= \"<div>Content2<table align='left'><tr><td>Table2 content</td></tr></table></div>\";\n*/\n$send = $mail->send ();\n$mail->SmtpClose ();\n\n\nIssue: I am unable to place my Content2 right after Table1(in a new/next line)\nI want similar to\n\n\n`content1`\n`table1`\n`content2`\n`table2`\n\n\nIn mail it is sending as\n\n\n`content1`\n`table1` `content2`\n`table2`\n\n\nI tried using <br \\>. Since my number of rows in table are dynamic we could maintain it with using a row counter by appending No. of <br />'s for number of rows in table1(i.e., If I have 5 rows in table 1, I will append 5 <br />'s) I would like to know if there is any better solution\n\nSolution:\nPreviously, I am using <table align='left'>, It is indirectly affecting <table> as float:left. Now my <br /> tag is working as expected after i remove align\n\nPic1\n\nPic2" ]
[ "php", "html", "email", "phpmailer" ]
[ "Scrapy: Images Pipeline, download images", "Following: scrapy's tutorial i made a simple image crawler (scrapes images of Bugattis). Which is illustrated below in EXAMPLE.\n\nHowever, following the guide has left me with a non functioning crawler! It finds all of the urls but it does not download the images.\n\nI found a duck tape solution: replace ITEM_PIPELINES and IMAGES_STORE such that;\n\nITEM_PIPELINES['scrapy.pipeline.images.FilesPipeline'] = 1 and \n\nIMAGES_STORE -> FILES_STORE\n\nBut I do not know why this works? I would like to use the ImagePipeline as documented by scrapy.\n\nEXAMPLE\n\nsettings.py\n\nBOT_NAME = 'imagespider'\nSPIDER_MODULES = ['imagespider.spiders']\nNEWSPIDER_MODULE = 'imagespider.spiders'\nITEM_PIPELINES = {\n 'scrapy.pipelines.images.ImagesPipeline': 1,\n}\nIMAGES_STORE = \"/home/user/Desktop/imagespider/output\"\n\n\nitems.py\n\nimport scrapy\n\nclass ImageItem(scrapy.Item):\n file_urls = scrapy.Field()\n files = scrapy.Field()\n\n\nimagespider.py\n\nfrom imagespider.items import ImageItem\nimport scrapy\n\n\nclass ImageSpider(scrapy.Spider):\n name = \"imagespider\"\n\n start_urls = (\n \"https://www.find.com/search=bugatti+veyron\",\n )\n\n def parse(self, response):\n for elem in response.xpath(\"//img\"):\n img_url = elem.xpath(\"@src\").extract_first()\n yield ImageItem(file_urls=[img_url])" ]
[ "python", "scrapy", "scrapy-spider", "scraper" ]
[ "How to remove and addArrangedSubvew without view blinking?", "I have some view that consists from one stackview. Every n second I should update this view with data from server. When the new data come, I clean stackView (with method removeFromSuperView of its children) and add arrangedSubviews again to update UI. Sometimes, server sends the same data as old data. But doing this update operation, my view is kinda shuddering. Its kinda dragging and shuddering every time I clean and add views to my stackview. Of course, I can only update my UI if oldData != newData. But this competition is difficult and hard to find correctly. So, how to update stackview with new data without shuddering and blinking?\nHere is my code:\nfunc configure(_ items: [Item]) {\n stackView.arrangedSubviews.forEach { $0.removeFromSuperview() }\n items.forEach { \n let someView = SomeView()\n someView.configure($0)\n stackView.addArrangedSubview(someView)\n }\n}" ]
[ "ios", "swift", "uiview", "uistackview" ]
[ "Generalized sum-function", "I'm new to C# and looking for a smart way to reduce redundancy in my code. \n\n public double sumx()\n {\n double temp = 0;\n foreach (var item in col)\n {\n temp= temp + item.x;\n }\n return temp;\n }\n public double sumy()\n {\n double temp = 0;\n foreach (var item in col)\n {\n temp = temp + item.y;\n }\n return temp;\n }\n\n\ncol is of type List< Point > and Point is a class by my own, which provides two properties (x and y) and an constructor Point(x,y).\n\nI want now the sum of all x, respectively sum of all y.\n\nI'm looking for a more generalized sum function, which maybe uses delegates or Lambda expressions. I have no Idea how to do this in a smart c# way.\n\nThanks in advance" ]
[ "c#" ]
[ "gradle task inputs are polluted", "I'm trying to create a task to build gwt modules. The compilation does work, but i have the problem with task inputs/ouputs. The task is being executed even when it shouldn't be, like when i change files outside the input folders.\nI created a task to get the information about tasks' inputs/outputs, and it showed that there are some 'implicit' inputs that affects on the task up-to-dateness. (like src/main/java and src/main/resources)\n\nhere are the gists of my build.gradle and taskInfo task output\n\nhttps://gist.github.com/demoth/7007823\n\nthe task i'm concerned about is gwtshared and gwtgwtgradle (line 63 and 80 in the second file).\n\nSomehow i need to remove the src/main/java and src/main/resources inputs." ]
[ "gwt", "gradle" ]
[ "Is SecureRandom weaken when seed with Random?", "Could a seed from java.util.Random for java.security.SecureRandom weaken the cryptographically strong random number generator?\nI saw this code and wonder why this is done in that specific way.\nrandomGenerator = new SecureRandom();\nfinal Random rnd = new Random();\nrandomGenerator.setSeed(rnd.nextLong());\n\nFrom the documentation, the call of setSeed will never reduce randomness. So why is setSeed called anyway?\n\npublic void setSeed(long seed)\nReseeds this random object, using the eight bytes contained in the given long seed. The given seed supplements, rather than replaces, the existing seed. Thus, repeated calls are guaranteed never to reduce randomness.\ndocs.oracle.com" ]
[ "java", "random", "cryptography" ]
[ "What is Scala's cheapest type?", "I need to use a type (any type) as a marker in an implicit as a type parameter, to distinguish it from another implicit. It's weird, but this may be another question.\n\nSince I can use any type, I was thinking of using the cheapest one, in terms of memory footprint and initialization time. It may not affect performance too much in this case, but the question is interesting: Which one is Scala's cheapest type?\n\nIn Java, the answer is obviously java.lang.Object. But Scala has a few \"interesting\" types: Any, AnyVal types, and bottom types with possible optimizations around them. The Nothing type cannot be instantiated, so it is excluded from this comparison." ]
[ "scala", "types" ]
[ "In SQL, how to switching rows to column on dynamic results?", "I had an interview where the question asked me to list people's names but in 1 row instead of the column 'Names'. Ahead of time you wouldn't know how many names will return. I know for static transposing like months you can just do case when 12 times. However for dynamic scenarios like this, short of SQLserver with a handy PIVOT. How would one go about doing this without knowing how many columns it will be ahead of time in a regular interview whiteboard?\nThanks!" ]
[ "sql" ]
[ "Retrieve all the items from a table where the text of a table column is contained in a list of items (ASP.NET Core 2.2 C# LINQ)", "I have a table called strategies which contains a number of Coping Strategies:\n\n[\n {\n \"id\": 6,\n \"title\": \"Coping with Depression\",\n \"description\": \"A coping strategy for depression. A description of the coping strategy. \\r\\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\",\n \"topic\": \"depression\"\n },\n {\n \"id\": 18,\n \"title\": \"Coping with Stress\",\n \"description\": \"A coping strategy for stress. A description of the coping strategy. \\r\\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.\",\n \"topic\": \"stress\"\n }\n]\n\n\nOne of the columns in that table, called Topic, can contain multiple Topic strings, e.g., \"stress depression\", etc. The sample data, above, illustrates the scenario that works, where there is only one Topic string in the Topic column.\n\nMy code is as follows:\n\nvar listOfTerms = new List<string>() { \"stress\", \"depression\" };\n\nvar strategies = _context.Strategies\n .Where(strategy => listOfTerms.Any(t => t.Equals(strategy.Topic)))\n .ToListAsync();\n\n\nI have also tried:\n\nvar strategies = _context.Strategies\n .Where(strategy => listOfTerms.Any(t => t.ToLower().Contains(strategy.Topic.ToLower())))\n .ToListAsync();\n\n\nThis code works for the scenario illustrated above, i.e., only one Topic string in the Topic column.\n\nIf I were to add the Topic string 'stress' to the Topic column of Scenario id = 6 then that row would not be returned in the list of strategies.\n\nSo, in summary, I want to retrieve all the items from _context.Strategies table where the text of the strategy.Topic column is contained in the text of an item in listOfTerms, were the text of the strategy.Topic column can contain more than one Topic string.\n\nAny help would be greatly appreciated.\n\nThanks." ]
[ "c#", "linq" ]
[ "Assigning variable value to textbox on next userform", "I am setting up a userform to capture new client data. Each client is assigned a client ID (number) next to which the input data is saved in an excel sheet. A new userform with an estimate design summary is opened once the first userform is completed.\n\nI want to save the assigned client ID number in die first userform to a textbox on the second userform, but a type mismatch error keeps popping up. On debugging it shows that the value assigned to the variable is not carried over to the textbox.\n\n(The same code worked previously on these same userforms and still works on later userforms\n\nPrivate Sub Continue1_Click()\n\n'Determine empty row\n\nDim emptyRow As Long\nSheet5.Activate\n\nemptyRow = WorksheetFunction.CountA(Range(\"B:B\")) + 1\n\n'Transfer userform data to spreadsheet\n\nCells(emptyRow, 2).Value = CName.Value\nCells(emptyRow, 3).Value = Business.Value\nCells(emptyRow, 4).Value = Region.Value\nCells(emptyRow, 5).Value = Email.Value\nCells(emptyRow, 6).Value = CNumber.Value\nCells(emptyRow, 7).Value = WSource.Value\nCells(emptyRow, 8).Value = Flow.Value\nCells(emptyRow, 9).Value = Pressure.Value\nCells(emptyRow, 10).Value = Irrigation.Value\n\n'Load Design Estimation userform\n\nDesignEst.Client_ID.Value = emptyRow - 1\nUnload Me\nDesignEst.Show\n\nEnd Sub\n\n\nIf emptyRow has a value of 5 this value has to be assigned to the Client_ID textbox on the DesignEst userform but currently it yields:\n\nDesignEst.Client_ID.Value = \"\"\n\n\ninstead of:\n\nDesignEst.Client_ID.Value = \"5\"" ]
[ "excel", "vba", "userform" ]
[ "How to make css reverse animation?", "I want to animate a DIV element and change it's background and text color. Then change it back to original colors. So CSS below sets background green and text color white. How do I animate switching colors back, e.g. white background and black text? So first 2 seconds it's changing to green/white and next 2 seconds white/black.\n\n.myClass {\n background-color: #4caf50;\n -webkit-animation-name: anim1; /* Safari 4.0 - 8.0 */\n -webkit-animation-duration: 2s; /* Safari 4.0 - 8.0 */\n animation-name: anim1;\n animation-duration: 2s;\n color: white;\n font-weight: bold;\n}\n\n@-webkit-keyframes anim1 {\n from {background-color: white;}\n to {background-color: #4caf50;}\n}\n\n@keyframes anim1 {\n from {background-color: white;}\n to {background-color: #4caf50;}\n}" ]
[ "css" ]
[ "iOS- Add keychain item to safari for HTTP-Authentication", "Is it possibe to add keychain items to safari within my app so that it will automatically use the information in the keychain item to pass a Basic Authentication challenge?\n\nMy problem at the moment is that I try to install an app with itms-services and [[UIApplication sharedApplication] openUrl:] and the ipa is secured with basic authentication. So when I try to install the app I get a challenge. But I don´t want the user to type in the credentials. I want safari to automatically do this instead.\n\nI already looked at MCSMInternetKeychainItem but I am not really sure if it can help me here." ]
[ "ios", "objective-c", "safari" ]
[ "Adding transition to a different property", "I have an element with two classes:\n\n<div class=\"class1 class2\"></div>\n\n.class1 {transition: background-color 0.4s;}\n.class2 {transition: top 1s;}\n\n\nThe problem is that the transition of class2 overwrites the transition of class1.\n\nI can't use .class2 {transition: all 1s} because the transition duration must be different.\n\nI also don't want to duplicate the code from class1 to class2 because class2 can be applied to other elements as well.\n\nIs there a way to add transitions to an element without overwriting existing ones?" ]
[ "css", "css-transitions" ]
[ "Algorithm for generating a random grid for materialUI with rows that add up to 3 columns", "I am building a React application working with the reddit api and oAuth.\n\nI am using MaterialUI, and I am attempting to use the Component to construct a 3 column grid of images that have dynamically generated column width values, max obviously being 3.\n\nThe first item in the array of fetched image posts will be given a key/value pair of a random number between 1 and 3. The second item will be given a key/value pair of a number completing the row, if the first item's value is != 3.\n\nThen, it will start over again, the idea being that every time the grid loads, its first item might be 1 column wide, 2 columns wide, or the whole row of 3 columns wide, and the algorithm is supposed to complete the rest of the grid accordingly, meaning the rows all must add up to 3.\n\nI have tried processing the array of posts in numerous ways, from assigning values to the first two objects in the array outside of a loop, then defining a 'last post' and 'post before that' variable to try to figure out a way to make the rows add up. I've tried to come up with a set of rules that would make this work regardless of array position, but cannot seem to come to an answer that doesn't have a few edge cases.\n\nmakeTiles() {\n let posts = this.props.posts;\n let postsWithCols = [];\n posts[0].cols = Math.floor(Math.random() * 3 + 1);\n console.log(posts[0])\n postsWithCols.push(posts[0]);\n let previousPost = postsWithCols[postsWithCols.length - 1];\n switch(previousPost.cols) {\n case 1: \n console.log('is1');\n posts[1].cols = Math.floor(Math.random() * 2 + 1);\n postsWithCols.push(posts[1]);\n break;\n case 2: \n console.log('is2');\n posts[1].cols = 1;\n postsWithCols.push(posts[1]);\n break;\n case 3: \n console.log('is3');\n posts[1].cols = Math.floor(Math.random() * 3 + 1);\n postsWithCols.push(posts[1]);\n break;\n default:\n console.log('something went wrong');\n break;\n }\n let postBeforeThat = postsWithCols[postsWithCols.length - 2];\n console.log(previousPost)\n console.log(postBeforeThat)\n console.log(postsWithCols)\n }\n render() {\n this.makeTiles();\n return (\n <div>\n open grid when i can get tileData figured out.\n {/* <ImageGrid tileData={this.makeTiles()} {...this.props}/> */}\n </div>\n );\n }\n}\n\n\nThe only way I have ever had this kind of work, it kept alternating between 1 and 2 after the first initial tile." ]
[ "javascript", "material-ui" ]
[ "JSP and Servlet life cycle method", "If JSP turns into a Servlet why there are different life cycle methods for example jspInit() and init() ?" ]
[ "java", "jsp", "servlets" ]
[ ".... undeclared (first use in this function)?", "I have a simple code in lex language and i generate lex.yy.c with Flex.\nwhen i want to compile lex.yy.c to .exe file i get some error like \"undeclared (first use in this function) \" ! when i search in web i understand i need a Const.h file, so i want to generate that file. \nhow i can do this ?\n\nSome Errors:\n\n35 C:\\Users\\Majid\\Desktop\\win\\lex.l STRING' undeclared (first use in this function) \n38 C:\\Users\\Majid\\Desktop\\win\\lex.lLC' undeclared (first use in this function) \n39 C:\\Users\\Majid\\Desktop\\win\\lex.l `LP' undeclared (first use in this function) \n....\n\nBeginnig of The Code is :\n\n%{int stk[20],stk1[20];\nint lbl=0,wlbl=0;\nint lineno=0;\nint pcount=1;\nint lcount=0,wlcount=0;\nint token=100;\nint dtype=0;\nint count=0;\nint fexe=0;\nchar c,str[20],str1[10],idename[10];\nchar a[100];\nvoid eatcom();\nvoid eatWS();\nint set(int);\nvoid check(char);\nvoid checkop();\nint chfunction(char *);%}\n\n Digit [0-9]\n Letter [a-zA-Z]\nID {letter}({letter}|{digit})*\nNUM {digit}+\n Delim [ \\t]\n A [A-Za-z]]\n%%\n\n\n\n \"/*\" eatcom();\n \"//\"(.)*\n \\\"(\\\\.|[^\\\"])*\\\" return (STRING);\n \\\"(\\\\.|[^\\\"])*\\n printf(\"Adding missing \\\" to sting constant\");\n\n \"{\" {a[count++]='{';fexe=0;eatWS();return LC;}\n \"(\" {a[count++]='(';eatWS();return LP;}\n \"[\" {a[count++]='[';eatWS();return LB;}\n \"}\" {check('{');eatWS();\n if(cflag)\n {\n //stk[lbl++]=lcount++;\n fprintf(fc,\"lbl%d:\\n\",stk[--lbl]);\n //stk[lbl++]=lcount++;\n printf(\"%d\\n\",stk[lbl]);\n cflag=0;\n }\n return RC;\n }\n \"]\" {check('[');eatWS();return RB;}\n \")\" {check('(');eatWS();return RP;}\n \"++\" | \"--\" return INCOP;\n [~!] return UNOP;\n \"*\" {eatWS();return STAR;}\n [/%] {eatWS();return DIVOP;}\n \"+\" {eatWS();return PLUS;}\n \"-\" {eatWS();return MINUS;}" ]
[ "lex", "flex-lexer" ]
[ "Marker doesn't show in maps api V3", "Why does my marker not appear?\nI also tried without the line \"marker.show\", but the marker just seems not to appear.\n\n<html><head><meta name=\"viewport\" content=\"initial-scale=1.0, user-scalable=no\" />\n<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\"/>\n<title>Google Maps JavaScript API v3 Example: Custom Control</title>\n<script type=\"text/javascript\" src=\"https://maps.google.com/maps/api/js?sensor=false\"> </script>\n<script type=\"text/javascript\" src=\"ZoomPanControl.js\"></script>\n<script type=\"text/javascript\">\nfunction initialize() { \n var myOptions = { \n zoom: 10, \n center: new google.maps.LatLng(47.3732589, 8.2382168), \n mapTypeId: google.maps.MapTypeId.ROADMAP, \n navigationControl: true } \n var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions); \n var marker = new google.maps.Marker({ position: google.maps.LatLng(47.3732589, 8.2382168), title: 'x', map:map}); \n marker.show; \n};\n</script></head> \n<body style=\"margin:0px; padding:0px;\" onload=\"initialize()\"> \n<div id=\"map_canvas\" style=\"width:100%; height:100%\"></div> \n</body></html>" ]
[ "javascript", "google-maps", "google-maps-markers" ]
[ "Wrapping anchor elements with text", "If an anchor element has text (and only text), but is not part of a larger block of text, does it matter (e.g. semantics, SEO, maintenance) whether or not that anchor tag is wrapped by a paragraph element? \n\n<!-- Wrapped -->\n<p><a href=''>Link Description</a></p>\n\n<!-- Standard -->\n<a href=''>Link Description</a>\n\n\nLooking at large websites, both ways appear to be popular. But are there any notable differences?" ]
[ "html", "seo", "anchor", "semantic-markup" ]
[ "How do you remove the default hypertext color when reloading a page using a CSS transition?", "I was making a transition for these navigation buttons that makes the padding 5px more with a shadow, it works. However, whenever the page gets reloaded the text is blue for .5 seconds (text when reloading) which happens to be the same time it takes for the buttons to get its padding and shadow. Is there a way I can make the text remain white (text .5 seconds after a reload) when reloading?" ]
[ "css" ]
[ "Chef cookbooks asking for windows and Mac dependencies for Linux box", "I assume this is something really stupid I'm not doing but can't seem to find the answer. \n\nI'm using chef with the default precise32 vagrant box\n\nEDIT: To clarify, I'm asking is there somewhere I can set the platform so that cookbooks and make dependency decisions. \n\nThanks" ]
[ "chef-infra", "vagrant" ]
[ "how can i implement popup on leaflet wms layer from geoserver", "i want to display popup for a layer on my map this layer is from geoserver wms \n\nmap.addEventListener(\"click\", onMapClick);\npopup_layer= new L.Popup({maxwidth:700});\nwms_server='http://localhost:8080/geoserver/wms';\n\n\nfunction onMapClick(e) {\n var BBOX=map.getBounds().toBBoxString();\n var WIDTH=map.getSize().x;\n var HEIGHT=map.getSize().y;\n var X=map.layerPointToContainerPoint(e.LayerPoint).x;\n var Y=map.layerPointToContainerPoint(e.LayerPoint).y;\n var URL=wms_server+'wms?service=WMS&version=1.1.0&request=GetMap&layers=abhbc%3Avw_ires&bbox='+BBOX+'&width=330&height=768&srs=EPSG%3A26191&format=application/openlayers';\n $.ajax({\n url: URL,\n datatype:\"html\",\n type:GET,\n success: function (data) {\n var popup= new L.popup({maxwidth:300})\n popup.setcontent(data)\n popup.setlatlng(e.latlng);\n map.openPopup(popup);\n },\n });\n}\n\n\nthis is a code that i tried but it does not work" ]
[ "popup", "leaflet", "geoserver" ]
[ "How a garbage value is assigned in c/c++", "In C++/C if we don't initialize a variable, it will have some garbage values right? I would like to know from where these values are coming? Is it assigned by the compiler? Does this value have range? Is it the previous value present in the memory allocated to that variable? If yes can 5 or 500 be a garbage value? \n\nThis is not for any coding purpose, I just what to know it for learning." ]
[ "c++", "c" ]
[ "Connection to Oracle works through a console application and doesn't work through a web service", "I can't connect to an Oracle schema through a asmx web service instead of I can through a console application [x86].\n\nThe code:\n\nvar conn = new OracleConnection(\"Data Source=xe;User ID=mySchema;Password=myPass\");\n\n\nThe exception:\n\nORA-12154: TNS:could not resolve the connect identifier specified\n\n\nThe environment: Windows 7 x64 - VS 2008.\n\nAny idea?\n\nkindly ask me for any extra information\n\nThanks in advance." ]
[ "c#", ".net", "oracle", "connection", "oracleclient" ]
[ "How to call a function within the same controller", "How to call a function within the same controller in Angular 2, because this gives me an error:\n\ninitialiseWeight(){\n this.storage.ready().then(() => {\n return this.storage.get('weightunit');\n })\n .then(retrievedUnit => {\n if (retrievedUnit) {\n this.data.weightunit = retrievedUnit;\n } else {\n this.data.weightunit = 'kg';\n this.storage.set('weightunit', this.data.weightunit);\n }\n })\n .catch(e => console.error('ERROR: could not read Storage Weight, error:', e));\n\n this.storage.ready().then(() => {\n return this.storage.get('realWeight');\n })\n .then(retrievedRealWeight => {\n if (retrievedRealWeight && retrievedRealWeight!== \"0\" ) {\n this.data.realWeight = parseInt(retrievedRealWeight, 10);\n this.storage.get('userWeight').then((value) => {\n this.data.userWeight = parseInt(value, 10);\n });\n if ( (this.data.realWeight * 1.02 < this.data.userWeight) && (!this.data.isWetsuit) ) {\n this.data.userWeight = this.data.realWeight;\n this.storage.set('userWeight', this.data.userWeight);\n }\n } else {\n this.data.realWeight = 70;\n this.data.userWeight = 70;\n this.storage.set('realWeight', this.data.realWeight);\n this.storage.set('userWeight', this.data.userWeight);\n }\n })\n .catch(e => console.error('ERROR: could not read Storage Weight, error:', e));\n}\nthis.initialiseWeight();" ]
[ "angular", "typescript", "ionic2" ]
[ "Get last executed time and name for SQL Server users functions", "I need to log SQL Server user-defined functions (Progammability/functions) and stored procedure calls (name of function/SP and last execution time). \n\nFor stored procedures, I use extended events (Session -> EVENT sqlserver.sp_statement_completed). \n\nIs it possible to use same approach for functions?" ]
[ "sql-server", "function", "stored-procedures" ]
[ "java multithreading for incrementing and decrementing score", "Working on a class assignment and I am struggling getting through it. \n\nThis needs to be thread safe and implement runnable. \n\nI need to create 2 score objects that are initialized to a unique ID and an initial score of 100. Then need to create 20 threads and assign 5 threads to the incrementer and 5 threads to the decrementer of the first object and an additional 5 threads for each of the second object.\n\nclass ScoreRunnerDemo implements Runnable\n{\n\nprivate long id = 1;\nprivate double score = 100;\n\nThread t1;\n// Count()\n{\n t1 = new Thread(this, \"Runnable Thread\")\n System.out.println(\"created thread \" + t1);\n t1.start();\n}\n\npublic void run ()\n{\n try\n {\n for (int i = 0; i<5; i++) {\n\n\n System.out.println(\"Printing the count \" + i);\n Thread.sleep(100);\n }\n }\n catch (InterruptedException e)\n {\n System.out.println(\"first increment thread \n interrupted\");\n\n }\n System.out.println(\"t1 is over\");\n}\n}\n\npublic class ScoreRunner\n{\npublic static void main(String[] args) {\n //number of threads\n\n int n = 20;\n for (int i = 0; i < n; i++) {\n ScoreRunnerDemo object = new ScoreRunnerDemo();\n while (ScoreRunnerDemo.getScore < 200) {\n System.out.println(\"Thread: \" + \nThread.currentThread().getId() + \" Score: \" + ScoreRunner.());\n }\n }\n}\n\n\nplease assist as I am unsure of what more I need. \n\nThe Score class is as follows:\n\nimport java.text.DecimalFormat;\n\npublic class Score\n{\nprivate long id;\nprivate double score;\nprivate DecimalFormat df = new DecimalFormat(\"#,###.##\");\n\n/**Grade\n * @param id\n * @param score\n */\npublic Score(long id, double score)\n{\n this.id = id;\n this.score = score;\n}\n\n/** Method getId\n * @return\n */\npublic long getId()\n{\n return id;\n}\n\n/** Method setId\n * @param id\n */\npublic void setId(long id)\n{\n this.id = id;\n}\n\n/** Method getScore\n * @return\n */\npublic double getScore()\n{\n return score;\n}\n\n/** Method setScore\n * @param score\n */\npublic void setScore(double score)\n{\n this.score = score;\n}\n\npublic synchronized void updateScore(double change)\n{\n score += change;\n System.out.println(\"ID: \" + id + \"\\t\" + \" Score: \" + df.format(score));\n}\n\n/* (non-Javadoc)\n * @see java.lang.Object#toString()\n */\n@Override\npublic String toString()\n{\n return id + \"\\t\" + \"\\t\" + score;\n}\n\n\n}" ]
[ "java", "multithreading", "increment", "decrement" ]
[ "add_action functions the same as add_filter in wp core", "I've been learning WP plugin development and the tutorial that I was looking at said that Wordpress has two hooks, one being add_action and the other being add_filter. Then i searched within the core to learn more about it and i noticed that the add_action function returned an add_filter function. What is the point of using add_action if i can just use add_filter? Can someone explain this?\n\nI found it here: /wp-includes/plugin.php\n\nfunction add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1)\n{\n return add_filter($tag, $function_to_add, $priority, $accepted_args);\n}\n\n\nI had an action using admin_init to play with wordpress, i changed it to use add_filter instead and it worked without any problems. Isnt add_filter only used for string outputs while add_action uses hooks added throughout the wp core?" ]
[ "php", "wordpress" ]
[ "I cant make rest calls with react", "I am learning to use React at the moment, and I have a problem: I want react to work with my Java Spring Boot backend (Tomcat). React is running on port 3000 (default) and my Tomcat server on port 8080 (default). Now, when I make a REST call, I get the following error\n\nscript.js:13 GET http://localhost:8080/api/path?p=test net::ERR_CONNECTION_REFUSED\n\n\nMy rest call looks like:\n\nfetch('http://localhost:8080/api/path?p=test')\n .then(res => {\n console.log(res);\n });\n\n\nWhat do I make wrong? I do not really have an idea." ]
[ "rest", "reactjs", "spring-boot" ]
[ "Python freezing on unexpected CL output with subprocess module", "I am writing a script to get version numbers from command line programs by using their appropriate 'version' command line flag i.e. --version, -v etc. The program as a whole uses a regex to get just the actual version number from the text output and then compares it to various conditions of minimum required or maximum allowed version pulled from an xml conf file etc.\n\nThe script works perfectly until executing bzip2.\n\nFor most programs there is no issue with the following code:\n\nargs = 'cmd --version'\n\noutput = subprocess.getstatusoutput(args)\n\n\npretty cut and dry. However! If you try this with, say, bzip2 (and so far this is the only program I've had an issue with) ala 'bzip2 --version' python \"freezes\" and you must ctrl-C to break out with no output recorded of course.\n\nI've tried various variations such as going the long route i.e.:\n\nimport subprocess\nfrom subprocess import PIPE, STDOUT\n\nproc = subprocess.Popen(args, stdout=PIPE, stderr=STDOUT)\nwhile(True):\n code = proc.poll()\n if(code is not None):\n break\n line = proc.stdout.readline() # or even read()\n etc.\n\n\nRegardless of which method I use to extract the relevant text, Python always hangs after a certain point. I've tried .kill() at certain points to head off the locking event but to no avail.\n\nIt's just with bzip2 I think because for some reason it's still expecting input with the --version flag.\n\nAny thoughts?" ]
[ "xml", "python-3.x", "version", "subprocess", "bzip2" ]
[ "Can I sync a Zumero client to a public facing server with only an eval key?", "I'm guessing from this section that I need to have an activation key in order to sync to a public facing server but I can't find anything explicitly says that:\n\nhttp://zumero.com/faq/#createactivation" ]
[ "zumero" ]
[ "GoogleFinance formula to find previous historical trading day of a stock", "I have been searching for a solid formula to find stock prices of "previous trading days" of a large batch of historical dates.\nThe formula I started with:\n=googlefinance(A5, "close", B5-1)\n\nwhere A5 refers to a ticker, and B5 refers to a date in the past.\nI get #NA results for previous days that fall on weekends or holidays.\nI need a formula that will work reliably for 365 days per year, no matter the day of the week or number of non-trading days prior. I have tried something like this:\n=index(googlefinance(A5, "close", (B5-1)-2,2),2,2)\n\nThat formula works if the B5 date is the first trading day of the week, but not if it falls anywhere midweek.\nI tried using WORKDAY(B5,-1) in a few ways but I realize that function can only calculate a number of workdays, not produce a date.\nI need a formula that I do not have to edit and adjust cell by cell." ]
[ "google-sheets", "formula", "stock" ]
[ "How to use native platform icons for ToolBarItems in Xamarin.Forms (programmatically)?", "What I have:\n\nI have a Xamarin.Forms app with a ToolBar (ActionBar on Android, Navigation Bar on iOS). Within the ToolBar I have a ToolBarItem to delete something.\n\nWhat I want:\n\nFor the ToolBarItem mentioned above I want to use the native platform icons (f.e. a trash can).\n\nMy question:\n\nWhat is the proper way to achieve this? It seems that the only way to do this is to add and load separate png-files as described here. For Android this is not such a big deal I can officially download the icon files from Google's developer page. For iOS this is not possible." ]
[ "android-actionbar", "icons", "uinavigationbar", "toolbar", "xamarin.forms" ]
[ "How to break out of a loop depending on a CheckBox Checked value while the loop is running?", "Lets say I want to call a function repeatedly if the user selects a CheckBox named \"repeat\" but the calls to the function should stop as soon as the user 'unchecks' the CheckBox. \n\nI tried using the 'Checked', 'Click' and 'Tap' event of the CheckBox but once the loop starts, it does not sense any changes in the checkbox's state. \n\nI even tried using a loop inside another button's _Click method, but then that creates a lock on the Button's 'pressed' state.\n\nAny ideas/alternate suggestions?" ]
[ "silverlight", "windows-phone-7" ]
[ "Using Stripe with Devise", "On Lines 3 and 15 on the second code snippet my IDE, it says Stripe is not defined. When I run the website and fill out a paid subscription form it gives me an action controller error and points me to certain files which are included herein (line 12 on the first code snippet). \n\n\r\n\r\nclass User < ActiveRecord::Base\r\n # Include default devise modules. Others available are:\r\n # :confirmable, :lockable, :timeoutable and :omniauthable\r\n devise :database_authenticatable, :registerable,\r\n :recoverable, :rememberable, :trackable, :validatable\r\n \r\n belongs_to :plan\r\n attr_accessor :stripe_card_token\r\n \r\n def save_with_payment\r\n if valid?\r\n customer = Stripe::Customer.create(description: email, plan: plan_id, card: stripe_card_token)\r\n self.stripe_customer_token = customer.id\r\n save!\r\n end\r\n end\r\nend\r\n\r\n\r\n\n\n\r\n\r\n$(document).ready(function() {\r\n \r\n Stripe.setPublishableKey($('meta[name=\"stripe-key\"]').attr('content'));\r\n // Watch for a form submission:\r\n $(\"#form-submit-btn\").click(function(event) {\r\n event.preventDefault();\r\n $('input[type=submit]').prop('disabled', true);\r\n var error = false;\r\n var ccNum = $('#card_number').val(),\r\n cvcNum = $('#card_code').val(),\r\n expMonth = $('#card_month').val(),\r\n expYear = $('#card_year').val();\r\n if (!error) {\r\n // Get the Stripe token:\r\n Stripe.createToken({\r\n number: ccNum,\r\n cvc: cvcNum,\r\n exp_month: expMonth,\r\n exp_year: expYear\r\n }, stripeResponseHandler);\r\n }\r\n return false;\r\n }); // form submission\r\n function stripeResponseHandler(status, response) {\r\n // Get a reference to the form:\r\n var f = $(\"#new_user\");\r\n // Get the token from the response:\r\n var token = response.id;\r\n // Add the token to the form:\r\n f.append('<input type=\"hidden\" name=\"user[stripe_card_token]\" value=\"' + token + '\" />');\r\n // Submit the form:\r\n f.get(0).submit(); \r\n }\r\n});" ]
[ "javascript", "ruby-on-rails", "devise", "stripe-payments" ]
[ "How do I add a UIDatePicker to a TableViewCell?", "I have a tableViewCell in a TableView that gets big if you click on it and if you click it again it goes back to its original size. \n\nWhat I'd like it to do is, display a datePicker when its big but every time I try to simply add a datePicker in my code it is at the bottom of the tableView and not inside the big cell.\n\nThis is my code for adding the datePicker when the cell gets big.\n\n- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{\n\n if (indexPath.row == 0) {\n\n return 150.0;\n }\n else if ([self cellIsSelected:indexPath] && indexPath.row == 1 ){\n\n [_dateLabel removeFromSuperview]; //just the label of the cell\n\n // Add the picker\n UIDatePicker *pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 350, 200)];\n pickerView.datePickerMode = UIDatePickerModeDate;\n\n [_cell addSubview:pickerView];\n\n return kCellHeight * 4.0;\n\n }\n else if (![self cellIsSelected:indexPath]) {\n\n [_myPicker removeFromSuperview];\n }\n\n return kCellHeight;\n}\n\n\nHow do I add a UIDatePicker to a TableViewCell?" ]
[ "ios", "xcode", "uitableview", "datepicker", "xcode6" ]
[ "Difference between Window and ApplicationWindow in QML?", "https://doc.qt.io/qt-5/qml-qtquick-controls2-menubar.html\nMenuBar is supported in ApplicationWindow and not in Window.\nFollowing throws an error "Invalid property name: MenuBar"\nWindow\n{\n visible: true\n width: 280; height: 280\n\n menuBar: MenuBar {\n Menu {}\n }\n}\n\nwhereas following works:\nApplicationWindow\n{\n visible: true\n width: 280; height: 280\n\n menuBar: MenuBar {\n Menu {}\n }\n}\n\nIn the new Qt version 5.12, the default code uses Window and not ApplicationWindow.\nWhat is the difference between Window and ApplicationWindow? Which one should be used in which case?" ]
[ "qt", "qml", "qtquick2", "qt5.12" ]
[ "i want to compute the distance between two numpy histogram", "i'm creating an image processing program and i want to measure the wasserstein distance between two numpy histograms.\nthe two histogram are created with the function numpy.histogram\n\ni tried the wasserstein_distance from the scipy.stats package like this\n\nfrom scipy.stats import wasserstein_distance \nwasserstein_distance(histogram1,histogram2)\n\n\nbut it gives me that error\n\n\n ValueError: setting an array element with a sequence.\n\n\nthe complete code:\n\nfirst the function that calculate the distance:\n\n def f_dist( histogram1 ,histogram2):\n return wasserstein_distance(histogram1,histogram2)\n\n\nthan the function that calculate the mask for the histograme creation:\n\ndef prepare_mask(polygon, image,value):\n\"\"\"Returns binary mask based on input polygon presented as list of coordinates of vertices\nParams:\n polygon (list) - coordinates of polygon's vertices. Ex: [(x1,y1),(x2,y2),...] or [x1,y1,x2,y2,...]\n image (numpy array) - original image. Will be used to create mask of the same size. Shape (H, W, C).\nOutput:\n mask (numpy array) - boolean mask. Shape (H, W).\n\"\"\"\n# create an \"empty\" pre-mask with the same size as original image\nwidth = image.shape[1]\nheight = image.shape[0]\nmask = Image.new('L', (width, height),value )\n# Draw your mask based on polygon\nImageDraw.Draw(mask).polygon(polygon, outline=1, fill=abs(value-1))\n# Covert to np array\nmask = np.array(mask).astype(bool)\nreturn mask\n\n\nthan the function that creat the histogram\n\ndef compute_histogram(mask, image):\n\"\"\"Returns histogram for image region defined by mask for each channel\nParams:\n image (numpy array) - original image. Shape (H, W, C).\n mask (numpy array) - boolean mask. Shape (H, W).\nOutput:\n list of tuples, each tuple (each channel) contains 2 arrays: first - computed histogram, the second - bins.\n\n\"\"\"\n# Apply binary mask to your array, you will get array with shape (N, C)\nregion = image[mask]\n\nhist = np.histogram(region.ravel(), bins=256, range=[0, 255])\n\nreturn hist\n\n\nand now for the main fnction:\n\npoints=[(633, 312), (630, 351), (623, 389), (611, 426), (594, 462), (573, 495), (548, 525), (519, 552), (488, 575), (453, 594), (417, 608), (379, 618), (340, 623), (301, 623), (262, 618), (224, 608), (188, 594), (153, 575), (122, 552), (93, 525), (68, 495), (47, 462), (30, 426), (18, 389), (11, 351), (9, 311), (11, 272), (18, 234), (30, 197), (47, 161), (68, 128), (93, 98), (122, 71), (153, 48), (188, 29), (224, 15), (262, 5), (301, 0), (340, 0), (379, 5), (417, 15), (453, 29), (488, 48), (519, 71), (548, 98), (573, 128), (594, 161), (611, 197), (623, 234), (630, 272)]\nmask1 = prepare_mask(points, image_gray, 0)\nmask2 = prepare_mask(points, image_gray, 1)\nhistogram1 = compute_histogram(mask1, image_gray)\nhistogram2 = compute_histogram(mask2, image_gray)\ndist=f_dist(histogram1,histogram2)" ]
[ "python", "numpy", "opencv", "histogram", "distance" ]
[ "MongoDB: use createCodecProvider generically", "Instead of having one hard-coded line per case class\n\n val codecRegistry = fromRegistries(\n fromProviders(\n classOf[CaseClassNameGoesHere],\n ...\n ),\n ...\n )\n\n\nI would like to create a method that could create them instead.\n\nBoth\n\n def method[T] = {\n Macros.createCodecProvider[T]()\n }\n\n\nand\n\n def method[T: ClassTag] = {\n Macros.createCodecProvider[T]()\n }\n\n\n... give me scala.ScalaReflectionException: type T is not a class\n\nI would hope that the compiler could look at every invocation of this method and do its thing.\n\nIs there a way of accomplishing that? Solutions \"far away\" from this approach will still be accepted as long as I don't have to create that list of classOfs." ]
[ "mongodb", "scala", "generics", "typeclass", "codec" ]
[ "GetComponentInChildren with child index when there are multiple child objects", "How can I select from which child I want to get a component from using .GetComponentInChildren when I have multiple child objects?\n\nWith this code I get the MeshRenderer of the first child only.\n\n selectedObj.GetComponentInChildren<MeshRenderer>().material.SetColor(\"_EmissionColor\", Color.red);" ]
[ "c#", "unity3d" ]
[ "cuSPARSE library calls inside openACC routine", "Is it possible to call the cuSPARSE library from within the routine directive. I have a double for loop on the host that calls for cuSPARSE function that runs on GPU, I am assuming that putting the for loops on the device would help some with performance.\n\n for ( int j = 0; j < nxChunk; j++ )\n {\n for ( int i = 0; i < nyChunk; i++ )\n { \n #pragma acc parallel \n setDiag( eig );\n\n triDiagCusparse( dl, ds, du, tmpMGReal );\n\n }\n }\n\n\nThanks for the help." ]
[ "cuda", "gpu", "openacc" ]
[ "error (429) Too Many Requests while geocoding with geopy in Python", "I have a Pandas dataframe with ~20k rows, and I am trying to geocode by address column into lat/long coordinates.\n\nHow do I use time.sleep() or maybe other function to stop OSM Nominatim from Too Many Requests 429 error that I am getting now?\n\nHere's the code I use for this:\n\nfrom geopy.geocoders import Nominatim\nfrom geopy.distance import vincenty\n\ngeolocator = Nominatim()\ndf['coord'] = df['address'].apply(geolocator.geocode).apply(lambda x: (x.latitude, x.longitude))\ndf.head()\n\n\nThanks in advance!" ]
[ "python", "pandas", "geocoding", "geopy" ]
[ "Rascal: What is the difference between \"label\" and \"name\" in the Syntax Definition documentation?", "The SyntaxDefinition documentation page of Rascal has two sections, where one speaks about \"labels\" (starting with \"Each alternative of a syntax definition is defined by a list of Symbols.\"), the other about \"names\" (starting with \"Alternatives can be named or not.\"). For both items a list of effects are given that largely overlap, e.g. both enable the is operator, are necessary for imploding ParseTrees or for writing Action functions. The Syntax section at the top of the page only lists a Name component, and Tags but no labels.\n\nIs \"label\" an alternative term for \"name\"? And if so why do the lists of the effects using them differ?" ]
[ "rascal" ]
[ "WP Run periodictask every 5 minute", "I've made an WP app, that checks in-game events of Guild Wars two. Looking up, MSDN states that the task will be run every 30 minute. Thing is, at 30 minute, an event might already be over, is there away to make it run 5 minute, or an alternative?\n\nAll the task needs to do, it download some text from a webpage and display a notification if an event is due." ]
[ "c#", "windows-phone-7", "background-agents", "periodic-task" ]
[ "Use external library from controller of symfony2", "I would like to use php library in symfony2 Command.\nhttp://phpmidiparser.com/quickstart\n\nI put the library on the same folder of symfony2 but in vain.\n\nCommand/Midi/bootstrap.php\nCommand/myCommand.php\n\n\n\n$ php app/console top:myCommand\n\n \n syntax error, unexpected 'use' (T_USE) in error at use \\Midi\\Parsing\\FileParser;\n\n\nrequire_once 'Midi/bootstrap.php';\n\nuse \\Midi\\Parsing\\FileParser;\nuse \\Midi\\Reporting\\TextFormatter;\nuse \\Midi\\Reporting\\Printer;\n\n$parser = new FileParser();\n$parser->load('/path/to/midi/file.mid');\n\n$printer = new Printer(new TextFormatter(), $parser);\n$printer->printAll();\n\n\nI use this library only in Command ,so I don't need to register this on autoload.\n\nPlease teach me basic guideline of using external library, where should I put the library and how can I 'require'?" ]
[ "php", "symfony" ]
[ "xbindkeys: pressed key value in command?", "I am trying to configure a hotkey with xbindkeys.\nIs it possible to reference the pressed KeyValue in the hotkey-command?\nLike:\n\n# send hotkeyvalue to pipe\n\"echo $pressedkey >> /tmp/somepipe\"\n m:0x0 + c:75\n F9\n\n\nQ: What is interpreting the command?\n\nQ: And what variables are available?" ]
[ "linux" ]
[ "Can stylecop for jetbrains be run in visual studio 2017", "We used to write our code in visual studio 2013 with stylecop as a seperate plugin. When we wanted to check our code qualtiy we pressed ctrl+shift+y to run stylecop and get a log of infractions (if any)\n\nRecently we switched to visual studio 2017 with resharper and integrated stylecop by JetBrains. While stylecop is still running (blue lines underneath infractions) we can't seem to get a complete log with all our errors (and when building a solution stylecop isn't automatically run).\n\nI tried looking in tools -> Options -> environment -> Keyboard -> Show commands containing \"Stylecop\" (you used to find lots of settings in VS2013, none in 2017)\n\n\nIs it still possible to run stylecop like we did in VS2013?\nIs it possible to have stylecop run after a build is completed (in a post build event)?" ]
[ "development-environment", "visual-studio-2017", "stylecop" ]
[ "How to route a substring of a path and service without path in ingress", "I have three issues:\n1 - How can I correctly implement regex to match the first part of a path in ingress?\n- path: /^search_[0-9A-Z]{9}\n backend:\n serviceName: global-search-service\n servicePort: 5050\n\nI would like to match any path that begins with /search_ e.g /search_model or /search_make\n2 - How can I access a service with no path just port.\n path: \n pathType: Exact\n backend:\n serviceName: chart-display\n servicePort: 10000\n\nI am just displaying this service using iframe. How do I access it since I only have the port number?\n3 - I am hosting two different react apps, both of them work when I set their path as root / .. how do I implement both of them to work with root path?\nTrying issue 3.\nSo I come up with something like this right?\napiVersion: networking.k8s.io/v1beta1\nkind: Ingress\nmetadata:\n name: admin-ingress\n annotations:\n nginx.ingress.kubernetes.io/rewrite-target: /\nspec:\n rules:\n - http:\n paths:\n - path: /admin\n backend:\n serviceName: web2-service\n servicePort: 2000\n\n--- \n\napiVersion: networking.k8s.io/v1beta1\nkind: Ingress\nmetadata:\n name: normal-ingress\n annotations:\n kubernetes.io/ingress.class: nginx\n nginx.ingress.kubernetes.io/use-regex: "true"\nspec:\n rules:\n - http:\n paths:\n - path: /\n backend:\n serviceName: web1-service\n servicePort: 1000\n\nLoading <my-ip>/admin does not go to web2-service, and if i leave them both at / , it automatically goes to web1-service. Kindly advice" ]
[ "kubernetes", "kubernetes-ingress", "nginx-ingress" ]
[ "Difference between CRF and Fully Connected CRF?", "Can anyone explain me the difference between Conditional Random Fields and Fully Connected Conditional Random Fields for semantic segmentation?\nI only understand so far, that with CRF you try to use two kinds of information to improve the segmentation mask:\n\nPixel Intensity: A good guess for a edge between to classes is pixel intensity. So with this we can weight the edges of objects\nPixel proximity: For pixel close together, there is a high chance that they blong to the same class. With out this, we would interpret edges inside a object at instances of another class, e.g. backround.\n\nAre my assumptions right? Is this true for CRFs or Fully connected CRFs, or both?\nThanks!" ]
[ "machine-learning", "image-processing", "semantic-segmentation", "deeplab" ]
[ "How to center one item with flexbox in React Native?", "I have the following component in React Native:\n\n <View styleName=\"nav\">\n <Back />\n <Image styleName=\"logo\" style={{ alignItems: \"center\", alignSelf: \"center\", justifyContent: \"center\" }} source={Img} />\n </View>\n\n\nAs you can see, I am trying just about everything to center the logo, with no luck. Every example I am seeing for flexbox shows > 2 items.\n\nNav has the following styles:\n\n.nav {\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n width: 100%;\n height: 70;\n padding-top: 20;\n}\n\n\nLogo size is set:\n\n.logo {\n width: 100;\n height: 40;\n}\n\n\nRight now I am getting something like this:\n\n[<Back Logo]\n\n\nI want something like this:\n\n[<Back Logo ]" ]
[ "css", "reactjs", "react-native", "flexbox" ]
[ "Vertical stretch of a table, without moving its content", "despite the fact that I'm working on a project using Angular and angular material, the solution might be pure CSS.\n\nSo I have a table with very few elements in it 2 or 3 rows for the moment and I want it to be at a fixed height (let's say 700px). I tried setting the height of the table to 700px, BUT, the content of my table is stretching to fill it, so if I have two rows, they will have top and bottom padding to fille the table. therefore the total height of each of my two cells is 350px (if my table body is 700px).\n\nAnother problem I have is that angular material doesn't have vertical separators for each column. Therefore I have to set a border to my cells, but if my cells don't take all the height of the table, I don't have a full vertical line, it ends at my last row.\n\nI tried playing around with flex attributes but nothing worked.\n\nThis is basicaly what I have for the moment:\n\n<div id=\"main-table\">\n <div id=\"table-container\">\n <table id=\"master\" mat-table [dataSource]=\"projects\">\n\n <!-- Name Column -->\n <ng-container matColumnDef=\"name\">\n <th mat-header-cell *matHeaderCellDef> Name </th>\n <td mat-cell *matCellDef=\"let project\" class=\"py-0 px-0\">\n <button mat-button (click)=\"getVersionsList(project);\" class=\"cell-button\"> {{project.name}} </button>\n </td>\n </ng-container>\n\n <!-- Description Column -->\n <ng-container matColumnDef=\"description\">\n <th mat-header-cell *matHeaderCellDef> Description </th>\n <td mat-cell *matCellDef=\"let project\" class=\"py-0\"> {{project.description}} </td>\n </ng-container>\n\n <tr mat-header-row *matHeaderRowDef=\"displayedColumns\"></tr>\n <tr mat-row *matRowDef=\"let row; columns: displayedColumns;\"></tr>\n </table>\n </div>\n\n <!-- other stuff -->\n\n</div>\n\n\n .mat-header-cell, .mat-cell{\n padding: 12px;\n }\n .py-0 { // padding on Y axis 0\n padding-top: 0 !important;\n padding-bottom: 0 !important;\n }\n\n .px-0, .cell-button { // padding on X axis 0\n padding-left: 0 !important;\n padding-right: 0 !important;\n }\n\n .cell-button{\n width: 100%;\n padding: 6px 0;\n }\n\n .mat-row {\n height: auto;\n }\n\n .mat-cell{\n //padding-top: 16px;\n //padding-bottom: 16px;\n //border-right: rgba(0,0,0,.12) 1px solid;\n border-bottom: 0;\n }\n\n\nMy CSS is quite empty since nothing was working.\n\nThanks for helping." ]
[ "css", "angular-material" ]
[ "JestJS: Async test isn't stopped", "I got two problems with this jest test:\n\n\nIs it possible to define the Content collection only once instead of doing that inside of the test?\nI do get this error:\n\nJest did not exit one second after the test run has completed.\nThis usually means that there are asynchronous operations that weren't stopped in your tests. Consider running Jest with --detectOpenHandles to troubleshoot this issue.\n\n\nI don't see why my async code weren't stopped...\n\nimport resolvers from 'resolvers/'\nimport Db from 'lib/db'\nconst db = new Db()\n\ndescribe('Resolver', () => {\n let token\n\n beforeAll(async () => {\n await db.connect()\n })\n beforeEach(async () => {\n token = 'string'\n await db.dropDB()\n })\n afterAll(async () => {\n await db.connection.close()\n })\n\n describe('articleGetContent()', () => {\n test('should return dataset', async () => {\n // SETUP\n const Content = db.connection.collection('content')\n const docs = [{\n // some content...\n }]\n await Content.insertMany(docs)\n // EXECUTE\n const result = await resolvers.Query.articleGetContent({}, {\n id: '123,\n language: 'en'\n }, {\n token\n })\n // VERIFY\n expect.assertions(1)\n expect(result).toBeDefined()\n })\n })\n})\n\n\nresolver\n\nimport { articleGetContent } from '../models/article'\n\nexport default {\n Query: {\n articleGetContent: async (obj, { id }, { token }) => articleGetContent(id, token)\n }\n}\n\n\n\n\nThis is how my db class looks like\n\ndb.js\n\nexport default class Db {\n constructor (uri, callback) {\n const mongo = process.env.MONGO || 'mongodb://localhost:27017'\n this.mongodb = process.env.MONGO_DB || 'testing'\n this.gfs = null\n this.connection = MongoClient.connect(mongo, { useNewUrlParser: true })\n this.connected = false\n return this\n }\n\n async connect (msg) {\n if (!this.connected) {\n try {\n this.connection = await this.connection\n this.connection = this.connection.db(this.mongodb)\n this.gfs = new mongo.GridFSBucket(this.connection)\n this.connected = true\n } catch (err) {\n console.error('mongo connection error', err)\n }\n }\n return this\n }\n\n async disconnect () {\n if (this.connected) {\n try {\n this.connection = await this.connection.close()\n this.connected = false\n } catch (err) {\n console.error('mongo disconnection error', err)\n }\n }\n }\n\n async dropDB () {\n const Content = this.connection.collection('content')\n await Content.deleteMany({})\n }\n}" ]
[ "javascript", "mongodb", "testing", "jestjs" ]
[ "Creating stacked chart in Altair with multiple axes and gaps", "I am trying to create a chart depicting two different processes on the same timescale in Altair. Here is an example in excel\n\nI have generated the stacked horizontal bar chart below in excel using the following data. The numbers in red are offsets/gaps, not to be displayed in the final plot. Nothing special about these numbers, please feel free to use any other set of numbers.\n\nThe numbers in red are offsets and\nI would have posted an attempt, but I am completely out of my depth guessing what functionality to begin with. Any help would be greatly appreciated." ]
[ "python", "data-visualization", "altair" ]
[ "Stream saver cancel/abort download on User Event", "I am using streamsaver.js to download larger files and it works perfectly fine.\nIn the meantime, I want to handle cancel events from the user to stop fetching the content from the server.\nIs it possible with AbortController and AbortSignal to stop readable streams fetching data?\nThe sample code would be below for the download part.\nfetch(url, { signal: abortSignal })\n .then(resp => {\n for (var pair of resp.headers.entries()) {\n console.log(pair[0] + ': ' + pair[1]);\n }\n total = Number(resp.headers.get('X-zowe-filesize'));\n return resp.body;\n })\n .then(res => {\n\n var progress = new TransformStream({\n transform(chunk, controller) {\n loaded += chunk.length;\n controller.enqueue(chunk);\n elem.style.width = (loaded / total) * 100 + '%';\n elem.innerHTML = (loaded / total) * 100 + '%';\n }\n })\n\n const readableStream = res\n // more optimized\n if (window.WritableStream && readableStream.pipeTo) {\n return readableStream\n .pipeThrough(progress)\n .pipeTo(fileStream, { signal: abortSignal })\n .then(() => console.log('done writing'))\n }\n\n window.writer = fileStream.getWriter()\n\n const reader = readableStream.getReader()\n const pump = () => reader.read()\n .then(res => res.done\n ? writer.close()\n : writer.write(res.value).then(pump))\n\n pump()\n })" ]
[ "javascript", "download", "fetch", "large-files" ]
[ "Accidentally deleted my htaccess file on cpanel", "I accidentally deleted htaccess file. \n\nI downloaded it before I did so and then afterwards I re-uploaded it to my public_html folder, but I can't get to the WP login anymore. It just gives me a 404 error. \n\nWhy doesn't it start working when I just re-upload?" ]
[ "wordpress", ".htaccess", "cpanel" ]
[ "dataimporthandler does not distribute documents on solr cloud", "we solr cloud with 4 shards and when we try to import the data using dataimporthandler, it does not distribute documents in all 4 shards." ]
[ "solr", "solrcloud" ]
[ "Dictionary with nested list TypeError: string indices must be integers", "My json response come back with this dictionary.\n\ndata = {\"offset\": 0, \"per-page\": 1, \"total\": 548, \"language\": \"en\", \n\"odds-type\": \"DECIMAL\", \"overall-staked-amount\": 23428.63548, \n\"profit-and-loss\": 4439.61471, \"events\": [{\"id\": 1042867904480016, \n\"name\": \"Gael Monfils vs Daniil Medvedev\", \"sport-id\": 9, \"sport- \nurl\": \"tennis\", \"sport-name\": \"Tennis\", \"start-time\": \"2019-02- \n16T14:29:00.000Z\", \"finished-dead-heat\": false, \"markets\": [{\"id\": \n1042867905130015, \"name\": \"Moneyline\", \"commission\": 0, \"net-win- \ncommission\": 0, \"profit-and-loss\": -0.59999, \"stake\": 0.59999, \n\"selections\": [{\"id\": \"1042867905220015_BACK\", \"runner-id\": \n1042867905220015, \"name\": \"Daniil Medvedev\", \"side\": \"BACK\", \"odds\": \n3.0, \"stake\": 0.59999, \"commission\": 0, \"profit-and-loss\": -0.59999, \n\"bets\": [{\"id\": 1043769075060320, \"offer-id\": 1043764555430020, \n\"matched-time\": \"2019-02-16T16:16:18.936Z\", \"settled-time\": \"2019- \n02-16T16:26:01.878Z\", \"in-play\": true, \"odds\": 3.0, \"stake\": \n0.59999, \"commission\": 0, \"commission-rate\": 2.0, \"profit-and-loss\": \n-0.59999, \"status\": \"PAID\"}]}], \"net-win-commission-rate\": 0.02}]}]}\n\n\nI am unable to get the attribute value for overall-staked-amount and inside the events list I cannot get name from events list. using list comprehension or a for loop.\n\nHere's my code.\n\nlist comp\n\noverall_staked = [d['overall-staked-amount'] for d in data]\n\nprint(overall_staked)\n\n\nfor loop\n\nfor d in data:\n overall_staked = d['overall-staked-amount']\n name = d['name']\n print(overall_staked,name)\n\n\nI receive an error TypeError: string indices must be integers\nwhat am I doing wrong or need to do?" ]
[ "python", "json", "django", "dictionary" ]
[ "Call to a member function format() on a non-object in Symfony2 (Doctrine)", "I have the some bug in my controller.\n\nI'd config the entity by this config:\n\npv\\MyBundle\\Entity\\NewsAuthorHistory:\n type: entity\n table: news_authors_history\n fields:\n id:\n id: true\n type: integer\n unsigned: false\n nullable: false\n column: id\n generator:\n strategy: AUTO\n date:\n type: datetime\n nullable: true\n column: date\n author_id:\n type: integer\n unsigned: true\n column: author_id\n nullable: false\n news_id:\n type: integer\n unsigned: true\n column: news_id\n nullable: false\n manyToOne:\n news:\n targetEntity: pv\\MyBundle\\Entity\\News\n joinColumn:\n name: news_id\n referencedColumnName: id\n author:\n targetEntity: pv\\MyBundle\\Entity\\Authors\n joinColumn:\n name: author_id\n referencedColumnName: id\n\n\nI have this code in my controller\n\n$history_event = new NewsAuthorHistory();\n$history_event->setAuthorId($author->getId());\n$history_event->setNewsId($news->getId());\n$history_event->setDate(\\DateTime('now'));\n\n$em->persist($history_event);\n$em->flush();\n\n\nBut, If I try to run this code, I have the the \n\n\n Fatal error: Call to a member function format() on a non-object in\n /vendor/doctrine/dbal/lib/Doctrine/DBAL/Types/DateTimeType.php on line\n 53\n\n\nI'd read a lot of posts about this error, but could not find a suitable solution for me.\n\nUPDATE:\nSome magic! O_o I added the following code to the file DateTimeType.php \n\nif (!method_exists($value, 'format')) {\n var_dump($value); \n var_dump(debug_backtrace()); \n} \n\n\nAnd here the magic begins… To the date field filled… with information about csrf-token. \nHow? Why? — I don't know… :(\n\nUnfortunately, I could not resolve the problem. I solved this problem by SQL-code generation and directing its implementation in the entity-manager." ]
[ "php", "symfony", "datetime", "doctrine-orm", "doctrine" ]
[ "TabbedPage on MonoAndroid", "I am using Microsoft Visual Studio 2017 Community and a physical device (Android 7.0 smartphone).\n\nI am looking for ways to launch a TabbedPage from MainActivity.cs. The project is not Cross Platform, just C# Android app on VS.\n\nPlease help. Thanks" ]
[ "c#", "visual-studio", "xamarin.android" ]
[ "How to limit by multiple categories(dynamically taken) in one SQL statement?", "Here is current SQL:\nhttp://www.copypastecode.com/22205/\n\nIt takes 70 new rows from table ads.\n\nBut it doesn't take proper amount(for example 5) of rows for each mr.region_id from joined table map_regions.\n\nFor example if I will add 50 ads in one region, it will take all 50 of them and leave 20 slots for the rest regions.\n\nPlease help me to upgrade current SQL, so it would take 5 rows from table ads for each mr.region_id in map_regions table." ]
[ "mysql", "limit" ]
[ "Entity with properties mapped on blob/text sql field", "I Have an entity (taht extends Drupal\\Core\\Entity\\ContentEntityBase). I try to map some property of this entity on blob or text mysql field.\n\nIn the documentation, I don't see wichh value I have to put in BaseFieldDefinition::create(VALUE ???).\n\nMaybe it's not possible ??" ]
[ "drupal-8" ]
[ "How do I merge these similar functions into one", "I've been trying to wrap my head around Javascript, been searching for a way to make this into one function that only affects the DOM element (which i also created with javascript through createElement) that is currently being hovered. I tried the .target and currentTarget stuff, didn work. If anyone could do as much as point me in the right direction I'd be eternally grateful!\n\n/* This first function is the experimental one, I tried this but to no avail */\nfunction displayTooltip1(tt) {\n var x = tt.currentTarget;\n x.style.cssText = \"width: 100px; height: 100px; display: inline-block; margin: 0;1.5px 0 1.5px; overflow: visible;\"\n}\n\nfunction displayTooltip2() {\n document.getElementById('image2').style.cssText = \"width: 100px; height: 100px; display: inline-block; margin: 0 1.5px 0 1.5px; overflow: visible;\";\n}\n\nfunction displayTooltip3() {\n document.getElementById('image3').style.cssText = \"width: 100px; height: 100px; display: inline-block; margin: 0 1.5px 0 1.5px; overflow: visible;\";\n}" ]
[ "javascript", "function", "refactoring" ]
[ "add pyqtgraph (plot) into QApplication", "hy,\n\nsoooo, i created the MainWindow.ui file with the QTDesigner. Then i import this gui with following command into my .py file:\n\nform_class = uic.loadUiType(\"ess_project.ui\")[0] \n\n\nWhat is the difference if i compile this .ui file with pyuic4 ?\n(every time i compiled my .ui file i got following error:\n\nRuntimeError: the sip module implements API v11.0 to v11.1 but the PyQt4.QtCore module requires API v10.1\n\n\nThe MainWindow create the first window, where all buttons etc. are placed.\n\nclass MainWindow(QtGui.QMainWindow, form_class):\n def __init__(self, parent=None):\n QtGui.QMainWindow.__init__(self, parent)\n PlotWindow.__init__(self)\n self.setupUi(self)\n self.pb_send.clicked.connect(self.pb_send_clicked)\n self.pb_open.clicked.connect(self.pb_open_clicked)\n self.pb_exit.clicked.connect(self.pb_exit_clicked)\n self.comboBox.currentIndexChanged.connect(self.combo_box_changed)\n\n\nfurthermore i have a second class named \"PlotWindow\". This class looks like this:\n\nclass PlotWindow(QtGui.QMainWindow):\n def __init__(self):\n QtGui.QMainWindow.__init__(self)\n self.w = QtGui.QMainWindow()\n self.cw = pg.GraphicsLayoutWidget()\n self.w.show()\n self.w.resize(900,600)\n self.w.setCentralWidget(self.cw)\n self.w.setWindowTitle('pyqtgraph: G-CODE')\n self.p = self.cw.addPlot(row=0, col=0)\n\n\nnow as you can see, the PloWindow - class create a second Window.\n\nHow can i implement the pg.GraphicsLayoutWidget() into the MainWindow - class ?? \n\nnot sure if this can help you ?!? :\n\ndef main():\n app = QtGui.QApplication([])\n myWindow = MainWindow(None)\n myWindow.show()\n app.exec_()\n\nif __name__ == '__main__':\n main()\n\n\nI am using python3 !!!\nfeel FREE to comment :)\nthanks !" ]
[ "python-3.x", "pyqt4", "pyqtgraph", "xubuntu" ]
[ "JQuery Handling events when elements are being generated at run time", "Disclaimer: I'm new to JQuery \n\nI don't know how to title this question but first my code is below\n\n$(document).on(\"click\" ,'[id^=\"picChangeAddress\"]', function() {\n $('div[id^=\"divAddressSet\"]').toggle();\n});\n\n\nPlease not that I have the same numbers of div's and checkboexes, each name format is same also such as checkboxes picChangeAddress1, picChangeAddress2 and so on, and div's divAddressSet1, divAddressSet2 and so on.\n\nI've used the above code because these id's are being generated at run time. There are few things i need to ask first when i click on one checkbox all it effects every div div[id^=\"divAddressSet\"] on the page and they all toggled when i click on any any of [id^=\"picChangeAddress\"] checkbox. I would like you to help me on how to only show or hide only one div at a time. \n\nAny Idea?" ]
[ "javascript", "php", "jquery", "html", "loops" ]
[ "android: how to access browser cookie from within app's webview", "let's say I visit some dedicated website www.mysite.com, that placed a cookie in my browser.\nlater, I want to use that cookie from within some app that opens a webview to the same website, so I can somehow correlate the activity that he user had done via the browser, and the activity he is now doing from within the native app's WebView.\n\nIs it possible to share cookies like that?" ]
[ "android", "cookies", "webview" ]
[ "Sending email via curl (smpt) in Docker Container", "I can receive email using following script locally. \n\nrtmp_url=\"smtp://smtp.xxx.com:25\"\nrtmp_from=\"[email protected]\"\nrtmp_to=\"[email protected]\"\n\nfile_upload=\"mail.txt\"\n\necho \"From: $rtmp_from\nTo: $rtmp_to\nSubject: example of mail\nCc:\nMIME-Version: 1.0\nContent-Type: multipart/mixed; boundary=\\\"MULTIPART-MIXED-BOUNDARY\\\"\n\n--MULTIPART-MIXED-BOUNDARY\nContent-Type: multipart/alternative; boundary=\\\"MULTIPART-ALTERNATIVE-BOUNDARY\\\"\n\n--MULTIPART-ALTERNATIVE-BOUNDARY\nContent-Type: text/plain; charset=utf-8\nContent-Disposition: inline\n\nThis is an email example. This is text/plain content inside the mail.\n--MULTIPART-ALTERNATIVE-BOUNDARY--\n--MULTIPART-MIXED-BOUNDARY\nContent-Type: application/octet-stream;\nContent-Transfer-Encoding: base64\nContent-Disposition: attachment; filename=\\\"logs.txt\\\"\" > ./mail.txt\n\ncat ./mail.txt | base64 >> ./mail.txt\n# end of uploaded file\necho \"--MULTIPART-MIXED-BOUNDARY--\" >> ./mail.txt\n\necho \"sending ....\"\n\ncurl --url 'smtp://smtp.xxx.com:25' --ssl-reqd --mail-from $rtmp_from --mail-rcpt $rtmp_to -T './mail.txt' --insecure\n\n\nBut I trying to run this script in docker container. I get this error in container : Failed connect to smtp.xxx.com:25; No route to host.\nIn my pc, I changed mailhub to smtp.xxx.com in /etc/ssmtp/ssmtp.conf and so it works locally. I am new to docker and don't know how can I achieve this in docker container. Please help." ]
[ "linux", "docker", "smtp", "openshift", "dockerfile" ]
[ "Angularjs slider, customValueToPosition not able work with range selection", "I am trying to use angularjs slider with for range selection and custom scaling.\n\nHere is the slider option object... \n\nvm.priceSlider = { \n min: 3, \n high: 10, \n options: { \n floor: 0, \n ceil: 3600, \n showTicksValues: true, \n step: 1, \n ticksArray: ticksArray, \n\n customValueToPosition: function(val, minVal, maxVal) { \n var pos = 1/16 * (ticksArray.indexOf(val)); \n if (positions.indexOf(pos) === -1){ \n positions.push(pos); \n } \n return pos; \n }, \n\n customPositionToValue: function(percent, minVal, maxVal) { \n var index = Math.round(percent * 16); \n\n var min = (ticksArray[index - 1]); \n var max = (ticksArray[index]); \n\n var minPos = positions[index -1]; \n var maxPos = positions[index]; \n\n var value = max - ((maxPos-percent)/(maxPos-minPos)) * (max - min); \n return Math.round(value); \n } \n } \n } \n\n\njsfiddle http://jsfiddle.net/cwhgLcjv/2527/\n\nThe issues I am facing are\n1) The slider pointer is not visible for in between values excluding ticks\n2) Not able to select the range properly\n\nApologies for bad formatting if any.." ]
[ "angularjs", "angularjs-3rd-party", "angularjs-slider" ]
[ "In second function x2() why return var pp only in second function?", "Can someone explain to me why the second function x2() needs to be returned second function f() to return our variable pp? Why not working only return pp after declare it?\n\n\r\n\r\nvar pp = 10;\r\n\r\nfunction x() {\r\n var pp = 20;\r\n return new Function('return pp;');\r\n}\r\n\r\nfunction x2() {\r\n var pp = 20;\r\n return function f() {\r\n return pp;\r\n }\r\n return f;\r\n}\r\n\r\nvar p1 = x();\r\nvar p2 = x2();\r\nconsole.log(p1());\r\nconsole.log(p2());" ]
[ "javascript", "closures" ]
[ "Post on a users wall on behalf of my app (not the user)", "For several years i have managed to sort things out without posting my own question, but by readings others instead. However, after reading over 200 useless posts, i've decided it's time i get some help.\n\nI'm building a facebook app, and what i wan't to do is extremelly simple to explain. I wan't to notify a certain user about some event in real-time. For example, \"the tv show you want to watch starts in an hour\". Unfortunately, facebook doesn't allow apps to send private messages to users (which was my first choice). The standard way of publishing on a users wall on HIS BEHALF is not good either, because no notification is triggered. Therefore, my idea is to post on his wall on behalf of the app (or any similar action that will trigger a notification).\n\nI know about app requests, but they are not what i'm looking for either, as you can see, they do not match what i want to do.\n\nAlso please note that the event may be particular for each user, so making a post or something for EVERYBODY to see is not an option (\"Peter, you have dinner with stacy in an hour\").\n\nFirstly, i want to know if posting on the apps behalf (or facebook page, or any other idea) is possible.\n\nIf it isn't, i would like to see any other ideas to sort this out. Remember, it's extremelly important to trigger the notification.\n\nThanks for your time reading this, but i have one last request. \n\nAlthough what i want to do is pretty simple, there are plenty of similar issues being disscused, which may lead to confusion, so please be SURE that you fully understood what i am asking before answering.\n\nThanks again" ]
[ "php", "facebook", "facebook-apps", "facebook-wall" ]
[ "Error invoking method, failed to launch jvm", "I'm developing a desktop application using javafx v8.0.40. I have created an exe file with inno 5. When I run exe file in my computer, it is installed and run without any problem. On the other hand, when I try to install and run it on some other computer, at the end of installation, window dialog pops up: \"Error invoking method\", I click Ok. Another window pop up saying \"Failed to launch jvm\". I searched the whole internet, but I couldn't find much about this topic. I hope I will get solution to this problem.\nThank you in advance." ]
[ "javafx", "javafx-8" ]
[ "Django : static files not loading", "My django project contains a folder STATIC in which there are it's child folders css, images, js and swf. My web-site can not locate these files raising a 404 in the development server running on the terminal.\nI have a settings_local.py file in which I have set the path such as (running on ubuntu 11.04)\nSTATIC_ROOT = '/home/zulaikha/dust.bin/my_project/static/'\nSTATIC_SERVE_PORT = 80\n\nThe sample settings-local.py file from the client suggest suggest so\n# static root\nSTATIC_ROOT = 'C:/Program Files (x86)/XAMPP/htdocs/static'\nSTATIC_SERVE_PORT = 8080\n\nI have seen some similar issues but all regard STATICFILES which I read was introduced in Django 1.3\nWhere am I wrong and how can I correct myself?" ]
[ "python", "django", "django-1.2" ]
[ "Passing parameters from JSP to Controller in Spring MVC", "I am trying out a sample project using Spring MVC annotated Controllers. All the examples I have found online so far bind the JSP to a particular model and the controller uses @ModelAttribute to retrive the model object in the handler method. \n\nHow do I go about passing other parameters (not present in the Model object) from the JSP to Controller? Do I use JavaScript to do this? Also can someone clarify what the HttpServletRequest object should be used for.\n\nThanks." ]
[ "java", "spring-mvc" ]
[ "Put jsonArray to SharedPreferenses", "I am new in programming and need your help. I have sharedPreferenses that I am use in a few activities in my application. I use it for saving username, password and so on. Now I need to save into it tasks(Strings). But the problem is that I could`t understand how I can save a few tasks in the shared preferenses. Code that I have now save only the last task I put.\n\npublic class MainPage extends AppCompatActivity {\n SharedPreferences prefs;\n EditText input;\n Button btnDel;\n\n @Override\n protected void onCreate(final Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.main);\n prefs = getSharedPreferences(\"myUsers\",MODE_PRIVATE);\n input = (EditText)findViewById(R.id.txtItem);\n\n\n\n protected void SavePreferences1(String task) {\n JSONObject ExistUser = getUserByName(\"katya\");//one of the users saved into sharedPreferences. \n try {\n JSONArray jsonArray = new JSONArray();\n ExistUser.put(\"tasks\", task);\n jsonArray.put(task);\n prefs.edit().putString(ExistUser.getString(\"name\"), ExistUser.toString()).commit();//save changed JSON\n } catch (JSONException e) {\n e.printStackTrace();\n }\n\n }\n\n public void SavePreferences(View v){\n\n SavePreferences1(input.getText().toString());\n }\n }" ]
[ "android", "arrays", "sharedpreferences" ]
[ "Binary matrix in R: how to turn all 1 to 0 if they lie within N-steps of original zero", "I apologise for the title, it will probably improve with suggestions.\nI need to edit a binary matrix in R so that where ever there was a zero, I turn all surrounding entries to zero (if not zero already), if they lie within N steps of the original zero. The path can be L-shaped or straight, including diagonal, and diagonal path followed by straight path, as long as they are continuous unbroken paths.\nSo if N=2, the effect would be to expand the one zero in my example into a cloud of zeros, like this\noriginal matrix:\n [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n [1,] 1 1 1 1 1 1 1 1 1 1\n [2,] 1 1 1 1 1 1 1 1 1 1\n [3,] 1 1 1 1 1 1 1 1 1 1\n [4,] 1 1 1 1 1 1 0 1 1 1\n [5,] 1 1 1 1 1 1 1 1 1 1\n [6,] 1 1 1 1 1 1 1 1 1 1\n [7,] 1 1 1 1 1 1 1 1 1 1\n [8,] 1 1 1 1 1 1 1 1 1 1\n [9,] 1 1 1 1 1 1 1 1 1 1\n[10,] 1 1 1 1 1 1 1 1 1 1\n\nwith N=2 becomes\n [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n [1,] 1 1 1 1 1 1 1 1 1 1\n [2,] 1 1 1 1 0 1 0 1 0 1\n [3,] 1 1 1 1 1 0 0 0 1 1\n [4,] 1 1 1 1 0 0 0 0 0 1\n [5,] 1 1 1 1 1 0 0 0 1 1\n [6,] 1 1 1 1 0 1 0 1 0 1\n [7,] 1 1 1 1 1 1 1 1 1 1\n [8,] 1 1 1 1 1 1 1 1 1 1\n [9,] 1 1 1 1 1 1 1 1 1 1\n[10,] 1 1 1 1 1 1 1 1 1 1\n\nand if N=3\n [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n [1,] 1 1 1 0 1 1 0 1 1 0\n [2,] 1 1 1 1 0 0 0 0 0 1\n [3,] 1 1 1 1 0 0 0 0 0 1\n [4,] 1 1 1 0 0 0 0 0 0 0\n [5,] 1 1 1 1 0 0 0 0 0 1\n [6,] 1 1 1 1 0 0 0 0 0 1\n [7,] 1 1 1 0 1 1 0 1 1 0\n [8,] 1 1 1 1 1 1 1 1 1 1\n [9,] 1 1 1 1 1 1 1 1 1 1\n[10,] 1 1 1 1 1 1 1 1 1 1\n\nI need the solution to cope with any sensible number of N steps. In practice N will be 8 or 10, and the matrices are around 8000x8000 in size.\nThe reason I need to do this is that the entries in these matrices are pixels from an image that I made binary (black and white). The zeros correspond to white lines and I want to "grow" the lines by N pixels (to represent imprecision of sampling in an analysis).\nI need to do this in R, and in this "simple" way, so that all my images from different sources end up being processed in a consistent reproducible way.\nI confess that the solution is beyond me, at least in a reasonable time frame, and so I am asking for help on this one. Image processors like GIMP do this all the time, so I am sure there is a solution.\nThank you very much." ]
[ "r", "matrix" ]
[ ".htaccess allow if url contains a word", "I want to allow access to specific domains. For example if domain contains the word asdf it should allow access. I final attempt before asking was:\n\nRewriteEngine on\nRewriteCond %{HTTP_REFERER} !^.*asdf.*$ [NC,OR]\nRewriteCond %{HTTP_REFERER} !^.*1234.*$\n#RewriteRule .* - [F]\n\n\nSo here I tried to restrict access to all but domains that contain asdf or 1234." ]
[ ".htaccess" ]
[ "Facebook SDK for iOS , on iOS 4.0 device", "Facebook SDK documents indicates that this SDK will work on iOS 4.0 and later. Then I tested their Scrumptions sample on a iPhone 3GS iOS 4.0 device. But it seems this application doesn't work. It keeps showing me the login screen although I logged in. \n\nThen I debugged and noticed FBSessionState always returnsFBSessionStateClosedLoginFailed. \nIt never returns FBSessionStateOpen.\n\nWhat could be the reason? However when I run this in iOS 5.1 emulator it works fine. Is it because SDK doesn't support iOS 4.0 or some other issue?" ]
[ "ios4", "facebook-ios-sdk" ]
[ "Tools for sparse least squares regression", "I want to do sparse high dimensional (a few thousand features) least squares regression with a few hundred thousands of examples. I'm happy to use non fancy optimisation - stochastic gradient descent is fine.\n\nDoes anyone know of any software already implemented for doing this, so I don't have to write to my own?\n\nKind regards." ]
[ "optimization", "math", "statistics", "regression", "least-squares" ]
[ "I want to respond images with Django", "I want Django to display an image when accessed.\nFor example, I want to display only the image as a response, \nsuch as when accessing the image below.\nAnd I want to do the URL as a normal URL without using .jpeg or .png.\n\nSample:\n\n\n\nBut now, no matter what method you try, it doesn't work.\n\nfrom django.http import HttpResponse\nimport os\nfrom django.core.files import File\nimport codecs\n\n\ndef image(request):\n file_name = os.path.join(\n os.path.dirname(__file__),\n '12.jpg'\n )\n try:\n with open(file_name, \"rb\") as f:\n a = f.read()\n return HttpResponse(a, content_type=\"image/jpeg\")\n except IOError:\n red = Image.new('RGBA', (1, 1), (255, 0, 0, 0))\n response = HttpResponse(content_type=\"image/jpeg\")\n red.save(response, \"JPEG\")\n return response\n\n\n\n\nurlpatterns = [\n url('image', image)\n]\n\n\nWith the above code, the following error occurs.\n\n'utf-8' codec can't decode byte 0xff in position 0: invalid start byte" ]
[ "python", "django" ]
[ "Sorting a deck of cards by suit and then rank", "I have this Java class:\n\nclass Card\n{\n private Suit suit;\n private int rank;\n}\n\n\n(Suit is an enum)\n\nThere are four suits with ranks 1-9 each and four suits with a single possible rank 0. Each card exists in an unknown but constant among all cards number of copies. How would I sort a deck in a set order of suits, and by increasing rank in each suit?" ]
[ "java", "algorithm", "sorting" ]
[ "How to exclude repeated keys in dictionary of dictionaries when reading a csv file?", "I have made a code so far that reads a csv file and returns the data in the form of nested dictionaries. The first column of the table in the csv file holds the keys and its keys values are the values of the same row. \n\nI want to transform my code so it can exclude a key and its values if it is subsequently repeated in this column with the same string name. For example, if I have twice the string \"Name\" in a column I want to exclude the first \"Name\" as a key field and replace it (along with all its values) by the subsequent \"Name\" which may be some lines after.\n\nMy code so far:\n\ndef dict_of_dicts (filename, keyfield):\n tabledict= {}\n with open (filename, \"rt\", newline='') as csv_file:\n csvreader=csv.DictReader(csv_file, skipinitialspace=True)\n for row in csvreader:\n tabledict[row[keyfield]]=row\n return tabledict" ]
[ "python", "csv", "dictionary" ]
[ "Dynamically copy rows of data from one Excel file to another", "I have large amounts of data for different serial numbers spread across many files that I would like to dynamically copy into a template using a reference cell value and the INDIRECT() function. I would like to do this without using VBA macros.\n\nFor example, in the template: Cell A1: SN016. Cell A2: =INDIRECT(\"C:\\Users\\Johannes\\TestData\\\"&A1&\"\\[data.xlsx]Sheet1!A2\")\n\nThe idea is to change A1 to the corresponding file location of the data and update the entire range of data in the template. I'm getting a #REF! result though when I try this. It would also be nice if I could drag the copy-formula box and have Sheet1!A2 become Sheet1!A3, Sheet1!A4, Sheet1!B2, etc. That might be asking for too much though!" ]
[ "excel", "excel-formula", "excel-indirect" ]
[ "Determining small devices: max-width really better than max-device-width / screen.width?", "What is an efficient way to detect small devices in javascript?\n\nI tried to do that with media queries, and I tested max-width and max-device-width.\n\nEverybody says that max-width should be used.\n\nBut in my test with Chrome on a Moto G5 max-device-width indicates the mobile device much better:\n\nwindow.innerWidth: 980 // could be a monitor\nwindow.innerHeight: 1394\n\nscreen.width: 360 // small, indicates a mobile device\nscreen.height: 640\n\nwindow.devicePixelRatio: 3\n\n(min-width: 500px): true\n...\n(min-width: 1200px): true // could be a monitor\n\n(min-device-width: 300px): true\n(min-device-width: 400px): false // small, indicates a mobile device\n\n\nmin-device-width seems to correspond to screen.width. Both distinguish the mobile device from a monitor.\n\nSince everybody is suggesting to use max-width I wonder:\n\nHow can you use that to distinguish mobile device from a monitor?\n\nWhere am I wrong?" ]
[ "javascript", "css", "mobile", "responsive-design" ]
[ "JSON response is not working in PHP version 5.3.24", "I am developing a Java application where I have to pass values to my server and receive the response from PHP file (version 5.3.24).The code is running fine in localhost and other live servers where the PHP version is greater than 5.3.24.\n\nThis is my Java code.\n\npublic static void send() {\n\ntry {\n// make json string, try also hamburger\nString json = \"{\\\"name\\\":\\\"Frank\\\",\\\"food\\\":\\\"pizza\\\",\\\"quantity\\\":3}\";\n\n// send as http get request\nURL url = new URL(\"http://www.matjazcerkvenik.si/php/json/pizzaservice.php?order=\"+json);\nURLConnection conn = url.openConnection();\n\n// Get the response\nBufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));\nString line;\nwhile ((line = rd.readLine()) != null) {\nSystem.out.println(line);\n}\nrd.close();\n} catch (Exception e) {\ne.printStackTrace();\n}\n}\n\npublic static void main(String[] args) {\nsend();\n}\n\n\nThis is my PHP code.\n\n<?php\n$order = $_GET[\"order\"];\n$obj = json_decode($order);\n$name = $obj -> {\"name\"};\n$food = $obj -> {\"food\"};\n$quty = $obj -> {\"quantity\"};\nif ($food == \"pizza\") {\n$price = 4000;\n} else if ($food == \"hamburger\") {\n$price = 5000;\n} else {\n$price = 0;\n}\n$price = $price * $quty;\nif ($price == 0) {\n$status = \"not-accepted\";\n} else {\n$status = \"accepted\";\n}\n$array = array(\"name\" => $name, \"food\" => $food, \"quantity\" => $quty, \"price\" => $price, \"status\" \n=> $status);\necho json_encode($array);\n?>" ]
[ "java", "php", "json" ]
[ "Android webView disable Wikipedia search bar", "I'm building an app which using webView and loading Wikipedia's web pages. I would like to disable this part:\n\n\nI don't know what is the best way to do this... I have thought of auto scrolling down, but then the user is able to scroll up.\nAuto scrolling down is also doesn't accurate and may hide some of the value's information. \n\nThanks." ]
[ "javascript", "android", "webview" ]
[ "Retaining delegate until it is used", "So I'm writing this API which looks something like this:\n\n @implementation TheApi\n - (ObjectLoaderCallbackDelegate *)createLoaderDelegateForCallback:(ObjectLoaderCallback)callback\n {\n ObjectLoaderCallbackDelegate *loaderDelegate = [[ObjectLoaderCallbackDelegate alloc] init];\n loaderDelegate.didLoadObject = ^(id object) {\n callback(object);\n };\n return loaderDelegate;\n }\n\n - (void)loadString:(ObjectLoaderCallback)callback\n {\n ObjectLoaderCallbackDelegate *callbackDelegate = [self createLoaderDelegateForCallback:callback];\n ObjectLoader *loader = [[ObjectLoader alloc] init];\n [loader load:@\"string\" delegate:callbackDelegate];\n }\n\n - (void)loadNumber:(ObjectLoaderCallback)callback\n {\n ObjectLoaderCallbackDelegate *callbackDelegate = [self createLoaderDelegateForCallback:callback];\n ObjectLoader *loader = [[ObjectLoader alloc] init];\n [loader load:@\"number\" delegate:callbackDelegate];\n }\n @end\n\n\nWhen I call [loader load:delegate:], it doesn't keep a strong reference to the delegate (which makes sense). But because the loader does asynchronous stuff before calling the delegate, the delegate is being released before it ever gets called, resulting in a crashed program. Here is my solution (which seems a bit dirty):\n\n @interface TheApi : NSObject\n - (void)loadString:(ObjectLoaderCallback)callback;\n - (void)loadNumber:(ObjectLoaderCallback)callback;\n - (void)runCalls;\n @end\n\n @implementation TheApi\n {\n NSMutableDictionary *loaderDelegates;\n NSMutableSet *callbacksCompleted;\n }\n\n - (TheApi *) init\n {\n self = [super init];\n if (self != nil) {\n loaderDelegates = [[NSMutableDictionary alloc] init];\n callbacksCompleted = [[NSMutableSet alloc] init];\n }\n return self;\n }\n\n - (void)runCalls\n {\n [loader runLoop];\n }\n\n - (ObjectLoaderCallbackDelegate *)createLoaderDelegateForCallback:(ObjectLoaderCallback)callback\n {\n NSNumber *delegateRefKey = [NSNumber numberWithUnsignedInt:arc4random()];\n ObjectLoaderCallbackDelegate *loaderDelegate = [[ObjectLoaderCallbackDelegate alloc] init];\n loaderDelegate.didLoadObject = ^(id object) {\n callback(object);\n [callbacksCompleted addObject:delegateRefKey];\n };\n [loaderDelegates setObject:loaderDelegate forKey:delegateRefKey];\n return loaderDelegate;\n }\n\n - (void)removeCompletedDelegates\n {\n // So we can remove items from callbacksCompleted in the loop...\n NSMutableSet *callbacksCompletedIterSet = [callbacksCompleted copy];\n\n // Remove old delegates for calls already completed which are stored\n for (id key in callbacksCompletedIterSet) {\n [loaderDelegates removeObjectForKey:key];\n [callbacksCompleted removeObject:key];\n }\n }\n\n - (void)loadString:(ObjectLoaderCallback)callback\n {\n [self removeCompletedDelegates];\n ObjectLoaderCallbackDelegate *callbackDelegate = [self createLoaderDelegateForCallback:callback];\n ObjectLoader *loader = [[ObjectLoader alloc] init];\n [loader load:@\"string\" delegate:callbackDelegate];\n }\n\n - (void)loadNumber:(ObjectLoaderCallback)callback\n {\n [self removeCompletedDelegates];\n ObjectLoaderCallbackDelegate *callbackDelegate = [self createLoaderDelegateForCallback:callback];\n ObjectLoader *loader = [[ObjectLoader alloc] init];\n [loader load:@\"number\" delegate:callbackDelegate];\n }\n @end\n\n\nSo here, I'm keeping a reference to the delegates in an instance-level dictionary where they key is unique for each API method call.\n\nSo my question is: is there a better way to do keep the delegates from being released and then freeing them after the loader calls them?" ]
[ "objective-c", "automatic-ref-counting", "objective-c-blocks" ]
[ "PHP array sorting cant get the correct output", "can any one help me how to get the sorting of the numbers; \n\nnum1 = 1\nnum2 = 1\nnum3 = 3\nnum4 = 5\n\n\n $values = array($_POST[\"num1\"] => 1, $_POST[\"num2\"] => 2,$_POST[\"num3\"] => 3,$_POST[\"num4\"] =>4);\n asort($values);\n foreach($values as $key => $val){\n echo \"<br>$key = $val<br>\";\n }\n\n\nThe num1 is not printed..\nand i got an out put of \n\n1 = 2 \n\n3 = 3\n\n4 = 4\n\nhow can i got the output complete like this?\n\n1 = 1 | 1 = 2 | 3 = 3 | 4 = 4" ]
[ "php", "arrays", "sorting" ]