text
stringlengths
15
59.8k
meta
dict
Q: Comparing two text files is not working in Powershell I am trying to compare the contents of two text files and have only the differences be outputted to the console. The first text file is based on the file names in a folder. $AsyFolder = Get-ChildItem -Path .\asy-data -Name I then remove the prefix of the file name that is set up by the user and is the same for every file and is separated from the relevant info with a dash. $AsyFolder| ForEach-Object{$_.Split("-").Replace("$Prefix", "")} | Where-Object {$_}|Set-Content -Path .\templog.txt The output looks like $Asyfolder Output bpm.art gbr.pdf asy.pdf fab.pdf as1.art odb.tgz ccam.cad read_me_asy.txt There is another file that is the reference and contains the suffixes of files that should be there. It looks like this Reference File tpm.art bpm.art gbr.pdf asy.pdf fab.pdf as1.art as2.art odb.tgz xyp.txt ccam.cad And its contents are received with $AsyTemplate = Get-Content -Path C:\Users\asy_files.txt The logic is as follows $AsyTemplate | ForEach-Object{ If(Select-String -Path .\templog.txt -Pattern $_ -NotMatch -Quiet){ Write-Host "$($_)" } } I have tried various ways of setting up the templog.txt with -InputObject: using Get-Content, Get-Content -Raw, a variable, writing an array manually. I have also tried removing -NotMatch and using -eq $False for the output of select string. Everytime though the output is just the contents of asy_files.txt (Reference File). It doesn't seem to care what is in templog.txt ($AsyFolder Output). I have tried using compare-object/where-object method as well and it just says that both files are completely different. A: Thank you @Lee_Dailey for your help in figuring out how to properly ask a question... It ended up being additional whitespace (3 tabs) after the characters in the reference file asy_files.txt. It was an artifact from where I copied from, and powershell was seeing "as2.art" and "as2.art " I am not 100% as to why that matters, but I found that sorting for any whitespace with /S that appears after a word character /W and removing it made the comparison logic work. The Compare-Object|Where-Object worked as well after removing the whitespace.
{ "language": "en", "url": "https://stackoverflow.com/questions/61647849", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I configure logback to use xz compression for my logs automatically? How do I configure logback to use xz compression for my logs automatically? Is xz even supported or only gz and zip? A: No, logback doesn't support xz. You can see it in source for RollingPolicyBase.java and source for Comressor.java
{ "language": "en", "url": "https://stackoverflow.com/questions/40163934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to generate a UI for a ListView Adapter for FaceBook like Feed how to creat a Arraylist adapter which will change the view based on a flag in the LISTVIEW, Flag can be IMAGE , IMAGETEXT, VIDEO , VIDEOTEXT, TEXT e.g like in facebook post , 1. if a friend posts a text, list row will only contain a text with his Name 2. if a friend posts a Image , list row will only contain a image with his Name 3. if a friend poasts a Video , list row will only contain a Video with his Name , and only Video onClick() , Playing that Video in a external Player * *Flag = text. view to be attached is text.xml *Flag = Video, View to be attached is video.xml *Flag = Image ,View to be attached is image.xml ANY HELP ON THIS. Thanks in Advance... A: override getItemViewType(int position) and getViewTypeCount() method in your adapter and inflate you view according to it from getView(). In you case write methods like @Override public int getItemViewType(int position) { if(list.get(position).flag == text) return 0; else if(list.get(position).flag == image) return 1; else return 2; } @Override public int getViewTypeCount() { return 3; } A: I am not pretty much sure but it's my concept that firstly create a layout for row that can hold every thing that you want show(image, video, text etc ). And make this layout such a way if one thing is not present then it automatically wrapped(means if video is not present then video space will not be there). Now make json of every list row and pass it to Adapter of list. Then override getView() method of the adapter and parse json there and display according to your layout. A: i implemented similar Custom Adapter for ListView which is used in this link , also used ViewHolders check this link http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley/
{ "language": "en", "url": "https://stackoverflow.com/questions/22401253", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Getting an Array from Return statement, deduce a string from that I have a 'Case' conditional code snippet wherein I am returning two objects. The psuedocode is - case name when 'a' object1 = - SQL Logic - when 'b' object1 = - SQL Logic - when 'c' object2 = - SQL Logic - when 'd' object2 = - SQL Logic - end return object1, object2 As evident, I am returning two objects. However, in my Controller I need one object at a time. The object are returned in form of Array like ['value', 'nil']. One of them is always nil. In my controller I am passing one of these objects as - Model.find_by_sql ["select * from #{object}"] #either object1 or object2 Is there any way that I can break off this array and return the object that is required at that place as String? Thanks. A: While you can use compact to eliminate the nil values from your array, I'm not sure why you need this in the first place. Doing case name when 'a' return "SQL statement" when 'b' return "SQL statement" when 'c' return "SQL statement" when 'd' return "SQL statement" end is way more intuitive. A: return [object1, object2].compact you can use compact method to remove nil value of array. A: You could write: return (['a', 'b'].include?(name) && - SQL Logic 1 -) || (['c', 'd'].include?(name) && - SQL Logic 2 -) If it's the last line of a method, you don't need return. Let's see what's happening. If ['a', 'b'].include?(name) #=> true, - SQL Logic 1 -, which is truthy, will be returned. If ['a', 'b'].include?(name) #=> false, the first && clause is false (- SQL Logic 1 - is not executed), so we consider the other || clause. ['c', 'd'].include?(name) must be true, so we return - SQL Logic 2 -.
{ "language": "en", "url": "https://stackoverflow.com/questions/30243090", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Contentful with Gatsby: rendering RichText field by accessing json not possible (raw instead) I am following a documentation on how to implement Contentful's RichText field type with Gatsby. My GraphQL query only returns a field raw on my RichText field called synopsis: query MyQuery { allContentfulCountry { edges { node { id synopsis { raw } } } } } It returns: { "data": { "allContentfulCountry": { "edges": [ { "node": { "id": "fa07b3db-6acb-5b9a-7c4b-c42ef3c191b0", "synopsis": { "raw": "{\"data\":{},\"content\":[{\"data\":{},\"content\":[{\"data\":{},\"marks\":[],\"value\":\"The actual rich text...\",\"nodeType\":\"text\"}],\"nodeType\":\"paragraph\"}],\"nodeType\":\"document\"}" }, "slug": "france" } } ] } } } The documentation assumes documentToReactComponents(node.bodyRichText.json, options) but I can't access json and need to do this: JSON.parse(country.synopsis.raw) Am I missing something? "@contentful/rich-text-react-renderer": "^14.1.2", "@contentful/rich-text-types": "^14.1.2", System: OS: macOS 11.0.1 CPU: (8) x64 Intel(R) Core(TM) i7-7820HQ CPU @ 2.90GHz Shell: 5.8 - /bin/zsh Binaries: Node: 12.13.0 - ~/.nvm/versions/node/v12.13.0/bin/node npm: 6.14.9 - ~/.nvm/versions/node/v12.13.0/bin/npm Languages: Python: 2.7.16 - /usr/bin/python Browsers: Firefox: 82.0.3 npmPackages: gatsby: ^2.26.1 => 2.26.1 gatsby-image: ^2.6.0 => 2.6.0 gatsby-plugin-intl: ^0.3.3 => 0.3.3 gatsby-plugin-newrelic: ^1.0.5 => 1.0.5 gatsby-plugin-react-helmet: ^3.3.5 => 3.3.5 gatsby-plugin-sharp: ^2.9.0 => 2.9.0 gatsby-source-contentful: ^4.1.0 => 4.1.0 gatsby-transformer-remark: ^2.11.0 => 2.11.0 gatsby-transformer-sharp: ^2.5.6 => 2.5.6 npmGlobalPackages: gatsby-cli: 2.14.0 A: Contentful DevRel here. There has been a breaking change in the gatsby-source-contentful in v4. It's now recommended to use raw. You can find more information in the changelog. A recommended Gatsby query from the changelog: export const pageQuery = graphql` query pageQuery($id: String!) { contentfulPage(id: { eq: $id }) { title slug description { raw references { ... on ContentfulPage { # contentful_id is required to resolve the references contentful_id title slug } ... on ContentfulAsset { # contentful_id is required to resolve the references contentful_id fluid(maxWidth: 600) { ...GatsbyContentfulFluid_withWebp } } } } } } `
{ "language": "en", "url": "https://stackoverflow.com/questions/64960708", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Extension SNMP Agent C# I am a complete newbie to SNMP. Recently, I am trying to write a simple program that is supposed to monitor and modify a data file in a remote machine. The file itself could just be a plain-text file or whatsoever. I was introduced to the SNMP, and tried to figure out a way to make SNMP do the job in Windows OS. The prefered language is C# or any .net. I have been googling for a few days, however, did not find a good how-to instruction to do so. Really need help on this to get my job done. Thank you very much, Terry A: Here's one SnmpSharpNet. More can be found here. A: I use SharpSnmpLib. It works very well for SNMPv2 and is pretty easy to understand
{ "language": "en", "url": "https://stackoverflow.com/questions/4340067", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Possible exception(s) thrown by CloudBlockBlob.UploadFromFile(...) Which exception(s) can be raised by Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob.UploadFromFile(...)? The C# metadata and online documentation page lists no exceptions for this method. Several examples on StackOverflow and elsewhere catch the base Exception class. Presumably only specific exceptions can be thrown. Quick-Starts and Tutorials on learn.microsoft.com don't include error handling. Could it be just Microsoft.Azure.Storage.StorageException? A: The method can throw lots of exceptions like ArgumentException, NotSupportedException, or etc. However, if your inputs are correct, the most possible exceptions are StorageException for communications against Azure Storage service and IOException for reading the file from local disk.
{ "language": "en", "url": "https://stackoverflow.com/questions/55837064", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: getting data using Importxml into a spread sheet I tried to import xml data from a website to a spreadsheet, but most of the xpaths work except this one, it keeps throwing errors This is my full syntax: =IMPORTXML("http://egypt.souq.com/eg-en/2724304505488/s/","//*[@id="content-body"]/header/div[2]/div[1]/div[1]/div/h1") Is this a problem with Google spread sheet or what ? A: You've used double quotes inside your XPath query. Switching these for single quotes allows sheets to parse the formula correctly: =IMPORTXML("http://egypt.souq.com/eg-en/2724304505488/s/","//*[@id='content-body']/header/div[2]/div[1]/div[1]/div/h1") But this still results in an error: Error Imported XML content cannot be parsed. You haven't been very specific but you can get the H1 content from the page in your code with this: =IMPORTXML("http://egypt.souq.com/eg-en/2724304505488/s/","//h1") This may well break for other pages, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/32121337", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create a nested list from an object? I have an tags object from treetagger's python wrapper that apparently is list: In: print type (tags) Out: <type 'list'> When I print the content of tags as follows, I get the following lists: In: def postag_directory(input_directory, output_directory): import codecs, treetaggerwrapper, glob, os for filename in sorted(glob.glob(os.path.join(input_directory, '*.txt'))): with codecs.open(filename, encoding='utf-8') as f: lines = [f.read()] #print 'lines:\n',lines tagger = treetaggerwrapper.TreeTagger(TAGLANG = 'en') tags = tagger.TagText(lines) print '\n\n**** labels:****\n\n',tags Out: [[u'I\tPP\tI', u'am\tVBP\tbe', u'an\tDT\tan', u'amateur\tJJ\tamateur']] [[u'This\tDT\tthis', u'my\tPP$\tmy']] [[u'was\tVBD\tbe', u'to\tTO\tto', u'be\tVB\tbe', u'my\tPP$\tmy', u'camera\tNN\tcamera', u'for\tIN\tfor', u'long-distance\tJJ\tlong-distance', u'backpacking\tNN\tbackpacking', u'trips\tNNS\ttrip', u'.\tSENT\t.', u'It\tPP\tit']] However, I would like to get just one single nested list like this: [[u'I\tPP\tI', u'am\tVBP\tbe', u'an\tDT\tan', u'amateur\tJJ\tamateur'],[u'This\tDT\tthis', u'my\tPP$\tmy'],[u'was\tVBD\tbe', u'to\tTO\tto', u'be\tVB\tbe', u'my\tPP$\tmy', u'camera\tNN\tcamera', u'for\tIN\tfor', u'long-distance\tJJ\tlong-distance', u'backpacking\tNN\tbackpacking', u'trips\tNNS\ttrip', u'.\tSENT\t.', u'It\tPP\tit']] I all ready tried with list(), append(), [] and also with: for sublist in [item]: new_list = [] new_list.append(sublist) print new_list Any idea of how can I nest each list from tags?. A: This is a list of one element (another list). [[u'I\tPP\tI', u'am\tVBP\tbe', u'an\tDT\tan', u'amateur\tJJ\tamateur']] So if item is a list of lists, each with one element, then you can do new_list = [sublist[0] for sublist in item] If you had more than one element in each sublist, then you'll need another nested loop in that. Though, in reality, you shouldn't use lines = [f.read()]. The documentation uses a single string when you use tag_text, so start with this # Initialize one tagger tagger = treetaggerwrapper.TreeTagger(TAGLANG='en') # Loop over the files all_tags = [] for filename in sorted(glob.glob(os.path.join(input_directory, '*.txt'))): with codecs.open(filename, encoding='utf-8') as f: # Read the file content = f.read() # Tag it tags = tagger.tag_text(content) # add those tags to the master tag list all_tags.append(tags) print(all_tags)
{ "language": "en", "url": "https://stackoverflow.com/questions/36805437", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Searching for one-word string occupying a line of a text with Python 2.7 I have (very) long document (in .txt) that has this format: Title text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text Whatever text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text I would like to collect a column of all the titles before each text. For now I have a problem identifying them and printing them out. I focus on the fact that there is an \n character before and after the 'title' of each text. I am not sure how to tell to python to select that 'title' that lies between the \n characters regardless of its length. I used the code from here text = "\n" + "" + "\n" searchfile = open("MyTEXT.txt", "r") for line in searchfile: if str(text) in line: print line searchfile.close() There are two problems with the code above that I do not know how to solve: 1) The first \n is in a different line (the line above), so the code above finds nothing. 2) The 'Title' string that I would like to collect are in varying lengths, some are 4 characters, but some are more (not more than 10). Any suggestions will be very helpful, thank you in advance! A: Is this what you were looking for? with open("MyTEXT.txt", "r") as myfile: wordlist = [line.rstrip('\n').split() for line in myfile] titlelist = [i[0] for i in wordlist if len(i) == 1 and i[0] != "unwanted"] For example, if MyTEXT.txt contained: unwanted 12345 2124 abcd efghi jkl mn o pqr 123 unwanted stu v wq y z unwanted 567 890 The output would be: >>> titlelist ['abcd', 'o', 'wq']
{ "language": "en", "url": "https://stackoverflow.com/questions/35988293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: android gradle monkeyTalk build issue I'm using monkeyTalk in order to get write test by this demo. I`m using AndroidAnnotations 2.7.1 and i faced an issue like this. Note: Generating source file:com.activity.SaveFileDialogActivity_ Note: Time measurements: [Whole Processing = 517 ms], [Generate Sources = 185 ms], [Extract Manifest = 102 ms], [Extract Annotations = 96 ms], [Validate Annotations = 68 ms], [Process Annotations = 54 ms], [Find R Classes = 11 ms], Note: Time measurements: [Whole Processing = 0 ms], warning: The following options were not recognized by any processor: '[androidManifestFile, resourcePackageName]' 189 errors 2 warnings :app:compileMonkeytalkJava FAILED FAILURE: Build failed with an exception. * What went wrong: Execution failed for task ':app:compileMonkeytalkJava'. > Compilation failed; see the compiler error output for details. * Try: Run with --info or --debug option to get more log output. * Exception is: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:compileMonkeytalkJava'. at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46) at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35) at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64) at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58) at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42) at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52) at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53) at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43) at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:305) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63) at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51) at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23) at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88) at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:29) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62) at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23) at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68) at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62) at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55) at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149) at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106) at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86) at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:80) at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:33) at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:24) at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:36) at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26) at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:51) at org.gradle.internal.Actions$RunnableActionAdapter.execute(Actions.java:171) at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:237) at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:210) at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:35) at org.gradle.launcher.cli.JavaRuntimeValidationAction.execute(JavaRuntimeValidationAction.java:24) at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:206) at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:169) at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33) at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22) at org.gradle.launcher.Main.doAction(Main.java:33) at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45) at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:54) at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:35) at org.gradle.launcher.GradleMain.main(GradleMain.java:23) at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:33) at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:130) at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48) Caused by: org.gradle.api.internal.tasks.compile.CompilationFailedException: Compilation failed; see the compiler error output for details. at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:44) at org.gradle.api.internal.tasks.compile.JdkJavaCompiler.execute(JdkJavaCompiler.java:35) at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.delegateAndHandleErrors(NormalizingJavaCompiler.java:97) at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:50) at org.gradle.api.internal.tasks.compile.NormalizingJavaCompiler.execute(NormalizingJavaCompiler.java:36) at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:34) at org.gradle.api.internal.tasks.compile.CleaningJavaCompilerSupport.execute(CleaningJavaCompilerSupport.java:25) at org.gradle.api.tasks.compile.JavaCompile.performCompilation(JavaCompile.java:158) at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:138) at org.gradle.api.tasks.compile.JavaCompile.compile(JavaCompile.java:92) at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:63) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:235) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:211) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:222) at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:200) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80) at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61) ... 47 more BUILD FAILED
{ "language": "en", "url": "https://stackoverflow.com/questions/31676760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Datascroller issue - When dataTable and dataScroller is nested inside loop DataScroller pagination issue - The requested page #2 isn't found in the model containing 1 pages. Paging is reset to page #1 I have used a4j:repeat to iterate rich:dataTable and rich:datascroller. The problem with rich:datascroller is that pagination is not working properly. I have also tried JSTL c:foreach also. But, still I am getting the following error in console. (UIDatascroller.java:471) - Datascroller indexId:j_id129:j_id139: The requested page #2 isn't found in the model containing 1 pages. Paging is reset to page #1 In the PageBean.java private List parentList; public List getParentList() { return parentList; } public void setParentList(List parentList) { this.parentList = parentList; } public String openPage(){ for(int i=0;i<10;i++){ List<BeanDto> dtoList = ...; if(dtoList!=null){ if(parentList==null){ parentList = new ArrayList<List<BeanDto>>(); } parentList.add(dtoList); } } return "page" } In the page.xhtml <a4j:repeat value="#{pageBean.parentList}" var="item"> <rich:dataTable id="table" rows="2" var="childDto" value="#{item}"> <f:facet name="header"> <rich:columnGroup> <rich:column> <h:outputText value="Name" /> </rich:column> <rich:column> <h:outputText value="Age" /> </rich:column> </rich:columnGroup> </f:facet> <rich:column> <h:outputText value="#{childDto.name}"/> </rich:column> <rich:column> <h:outputText value="#{childDto.age}"/> </rich:column> </rich:dataTable> <rich:datascroller for="table" maxPages="10"> </rich:datascroller> </a4j:repeat> Tables were displayed in the screen, but pagination is not working. I have also tried to give index to the <rich:dataTable>'s id; That is also not woeking properly. Could you help me on this.
{ "language": "en", "url": "https://stackoverflow.com/questions/41484992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: simple while loop excercise im learning java and currently im stuck on one exercise in which i cannot comprehend why is code behaving this way. Im tracing my steps on paper, but i would expect different answer than program actually does. If anyone could please explain why it does what it does CODE: System.out.print("Enter an integer: "); int numb = in.nextInt(); while (in.hasNextInt()) { System.out.println(numb); System.out.print("Enter an integer: "); numb = in.nextInt(); } TESTER is just entering numbers, so output should look like this: Enter an integer: 5 - 5 - Enter an integer: 10 - 10 - Enter an integer: 8 - 8 - Enter an integer: k ... But it looks like this: Enter an integer: 5 - 10 - 5 - Enter an integer: -4 - 10 - Enter an integer: 8 - -4 - Enter an integer: -6 - 8 - Enter an integer: 11 - -6 - Enter an integer: -1 A: This is because you use in.hasNextInt() too soon (or too late, depending on how you look at it): the Scanner cannot tell you if it sees an integer or not until after the end user has entered a value. If you prompt for a number and then check for hasNextInt, your code should not skip the second prompt: System.out.print("Enter an integer: "); while (in.hasNextInt()) { int numb = in.nextInt(); System.out.println(numb); System.out.print("Enter an integer: "); } This would also prevent an exception in situations when the very first entry is not a number.
{ "language": "en", "url": "https://stackoverflow.com/questions/21945481", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Nothing is being returned? Can I not assign a two-dimensional array all the values of a pre-existing one? I am trying to return an array of points by looping through an existing two-dimensional point array. findMatches(b) contains an array of arrays of points from a board. If I could just access and alter these points directly so as to return them all to the point array I am returning, that would be great, but I don't suppose it is that easy. Here is my code: public static Point[] findPossibleSwaps(Board b) { Point[][] nums = new Point[findMatches(b).length][]; nums = findMatches(b); Point[] foundSwaps = new Point[3]; int xH = 0; int yV = 0; int index = 0; int x = 0; int y = 0; for(int a = 0; a<nums.length; a++) { Point [] lop = nums[a]; for(int h = 0; h<lop.length; h++) { Point qo = new Point(x,y); qo = lop[h]; if(qo.x!=0) { xH = qo.x-1; foundSwaps [index] = new Point(xH,qo.y); index++; } if(qo.y!=0) { yV = qo.y-1; foundSwaps [index] = new Point(qo.x,yV); index++; } } } return foundSwaps; } Thanks everyone
{ "language": "en", "url": "https://stackoverflow.com/questions/27175418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Check if function will result in error before executing I have this discord bot I have been playing around with. Since I constantly am trying things, I decided to do a command-command, which I would call by doing !cmd (message.channel or whatever). However, due me being bad at typing and forgetting to do things like declare variables, the commands often result in (obvious) errors. Is there a way to check if the function will result in an error? My current code is this: if(splitMessage[0] === '!cmd'){ //splitMessage is the variable that splits !cmd from the rest (no problems with it yet) var c = message.content.split(/ (.+)/)[1]; eval(c); } My eventual goal is something like if(splitMessage[0] === '!cmd'){ var c = message.content.split(/ (.+)/)[1]; if(eval(c) == error){ eval(c); } } A: if(splitMessage[0] === '!cmd'){ var c = message.content.split(/ (.+)/)[1]; try { eval(c); } catch (err) { console.log('There is an error!') } } Modifying a code in runtime is so bad though.
{ "language": "en", "url": "https://stackoverflow.com/questions/61552366", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to store Array of objects into redis cache using php I Have an array of objects that I need to store into redis cache and use it later. $obj = array( 'request_id' => $request_id, 'request_start_dttm' => $start_time, 'client_id' => $clientId, ); $redis = Redis::connection(); $name = "API".bin2hex(random_bytes(3)); $redis->rpush($name,$obj); print_r($redis->lrange($name,0,-1)); But I get the output as following: array ( 0 => '1732478', 1 => '2021-10-18 12:55:39.000000', 2 => '3' ) What should I do to preserve the key value pair using redis php?
{ "language": "en", "url": "https://stackoverflow.com/questions/69624784", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Pandas DataFrame Replace every value by 1 except 0 I'm having a pandas DataFrame like following. 3,0,1,0,0 11,0,0,0,0 1,0,0,0,0 0,0,0,0,4 13,1,1,5,0 I need to replace every other value to '1' except '0'. So my expected output. 1,0,1,0,0 1,0,0,0,0 1,0,0,0,0 0,0,0,0,1 1,1,1,1,0 A: Just use something like df[df != 0] to get at the nonzero parts of your dataframe: import pandas as pd import numpy as np np.random.seed(123) df = pd.DataFrame(np.random.randint(0, 10, (5, 5)), columns=list('abcde')) df Out[11]: a b c d e 0 2 2 6 1 3 1 9 6 1 0 1 2 9 0 0 9 3 3 4 0 0 4 1 4 7 3 2 4 7 df[df != 0] = 1 df Out[13]: a b c d e 0 1 1 1 1 1 1 1 1 1 0 1 2 1 0 0 1 1 3 1 0 0 1 1 4 1 1 1 1 1 A: As an unorthodox alternative, consider %timeit (df/df == 1).astype(int) 1000 loops, best of 3: 449 µs per loop %timeit df[df != 0] = 1 1000 loops, best of 3: 801 µs per loop As a hint what's happening here: df/df gives you 1 for any value not 0, those will be Inf. Checking ==1 gives you the correct matrix, but in binary form - hence the transformation at the end. However, as dataframe size increases, the advantage of not having to select but simply operate on all elements becomes irrelevant - eventually you it becomes less efficient. A: Thanks Marius. Also works on just one column when you want to replace all values except 1. Just be careful, this does it inplace create column 280 from 279 for class {1:Normal,0:Arrhythmia} df[280] = df[279] df[280][df[280]!=1] = 0
{ "language": "en", "url": "https://stackoverflow.com/questions/25028944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android - Python communication using zeroMQ With zeroMQ, is it possible to send ('Hello' message) from an Android app I created to a commandline running .recv() in python? I made an android app with a button, once pressed it sends "hello" to the tcp://machine2:5555. An extract of the button listener: settingsButton.setOnClickListener(new OnClickListener(){ public void onClick(final View v) { Toast toast = Toast.makeText(getApplicationContext(), "Playing video", Toast.LENGTH_SHORT); toast.show(); // insert SSH command for ffmpeg here ZMQ.Context ctx = ZMQ.context(1); Socket soc = ctx.socket(ZMQ.REQ); soc.connect("tcp://192.168.0.16:5555"); //System.out.print("established"); String msg = "hi"; soc.send(msg.getBytes(),0); } }); The python receiver running in the terminal will display the message received. import zmq import time import subprocess port = "5555" #first create a context for zeroMQ to begin communication context = zmq.Context() #pair communication socket = context.socket(zmq.REP) #bind ip address and port opened for communication socket.bind("tcp://*:%s" % port) print "tcp://192.168.0.16" while True: msg = socket.recv() if msg is not None: print msg #run_command(msg)[0] #subprocess.call(["mplayer","/home/kevo/capture003.dv"]) subprocess.call(["time", "mplayer","/home/kevo/Desktop/small.mp4"]) time.sleep(1) But nothing shows on my terminal so far.
{ "language": "en", "url": "https://stackoverflow.com/questions/26697702", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can I fire event only when user finishes modifying Text widget? I have an SWT Text control. I am trying to figure out how to listen for when the user is finished modifying the control, ie it is modified and then tabbed out of. I don't want my listener to be called every time a character changes in the textbox, and I don't want it to be called when the user traverses through the fields on the page. I only want it when the user modifies and then leaves the control. I've looked at the various listeners available for the Text control, but unless I'm missing something, I don't see anything like this. Did I miss it? A: It sounds like you are looking for a FocusListener. The Text control inherits addFocusListener() etc. from Control, so check the inherited methods section of its API docs. A: * *Save the text content to a variable on focus gain, then on focus lost compare it with the latest text - if different then text is modified else not. *This listener will not be called on each and every character change. *If you simply traverse the controls(with TAB key) then also you can detect whether text is changed or not. import org.eclipse.swt.SWT; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class Snippet19 { private static String temp = ""; public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); shell.setLayout(new GridLayout()); final Text text = new Text(shell, SWT.BORDER); text.setLayoutData(new GridData()); text.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { if (temp.equals(text.getText())) { System.out.println("Text not modified"); } else { System.out.println("Text conent modified"); } } @Override public void focusGained(FocusEvent e) { temp = text.getText(); } }); final Text text1 = new Text(shell, SWT.BORDER); text1.setText("chandrayya"); text1.setLayoutData(new GridData()); final Text text2 = new Text(shell, SWT.BORDER); text2.setText("chandrayya"); text2.setLayoutData(new GridData()); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/25691419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to fit Cos function to a list of integers without shrinking the X or Y axis in Python? I have a list of numbers called img which has 400 numbers in it. Once I plot it, I can clearly see the cos pattern in it. Once I try to fit using optimize.curve_fit, the function is not able to fit correctly, unless I divide img by a large number and also shrink the X axis range. For example in the below code, rangeY and rangeX are the factors I use to shrink the list in both Y and X dimensions respectively. In the first example you can see the fitting works perfectly: import numpy as np from scipy import optimize import matplotlib.pyplot as plt rangeY = 8000 rangeX = 3 def test_func(x, a, b, c, d): return a + b * np.cos(c * x + d) def fitCurve (img): x_data = np.linspace(0,rangeX,num=400) y_data = [] for i in range(0,len(img)): y_data += [img[i] / rangeY] y_data = np.array(y_data) param_bounds = ([-np.inf, 0, 0, -np.inf], [np.inf, np.inf, np.inf, np.inf]) params, params_covariance = optimize.curve_fit(test_func, x_data, y_data, bounds=param_bounds,maxfev=100000) y_curve = test_func(x_data, params[0], params[1], params[2], params[3]) MSE = round(np.square(np.subtract(y_data, y_curve)).mean(), 5) return (params,y_curve,MSE,x_data,y_data) img = [8452, 8421, 8498, 8521, 8427, 8523, 8667, 8196, 8515, 8110, 8551, 8732, 8189, 8429, 8539, 8360, 8622, 8726, 8529, 8412, 8465, 8497, 8724, 8201, 8804, 8990, 8732, 8985, 8671, 8675, 8450, 8959, 8865, 8665, 8776, 8822, 9230, 8749, 8758, 8849, 8753, 9108, 9100, 8964, 8808, 9352, 8786, 9070, 9359, 8895, 9131, 9117, 8994, 9087, 9352, 9163, 9073, 9190, 9277, 9073, 9276, 9413, 9395, 9223, 9353, 9420, 9462, 9512, 9512, 9571, 9580, 9595, 9593, 9639, 9622, 9647, 9710, 9710, 9725, 9758, 9785, 9814, 9831, 9862, 9889, 9902, 9921, 9941, 9964, 9992, 10050, 10091, 10131, 10131, 10133, 10179, 10177, 10164, 10241, 10291, 10332, 10332, 10316, 10332, 10332, 10333, 10340, 10333, 10333, 10368, 10385, 10391, 10391, 10403, 10439, 10454, 10428, 10407, 10428, 10459, 10480, 10523, 10530, 10539, 10556, 10562, 10586, 10606, 10592, 10612, 10621, 10621, 10587, 10587, 10574, 10574, 10574, 10574, 10587, 10594, 10584, 10597, 10598, 10599, 10606, 10677, 10620, 10620, 10677, 10677, 10633, 10633, 10620, 10633, 10619, 10619, 10619, 10619, 10599, 10599, 10599, 10621, 10616, 10621, 10621, 10616, 10593, 10635, 10582, 10521, 10514, 10484, 10474, 10468, 10456, 10475, 10481, 10481, 10426, 10413, 10386, 10380, 10370, 10370, 10365, 10363, 10336, 10336, 10322, 10318, 10275, 10299, 10275, 10299, 10299, 10275, 10275, 10272, 10264, 10250, 10201, 10184, 10182, 10178, 10176, 10176, 10136, 10178, 10163, 10163, 10170, 10170, 10111, 10147, 10081, 10081, 10074, 10055, 10055, 10063, 10063, 10055, 10030, 10013, 10013, 9958, 9905, 9872, 9864, 9855, 9855, 9864, 9896, 9899, 9899, 9900, 9901, 9923, 9901, 9843, 9836, 9830, 9830, 9810, 9802, 9801, 9783, 9760, 9761, 9739, 9760, 9739, 9712, 9771, 9771, 9734, 9722, 9675, 9632, 9632, 9610, 9624, 9610, 9579, 9597, 9570, 9579, 9555, 9519, 9519, 9517, 9517, 9516, 9516, 9495, 9480, 9428, 9426, 9408, 9408, 9379, 9379, 9391, 9379, 9358, 9327, 9319, 9304, 9297, 9280, 9280, 9288, 9271, 9288, 9297, 9295, 9246, 9246, 9240, 9267, 9246, 9222, 9187, 9169, 9154, 9139, 9100, 9074, 9101, 9101, 9100, 9076, 9074, 9101, 9104, 9116, 9140, 9143, 9133, 9106, 9081, 9090, 9081, 9077, 9067, 9079, 9093, 9093, 9082, 9082, 9079, 9076, 9025, 9017, 9006, 9006, 8991, 9015, 9015, 9006, 9039, 9063, 9096, 9106, 9120, 9120, 9120, 9096, 9113, 9078, 9071, 9078, 9102, 9102, 9117, 9117, 9117, 9117, 9125, 9126, 9145, 9164, 9170, 9178, 9190, 9237, 9265, 9265, 9245, 9251, 9245, 9245, 9251, 9239, 9260, 9267, 9267, 9267, 9259, 9277, 9277, 9261, 9261, 9261, 9286, 9272, 9266, 9266, 9313, 9329, 9313, 9313, 9331, 9328, 9335, 9335, 9385, 9406, 9406, 9403] params, y_curve, MSE, x_data, y_data = fitCurve(img) plt.figure(figsize=(6, 4)) plt.scatter(x_data, y_data, label='Data') plt.plot(x_data, y_curve, color="red", label='Fitted function') plt.legend(loc='best') plt.show() Now if I change rangeY to a smaller number such as 100, fitting does not work properly, so for the same code: rangeY = 100 rangeX = 3 Or if I don't shrink the X axis (rangeX=400) it still doesn't fit properly: rangeY = 8000 rangeX = 400 Now my question is: Is there any way to correctly fit the red curve on the blue dots without shrinking the Y and X axis range, or at least without shrinking the X axis? If not, how should I find the right values for rangeX and rangeY? Thanks A: After digging into the manual of optimize.curve_fit, I figured out this needs a boundary limit for "c" in func. Because this parameter depends on the T of the curve so it definitely needs a limit. So here we are with the new set of limits and the nice fitting curve, kudos to myself :-) rangeX = 400 rangeY = 8000 param_bounds = ([-np.inf, 0, 0, -np.inf], [np.inf, np.inf, 0.02, np.inf])
{ "language": "en", "url": "https://stackoverflow.com/questions/61247169", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is there a way to search a field name in the design view of Table or Query? I heave a table with about 100 fields, when I want to edit a field I found a difficulty to visual search among such No. of fields. The work around is copying one field to Excel then search on Excel for the specific field name, but if the layout view is not as design sort it is not helpful. For queries I'm copying SQL code to Notepad or ms-word and do searches. Is there a direct way to search a field name in the design view of a Table or a Query? A: There is no built-in way for searching, but I use a free addon Access Dependency Checker. It has many useful features, shows table/query structure, highlights a found field position and allows to open objects in design mode.
{ "language": "en", "url": "https://stackoverflow.com/questions/53644879", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Authenticating guest/anonymous users using JWT I'm building an SPA that a user can upload some files. The front-end is written in AngularJS while the back-end is using an API in Laravel 5.7. The authentication is implemented using the jwt-auth library. So far I have implemented this for registered users where each user has a personal directory on the server where he/she uploads the files. The difference between the registered and the anonymous users is that the files of the anonymous will be deleted after a while. Now, I want to do the same for anonymous/guest users (if the press the button continue as a guest). So what I tried first in the authContrroller.php side is to use something like this: public function authentication(Request $rrequest) { $credentials = $request->only('email', 'password'); // Guest authentication if( $credentials['email'] === 'guest' && $credentials['password'] === 'guest' ) { $payload = auth()->factory()->claims(['sub' => $this->createRandomDir()])->make(); $token = auth()->manager()->encode($payload); // OR $factory = JWTFactory::customClaims([ 'sub' => $this->createRandomDir(), ]); $payload = $factory->make(); $token = JWTAuth::encode($payload); } // Registered user authentication authentication else { if (! $token = auth()->setTTL(60)->attempt($credentials)) return response()->json(['error' => 'invalid_credentials'], 400); } return response()->json(compact('token')); } The idea was to create a random directory and enclose it inside the payload and use it on the next requests. But in the case of the guest, the server returns as a token an empty object. Possibly because there wasn't a user in the DB. Another idea that I'm thinking of is to create a random user (add it to the DB) and assign to it a random directory each time a user needs to use the app as guest/anonymous. The only thing that I'm afraid on that approach is that if there are thousands of guests then thousands random users should be created on the DB. So what do you think? Is there any other and more efficient way to handle this? Any idea is welcomed.
{ "language": "en", "url": "https://stackoverflow.com/questions/52664910", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Assigning to an array which is a member of struct This question may be a duplicate. But I am asking it again because the solution provided there dint help me compile the code error free. I have a following code snippet #include<stdlib.h> using namespace std; void initgrid(); struct gridblock { bool occ; double col[3]; double trans[3]; }grid[10][19]; void initgrid() { grid[0][0].occ=false; grid[0][0].trans={-23.0,0.0,-24.0}; .... } int main(int argc, char **argv) { initgrid(); return 0; } when I compile the above snippet with g++ <filename>.cpp -o test I have been shown the following warning followed by an error I am looking for a solution to overcome this. I have tried initializer_list and memcpy but that dint work. The line number 17 is grid[0][0].trans={-23.0,0.0,-24.0} A: Ok, so firstly your initialisation is completely wrong! Secondly where is your declaration for your struct instance? Thirdly you are missing several semi-colons to close off statements, next you are accessing your arrays wrong, please look at my code ad work from that. struct gridblock { bool occ; double col[3]; double trans[3]; }grid[10][19]; void initgrid(gridblock& grid[10][19]) { grid[0][0].trans[0] = 3.3; grid[0][0].trans[1] = 5.1; grid[0][0].trans[2] = 7.0; grid[0][0].occ = false; .... } int main(int argc, char **argv) { gridblock grid; initgrid(grid); return 0; } I would also recommend going through a beginner C++ book to learn these fundamental concepts, I get the feeling you have jumped ahead to structs way to fast! A: The problem is that you have not enabled the C++11 compiler switch. That capability is new. The warning you is telling you to enable the switch. Changing the code won't help. You have to change the configuration of your compiler.
{ "language": "en", "url": "https://stackoverflow.com/questions/22215660", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Why my error in subscirbe(()=>{},err=>{here}) is different from the error in browser console This is loadSize() function and it calls a getTotalNumberCampaigns() function in my campaignsService class. loadSize() { this.campaignsService.getTotalNumberCampaigns().subscribe(value => {//async call this.campaignSize = value; }, (err: any) => { console.log(err.status); console.log(err);} ); } this is my getTotalNumberCampaigns() getTotalNumberCampaigns(): Observable<number> { return this.http.get(`${this.apiUrl}/Count`, { headers: this.headers }) .map<any>(res => res.json()) } I start up the backend api everything works fine, now I stop the api and refresh my page. It will fire the console.log(err.status); console.log(err); since it's connection failed. but I actually got 200 status while in my browser console it says it is a 502 error. anyone tell me why? A: In fact, in the case of a connection failure, the response object you receive in your error callback is an error one since the value of its type attribute is 3 (ERROR). What is a bit strange is that it seems that the preflighted request is executed and received a response. Could you give us its details from the Network tab in dev tools (by clicking on "OPTIONS http://localhost:...")? See this question for more details: * *Get error message from Angular 2 http
{ "language": "en", "url": "https://stackoverflow.com/questions/35718175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Long-polling amazon sqs with android and ios sdk How would someone achieve this with not using http requests (rest). Is this possible with the native sdks? On android I am running a "every-2-second" iteration of a intent service call: scheduleTaskExecutor= Executors.newScheduledThreadPool(10); scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() { public void run() { Intent i = new Intent(MainActivity.this, AzureServiceBusHttpService.class); i.setAction(AzureServiceBusHttpService.START_LONG_POOL); startService(i); } }, 0, 2, TimeUnit.SECONDS); And on the service side (xxx is sensible data): AWSCredentials credentials = new BasicAWSCredentials("xxx", "xxx"); AmazonSQSClient sqsClient = new AmazonSQSClient(credentials); ReceiveMessageRequest rmr = new ReceiveMessageRequest("https://xxx.amazonaws.com/xxx/xxx"; rmr.setMaxNumberOfMessages(10); rmr.setVisibilityTimeout(30); ReceiveMessageResult result = sqsClient.receiveMessage(rmr); if (result.getMessages().size() > 0) { EventBus.getDefault().post(new MsgEvent(result.getMessages().get(0).getBody())); DeleteMessageRequest rreq = new DeleteMessageRequest("https://xxx.amazonaws.com/xxx/xxx", result.getMessages().get(0).getReceiptHandle()); sqsClient.deleteMessage(rreq); } I am wondering if this can be improved (reduced calls with long polling)? A: Long poll with setWaitTimeSeconds(waitTimeSeconds)? Or switch from pull (via SQS) to push (via SNS)?
{ "language": "en", "url": "https://stackoverflow.com/questions/31195333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Regex error c#? How i can use "/show_name=(.?)&show_name_exact=true\">(.?) Match m = Regex.Match(input, "/show_name=(.*?)&amp;show_name_exact=true\">(.*?)</i", RegexOptions.IgnoreCase); // Check Match instance if (m.Success) { // Get Group value string key = m.Groups[1].Value; Console.WriteLine(key); // alternate-1 } Error, Unterminated string literal(CS1039)] Error, Newline in constant(CS1010)] What I am doing wrong? A: I think you're mixing up .NET's regex syntax with PHP's. PHP requires you to use a regex delimiter in addition to the quotes that are required by the C# string literal. For instance, if you want to match "foo" case-insensitively in PHP you would use something like this: '/foo/i' ...but C# doesn't require the extra regex delimiters, which means it doesn't support the /i style for adding match modifiers (that would have been redundant anyway, since you're also using the RegexOptions.IgnoreCase flag). I think this is what you're looking for: @"show_name=(.*?)&amp;show_name_exact=true"">(.*?)<" Note also how I escaped the internal quotation mark using another quotation mark instead of a backslash. You have to do it that way whether you use the old-fashioned string literal syntax or C#'s verbatim strings with the leading '@' (which is highly recommended for writing regexes). That's why you were getting the unterminated string error.
{ "language": "en", "url": "https://stackoverflow.com/questions/575359", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Longest Common Subsequence of Three Sequences I've implemented my version of Longest Common Subsequence of Three Sequences and cannot find a mistake. But Coursera grader says that I fail last test case. It means that the algorithm is almost corrects but outputs a wrong answer in a specific case. But what case is it? Constraints: length of the list is not less than one and not bigger than 100. Numbers in the lists are integers from -10^9 to 10^9. import sys def lcs3(a, b, c): start_b = 0 start_c = 0 result = [] for i in range(len(a)): for j in range(start_b, len(b)): if a[i] == b[j]: for k in range(start_c, len(c)): if b[j] == c[k]: start_b = j+1 start_c = k+1 result.append(a[i]) break if b[j] == c[k]: break return len(result) def lcs3_reversed(a,b, c): # check reversed sequence which can be with different order a_rev = a[::-1] b_rev = b[::-1] c_rev = c[::-1] result = lcs3(a, b, c) result_reversed = lcs3(a_rev, b_rev, c_rev) if result == result_reversed: return result else: return result_reversed if __name__ == '__main__': input = sys.stdin.read() data = list(map(int, input.split())) an = data[0] data = data[1:] a = data[:an] data = data[an:] bn = data[0] data = data[1:] b = data[:bn] data = data[bn:] cn = data[0] data = data[1:] c = data[:cn] print(lcs3_reversed(a, b, c)) Update: added the function lcs3_reversed to solve the cases described by you. Anyway cannot pass the test case. Output should contain the length of common subsequence. For example, for input: 3 1 2 3 3 2 1 3 3 1 3 5 output is 2 because the common part is (1, 3) for these 3 lists. Runtime for failed case is 0.04 seconds and it looks like that the lists are rather long since most of my own tests worked much faster. Thanks for your help! Update2: I've tried another version. First we find the Longest Common Subsequence of 2 lists and then use it again on our result and the 3-rd list. def lcs2(a, b): start_b = 0 result = [] for i in range(len(a)): for j in range(start_b, len(b)): if a[i] == b[j]: start_b = j+1 result.append(a[i]) break return result def lcs2_reversed(a, b): # check reversed sequence which can be with different order a_rev = a[::-1] b_rev = b[::-1] result_reversed = lcs2(a_rev, b_rev)[::-1] return result_reversed def lcs3_reversed(a, b, c): lcs2_str = lcs2(a, b) lcs2_rev = lcs2_reversed(a, b) lcs3_str_str = lcs2(lcs2_str, c) lcs3_rev_rev = lcs2_reversed(lcs2_rev, c) lenghts = [len(lcs3_str_str), len(lcs3_rev_rev)] return max(lenghts) if __name__ == '__main__': an = input() a = input().split() bn = input() b = input().split() cn = input() c = input().split() print(max(lcs3_reversed(a, b, c), lcs3_reversed(a, c, b), lcs3_reversed(b, a, c), lcs3_reversed(b, c, a), lcs3_reversed(c, a, b), lcs3_reversed(c, b, a))) Moreover, I tried all the combinations of orders but it did not help... Again I cannot pass this last test case. A: Your example breaks with something like: a = [1,2,7,3,7] b = [2,1,2,3,7] c = [1,2,3,1,7] The sequence should be [1,2,3,7] (if I understand the exercise correctly), but the problem is that the last element of a gets matched to the last elements of b and c, which means that start_b and start_c are set to the last elements and therefore the loops are over.
{ "language": "en", "url": "https://stackoverflow.com/questions/36119853", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: WPF DataGrid Last column not resizing properly I am using a DataGrid control to display some data and the last comun of the grid does not resize appropriately when the grid receives new data. When the grid loads is completely empty and data gets inserted after some user input. All other columns of the Grid behave as supposed to, any ideas of what I should do to make the last column resize? My DataGrid XAML: <DataGrid Grid.Row="4" Grid.Column="0" Margin="4,4,4,4" ItemsSource="{Binding Order.OrderItems}" CanUserReorderColumns="True" SelectedItem="{Binding OrderItem}" Height="200" AutoGenerateColumns="False" CanUserSortColumns="True" SelectionMode="Single" VerticalScrollBarVisibility="Auto" CanUserAddRows="False"> <DataGrid.Columns> <DataGridTextColumn Header="SKU" Binding="{Binding SellerCode}"/> <DataGridTextColumn Header="Description" Width="*" Binding="{Binding Description}"/> <DataGridTextColumn Header="Quantity" Binding="{Binding Quantity}"/> <DataGridTextColumn Header="Net Cost" Binding="{Binding UnitCost, StringFormat='£ #,##0.00'}"/> <DataGridTextColumn Header="Total Cost" Binding="{Binding TotalCost, StringFormat='£ #,##0.00'}"/> <DataGridTextColumn Header="Gross" Binding="{Binding TotalCostWithVat, StringFormat='£ #,##0.00'}" Width="auto"/> </DataGrid.Columns> </DataGrid> Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/35454278", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Defining dictionary inside a class in python I am creating an empty dictionary inside a class and then I am trying to give the variables inside the dictionary some value. As shown in the code below. In the end, I am trying to print the dictionary values in the console but I receiving errors In the editor: import numpy as np class A: def __init__(self, variables = {}): self.variables = {} if ("leng") in variables: self.variables["leng"] = variables["leng"] else: self.variables["leng"] = np.array([10,]) if ("width") in variables: self.variables["width"]= variables["width"] else: self.variables["width"] = np.array([10,]) In the Console: variables.items() >>>"leng" : 10 >>>"width" : 10 A: Just use an object to call class items. m=A() and then m.variables
{ "language": "en", "url": "https://stackoverflow.com/questions/56527907", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Separate Socket.io into app.js I'm working on my Express project right, currently I have app.js, socket folder where are my sockets , but all my logic is in bin/www since Im using sockets in my routes like this: req.io.emit('dataUpdated', { id: client }); but I would like to seperate it into app.js how could I do that without breaking my app. here is my www file: var express = require('express'); var path = require('path'); var logger = require('morgan'); var bodyParser = require('body-parser'); var mongoose = require('mongoose'); var config = require('../config.json'); var appRoutes = require('./routes/Approutes'); var app = express(); app.use(express.static(path.join(__dirname, '../public'))); mongoose.Promise = global.Promise; mongoose.connect('localhost/db_test'); app.set('views', path.join(__dirname, '../views')); app.set('view engine', 'hjs'); app.set('appProperties', { secret: config.secret }); var siofu = require("socketio-file-upload"); app.use(siofu.router); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); var debug = require('debug')('express-seed:server'); var server = require('http').Server(app); /** * Get port from environment and store in Express. */ var port = normalizePort(process.env.PORT || '3000'); app.set('port', port); /** * Set socket */ var socketioJwt = require('socketio-jwt'); var socketIo = require('socket.io'); var io = socketIo.listen(server); io.use(socketioJwt.authorize({ secret: config.secret, handshake: true })); app.io = io; app.use(function(req, res, next) { 'use strict'; req.io = io; next(); }); app.use('/', appRoutes); require('../sockets/user')(io); /** * Listen on provided port, on all network interfaces. */ server.listen(port); server.on('error', onError); server.on('listening', onListening); /** * Normalize a port into a number, string, or false. */ function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('Listening on ' + bind); } my app.js file is empty... and my socket file exports = module.exports = function (io) { io.sockets.on('connection', (socket) => { socket.on('clientGetList', (req) => { // getting clientList }); }) } How can I move my logic from www file to app.js file without breaking the app? A: I would like to move my middleware, and socket connection to app.js and in www just to start server You can separate the code like this and pass both app and server variables to your app.js module where it can run the rest of the initialization code (middleware, routes, socket.io setup, etc...): // www const express = require('express'); const app = express(); const server = require('http').Server(app); const port = normalizePort(process.env.PORT || '3000'); app.set('port', port); // load app.js and let it do it's part of the initialization of app and server require('./app.js')(app, server); server.listen(port); server.on('error', onError); server.on('listening', onListening); /** * Normalize a port into a number, string, or false. */ function normalizePort(val) { var port = parseInt(val, 10); if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } /** * Event listener for HTTP server "error" event. */ function onError(error) { if (error.syscall !== 'listen') { throw error; } var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port; // handle specific listen errors with friendly messages switch (error.code) { case 'EACCES': console.error(bind + ' requires elevated privileges'); process.exit(1); break; case 'EADDRINUSE': console.error(bind + ' is already in use'); process.exit(1); break; default: throw error; } } /** * Event listener for HTTP server "listening" event. */ function onListening() { var addr = server.address(); var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port; debug('Listening on ' + bind); } And, then this would be an outline for app.js: const bodyParser = require('body-parser'); const siofu = require("socketio-file-upload"); const config = require('../config.json'); const appRoutes = require('./routes/Approutes'); const socketioJwt = require('socketio-jwt'); const socketIo = require('socket.io'); // export one function that gets called once as the server is being initialized module.exports = function(app, server) { app.set('views', path.join(__dirname, '../views')); app.set('view engine', 'hjs'); app.set('appProperties', { secret: config.secret }); app.use(siofu.router); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); var io = socketIo.listen(server); io.use(socketioJwt.authorize({ secret: config.secret, handshake: true })); app.io = io; app.use(function(req, res, next) { 'use strict'; req.io = io; next(); }); app.use('/', appRoutes); require('../sockets/user')(io); }
{ "language": "en", "url": "https://stackoverflow.com/questions/51053199", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get the same date result from Model.objects.create and Model.objects.get in Django? Given the following Django model: from django.db import models class SomeModel(models.Model): date = models.DateField() When I create an object with following code, type of date field is unicode obj = SomeModel.objects.create(date=u'2015-05-18') But when I get the same object from database, type of date field will be datetime.date obj = SomeModel.objects.get(pk=obj.pk) I know Django will transform u'2015-05-18' to a datetime.date object automatically, but why it returns the original unicode string with Model.objects.create()? is there a way to always get datetime.date from Model.objects.create() and Model.objects.get()? A: Simply pass an datetime object to the create method: from datetime import date obj = SomeModel.objects.create(date=date(2015, 5, 18)) or obj = SomeModel.objects.create(date=date.strftime('2015-05-18', '%y-%m-%d')) A: There are two ways Django transforms the data in a model. The first, when saving the model the data is transformed to the correct data type and send to the backend. The data on the model itself is not changed. The second, when the data is loaded from the database, it is converted to the datatype that Django thinks is most appropriate. This is by design: Django does not want to do any magic on the models itself. Models are just python class instances with attributes, so you are free to do whatever you want. This includes using the string u'2015-05-18' as a date or the string 'False' to store as True (yeah that's right). The database cannot store dates as arbitrary data types, so in the database it is just the equivalent of a Python date object. The information that it used to be a string is lost, and when loading the data directly from the database with get(), the data is consistently converted to the most appropriate Python data type, a date.
{ "language": "en", "url": "https://stackoverflow.com/questions/30296796", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Issue Initializing select2 dynamically Select2 initializes for the first item generated with on click and then on generating new div item with on click the select2 property is removed from the first item and initializes on the 2nd. $(document).ready(function(){ $("#packages #add_package").on("click", function(){ $(this).before( "<div class='col-12 packageCard'>"+ "<div class='col-4'>"+ "<div class='form-group'>"+ "<label>Container Type</label>"+ "<select name='cntType' id='cntType' class='form-control select2' data-dropdown-css-class='select2' style='width: 100%;'>"+ "<option value='0' selected='selected' disabled>Select Container Type</option>"+ "<option>20 feet</option>"+ "<option>40 feet</option>"+ "</select>"+ "</div>"+ "</div>"+ "</div>"); $('.select2').select2(); }); }) A: If you check your browser's devtools console, you will see a Javascript error thrown when you try to add the second select2: Uncaught query function not defined for Select2 undefined If you search for that error, you will find some other questions about this, for eg this one: "query function not defined for Select2 undefined error" And if you read through the answers and comments, you will find several which describe what you are doing: * *This comment: This problem usually happens if the select control has already been initialized by the .select2({}) method. A better solution would be calling the destroy method first. Ex: $("#mySelectControl").select2("destroy").select2({}); * *This answer: One of its other possible sources is that you're trying to call select2() method on already "select2ed" input. * *Also this answer: I also had this problem make sure that you don't initialize the select2 twice. ... and possibly more. These describe what you are doing - calling .select2() on elements which are already initialised as select2s. The second time $('.select2').select2() runs, as well as trying to initialise your new select2, it is re-initialising the first select2 as a select2 again. You have another problem in your code - every select has the same ID: id='cntType'. IDs must be unique on the page, so this is invalid HTML. We can solve both problems at once by keeping track of how many selects you have on the page, and giving each new one an ID including its number, like say cntType-1, cntType-2, etc. Then we can target just the new ID to initialise it as a select2. Here's a working example. $(document).ready(function () { // Track how many selects are on the page let selectCount = 0; $("#packages").on("click", function () { // New select! Increment our counter selectCount++; //. Add new HTML, using dynamically generated ID on the select $(this).before( "<div class='col-12 packageCard'>" + "<div class='col-4'>" + "<div class='form-group'>" + "<label>Container Type</label>" + "<select name='cntType' id='cntType-" + selectCount + "' class='form-control select2' data-dropdown-css-class='select2' style='width: 100%;'>" + "<option value='0' selected='selected' disabled>Select Container Type</option>" + "<option>20 feet</option>" + "<option>40 feet</option>" + "</select>" + "</div>" + "</div>" + "</div>"); // Initialise only our new select $('#cntType-' + selectCount).select2(); }); }) <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.0.0/select2.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/2.1.0/select2.min.js"></script> <button id="packages">Add</button>
{ "language": "en", "url": "https://stackoverflow.com/questions/74288361", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Visual Studio / Properties / Debug / Working Directory want it permanent but don't want to check in the *.user file The project setting Debugging / Working Directory in Visual Studio 20015 will be saved by default in the *.user file wich I don't check in in to my repo because it's user specific. Still, I would like to have something other than $(ProjectDir) standing there when I do a clean checkout of my project. Is there an other place to store the Working Directory besides the *.user file? Edit 1: The original idea is that I have a solution with multiple projects and all the binaries (dlls and exes) created end up in a folder called bin. If I want to debug it, I don't want to always edit the working directory again after a clean checkout. Edit 2: In a post build step of every project within my solution, I copy the binaries in to the bin folder. If I start one of the executables from within VS, it starts them from the $(ProjectDir) folder, and of course not from the bin folder. This is why it does not find the dlls and why I want to set the working directory. I could change the output directory of my projects but then I get a lot of files ending up in the bin folder I don't want there. I will try it anyway; maybe I missed something. To be continued... Edit 3: As expected, if I change the output directory to the bin folder, everything works fine except for some extra files that end up there and I don't want that (e.g. *.pbo, which would be okay, *.iobj, *.ipdb, etc.) Maybe that is the price I have to pay, but I don't like it. So, the question remains: How can I have more control over which file ends up where after a build and still be able to run it from VS without changing the working dir? A: The working directory should not have to be the directory that contains your DLLs. In fact, you definitely don't want that to be a requirement for running your application. Not only is it a hugely unexpected failure mode, but it could also be a potential security risk. Put the required DLLs in the same directory as your application's executable. That's the first place that the loader will look. If necessary, use a post-build event in your library projects to copy them there. A: Well since no body can help me I decided that I will change the output directory to the bin folder so VS will start my applications from the correct folder. And how I can get rid of all the extra files that don't belong there I will find a way later.
{ "language": "en", "url": "https://stackoverflow.com/questions/35036410", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Retrieving the last record in each group - MongoDB There is a collection of items with the following fields: id item_id quantity last_update ------------------------------------------- 1 111 10 2020-02-10 09:00:00 2 222 10 2020-02-10 09:00:00 2 222 15 2020-02-10 10:00:00 I want to retrieve the last updated record , for each group by id and item_id . The results should be: id item_id quantity last_update ------------------------------------------- 1 111 10 2020-02-10 09:00:00 2 222 15 2020-02-10 10:00:00 If it was SQL , then i would do something like: SELECT a.* FROM items a JOIN ( SELECT id ,item_id , max(last_update) as max_last_update FROM items ) as b ON a.id=b.id AND a.item_id=b.item_id AND a.last_update=b.max_last_update (or using self join) . I'm new to mongoDB , I did the inner query like: inner_query = db.items.aggregate({ $group : { _id: {id:"$id" , item_id:"$item_id"}, max_last_update: { $max : "$last_update" }}}) How can I use inner_query var to get the expected results? What is the equivalent in Mongo to JOIN or subquery? (i'm using mongodb 4.0.4) Thanks! A: Try this one: db.collection.aggregate([ { $sort: { id: 1, item_id: 1, last_update: -1 } }, { $group: { _id: { id: "$id", item_id: "$item_id" }, last_update: { $max: "$last_update" }, quantity: { $first: "$quantity" }, } }, { $project: { last_update: 1, quantity: 1, id: "$_id.id", item_id: "$_id.item_id", _id: 0 } } ]) Note, make proper $sort, otherwise $frist will return wrong value.
{ "language": "en", "url": "https://stackoverflow.com/questions/60154484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Fastest and efficient way to update mysql data I have 2 db tables: Tbl1: * *user_id *item_id *qty *date_purchase Tbl2 (summary of table 1): * *user_id *item_id *number_of_qty_purchased *last_purchase For now I have only a few thousands of Tbl1. My concern is the scalability of my current approach (retrieve and manually loop on program level, then update the Tbl2) What is the best way to update Tbl2? Best regards. A: You don't need table 2 at all. You can determine what you're after from table 2 by querying table 1. * *Number purchased of any item: Select sum(qty) from table_1 where item_id = [id of your item] and user_id = [id of your user]; * *Last purchased date of given item for given user select max(date_purchase) from table_1 where item_id = [id of your item] and user_id = [id of your user]; Also, remember to add indexes to table 1 so that your querying is as fast as possible.
{ "language": "en", "url": "https://stackoverflow.com/questions/45389717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: I am trying to get json data from bitbns.com but getting an error I am very new to javascript and I am trying to get json data from bitbns but getting error - "(Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://www.bitbns.com’)." I searched a lot on internet but could not find any solution. <script> url="https://www.bitbns.com/order/getTicker"; var request = new Request(url); fetch(request, {mode: "cors", }).then(function(response) { return response.json(); }).then(function(j) { console.log(JSON.stringify(j)); }).catch(function(error) { console.log('Request failed', error) }); console.log(request.headers) </script> Can anyone help me with this at all? A: var proxyUrl = 'https://cors-anywhere.herokuapp.com/' var url="https://www.bitbns.com/order/getTicker"; let x = proxyUrl + url fetch(x, {mode: "cors", }).then(function(response) { return response.json(); }).then(function(j) { console.log(JSON.stringify(j)); }).catch(function(error) { console.log('Request failed', error) }); This will get things rolling, but it is better not to use this for production due to lack of security. https://cors-anywhere.herokuapp.com/ is a link that add cors header. A: Here is what i found on https://www.sencha.com/forum/showthread.php?299915-How-to-make-an-ajax-request-cross-origin-CORS $.ajax({ url: 'http:ww.abc.com?callback=?', dataType: 'JSONP', jsonpCallback: 'callbackFnc', type: 'GET', async: false, crossDomain: true, success: function () { }, failure: function () { }, complete: function (data) { if (data.readyState == '4' && data.status == '200') { errorLog.push({ IP: Host, Status: 'SUCCESS' }) } else { errorLog.push({ IP: Host, Status: 'FAIL' }) } } });
{ "language": "en", "url": "https://stackoverflow.com/questions/48599173", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to filter data using Linq in List I am calling stored procedure to get data from database using Linq. This stored procedure is using more than one table to return result using join : public static List<classname> GetMediaTemp() { var medialist = (from m in Context.sp_Temp() select new classname { str_image = m.str_image, str_image_type = m.str_image_type, str_photodrawvideo = m.str_photodrawvideo, }).ToList(); if (medialist.Count > 0) { return medialist } } Everything working fine but now i have to filter data in this object list like on the calling end List<classname> photoList = GetMediaTemp();//Here i want to filter list on the basis on str_photodrawvideo column. Problem : How i can perform this filter ? Thanks in Advance. For more info please let me know. A: you can do as below var objList = Context.sp_Temp().ToList(); var photoList = objList.Where(o=>o._int_previous == 1).ToList(); Or you can cast the object to Class which build the object list as below var photoList = (from pht in objList let x=>(sp_TempResult)pht where x._int_previous == 1 select pht).ToList();
{ "language": "en", "url": "https://stackoverflow.com/questions/19396781", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: IPhone SDK - How to serialize ABRecord? I'm new in iPhone development, can you advice me how to serialize AdressBook records? I have read stackoverflow - How do I serialize a simple object in iPhone sdk, but I still have questions: should I extend ABRecordRef? Is it possible? Or should I implement own class NSObject? (similar question was on Mac forums and was left without answer) Thank you! A: ABRecord is an opaque C type. It is not an object in the sense of Objective-C. That means you can not extend it, you can not add a category on it, you can not message it. The only thing you can do is call functions described in ABRecord Reference with the ABRecord as a parameter. You could do two things to be able to keep the information referenced by the ABRecord arround: * *Get the ABRecords id by ABRecordGetRecordID(). The ABRecordID is defined as int32_t so you can cast it to an NSInteger and store it wherever you like. You can later get the record back from ABAddressBookGetPersonWithRecordID () or ABAddressBookGetGroupWithRecordID(). But aware, the record could be changed or even deleted by the user or another app meanwhile. *Copy all values inside the record to a standard NSObject subclass and use NSCoding or other techniques to store it. You will then of cause not benefit from changes or additions to the record the user could have made. Of cause you can combine both approaches.
{ "language": "en", "url": "https://stackoverflow.com/questions/3204712", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Platform Migration: Error when compiling project A few weeks ago I started a Firebase course with flutter, and I was programming on a Windows computer, and now I've been using a Mac for a few days, to learn how to make firebase with iOS too. However, I have received these errors, and I do not know if I am missing a file, lines of code or if I have obsolete code. I tried some solutions I found on the internet, like deleting the files pubspec.lock, podfile, podfile.lock, reinstalling using pod init and pod install, but none of these solutions managed to solve the problem. I know very little about Swift / Objective-C, and this project is connected (android) on firebase. /Users/mobileteam/Desktop/pasta_mary/aikoBot/aiko_bot/ios/Pods/FirebaseCrashlytics/Crashlytics/Shared/FIRCLSFABHost.m100:11: warning: 'UI_USER_INTERFACE_IDIOM' is deprecated: first deprecated in iOS 13.0 - Use -[UIDevice userInterfaceIdiom] directly. [-Wdeprecated-declarations] switch (UI_USER_INTERFACE_IDIOM()) { ^ In module 'UIKit' imported from /Users/mobileteam/Desktop/pasta_mary/aikoBot/aiko_bot/ios/Pods/FirebaseCrashlytics/Crashlytics/Shared/FIRCLSFABHost.m:20: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator14.1.sdk/System/Library/Frameworks/UIKit.framework/Headers/UIDevice.h:97:36: note: 'UI_USER_INTERFACE_IDIOM' has been explicitly marked deprecated here static inline UIUserInterfaceIdiom UI_USER_INTERFACE_IDIOM() API_DEPRECATED("Use -[UIDevice userInterfaceIdiom] directly.", ios(2.0, 13.0), tvos(9.0, 11.0)) { ^ 1 warning generated. /Users/mobileteam/Desktop/pasta_mary/aikoBot/aiko_bot/ios/Runner/AppDelegate.swift:14:18: error: cannot override with a stored property 'window' override var window: UIWindow? ^ Flutter.FlutterAppDelegate:2:14: note: attempt to override property here open var window: UIWindow! { get set } ^ note: Using new build system note: Building targets in parallel note: Planning build note: Constructing build description
{ "language": "en", "url": "https://stackoverflow.com/questions/64822466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Three.js particles vs particle system and picking I have an app that uses a Three.js ParticleSystem to render on the order of 50,000 points. I have spent a lot of time searching for efficient ways to do picking (ray-casting) so as to be able to interact with individual points but have not found a good solution. I am considering changing to just using an array of Particles instead of ParticleSystems. My questions are: * *Am I missing something; is there a good way to do picking with the ParticleSystem? *Will I suffer a performance hit using an array of Particles instead of the ParticleSystem, especially since I am taking advantage of the ability to pass several arrays of attributes into the shader. Thanks for any insight anyone can provide! A: You're checking 50,000 points every time. That's a bit too much. You may want to split those points into different ParticleSystems... Like 10 objects with 5000 particles each. Ideally each object would compose a different "quadrant" so the Raycaster can check the boundingSphere first and ignore all those points if not intersecting.
{ "language": "en", "url": "https://stackoverflow.com/questions/24565368", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: findViewById returns null for EditText passing values from one class to another class Here is my code. public void HandleSearchButtonValue(int START_INDEX,int places,String featurea) { try { EditText locationEdit=(EditText)findViewById(places); InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(locationEdit.getWindowToken(), 0); String locationAddress =locationEdit.getText().toString(); /*try { Geocoder geocoder; List<Address> addresses; geocoder = new Geocoder(this, Locale.getDefault()); addresses = geocoder.getFromLocation(lat, longt, 1); addressline = addresses.get(0).getAddressLine(0); } catch (IOException e) { return; } String locationAddress =addressline;*/ if (locationAddress.equals("")){ removePoint(START_INDEX); map.invalidate(); return; } Toast.makeText(this, "Searching:\n"+locationAddress, Toast.LENGTH_LONG).show(); AutoCompleteOnPreferences.storePreference(this, locationAddress, SHARED_PREFS_APPKEY, PREF_LOCATIONS_KEY); new GeocodingTask().execute(locationAddress, START_INDEX); String feature = featurea; mPoiMarkers = new RadiusMarkerClusterer(this); Drawable clusterIconD = getResources().getDrawable(R.drawable.marker_atm); Bitmap clusterIcon = ((BitmapDrawable) clusterIconD).getBitmap(); mPoiMarkers.setIcon(clusterIcon); mPoiMarkers.mAnchorV = Marker.ANCHOR_BOTTOM; mPoiMarkers.mTextAnchorU = 0.70f; mPoiMarkers.mTextAnchorV = 0.27f; mPoiMarkers.getTextPaint().setTextSize(12.0f); map.getOverlays().add(mPoiMarkers); updateUIWithPOI(mPOIs, ""); if (!feature.equals("")) Toast.makeText(this, "Searching:\n" + feature, Toast.LENGTH_LONG).show(); getPOIAsync(feature); } catch (Exception e) { e.getMessage(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/31959121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Aggregate root references another aggregate root by ID, how to maintain integrity using RavenDB? Say I have X as an aggregate root, and Y as another aggregate root. Using a NoSql document database, X holds a reference to Y by Y's Id. If Y is deleted (independently outside of X's context), then X holds a reference to a Y that does not exist. What is a proposed solution to eliminate or solve this problem in DDD? A: A delete operation should have a business meaning. For example, just because someone deleted a product from the inventory collection, does not mean it should be deleted from users invoices. If there is a real need for a delete. You can always define an index in RavenDB and update the entities containing that aggregate root ID. A: I do not know if DDD speaks to your problem directly but the proposed "solution" may lie in Domain Events / Messaging. If the related aggregate is in the same bounded context a domain event may suffice else you may need messaging infrastructure to communicate with another bounded context. What happens when you receive the 'deleted' event is another story and possibly your domain experts can help. As alluded to by @Dmitry S. you may need to denormalize the related aggregate data into a value object so that you have enough information to keep the main aggregate consistent. When processing the 'deleted' event then you may want to set some indicator on your main aggregate or update the data somehow to reflect the deletion. A: Why would you ever delete an aggregate? You might want to Expire() it or Suspend(). Deactivate(), Disable(), Ban(), Cancel(), Finish() or Archive(). But what benefit would you get from loosing your data with Delete()? If you really need that (possibly due to legal purposes) maybe some EvaporaitonService should be created and it would find all related aggregates and whipe all references.
{ "language": "en", "url": "https://stackoverflow.com/questions/22303668", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can a Java application be informed on receipt of a [FIN,ACK] on a TCP connection? I have 2 connections established from a JMeter instance to an Apache Server, and from the Apache server to a Java application deployed in Jonas. When I kill the JMeter process, the connection to Apache is closed with a [RST]. Then Apache sends a [FIN, ACK] to Jonas. Jonas has not sent all data, so it keeps sending data. Jonas closes the connection later with a [FIN,ACK]. This behaviour is described in TCP RFC. So, the problem is Apache receives all data from Jonas, even if Apache can not send it to JMeter. My question is: Can my Java application be triggered on receipt of the FIN,ACK send from Apache ? A: Not directly, eventually java may throw a IOException from the InputStream or OutputStream but this is platform dependent. there was talk of a "raw sockets" java implementation prior to the release of JDK 7 but somehow I don't think it ever got off the ground. A: Can my Java application be triggered on receipt of the FIN,ACK send from Apache ? Yes, but you would have to be reading from the connection. You will get end of stream in one of its various forms, depending on which read method you call. See the Javadoc.
{ "language": "en", "url": "https://stackoverflow.com/questions/29006747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java JVM Default Garbage Collector: is it configured the same across different applications? Simply as specified in the title. I ran a test and recorded its memory heap usage pattern over time using JMX. Then I reran my jar file later and studied its memory behavior again. The result was a slightly different memory pattern. In both cases I didn't preconfigure my garbage collector. So I want to know now if two default garbage collectors have the same configurations on the same machine. If not, how can I ensure that my garbage collector is the same without specifying many parameters? Also what could contribute to my result if not the GC config? A: If you run the same application on the same machine, with the same JVM, the heap and GC parameters will be the same. Ergonomics was a feature introduced way back in JDK 5.0 to try and take some of the guesswork out of GC tuning. A server-class machine (2 or more cores and 2 or more Gb of memory) will use 1/4 of physical memory (up to 1Gb) for both the initial and maximum heap sizes (see https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/ergonomics.html). So different machines may have different configurations by default. To find out exactly what flags you have set, use: java -XX:+PrintFlagsFinal -version The difference in memory usage pattern is simply the non-deterministic behaviour of your application. Even with the exact same set of inputs, I doubt you'd see exactly the same memory behaviour just down to so many other OS and hardware effects (cache, core affinity, etc.)
{ "language": "en", "url": "https://stackoverflow.com/questions/54884503", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Manage token life duration with SimpleCookie in Python Already got token working correctly, which is set this way: session_cookie = SimpleCookie() session_cookie['key'] = any_string_value session_cookie['key']["Path"] = '/' headers = [] headers.extend(("set-cookie", morsel.OutputString()) for morsel in session_cookie.values()) start_response(status, headers) I am also able to read the token and extract the information I need: # Get cookies cookies = request.get_cookies() # Get current token from cookies token = cookies['token'].value Now, what would be the best approach to set an expiration to a cookie, I know there is 2 possible keys: * *session_cookie['key']['max-age'] = "time in secods" *session_cookie['key']['expiration'] = "a date in the future" How could I know if a token is expired or what could be the best way to manage expired tokens ? Thanks a lot! A: You can know if a token has expired if the token does not exist when you try to get it. token = cookies['token'].value #this will not exist The browser deletes the cookie and everything related to that when the expiration date passes. This way in many implementations you can even delete cookies or for example log-out a user just but setting the expiration date of the user_id cookie to something in the past( eg a negative number). Now as I understand you need a policy to detect expired tokens server side and that can be accomplished by double validation. Eg try to store an unique identifier for each token and server side when you read the token try to check if it has expired. It's also possible for the user to manipulate his cookies so never blindly trust cookies to store significant data or make any user_id simple validation. I hope I helped. EDIT From rfc2109 Max-Age=delta-seconds Optional. The Max-Age attribute defines the lifetime of the cookie, in seconds. The delta-seconds value is a decimal non- negative integer. After delta-seconds seconds elapse, the client should discard the cookie. A value of zero means the cookie should be discarded immediately. And from wiki http cookies The Expires directive tells the browser when to delete the cookie. Derived from the format used in RFC 1123, the date is specified in the form of “Wdy, DD Mon YYYY HH:MM:SS GMT”,[29] indicating the exact date/time this cookie will expire. As an alternative to setting cookie expiration as an absolute date/time, RFC 6265 allows the use of the Max-Age attribute to set the cookie’s expiration as an interval of seconds in the future, relative to the time the browser received the cookie. I would recommend to use max-age because saves some trouble from setting dates etc. You just calculate an interval. Reading a bit more I found that max-age is not supported by IE < 9 and that means that expires is preferred Max-Age vs Expires That should help ;-)
{ "language": "en", "url": "https://stackoverflow.com/questions/14141373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Push a set of values to an array based on another unique value in the same array Question background Hello, I have the following array of movie crew members: array:7 [▼ 0 => array:6 [▼ "credit_id" => "52fe49dd9251416c750d5e9d" "department" => "Directing" "id" => 139098 "job" => "Director" "name" => "Derek Cianfrance" "profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg" ] 1 => array:6 [▼ "credit_id" => "52fe49dd9251416c750d5ed7" "department" => "Writing" "id" => 139098 "job" => "Story" "name" => "Derek Cianfrance" "profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg" ] 2 => array:6 [▼ "credit_id" => "52fe49dd9251416c750d5edd" "department" => "Writing" "id" => 132973 "job" => "Story" "name" => "Ben Coccio" "profile_path" => null ] 3 => array:6 [▼ "credit_id" => "52fe49dd9251416c750d5ee3" "department" => "Writing" "id" => 139098 "job" => "Screenplay" "name" => "Derek Cianfrance" "profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg" ] 4 => array:6 [▼ "credit_id" => "52fe49dd9251416c750d5ee9" "department" => "Writing" "id" => 132973 "job" => "Screenplay" "name" => "Ben Coccio" "profile_path" => null ] 5 => array:6 [▼ "credit_id" => "52fe49dd9251416c750d5eef" "department" => "Writing" "id" => 1076793 "job" => "Screenplay" "name" => "Darius Marder" "profile_path" => null ] 11 => array:6 [▼ "credit_id" => "52fe49de9251416c750d5f13" "department" => "Camera" "id" => 54926 "job" => "Director of Photography" "name" => "Sean Bobbitt" "profile_path" => null ] ] As you can see this is a list of credits I'm getting via the TMDb API. The first step of building the above array was to filter out all jobs that I don't want to display, here's how I did that: $jobs = [ 'Director', 'Director of Photography', 'Cinematography', 'Cinematographer', 'Story', 'Short Story', 'Screenplay', 'Writer' ]; $crew = array_filter($tmdbApi, function ($crew) use ($jobs) { return array_intersect($jobs, $crew); }); My question I'd like to figure out how to take the above result one step further and combine jobs where the id is the same, so as to end up with something like this, for example: array:7 [▼ 0 => array:6 [▼ "credit_id" => "52fe49dd9251416c750d5e9d" "department" => "Directing" "id" => 139098 "job" => "Director, Story, Screenplay" "name" => "Derek Cianfrance" "profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg" ] I have also considered ditching doing this in my logic and instead doing it in my blade template, but I'm not sure how to achieve that. How would you accomplish this? A: Since you are trying to edit the array elements and its size, I believe array_map() or array_filter() won't be a solution to this. This is what I could come up with... $jobs = [ 'Director', 'Director of Photography', 'Cinematography', 'Cinematographer', 'Story', 'Short Story', 'Screenplay', 'Writer' ]; $crew = []; foreach($tmdbApi as $key => $member) { if($member['id'] == $id && in_array($member['job'], $jobs)) { if(!isset($crew[$key])) { $crew[$key] = $member; } else { $crew_jobs = explode(', ', $crew[$key]['job']); if(!in_array($member['job'], $crew_jobs)) { $crew_jobs[] = $member['job']; } $crew[$key]['job'] = implode(', ', $crew_jobs); } } } Hope this answers your question :) A: You could nicely use Laravel's Collection in such a situation, which has a great number of methods which will help you in this case. First, turn this array (the one you already filtered on jobs) to a Collection: $collection = collect($crew); Second, group this Collection by it's ids: $collectionById = $collection->groupBy('id'); Now, the results are grouped by the id and transformed to a Collection in which the keys correspond to the id, and the value an array of 'matching' results. More info about it here. Finally, just a easy script that iterates through all the results for each id and combines the job field: $combinedJobCollection = $collectionById->map(function($item) { // get the default object, in which all fields match // all the other fields with same ID, except for 'job' $transformedItem = $item->first(); // set the 'job' field according all the (unique) job // values of this item, and implode with ', ' $transformedItem['job'] = $item->unique('job')->implode('job', ', '); /* or, keep the jobs as an array, so blade can figure out how to output these $transformedItem['job'] = $item->unique('job')->pluck('job'); */ return $transformedItem; })->values(); // values() makes sure keys are reordered (as groupBy sets the id // as the key) At this point, this Collection is returned: Collection {#151 ▼ #items: array:4 [▼ 0 => array:6 [▼ "credit_id" => "52fe49dd9251416c750d5e9d" "department" => "Directing" "id" => 139098 "job" => "Director, Story, Screenplay" "name" => "Derek Cianfrance" "profile_path" => "/zGhozVaRDCU5Tpu026X0al2lQN3.jpg" ] 1 => array:6 [▼ "credit_id" => "52fe49dd9251416c750d5edd" "department" => "Writing" "id" => 132973 "job" => "Story, Screenplay" "name" => "Ben Coccio" "profile_path" => null ] 2 => array:6 [▼ "credit_id" => "52fe49dd9251416c750d5eef" "department" => "Writing" "id" => 1076793 "job" => "Screenplay" "name" => "Darius Marder" "profile_path" => null ] 3 => array:6 [▼ "credit_id" => "52fe49de9251416c750d5f13" "department" => "Camera" "id" => 54926 "job" => "Director of Photography" "name" => "Sean Bobbitt" "profile_path" => null ] ] } Note: to use this Collection as an array, use: $crew = $combinedJobCollection->toArray(); There are multiple ways to achieve this, for example: search the array for overlapping id's, but I think this is the easiest way to achieve this. Goodluck!
{ "language": "en", "url": "https://stackoverflow.com/questions/40821900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Adding text from custom script to Kodi Home page via XML I'm guessing this is fairly easy for someone who knows what they are doing. Unfortunately I don't and as much as I would like to spend the next three days googling stuff my 4 year old got a lot of new presents for Christmas and I really should play with him so maybe someone can help me out. I want to add my external IP address and Geo location to the Kodi home page. I've taken a copy of the default skin and located the Home.xml file that is used to generate the home page. I have added a label but I don't know how to get this label to display the results of a script. For example I have a bash getmyip.sh script that is located in /storage/downloads/ and runs the simple bit of code below. curl -s http://whatismijnip.nl |cut -d " " -f 5 This gives me my external IP. I've added a label to the home.xml file as shown below. This was written by someone else and gives me my internal IP. The question is how can I modify it by running my script (or heck some other method) to get my external IP and Geo location when connected to my VPN? Any suggestions gratefully received. I just don't really know any XML. Thank you! <control type="label"> <description>IP Address</description> <left>200</left> <top>5</top> <height>49</height> <width min="200" max="300">auto</width> <label>IP: $INFO[Network.IPAddress]</label> <align>left</align> <aligny>center</aligny> <font>font12</font> <textcolor>white</textcolor> <shadowcolor>black</shadowcolor> </control> A: You have to adjust your getmyip.sh to the following code: #!/bin/sh python getmyexternalip.py Then create the python file called getmyexternalip.py and add following code: import subprocess import xbmcgui output = subprocess.check_output("curl -s http://whatismijnip.nl |cut -d ' ' -f 5", shell=True) output = output.rstrip('\n') xbmcgui.Window(10000).getControl(32000).setLabel("IP: " + str(output)) Also you have to adjust the XML to have an id on this control: <control type="label" id="32000"> Please consider that the id has to be the same as in the parameter in the xbmcgui.Window(10000).getControl function. The ID 10000 in the python script for the window is the default Window ID for the Home.xml
{ "language": "en", "url": "https://stackoverflow.com/questions/41383151", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using multiple Perl regular expressions to find and replace I'm a Perl and regex newcomer in need of your expertise. I need to process text files that include placeholder lines like Foo Bar1.jpg and replace those with with corresponding URLs like https:/baz/qux/Foo_Bar1.jpg. As you may have guessed, I'm working with HTML. The placeholder text refers to the filename, which is the only thing available when writing the document. That's why I have to use placeholder text. Ultimately, of course, I want to replace the filename with the URL (after I upload file to my CMS to get the URL). At that point, I have all of the information at hand — the filename and the URL. Of course, I could just paste the URLs over the placeholder names in the HTML document. In fact, I've done that. But I'm certain that there's a better way. In short, I have placeholder lines like this: Foo Bar1.jpg Foo Bar2.jpg Foo Bar3.jpg And I also have URL lines like this: https:/baz/qux/Foo_Bar1.jpg https:/baz/qux/Foo_Bar2.jpg https:/baz/qux/Foo_Bar3.jpg I want to find the placeholder string and capture a differentiator like Bar1 with a regex. Then I want to use the captured part like Bar1 to perform another regex search that matches part of the corresponding URL string, i.e. https:/baz/qux/Foo_Bar1.jpg. After a successful match, I want to replace the Foo Bar1.jpg line with https:/baz/qux/Foo_Bar1.jpg. Ultimately, I want to do that for every permutation, so that https:/baz/qux/Foo_Bar2.jpg also replaces Foo Bar2.jpg and so on. I've written regular expressions that match both the placeholder and the URL. That's not my problem, as far as I can tell. I can find the strings I need to process. For example, /[a-z]+\s([a-z0-9]+)\.jpg/ successfully matches what I'm calling the placeholder text and captures what I'm calling the differentiator. However, though I've spent an embarrassing number of hours over the past week reading through Stack Overflow, various other sites and O'Reilly books on Pearl and Pearl Regular Expressions, I can't wrap my mind around how to process what I can find. A: I think the piece you are missing is the idea of using Perl's internal grep function, for searching a list of URL lines based on what you are calling your "differentiator". Slurp your URL lines into a Perl array (assuming there are a finite manageable number of them, so that memory is not clobbered): open URLS, theUrlFile.txt or die "Cannot open.\n"; my @urls = <URLS>; Then within the loop over your file containing "placeholders": while (my $key = /[a-z]+\s([a-z0-9]+)\.jpg/g) { my @matches = grep $key, @urls; if (@matches) { s/[a-z]+\s$key\.jpg/$matches[0]/; } } You may also want to insert error/warning messages if @matches != 1.
{ "language": "en", "url": "https://stackoverflow.com/questions/38056507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: I am getting an error when transforming datetime javascript I'm using date.toISOString() to use DateTime format "yyyy-MM-dd'T'HH: mm: ss'Z '", I must use ISO 8601 format. At the time of transformation, the time is showing it 5 hours in advance, that is, I am receiving for example this hour 2020-12-03 16:28:20 and at the time of transforming I show this 2020-12-03T21: 26: 52.000Z (5 hours in advance). I would like to know why it happens? Thank you
{ "language": "en", "url": "https://stackoverflow.com/questions/65183502", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: occasionally i get Server Error (500) Missing staticfiles manifest entry Before you mark it as duplicate, i did search and go throw many questions https://stackoverflow.com/search?q=[django]+Missing+staticfiles+manifest+entry my site works, but sometimes i get Server Error (500), And in logs i get: ValueError: Missing staticfiles manifest entry for 'css/jquery-ui.css' it's the first file in base.html. i think when staticfiles is missing a file, the site should stop at once. in staticfiles.json there is "css/jquery-ui.css": "css/jquery-ui.koi84nfyrp.css", mysite: storage = s3 cdn = cloudflare django = 4.0.4 P.S: in AWS bill center, there is $0.03 total, but i never get a bill or bay them any. Error Traceback ERROR [django.request:241] Internal Server Error: / Traceback (most recent call last): File "/django-my-site/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/django-my-site/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/django-my-site/venv/lib/python3.8/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content File "/django-my-site/venv/lib/python3.8/site-packages/django/template/response.py", line 92, in rendered_content return template.render(context, self._request) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/backends/django.py", line 62, in render return self.template.render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 175, in render return self._render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 167, in _render return self.nodelist.render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 1000, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 1000, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 958, in render_annotated return self.render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/loader_tags.py", line 157, in render return compiled_parent._render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 167, in _render return self.nodelist.render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 1000, in render return SafeString("".join([node.render_annotated(context) for node in self])) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 1000, in <listcomp> return SafeString("".join([node.render_annotated(context) for node in self])) File "/django-my-site/venv/lib/python3.8/site-packages/django/template/base.py", line 958, in render_annotated return self.render(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/templatetags/static.py", line 116, in render url = self.url(context) File "/django-my-site/venv/lib/python3.8/site-packages/django/templatetags/static.py", line 113, in url return self.handle_simple(path) File "/django-my-site/venv/lib/python3.8/site-packages/django/templatetags/static.py", line 129, in handle_simple return staticfiles_storage.url(path) File "/django-my-site/venv/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 166, in url return self._url(self.stored_name, name, force) File "/django-my-site/venv/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 145, in _url hashed_name = hashed_name_func(*args) File "/django-my-site/venv/lib/python3.8/site-packages/django/contrib/staticfiles/storage.py", line 465, in stored_name raise ValueError( ValueError: Missing staticfiles manifest entry for 'css/jquery-ui.css' settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # 3rd Party 'crispy_forms', 'crispy_bootstrap5', 'hitcount', 'corsheaders', 'storages', 'verify_email.apps.VerifyEmailConfig', # Local apps '...' ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', # 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = [ 'http://localhost:8000', 'http://127.0.0.1:8000', ] AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / "media" STATICFILES_DIRS = [ BASE_DIR / "static", ] AWS_ACCESS_KEY_ID = '***' AWS_SECRET_ACCESS_KEY = '***' AWS_STORAGE_BUCKET_NAME = '***' AWS_REGION_NAME = '***' AWS_QUERYSTRING_AUTH = False AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATIC_URL = 'https://%s/' % AWS_S3_CUSTOM_DOMAIN STATICFILES_STORAGE = 'storages.backends.s3boto3.S3ManifestStaticStorage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
{ "language": "en", "url": "https://stackoverflow.com/questions/72653856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Record video with AVAssetWriter: first frames are black I am recording video (the user also can switch to audio only) with AVAssetWriter. I start the recording when the app is launched. But the first frames are black (or very dark). This also happens when I switch from audio to video. It feels like the AVAssetWriter and/or AVAssetWriterInput are not yet ready to record. How can I avoid this? I don't know if this is a useful info but I also use a GLKView to display the video. func start_new_record(){ do{ try self.file_writer=AVAssetWriter(url: self.file_url!, fileType: AVFileTypeMPEG4) if video_on{ if file_writer.canAdd(video_writer){ file_writer.add(video_writer) } } if file_writer.canAdd(audio_writer){ file_writer.add(audio_writer) } }catch let e as NSError{ print(e) } } func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, from connection: AVCaptureConnection!){ guard is_recording else{ return } guard CMSampleBufferDataIsReady(sampleBuffer) else{ print("data not ready") return } guard let w=file_writer else{ print("video writer nil") return } if w.status == .unknown && start_recording_time==nil{ if (video_on && captureOutput==video_output) || (!video_on && captureOutput==audio_output){ print("START RECORDING") file_writer?.startWriting() start_recording_time=CMSampleBufferGetPresentationTimeStamp(sampleBuffer) file_writer?.startSession(atSourceTime: start_recording_time!) }else{ return } } if w.status == .failed{ print("failed /", w.error ?? "") return } if captureOutput==audio_output{ if audio_writer.isReadyForMoreMediaData{ if !video_on || (video_on && video_written){ audio_writer.append(sampleBuffer) //print("write audio") } }else{ print("audio writer not ready") } }else if video_output != nil && captureOutput==video_output{ if video_writer.isReadyForMoreMediaData{ video_writer.append(sampleBuffer) if !video_written{ print("added 1st video frame") video_written=true } }else{ print("video writer not ready") } } } A: Ok, stupid mistake... When launching the app, I init my AVCaptureSession, add inputs, outputs, etc. And I was just calling start_new_record a bit too soon, just before commitConfiguration was called on my capture session. At least my code might be useful to some people. A: SWIFT 4 SOLUTION #1: I resolved this by calling file_writer?.startWriting() as soon as possible upon launching the app. Then when you want to start recording, do the file_writer?.startSession(atSourceTime:...). When you are done recording and call finishRecording, when you get the callback that says that's complete, set up a new writing session again. SOLUTION #2: I resolved this by adding half a second to the starting time when calling AVAssetWriter.startSession, like this: start_recording_time = CMSampleBufferGetPresentationTimeStamp(sampleBuffer) let startingTimeDelay = CMTimeMakeWithSeconds(0.5, 1000000000) let startTimeToUse = CMTimeAdd(start_recording_time!, startingTimeDelay) file_writer?.startSession(atSourceTime: startTimeToUse) SOLUTION #3: A better solution here is to record the timestamp of the first frame you receive and decide to write, and then start your session with that. Then you don't need any delay: //Initialization, elsewhere: var is_session_started = false var videoStartingTimestamp = CMTime.invalid // In code where you receive frames that you plan to write: if (!is_session_started) { // Start writing at the timestamp of our earliest sample videoStartingTimestamp = currentTimestamp print ("First video sample received: Starting avAssetWriter Session: \(videoStartingTimestamp)") avAssetWriter?.startSession(atSourceTime: videoStartingTimestamp) is_session_started = true } // add the current frame pixelBufferAdapter?.append(myPixelBuffer, withPresentationTime: currentTimestamp) A: This is for future users... None of the above worked for me and then I tried changing the camera preset to medium which worked fine
{ "language": "en", "url": "https://stackoverflow.com/questions/44135223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How to support (on win7) GDI, D3D11 interoperability? I created a D3D11 device and can perform operations such as rendering pictures smoothly, but in order to also support GDI, I tried several methods: * *Through swapchain -> GetBuffer(ID3D11Texture2D) -> CreateDxgiSurfaceRenderTarget -> ID2D1GdiInteropRenderTarget -> GetDC, finally get the DC. It runs normally on my Win10, but an exception report when running GetDC on Win7: _com_error. *Via swapchain -> GetBuffer(IDXGISurface1) -> GetDC, same as 1. I suspect that the ID3D11Texture2D/IDXGISurface1 obtained by GetBuffer on Win7 will have some restrictions on the use of GDI, so I changed to dynamically create a new ID3D11Texture2D by myself, and now use DC alone/D3D11 drawing interface alone It works fine, but if I interoperate, I will find that gdi opertaion is drawn on the custom-created ID3D11Texture2D instead of the back_buffer of swapchain: _d3d->Clear(); _d3d->DrawImage(); HDC hdc = _d3d->GetDC(); DrawRectangleByGDI(hdc); _d3d->ReleaseDC(); _d3d->Present(); So how to do it: Whether the D3D or DC methods is drawn, they are all on the same ID3D11Texture2D? This way, it is also convenient for my CopyResource. HRESULT CGraphRender::Resize(const UINT32& width, const UINT32& height) { _back_texture2d = nullptr; _back_rendertarget_view = nullptr; _dc_texture2d = nullptr; _dc_render_target = nullptr; float dpi = GetDpiFromD2DFactory(_d2d_factory); //Backbuffer HRESULT hr = _swap_chain->ResizeBuffers(2, width, height, DXGI_FORMAT_B8G8R8A8_UNORM, _is_gdi_compatible ? DXGI_SWAP_CHAIN_FLAG_GDI_COMPATIBLE : 0); RETURN_ON_FAIL(hr); hr = _swap_chain->GetBuffer(0, __uuidof(ID3D11Texture2D), (void**)&_back_texture2d); RETURN_ON_FAIL(hr); hr = CreateD3D11Texture2D(_d3d_device, width, height, &_dc_texture2d); RETURN_ON_FAIL(hr); D3D11_RENDER_TARGET_VIEW_DESC rtv; rtv.Format = DXGI_FORMAT_B8G8R8A8_UNORM; rtv.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; rtv.Texture2D.MipSlice = 0; hr = _d3d_device->CreateRenderTargetView(_back_texture2d, &rtv, &_back_rendertarget_view); RETURN_ON_FAIL(hr); ... } HRESULT CGraphRender::Clear(float color[]) { CComPtr<ID3D11DeviceContext> immediate_context; _d3d_device->GetImmediateContext(&immediate_context); if (!immediate_context) { return E_UNEXPECTED; } ID3D11RenderTargetView* ref_renderTargetView = _back_rendertarget_view; immediate_context->OMSetRenderTargets(1, &ref_renderTargetView, nullptr); immediate_context->ClearRenderTargetView(_back_rendertarget_view, color); return S_OK; } HDC CGraphRender::GetDC() { if (_is_gdi_compatible) { CComPtr<IDXGISurface1> gdi_surface; HRESULT hr = _dc_texture2d->QueryInterface(__uuidof(IDXGISurface1), (void**)&gdi_surface); if (SUCCEEDED(hr)) { HDC hdc = nullptr; hr = gdi_surface->GetDC(TRUE, &hdc); if (SUCCEEDED(hr)) { return hdc; } } } return nullptr; } HRESULT CGraphRender::CopyTexture(ID3D11Texture2D* dst_texture, ID3D11Texture2D* src_texture, POINT* dst_topleft/* = nullptr*/, POINT* src_topleft/* = nullptr*/) { if (!dst_texture && !src_texture) { return E_INVALIDARG; } CComPtr<ID3D11DeviceContext> immediate_context; _d3d_device->GetImmediateContext(&immediate_context); if (!immediate_context) { return E_UNEXPECTED; } ID3D11Texture2D* dst_texture_real = dst_texture ? dst_texture : _dc_texture2d; POINT dst_topleft_real = dst_topleft ? (*dst_topleft) : POINT{ 0, 0 }; ID3D11Texture2D* src_texture_real = src_texture ? src_texture : _dc_texture2d; POINT src_topleft_real = src_topleft ? (*src_topleft) : POINT{ 0, 0 }; D3D11_TEXTURE2D_DESC src_desc = { 0 }; src_texture_real->GetDesc(&src_desc); D3D11_TEXTURE2D_DESC dst_desc = { 0 }; dst_texture_real->GetDesc(&dst_desc); if (!dst_topleft_real.x && !src_topleft_real.x && !dst_topleft_real.y && !src_topleft_real.y && dst_desc.Width == src_desc.Width && dst_desc.Height == src_desc.Height) { immediate_context->CopyResource(dst_texture_real, src_texture_real); } else { D3D11_BOX src_box; src_box.left = min((UINT)src_topleft_real.x, (UINT)dst_topleft_real.x + dst_desc.Width); src_box.top = min((UINT)src_topleft_real.y, (UINT)dst_topleft_real.y + dst_desc.Height); src_box.right = min((UINT)src_box.left + src_desc.Width, (UINT)dst_topleft_real.x + dst_desc.Width); src_box.bottom = min((UINT)src_box.top + src_desc.Height, (UINT)dst_topleft_real.y + dst_desc.Height); src_box.front = 0; src_box.back = 1; ATLASSERT(src_box.left < src_box.right); ATLASSERT(src_box.top < src_box.bottom); immediate_context->CopySubresourceRegion(dst_texture_real, 0, dst_topleft_real.x, dst_topleft_real.y, 0, src_texture_real, 0, &src_box); } return S_OK; } A: I don’t think Windows 7 supports what you’re trying to do. Here’s some alternatives. * *Switch from GDI to something else that can render 2D graphics with D3D11. Direct2D is the most straightforward choice here. And DirectWrite if you want text in addition to rectangles. *If your 2D content is static or only changes rarely, you can use GDI+ to render into in-memory RGBA device context, create Direct3D11 texture with that data, and render a full-screen triangle with that texture. *You can overlay another Win32 window on top of your Direct3D 11 rendering one, and use GDI to render into that one. The GDI window on top must have WS_EX_LAYERED expended style, and you must update it with UpdateLayeredWindow API. This method is the most complicated and least reliable, though.
{ "language": "en", "url": "https://stackoverflow.com/questions/64370272", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Difference between old and new state I am developing a SOAP server that should send state changes to clients. The server communicate with other systems to update its internal state. I am searching for a solution (pattern o whatever) that let me track the state changes after an update. I watched to memento pattern but it is not what I am looking for, because I don't need the previous state but the change. I can't simply propagate the change to clients because its a pull architecture (clients poll for changes). Use case Suppose the server state is a list of object with 3 elements and the update modifies it adding a new element. The client must receive only the newly added element and not a list with 4 elements. Any solution? A: You could define a set of serializable commands (see command design pattern for further details) that are generated whenever a change must be performed. Then you can execute those commands locally to apply changes to your model and serialize those commands in a queue. Whenever a client pulls them, it can simply reapply the same commands in order to its local model and get the same result you achieved server side. Somehow your server behaves exactly like a client in regard of the changes to be applied, with the difference that it pulls them immediately. Considering your use case, commands can be defined as insertions in a list and created along with all the required parameters. You can easily extend it to deletions and updates to the objects of the list.
{ "language": "en", "url": "https://stackoverflow.com/questions/42158633", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Entity framework 6.1.3 large models I am using Entity framework 6.1.3 and i am getting limitation in adding/updating models when exceed to its limits and getting below error. Unable to generate the model because of the following exception: 'System.Data.Entity.Core.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.Data.SqlClient.SqlException: The incoming request has too many parameters. The server supports a maximum of 2100 parameters. Reduce the number of parameters and resend the request. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds, Boolean describeParameterEncryptionRequest) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource1 completion, Int32 timeout, Task& task, Boolean asyncWrite) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.<Reader>b__c(DbCommand t, DbCommandInterceptionContext1 c) at System.Data.Entity.Infrastructure.Interception.InternalDispatcher1.Dispatch[TTarget,TInterceptionContext,TResult](TTarget target, Func3 operation, TInterceptionContext interceptionContext, Action3 executing, Action3 executed) at System.Data.Entity.Infrastructure.Interception.DbCommandDispatcher.Reader(DbCommand command, DbCommandInterceptionContext interceptionContext) at System.Data.Entity.Internal.InterceptableDbCommand.ExecuteDbDataReader(CommandBehavior behavior) at System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) --- End of inner exception stack trace --- at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) at System.Data.Entity.Core.EntityClient.Internal.EntityCommandDefinition.Execute(EntityCommand entityCommand, CommandBehavior behavior) at System.Data.Entity.Core.EntityClient.EntityCommand.ExecuteReader(CommandBehavior behavior) at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery.EntityStoreSchemaGeneratorDatabaseSchemaLoader.LoadDataTable[T](String sql, Func2 orderByFunc, DataTable table, EntityStoreSchemaFilterObjectTypes queryTypes, IEnumerable1 filters, String[] filterAliases) at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery.EntityStoreSchemaGeneratorDatabaseSchemaLoader.LoadRelationships(IEnumerable1 filters) at Microsoft.Data.Entity.Design.VersioningFacade.ReverseEngineerDb.SchemaDiscovery.EntityStoreSchemaGeneratorDatabaseSchemaLoader.LoadStoreSchemaDetails(IList1 filters) at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelGenerator.GetStoreSchemaDetails(StoreSchemaConnectionFactory connectionFactory) at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelGenerator.CreateStoreModel() at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelGenerator.GenerateModel(List1 errors) at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelBuilderEngine.GenerateModels(String storeModelNamespace, ModelBuilderSettings settings, List1 errors) at Microsoft.Data.Entity.Design.VisualStudio.ModelWizard.Engine.ModelBuilderEngine.GenerateModel(ModelBuilderSettings settings, IVsUtils vsUtils, ModelBuilderEngineHostContext hostContext)'. Loading metadata from the database took 00:00:01.8445312. Generating the model took 00:00:15.0864187. A: It is not an entity framework limitation but SQL server limitation. You cannot have more then 2100 parameters for IN statement. SELECT * FROM YourTable WHERE YourColumn IN (1,2,....,2101) So I see 2 workarounds for it: * *Split the query in several queries sending each time less then <2100 parameters for the IN statement. *Insert all the parameters in a special DB Table and then perform your query against that table. For example, you can create a temporary table, insert there more then 2100 parameters and then JOIN your table with this temporary table. CREATE TABLE #temptable (id int); INSERT INTO #temptable (id) VALUES (1), (2), (3) SELECT * FROM YourTable yt INNER JOIN #temptable tt ON yt.id = tt.id A: I had the same issue, what I did is, removed all the entities from the model and then added them back to model and it's worked.
{ "language": "en", "url": "https://stackoverflow.com/questions/36468402", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: checking if characters are equal to a word do { System.out.println("Word: " + secretWord.getWordMask()); //System.out.print("Guesses: " + guesses); System.out.print("Enter your guess: "); Scanner keyboard = new Scanner(System.in); String guess = keyboard.next(); WordHider revealChar = new WordHider(); revealChar.revealLetter(guess); System.out.println(revealChar.getWordMask()); secretWord.revealLetter(guess); } while (); what my code does now is continuously ask the user for a letter, then revelas it if its part of the word. I have another method in a different class that checks to see if the hidden word is found or not public boolean isHiddenWordFound() { for (int i = 0; i < wordMask.length(); i++) { if(wordMask.charAt(i) == HIDE_CHAR.charAt(0)) { return false; and i need to figure out how to make the while part check for that. But i am simply at a loss, any ideas? A: If isHiddenWordFound says that the file is not found if part of it is hidden, then you need to inverse it to be true to continue the loop, once the word is found it will return true at which point the inverse will be false allowing the program execution to continue: while (!isHiddenWordFound()); A: It seems the isHiddenWordFound method is there for precisely this purpose. do { ... } while (!isHiddenWordFound());
{ "language": "en", "url": "https://stackoverflow.com/questions/15711697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can you inherit a generic factory method? Say you have a class Person, and create a collection class for it by extending e.g. ArrayBuffer: class Persons extends ArrayBuffer[Person] { // methods operation on the collection } Now, with ArrayBuffer, can create a collection with the apply() method on the companion object, e.g.: ArrayBuffer(1, 2, 3) You want to be able to do the same with Persons, e.g.: Persons(new Person("John", 32), new Person("Bob", 43)) My first intuition here was to extend the ArrayBuffer companion object and getting the apply() method for free. But it seems that you can't extend objects. (I'm not quite sure why.) The next idea was to create a Persons object with an apply() method that calls the apply method of ArrayBuffer: object Persons { def apply(ps: Person*) = ArrayBuffer(ps: _*) } However, this returns an ArrayBuffer[Person] and not a Persons. After some digging in the scaladoc and source for ArrayBuffer, I came up with the following, which I thought would make the Persons object inherit apply() from GenericCompanion: EDIT: object Persons extends SeqFactory[ArrayBuffer] { def fromArrayBuffer(ps: ArrayBuffer[Person]) = { val persons = new Persons persons appendAll ps persons } def newBuilder[Person]: Builder[Person, Persons] = new ArrayBuffer[Person] mapResult fromArrayBuffer } However, it gives the following error message: <console>:24: error: type mismatch; found : (scala.collection.mutable.ArrayBuffer[Person]) => Persons required: (scala.collection.mutable.ArrayBuffer[Person(in method newBuilder)]) => Persons def newBuilder[Person]: Builder[Person, Persons] = new ArrayBuffer[Perso n] mapResult fromArrayBuffer ^ Perhaps this should disencourage me from going further, but I'm having a great time learning Scala and I'd really like to get this working. Please tell me if I'm on the wrong track. :) A: Rather than extending ArrayBuffer[Person] directly, you can use the pimp my library pattern. The idea is to make Persons and ArrayBuffer[Person] completely interchangeable. class Persons(val self: ArrayBuffer[Person]) extends Proxy { def names = self map { _.name } // ... other methods ... } object Persons { def apply(ps: Person*): Persons = ArrayBuffer(ps: _*) implicit def toPersons(b: ArrayBuffer[Person]): Persons = new Persons(b) implicit def toBuffer(ps: Persons): ArrayBuffer[Person] = ps.self } The implicit conversion in the Persons companion object allows you to use any ArrayBuffer method whenever you have a Persons reference and vice-versa. For example, you can do val l = Persons(new Person("Joe")) (l += new Person("Bob")).names Note that l is a Persons, but you can call the ArrayBuffer.+= method on it because the compiler will automatically add in a call to Persons.toBuffer(l). The result of the += method is an ArrayBuffer, but you can call Person.names on it because the compiler inserts a call to Persons.toPersons. Edit: You can generalize this solution with higher-kinded types: class Persons[CC[X] <: Seq[X]](self: CC[Person]) extends Proxy { def names = self map (_.name) def averageAge = { self map (_.age) reduceLeft { _ + _ } / (self.length toDouble) } // other methods } object Persons { def apply(ps: Person*): Persons[ArrayBuffer] = ArrayBuffer(ps: _*) implicit def toPersons[CC[X] <: Seq[X]](c: CC[Person]): Persons[CC] = new Persons[CC](c) implicit def toColl[CC[X] <: Seq[X]](ps: Persons[CC]): CC[Person] = ps.self } This allows you to do things like List(new Person("Joe", 38), new Person("Bob", 52)).names or val p = Persons(new Person("Jeff", 23)) p += new Person("Sam", 20) Note that in the latter example, we're calling += on a Persons. This is possible because Persons "remembers" the underlying collection type and allows you to call any method defined in that type (ArrayBuffer in this case, due to the definition of Persons.apply). A: Apart from anovstrup's solution, won't the example below do what you want? case class Person(name: String, age: Int) class Persons extends ArrayBuffer[Person] object Persons { def apply(ps: Person*) = { val persons = new Persons persons appendAll(ps) persons } } scala> val ps = Persons(new Person("John", 32), new Person("Bob", 43)) ps: Persons = ArrayBuffer(Person(John,32), Person(Bob,43)) scala> ps.append(new Person("Bill", 50)) scala> ps res0: Persons = ArrayBuffer(Person(John,32), Person(Bob,43), Person(Bill,50))
{ "language": "en", "url": "https://stackoverflow.com/questions/3374923", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How do I upgrade from Ruby 1.8.6 to 1.8.7 on Windows? On one machine I seemed to have upgrade to 1.8.7 -- mostly because of the TLS support for sending via Gmail -- but I don't remember how I did it, or what to do and have a laptop on Windows 7. How do I upgrade for the 1.8.6 from OneClick? A: Install RubyInstaller RC2, version 1.8.7-p249. http://rubyinstaller.org/download.html A: You can use pik, a ruby version manager for windows * *a simple guide: http://www.dixis.com/?p=117
{ "language": "en", "url": "https://stackoverflow.com/questions/2741180", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ADFS Powershell script to add additional SamlEndpoints to existing This question likely doesn't require actual knowledge of ADFS, but I'm providing that for context. The command "Set-AdfsRelyingPartyTrust -Name X -SamlEndpoint Y" overwrites all SAML endpoints with what you specify. What I'd like to do is create a script that takes the existing SAML endpoints and sets them as variables so that I can then add them all back along with the new endpoint. If there's only one existing endpoint, I can put it into a variable using this and it works: $EP = New-AdfsSamlEndpoint -Binding "POST" -Protocol "SAMLAssertionConsumer" -Uri "https://test.com" -Index 1 $EP1 = Get-ADFSRelyingPartyTrust -Name "X" | Select-Object -ExpandProperty SamlEndpoints Set-AdfsRelyingPartyTrust -TargetName "PsTest" -SamlEndpoint $EP,$EP1 The problem with this is that, if multiple endpoints exist, expand-property returns them all as a single value which breaks the function. Using "-limit 1" doesn't work because the whole output of expand-property is considered 1. What I can do is to generate a numbered list of each index value using this command: Get-AdfsRelyingPartyTrust -Name "X" | Select-Object -ExpandProperty SamlEndpoints | Select-Object -ExpandProperty Index and then create a unique variable for each corresponding index value $EP1 = Get-ADFSRelyingPartyTrust -Name "X" | Select-Object -ExpandProperty SamlEndpoints | Where-Object {$_.Index -eq 2} But in order to completely script this rather than setting variables by hand, I'd need automate setting "$_.Index -eq" to each index value that's output from "-ExpandProperty Index", and to assign a unique variable to each of those, which is where I'm stuck. What's the best way to approach this? A: I don't have access to these command so I am having to guess a little here, but it looks like your command Set-AdfsRelyingPartyTrust -TargetName "PsTest" -SamlEndpoint $EP,$EP1 accepts an array for the -samlEndpoint parameter. What I would do it work with the arrays like so. $EP = New-AdfsSamlEndpoint -Binding "POST" -Protocol "SAMLAssertionConsumer" -Uri "https://test.com" -Index 1 $EndPoints = @(Get-ADFSRelyingPartyTrust -Name "X" | Select-Object -ExpandProperty SamlEndpoints) $Endpoints += $EP Set-AdfsRelyingPartyTrust -TargetName "PsTest" -SamlEndpoint $EndPoints
{ "language": "en", "url": "https://stackoverflow.com/questions/51410010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Given a user's latitude and longitude, I want to retrieve other users around me from the database. Possible Duplicate: How to call user defined function in LINQ in my visual C# web service for my android application? I am currently developing an application on Android that will make use of the user location. The database will keep all the user location by latitude and longitude. I know how to calculate the distance from two points and it is a bit complicated. However, in my webservice written in visual C#, I can't write something like this: from a in db.Location.Where(a => distanceBetweenTwoLocations(givenLat, givenLong, a.lat, a.longi)<500) select new {...} because the linq wont let me call my own function. Can anyone suggest some way to achieve my goal? For simplicity, i want to find other users that is 500m around me. I have all the user locations in latitude and longitude in my database. A: Have a look at Nerddinner. http://nerddinnerbook.s3.amazonaws.com/Part11.htm (use distancebetween function) Create the relevant functions in your db. then call them in your c# A: There is an answer already, although it is in miles (1609.344 meters) instead of 500, but the calculation used is likely to fit your bill. It is using SQL, not LINQ, but you can easily convert this to a LINQ expression, especially if you have a tool like LINQPad.
{ "language": "en", "url": "https://stackoverflow.com/questions/9789943", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Setting headers in websphere portal I am new to websphere portal. How to set headers in websphere portlet 8? A: You can do this by enabling two-phase rendering: https://www.ibm.com/support/knowledgecenter/en/SSHRKX_8.5.0/mp/dev-portlet/jsr2phase_overview.html. Enable two-phase rendering in the portlet.xml like this: <portlet> ... <container-runtime-option> <name>javax.portlet.renderHeaders</name> <value>true</value> </container-runtime-option> </portlet> Then you can set the headers within the doHeaders method by using the setProperty or addProperty response methods: @Override protected void doHeaders(RenderRequest request, RenderResponse response) { response.addProperty("MyHeader", "MyHeaderValue"); }
{ "language": "en", "url": "https://stackoverflow.com/questions/44862811", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Rmagick custom text width/padding using annotate method As per the documentation on Rmagick we can set the width of the rectangle within which our text is placed. http://www.simplesystems.org/RMagick/doc/draw.html#annotate Below is the code that we are using but we are unable to set the padding or a custom width for the text in the annotate block. For a use case we wanted to have a custom padding for the text that we give in the annotate block. img=Image.new(1500,600) b=Magick::Draw.new b.annotate(img,120,10,120,120,"5"){ |txt| txt.pointsize = 58 txt.undercolor= "blue" } b.get_type_metrics(img, "5") img.write("undercolor3.gif") Have tried a ton number of things but couldn't make it work.Any ideas? A: Draw a block of the desired undercolor on the image, then annotate the image such that the text is over the block. To determine the desired size of the block, use get_type_metrics or get_multiline_type_metrics to get the dimensions of your text, then add in how much padding you want. A: Annotate in ImageMagick does not have any option to pad the undercolor. But you can trick it. The simplest ways is to put spaces on the left and right side of your text using "\ ". But that will only pad on the left and right. In label: you can add newlines, but that does not work in annotate. You could add -interline-spacing, but that will only pad on the bottom. But here is a trick. Create text in the undercolor with a slightly larger pointsize, then write over it with your desired color text. For example: Without padding: convert logo.jpg -gravity center -undercolor pink -pointsize 24 -fill black -annotate +0+0 "This Is Some Text" result1.jpg With padding: convert logo.jpg -gravity center -pointsize 34 -undercolor pink -fill pink -annotate +0+0 "X X" -pointsize 24 -fill black -annotate +0+0 "This Is Some Text" result2.jpg Alternately, you could just draw a pink rectangle in the center of the image of the desired size.
{ "language": "en", "url": "https://stackoverflow.com/questions/45013464", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Redirect to a specific screen from React Native Firebase Push Notifications based on a Deeplink I got a problem, 1 ) I'm using Firebase to send remote Push Notifications, i test by sending from FCM tester. 2 ) I've activated Deep-Linking in my project and started to use it. 3 ) In FCM tester i pass this key value into "notifications.data" : { "link" : "MY_LINK" } Now i want my app to be able to recognize there is a deepLink in it & read it. Which i achieved to do somehow but not the way i was looking for. What i did : NotificationContextProvider.ts useEffect(() => { const unsubscribeClosedApp = messaging().onNotificationOpenedApp( remoteMessage => { addNotification(remoteMessage); console.log( 'Notification caused app to open from background state:', remoteMessage.notification, ); redirectFromKey(remoteMessage.data?.redirection); console.log(remoteMessage.data, 'remote message data'); console.log(remoteMessage, 'remote message full'); console.log(remoteMessage.notification?.body, 'remote message body'); console.log(remoteMessage.notification?.title, 'remote message title'); if (remoteMessage.data?.link === 'https://[MY-LINK]/TnRV') { console.log(remoteMessage.data?.link, 'Deeplink detected & opened'); navigation.navigate({ name: 'Logged', params: { screen: 'Onboarded', params: { screen: 'LastAnalyse', }, }, }); } }, ); And it's working fine but it's not based on reading a link, but by comparing a value and it's not what i'm trying to achieve. Firebase Doc' give us a way to do this : https://rnfirebase.io/dynamic-links/usage#listening-for-dynamic-links This is what Firebase suggests : import dynamicLinks from '@react-native-firebase/dynamic-links'; function App() { const handleDynamicLink = link => { // Handle dynamic link inside your own application if (link.url === 'https://invertase.io/offer') { // ...navigate to your offers screen } }; useEffect(() => { const unsubscribe = dynamicLinks().onLink(handleDynamicLink); // When the component is unmounted, remove the listener return () => unsubscribe(); }, []); return null; } And i have no clue how to make it works. I got to mention that deep-links are correctly setup in my project and working fine, my code is in Typescript. Basicaly you can find on this web page what i'm trying to achieve but i want to use Firebase/messaging + Dynamic links. My project don't use local notifications and will never do : https://medium.com/tribalscale/working-with-react-navigation-v5-firebase-cloud-messaging-and-firebase-dynamic-links-7d5c817d50aa Any idea ? A: I looked into this earlier, it seems that... * *You can't send a deep link in an FCM message using the firebase Compose Notification UI. *You probably can send a deep link in an FCM message using the FCM REST API. More in this stackoverflow post. The REST API looks so cumbersome to implement you're probably better off the way you're doing it: Using the firebase message composer with a little data payload, and your app parses the message data with Invertase messaging methods firebase.messaging().getInitialNotification() and firebase.messaging().onNotificationOpenedApp(). As for deep linking, which your users might create in-app when trying to share something, or you might create in the firebase Dynamic Links UI: For your app to notice actual deep links being tapped on the device, you can use Invertase dynamic links methods firebase.dynamicLinks().getInitialLink() and firebase.dynamicLinks().onLink().
{ "language": "en", "url": "https://stackoverflow.com/questions/70987037", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Android Static functions I'm wondering how I can access the return statement with a static function. I have a static function with Async and I want to then get the return statement in another class - I know it sounds complex but, I'm sure it's an easy solution. Login.class public class LogIn extends Activity { Button login; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.login); TextView top = (TextView) findViewById(R.id.textView2); final EditText user = (EditText) findViewById(R.id.etUser); final EditText pass = (EditText) findViewById(R.id.etPass); CheckBox stay = (CheckBox) findViewById(R.id.cBStay); Button login = (Button) findViewById(R.id.btLogin); login.setOnClickListener( new View.OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub String user1 = user.getText().toString(); String pass1 = pass.getText().toString(); if(user1 !=null &user1.length()>=1 & pass1 !=null &pass1.length()>=1) { ComHelper.SendLogin(user1, pass1); } } }); } } ComHelper.class public class ComHelper extends AsyncTask<String, Void, String> { static String adress ="http://gta5news.com/login.php"; String user; String pass; public static boolean SendLogin(String user1, String pass1){ String user = user1.toString(); String pass = pass1.toString(); new ComHelper().execute(user1, pass1, adress); return true; } private static StringBuilder inputStreamToString(InputStream is) { String line = ""; StringBuilder total = new StringBuilder(); // Wrap a BufferedReader around the InputStream BufferedReader rd = new BufferedReader(new InputStreamReader(is)); // Read response until the end try { while ((line = rd.readLine()) != null) { total.append(line); } } catch (IOException e) { e.printStackTrace(); } // Return full string return total; } @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub InputStream inputStream = null; HttpClient httpclient = new DefaultHttpClient(); HttpPost post = new HttpPost(adress); try { /*Add some data with NameValuePairs */ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("user", user)); nameValuePairs.add(new BasicNameValuePair("password", pass)); post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); /*Execute */ HttpResponse response = httpclient.execute(post); String str = inputStreamToString(response.getEntity().getContent()) .toString(); Log.w("HttpPost", str); if (str.toString().equalsIgnoreCase("true")) return str; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } return null; } } Now, I want to see if ComHelper.SendLogin() returned true/or at least returned something. EDIT: When the code is executed nothing happens, I guess that's because I'm not doing anything with the return statement. A: You want to implement protected void onPostExecute (Result result) on your AsyncTask implementation. The result parameter will be whatever you return from the doInBackground method. Since this runs in the UI thread you can modify the UI how you want at that time. A: If you want to look at the value, then you need to save the return value of the method in a local variable if(user1 !=null && user1.length() > 0 && pass1 !=null && pass1.length() > 0) { boolean comLogin = ComHelper.SendLogin(user1, pass1); if(comLogin) { //do something } }
{ "language": "en", "url": "https://stackoverflow.com/questions/10883383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: postgresql creating rules on columns? I need to format my SELECT queries on a text column. How may I do it without expliciting inserting it together with the query? Do i use a rule in this case? I have tried creating a rule on the tables' column but apparently it won't work. create or replace rule t_format AS ON SELECT TO site_ss_last_entry2 DO INSTEAD select internet_date(site_ss.last_entry2) from site_ss; A: Just create a VIEW and SELECT from this VIEW to get what you're looking for.
{ "language": "en", "url": "https://stackoverflow.com/questions/3394105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Gradle ignores private Nexus repository when searching for dependencies I am trying to pull some internal dependencies from a private Nexus repository. But when I build the project, gradle does not search for the dependency in the private repo but looks for it in the maven repos. I did some investigations and found that this is happening with only one project. Dependencies do get pulled in other projects. I still don't know why it is happening. This is how I have added the repository: repositories { mavenLocal() mavenCentral() jcenter() maven { url 'https://jitpack.io' } maven { url 'https://ci-artifactory.corda.r3cev.com/artifactory/corda' } maven { url 'https://repo.gradle.org/gradle/libs-releases' } maven { url 'http://private/repository/project' credentials { username = "user" password = "password" } } } dependency: implementation 'com.project:project-1' This is what gradle shows: * What went wrong: Execution failed for task ':workflows:compileKotlin'. > Could not resolve all files for configuration ':workflows:compileClasspath'. > Could not find project:0.1. Searched in the following locations: - file:/C:/Users/local/.m2/repository/com/project/directory/0.1-SNAPSHOT/project-1.pom - file:/C:/Users/local/.m2/repository/com/project/directory/0.1-SNAPSHOT/project-1.jar - https://jcenter.bintray.com/com/project/directory/0.1-SNAPSHOT/project-1.pom - https://jcenter.bintray.com/com/project/directory/0.1-SNAPSHOT/project-1.jar - https://repo.maven.apache.org/maven2/com/project/directory/0.1-SNAPSHOT/project-1.pom - https://repo.maven.apache.org/maven2/com/project/directory/0.1-SNAPSHOT/project-1.jar - https://software.r3.com/artifactory/corda/com/project/directory/0.1-SNAPSHOT/project-1.pom - https://software.r3.com/artifactory/corda/com/project/directory/0.1-SNAPSHOT/project-1.jar - https://jitpack.io/com/project/directory/0.1-SNAPSHOT/project-1.pom - https://jitpack.io/com/project/directory/0.1-SNAPSHOT/project-1.jar It does not search in the private repository. A: The project I was working with had two gradle files, repositories.gradle & build.gradle I was adding the nexus URL to repositories.gradle file in the repositories block. But the URL was not being searched for dependencies. After a bit of exploration I found that the build.gradle file also has a repositories block: allProjects { . . . . . . . . . . repositories { . . . . . . . . . . . . . . . . . . . . } } This seems to be overriding the repositories block in repositories.gradle file. When I added the nexus URL in here the dependencies were resolved. Hope that helps anyone having a similar issue :) A: As an updated information and solution for me was in the settings.gradle There is another repositories block in dependencyResolutionManagement.
{ "language": "en", "url": "https://stackoverflow.com/questions/57703356", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Detect if browser supports "@supports"? I realize this may be a dumb question because I am returning to web dev after some time anyway, so please don't be shy to enlighten me! To me it seems that the art of css hacks (like back in the day to sniff out old IE browsers) could be used to fill the gap between the new-ish @supports queries and old browsers that do not support these features. Potential to save yourself and your site from alot of javascript? Even aid in dropping javascript altogether in small projects. Is anyone aware of any projects like this? It is also possible I have failed to search with proper keywords... A: Yes, you can do this with the next commands: The all following examples are valid: @supports not (not (transform-origin: 2px)) - for test browser on non-support or @supports (display: grid) - for test browser on support or @supports (display: grid) and (not (display: inline-grid)). - for test both See MDN for more info: https://developer.mozilla.org/en-US/docs/Web/CSS/@supports
{ "language": "en", "url": "https://stackoverflow.com/questions/50116732", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Where does the connection to database need to be made? I am creating a twitter bot that searches twitter for ticker symbols. I am then sending them to a database. The problem that I have here is that the list that is getting sent is not changing. Maybe I have to keep connecting to the database, but I can not figure out where my problem is. Can anyone figure out how to make make the list of tickers be different everytime? def searchTwit(): tweets = api.search("#stocks",count=100) return tweets print("connecting to database") #connecting to the database conn = pyodbc.connect( "Driver={SQL Server};" "Server=..............;" "Database=master;" "Trusted_Connection=yes;") cursor = conn.cursor() tickList=[] def getTicker(tweets): for tweet in tweets: if "$" in tweet.text: x = tweet.text.split() for i in x: if i.startswith("$") and i[1].isalpha(): i.strip(".") i.upper() tickList.append(i) # print(var_string) def retrieveTickers(): for i in tickList: cursor.execute('INSERT INTO master.dbo.TickerTable (TickerName) VALUES (?);', (i)) conn.commit() # thing to run print("about to do while ") while True: sleep(60 - time() %60) print("searchtwit") searchTwit() theTweets = searchTwit() getTicker(theTweets) print("getting Tickers") retrieveTickers() print("sending tickers") print(tickList) tickList=[] print(tickList) A: You can connect to a remote database or on your local machine. Define which database you want to use, so in your database server be 127.0.0.1:PORT (that means that the database is your machine) (THE PORT will change depending on which SGDB you want
{ "language": "en", "url": "https://stackoverflow.com/questions/65082692", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can't even make the Bootstrap carousel example code work. Specifically the prev and next buttons I was exploring the basics of Bootstrap and everything seemed to worked fine(the very basic stuff, tables, col, etc.). However, I tried to make a carousel by following the example on the bootstrap website and it didn't work. The carousel appeared fine with everything but the next and prev buttons did nothing. So I just copied the example on the website directly and the same thing happens, everything is there but non-functional. I was using the bootstrap files given to me by WebStorm but I changed it to the CDN links as a troubleshooting step to no avail. I tried in Edge and Chrome too. [edit]I also tried a suggestion that I found on SO to change the anchor tags to button tags for the buttons but it didn't work[/edit] Am I missing a dependency somewhere? I believe I have everything I need: * *bootstrap.min.css *bootstrap.bundled.min.js *jquery.min.js Thank you. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> <title>Title</title> </head> <body> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <li data-target="#carouselExampleIndicators" data-slide-to="1"></li> <li data-target="#carouselExampleIndicators" data-slide-to="2"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="https://placeimg.com/1080/500/animals" alt="First slide"> <div class="carousel-caption d-none d-md-block"> <h5>My Caption Title (1st Image)</h5> <p>The whole caption will only show up if the screen is at least medium size.</p> </div> </div> <div class="carousel-item"> <img class="d-block w-100" src="https://placeimg.com/1080/500/arch" alt="Second slide"> </div> <div class="carousel-item"> <img class="d-block w-100" src="https://placeimg.com/1080/500/nature" alt="Third slide"> </div> </div> <button class="carousel-control-prev" data-target="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </button> <button class="carousel-control-next" data-target="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </button> </div> <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" crossorigin="anonymous"></script> </body> </html> A: Like @CBroe pointed out in the comment there was a version mismatch, the code was for Bootstrap 4.0 and the Bootstrap version I was using was 5.0.
{ "language": "en", "url": "https://stackoverflow.com/questions/71956048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Using a web service with cascading drop downs Below is my code - <asp:DropDownList ID="ddlCategories" runat="server" /> <asp:CascadingDropDown ID="cddCategory" runat="server" ServicePath="~\Categories.asmx" ServiceMethod="GetCategories" TargetControlID="ddlCategories" Category="Category" PromptText="Please select a category" LoadingText="[Loading categories...]" /> <br /> In my Page_Load function I have { ddlCategories.DataBind(); } and my GetCategories Method is [WebMethod] public CascadingDropDownNameValue[] GetCategories( string knownCategoryValues, string category) { List<CascadingDropDownNameValue> l = new List<CascadingDropDownNameValue>(); l.Add(new CascadingDropDownNameValue("International", "1")); l.Add(new CascadingDropDownNameValue("Electronic Bike Repairs & Supplies", "2")); l.Add(new CascadingDropDownNameValue("Premier Sport, Inc.", "3")); return l.ToArray(); } But when the page is loaded, the GetCategories function is never called. And my ddlCategories drop down has these items in the list - Please select a category [Method Error 400] Is there a step I am missing? A: From looking at the CascadingDropDown sample and your code, I think you may have the properties set slightly wrong. Your CascadingDropDown's TargetControlId is currently ddlCategories, however I think this value should be set to the ParentControlId property instead, and you need another DropDownList which becomes the target control of the extender e.g. <asp:DropDownList ID="ddlCategories" runat="server" /><br/> <asp:DropDownList id="ddlSubcategories" runat="server" /> <asp:CascadingDropDown ID="cddCategory" TargetControlID="ddlSubcategories" ParentControlId="ddlCategories" runat="server" ServicePath="~\Categories.asmx" ServiceMethod="GetCategories" Category="Category" PromptText="Please select a category" LoadingText="[Loading categories...]" />
{ "language": "en", "url": "https://stackoverflow.com/questions/6058372", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get assembly of code that instantiated object (with inheritance) I have an abstract class that will need to be able to load files contained in the assembly that made an object of the class. What I could use is FileAssembly = Assembly.GetCallingAssembly() for every child of my class, but since it is a library that people can extend I want that to happen without requiring them to do this. My setup right now is something along the lines of: public abstract class ExternalResource : Resource, IDisposable { public string File { get; private set; } protected Assembly FileAssembly { get; set; } protected ExternalResource(string id, string file) : base(id) { File = file; } //and s'more code } public class Sound : ExternalResource { public Sound (string id, string file) : base(id, file) { //this is the line I want to be able to get rid of FileAssembly = Assembly.GetCallingAssembly(); } } Someone using my library could make their own ExternalResource without setting the FileAssembly, which is not desirable. It gets really messy if they would inherit from a class that already inherits from ExternalResource. How can I get the assembly of the code instantiating the object? Any other way to work around it without too much changing to the existing system would be appreciated too! A: You can use the StackTrace class from the System.Diagnostics namespace: In the constructor of your ExternalResource class: var stack = new StackTrace(true); var thisFrame = stack.GetFrame(0); // ExternalResource constructor var parentFrame = stack.GetFrame(1); // Sound constructor var grandparentFrame = stack.GetFrame(2); // This is the one! var invokingMethod = grandparentFrame.GetMethod(); var callingAssembly = invokingMethod.Module.Assembly; The references to thisFrame and parentFrame are there simply to aid understanding. I would suggest that you actually walk up the stack frame and do it more robustly, rather than just assuming that it's always frame 2 that you want (which won't give the right answer if you have an additional subclass). A: Using the calling assembly will likely frustrate someone down the road who moves their ExternalResource related code into a new separate assembly without realizing it has an assembly dependency, or wants to move their resources into a separately identified assembly (e.g. for localization). My suggestion would be: * *Add an explicit assembly parameter to the constructor, making it very clear it's doing something with some assembly. *Provide a factory method that determines the calling assembly for the user as a convenience Your factory method could be generic if all of your derived types expect constructor parameters string id, string file and then the new explicit assembly parameter. Something like: public static TExternalResource CreateExternalResource<TExternalResource>(string id, string file, Assembly assembly = null) where TExternalResource : ExternalResource { var ResolvedAssembly = assembly ?? Assembly.GetCallingAssembly(); return Activator.CreateInstance(typeof(TExternalResource), id, file, ResolvedAssembly) as TExternalResource; }
{ "language": "en", "url": "https://stackoverflow.com/questions/29061017", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Applescript: Repeat until reCaptcha occurs I am pretty new in coding, especially with applescript. I managed to make the following code work: tell application "Safari" repeat delay 7.5 set the URL of document 1 to "https://url.com" delay 2 tell document 1 do JavaScript "document.getElementById(\"id1\").click()" do JavaScript "document.getElementById(\"id2\").click()" do JavaScript "document.getElementById(\"id3\").click()" do JavaScript "document.getElementById(\"id4\").click()" do JavaScript "document.getElementById(\"id5\").click()" do JavaScript "document.getElementById(\"id6\").click()" delay 0.25 end tell tell application "Safari" activate end tell tell application "System Events" delay 0.25 tell process "Safari" to key code 48 delay 0.5 key code 21 end tell delay 0.25 tell application "Safari" tell document 1 do JavaScript "document.getElementById(\"book\").click()" end tell end tell end repeat end tell Instead of repeating the code all the time I would like to make the code repeat until the Google reCaptcha occurs which pops up after the last javascript action. A: My recommendation would be to restructure your repeat statement like this... set done to false repeat while not done if reCaptcha = "something" then set done to true end if end repeat
{ "language": "en", "url": "https://stackoverflow.com/questions/36234919", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Not enough replicas available for query at consistency LOCAL_ONE (1 required but only 0 alive) I am running spark-cassandra-connector and hitting a weird issue: I run the spark-shell as: bin/spark-shell --packages datastax:spark-cassandra-connector:2.0.0-M2-s_2.1 Then I run the following commands: import com.datastax.spark.connector._ val rdd = sc.cassandraTable("test_spark", "test") println(rdd.first) # CassandraRow{id: 2, name: john, age: 29} Problem is that following command gives an error: rdd.take(1).foreach(println) # CassandraRow{id: 2, name: john, age: 29} rdd.take(2).foreach(println) # Caused by: com.datastax.driver.core.exceptions.UnavailableException: Not enough replicas available for query at consistency LOCAL_ONE (1 required but only 0 alive) # at com.datastax.driver.core.exceptions.UnavailableException.copy(UnavailableException.java:128) # at com.datastax.driver.core.Responses$Error.asException(Responses.java:114) # at com.datastax.driver.core.RequestHandler$SpeculativeExecution.onSet(RequestHandler.java:467) # at com.datastax.driver.core.Connection$Dispatcher.channelRead0(Connection.java:1012) # at com.datastax.driver.core.Connection$Dispatcher.channelRead0(Connection.java:935) # at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105) And the following command just hangs: println(rdd.count) My Cassandra keyspace seems to have the right replication factor: describe test_spark; CREATE KEYSPACE test_spark WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '3'} AND durable_writes = true; How to fix both the above errors? A: I assume you hit the issue with SimpleStrategy and multi-dc when using LOCAL_ONE (spark connector default) consistency. It will look for a node in the local DC to make the request to but theres a chance that all the replicas exist in a different DC and wont meet the requirement. (CASSANDRA-12053) If you change your consistency level (input.consistency.level to ONE) I think it will be resolved. You should also really consider using the network topology strategy instead.
{ "language": "en", "url": "https://stackoverflow.com/questions/42446887", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: ActiveTab setting in javascript When i am setting the tabcontainer first tab as active tab through javascript with the following code : var tc = document.getElementById('<%= tabContainer.ClientID %>'); tc.firstChild.lastChild.style.visibility = "hidden"; tc.set_activeTabIndex(0); i am getting the exception like: Propert or method not supported with this object. note that the second line succefully hides the second tab panel but the third line raises the excception Any suggestion how to set a tab active through javascript? A: Error is generated for line tc.set_activeTabIndex(0); We don't have built-in set_activeTabIndex() method. You should apply appropriate CSS properties for enabling/disabling tabs. A: You need the client control; not the DOM element. In order to get the control use the $find method. After that you can use the set_activeTab method. ctrl = $find("<%= tabContainer.ClientID %>"); ctrl.set_activeTab(ctrl.get_tabs()[yourTabNumber]);
{ "language": "en", "url": "https://stackoverflow.com/questions/3316631", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Peculiar Map/Reduce result from CouchDB I have been using CouchDB for quite sometime without any issues. That is up until now. I recently saw something in my map/reduce results which I had overlooked! This is before performing a sum on the "avgs" variable. I'm basically trying to find the average of all values pertaining to a particular key. Nothing fancy. The result is as expected. Note the result for timestamp 1308474660000 (4th row in the table): Now I sum the "avgs" array. Now here is something that is peculiar about the result. The sum for the key with timestamp 1308474660000 is a null!! Why is CouchDB spitting out nulls for a simple sum? I tried with a custom addition function and its the same problem. Can someone explain to me why is there this issue with my map/reduce result? CouchDB version: 1.0.1 UPDATE: After doing a rereduce I get a reduce overflow error! Error: reduce_overflow_error Reduce output must shrink more rapidly: Current output: '["001,1,1,1,1,1,11,1,1,1,1,1,1,11,1,1,1,1,1,1,11,1,1,1,1,1,1,11,1,1,1,1,1,101,1,1,1,1,1,1,11,1,1,1,1'... (first 100 of 396 bytes) This is my modified reduce function: function (key, values, rereduce) { if(!rereduce) { var avgs = []; for(var i=values.length-1; i>=0 ; i--) { avgs.push(Number(values[i][0])/Number(values[i][1])); } return avgs; } else { return sum(values); }; } UPDATE 2: Well now it has gotten worse. Its selectively rereducing. Also, the ones it has rereduced show wrong results. The length of the value in 4th row for timestamp (1308474660000) should be 2 and not 3. UPDATE 3: I finally got it to work. I hadn't understood the specifics of rereduce properly. AFAIK, Couchdb itself decides how to/when to rereduce. In this example, whenever the array was long enough to process, Couchdb would send it to rereduce. So I basically had to sum twice. Once in reduce, and again in rereduce. function (key, values, rereduce) { if(!rereduce) { var avgs = []; for(var i=values.length-1; i>=0 ; i--) { avgs.push(Number(values[i][0])/Number(values[i][1])); } return sum(avgs); } else { return sum(values); //If my understanding of rereduce is correct, it only receives only the avgs that are large enough to not be processed by reduce. } } A: Your for loop in the reduce function is probably not doing what you think it is. For example, it might be throwing an exception that you did not expect. You are expecting an array of 2-tuples: // Expectation values = [ [value1, total1] , [value2, total2] , [value3, total3] ]; During a re-reduce, the function will get old results from itself before. // Re-reduce values values = [ avg1 , avg2 , avg3 ] Therefore I would begin by examining how your code works if and when rereduce is true. Perhaps something simple will fix it (although often I have to log() things until I find the problem.) function(keys, values, rereduce) { if(rereduce) return sum(values); // ... then the same code as before. } A: I will elaborate on my count/sum comment, just in case you are curious. This code is not tested, but hopefully you will get the idea. The end result is always a simple object {"count":C, "sum":S} and you know the average by computing S / C. function (key, values, rereduce) { // Reduce function var count = 0; var sum = 0; var i; if(!rereduce) { // `values` stores actual map output for(i = 0; i < values.length; i++) { count += Number(values[i][1]); sum += Number(values[i][0]); } return {"count":count, "sum":sum}; } else { // `values` stores count/sum objects returned previously. for(i = 0; i < values.length; i++) { count += values[i].count; sum += values[i].sum; } return {"count":count, "sum":sum}; } } A: I use the following code to do average. Hope it helps. function (key, values) { return sum(values)/values.length; }
{ "language": "en", "url": "https://stackoverflow.com/questions/6468637", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: KSQL db - UDF look up a ksqldb table Is it possible to create a UDF to receive/look up a ksqldb table? For example: Creating UDF which receives Int UserId as a parameter and retrieves from User Table the user name by the received UserId? I know it can be done by scalar functions with join, but I need to do it by UDF alternatively, is it possible to receive a ksqldb table row as JSON to UDF (as a parameter)?
{ "language": "en", "url": "https://stackoverflow.com/questions/74029505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: await resp.prepare(request) AttributeError: 'NoneType' object has no attribute 'prepare' async def index(request): async with aiohttp.ClientSession() as client: data=await(email_verification(client)) await client.post('http://127.0.0.1:8000/acc/signup',data=data) async def email_verification(client): async with client.get('http://www.mocky.io/v2/5c18dfb62f00005b00af1241') as resp: return await(resp.json()) but whenever i tried to acess the url i got this error await resp.prepare(request) AttributeError: 'NoneType' object has no attribute 'prepare' i cant even understand what the issue is and where this resp.prepare came from please A: Web-handler should return a response object, not None. The fixed code is: async def index(request): async with aiohttp.ClientSession() as client: data=await(email_verification(client)) await client.post('http://127.0.0.1:8000/acc/signup',data=data) return web.Response(text="OK") async def email_verification(client): async with client.get('http://www.mocky.io/v2/5c18dfb62f00005b00af1241') as resp: return await(resp.json())
{ "language": "en", "url": "https://stackoverflow.com/questions/53833244", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Get the key attribute in child component when using v-for in VueJS According to the VueJS documentation I have to pass a :key attribute which is a unique identifier for the component. I have the following component iterator. <line-reactive v-for="(chart, index) in chartcfg" :index="index" :key="chart.id"></line-reactive> How can I access the :key attribute inside LineReactive (the child component)? When I'm in my LineReactive component and do this.key it returns undefined
{ "language": "en", "url": "https://stackoverflow.com/questions/46408034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: C# Passing Table Valued Parameter to SqlCommand not Working I'm trying to run a test case, and this won't even work... What am I doing wrong here? Here's the SQL: CREATE TABLE Playground.Test (saved DateTime) GO CREATE TYPE Playground.DateTimeTable AS TABLE ([time] DATETIME); GO CREATE PROCEDURE Playground.InsertDate @dt Playground.DateTimeTable READONLY AS BEGIN INSERT INTO Playground.Test (saved) SELECT [time] FROM @dt END GO And code to connect and execute the procedure: const String connString = "server = SERVER; database = DB; UID = myUserID; pwd = myPassword;"; static void Main(string[] args) { SqlCommand command = new SqlCommand( "EXEC Playground.InsertDate", new SqlConnection(connString)); DataTable table = new DataTable("DateTimeTable"); table.Columns.Add("[time]", typeof(DateTime)); table.Rows.Add(DateTime.Parse("10/27/2004")); SqlParameter tvp = command.Parameters.AddWithValue("@dt", table); tvp.SqlDbType = SqlDbType.Structured; tvp.TypeName = "Playground.DateTimeTable"; command.Connection.Open(); int affected = command.ExecuteNonQuery(); command.Connection.Close(); Console.WriteLine(affected); Console.ReadKey(); } I'm not getting any errors. Just 0 rows affected. This works in SQL Server, though: DECLARE @dt Playground.DateTimeTable INSERT INTO @dt VALUES ('2004-10-27') EXEC Playground.InsertDate @dt What am I supposed to be doing here? A: You are not setting your SqlCommand object to be a stored procedure. You should do a couple of things: * *Remove the EXEC prefix from the string ~(it's not needed) *Set command to be a stored procedure: command.CommandType = CommandType.StoredProcedure; *Not sure how the square braces around the DataTable column names will affect this either, but I suspect it's better with them removed.
{ "language": "en", "url": "https://stackoverflow.com/questions/30600117", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Where Clsid comes from when registering COM When I register COM dll by running regsvr32 MyCOMdll.dll in CMD I see several entries created in registry, one of them is: [HKEY_CLASSES_ROOT\MyCOMdll.MyClass\Clsid] @="{DB402D5A-5584-4F68-A750-45D3E8133121}" I'd like to understand where DB402D5A-5584-4F68-A750-45D3E8133121 comes from, initially I thought that GUID generated at point when you register this DLL, however I checked this at different environments and I see it has same value. It looks like these GUIDs are embedded into DLL, but I cannot confirm or find out at which point. Context: I want to perform a "hot swap" of that COM, however it doesn't seem to be straightforward. I tried to update GUIDs in registry after I register new DLL, but getting error ClassFactory cannot supply requested class. A: When you register a COM dll using regsvr32, CLSIDs are defined inside the dll. In typical ATL COM project, these entries are specified in *.rgs files, and registry is updated based on that content. Of course, this is not the only way to do it and other toolsets and technologies do it in different way. These CLSIDs are actually defined in the .idl file of the project (again, this is valid for ATL projects), and .rgs file must correctly match the values. The .idl file itself contains IDL definitions of all COM types in the library, and is used by MIDL compiler to generate the type library.
{ "language": "en", "url": "https://stackoverflow.com/questions/34808767", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Move data from Google Cloud-SQL to Cloud Datastore I am trying to move my data from Cloud SQL to Cloud Datastore. There are a bit under 5 million entries in the SQL database. It seems like I can only move over 100,000 entities per day before I get a quota error. I can't figure out which exact quota I'm exceeding, however I have exponential backoff to make sure I'm not sending it too fast. Eventually it hits 5 minutes and the connection to the SQL server dies, but I don't think the writes per second quota is the problem. And I don't see any other quota exceeding in my APIs page or the App Engine API page. I have tried two different APIs to write the records. The GCP Datastore API import googledatastore Here is the code: https://gist.github.com/nburn42/d8b488da1d2dc53df63f4c4a32b95def And the Dataflow API from apache_beam.io.gcp.datastore.v1.datastoreio import WriteToDatastore Here is the code: https://gist.github.com/nburn42/2c2a06e383aa6b04f84ed31548f1cb09 Here is the error I see after one or two hundred thousand good writes. RPCError: datastore call commit [while running 'Write To Datastore/Write Mutation to Datastore'] failed: Error code: RESOURCE_EXHAUSTED. Message: Quota exceeded. I'm running this on compute engine. Any help is greatly appreciated! Thanks, Nathan A: I asked for a quota increase and someone at google checked my account to find the problem. Here is their reply. I understand that you want to know what specific quota you are reaching whenever you try to backup your Cloud SQL to Cloud Datastore. Upon checking your project, it seems that the problem is that your App Engine application is at or near its spending limit. As of this time of writing, the Datastore Write Operations you have executed costed you 1.10$, which will be refreshed after 5 hours. It can definitely cause your resources to become unavailable until the daily spending limit is replenished. Kindly try to increase your spending limit as soon as possible to avoid service interruption and then run or execute your datastore write operations. Give this a shot and let me know what happens. I will be looking forward to your reply. This fixed the problem. I just needed to go into app engine and set a much higher daily spending limit. Hopefully the code I included above will help others.
{ "language": "en", "url": "https://stackoverflow.com/questions/43332598", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why HTTP/2 on a specific site works in FF, but doesn't work in Chrome, IE and Edge on the same Windows 10 computer? I have a site, that runs on a Nginx 1.10.0 on Ubuntu 16.04 server (OpenSSL 1.0.2h). I want to serve this site over HTTP/2, so I configured Nginx accordingly: listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server And it works fine in FF 47 and Chrome 51 on my office Ubuntu 15.10 desktop and in the same browsers on my home Ubuntu 15.10 desktop. However on my home Windows 10 desktop and laptop HTTP/2 works only in FF. Chrome 51, IE 11 and Edge are using HTTP/1.1 on this site. So, I'm baffled. This service says, that my site supports HTTP/2 and ALPN (which is required for HTTP/2 to work in Chrome since version 51). Chrome versions and capabilities are exactly the same: HTTPS works, and Security panel in Chrome Dev Tools shows, that everything is secured. This demo in Chrome, IE and Edge displays message "This browser is not HTTP/2 enabled.", and "Your browser supports HTTP/2!" in FF. But HTTP/2 on medium.com works just fine in all of this browsers. So, my question is: what's going on and how to fix this? A: Are you using antivirus software (e.g. Avast) and is it inspecting your HTTPS traffic? It does this by acting like a MITM so you connect it it and it connects to the real website. And if they only support http/1 (which as far as I know they only do) then that would explain this. Though oddly not for for Medium unless you have an exception for this. Should be easy enough to check by looking at the HTTPS cert when visiting the site to see if it was "issued" by your local Avast server. If not that then suggest you look at your ciphers as HTTP/2 is picky about which ones it uses. Anything weird showing on https://www.ssllabs.com/servertest for your site? What cipher is it using for Chrome?
{ "language": "en", "url": "https://stackoverflow.com/questions/38368099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Please tell me how to write nuxt plugins 'printd' During development, we implemented the page to print using Printd. create plugins / printd.ts import Vue from "vue"; import { Printd } from "printd"; Vue.use(Printd); The 'plugins' part of nuxt.conifg.ts. plugins: [ ... , { src: "~/plugins/printd", ssr: false }] but the error is shown below 10:9 No overload matches this call. Overload 1 of 2, '(plugin: PluginObject<unknown> | PluginFunction<unknown>, options?: unknown): VueConstructor<Vue>', gave the following error. Argument of type 'typeof Printd' is not assignable to parameter of type 'PluginObject<unknown> | PluginFunction<unknown>'. Property 'install' is missing in type 'typeof Printd' but required in type 'PluginObject<unknown>'. Overload 2 of 2, '(plugin: PluginObject<any> | PluginFunction<any>, ...options: any[]): VueConstructor<Vue>', gave the following error. Argument of type 'typeof Printd' is not assignable to parameter of type 'PluginObject<any> | PluginFunction<any>'. Property 'install' is missing in type 'typeof Printd' but required in type 'PluginObject<any>'. 8 | 9 | > 10 | Vue.use(Printd); | ^ 11 | help me!! A: This worked for me : import Vue from "vue" import { Printd } from "printd"; Vue.prototype.$Printd = new Printd(); Then you can access this.$Printd in your whole app. A: Try adding: as any just like in the following. import Vue from "vue"; import { Printd } from "printd"; Vue.use(Printd as any); This might be your answer. But if that does not work, try this. import Vue from "vue"; const Printd = require("printd").Printd; Vue.use(Printd); ... And if that still does not work, try this. file: ~/types/index.d.ts declare module "printd"
{ "language": "en", "url": "https://stackoverflow.com/questions/60071580", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I call a Java method that takes a Non-null Void parameter from Kotlin? Primary Question Is it possible to call a Java method with a signature like this (from a third-party library, so the method signature cannot be changed) from Kotlin? If so, how? class Uncallable { void myMethod(@NonNull Void a) { System.out.println("Ran myMethod"); } } I can call this from another Java class with Uncallable u = new Uncallable(); u.myMethod(null); // IDE warns about nullability but still runs fine but from Kotlin, none of these options work val u = Uncallable() u.myMethod() // No value passed for parameter 'a' u.myMethod(null) // Null can not be a value of a non-null type Void u.myMethod(Unit as Void) // ClassCastException: class kotlin.Unit cannot be cast to class java.lang.Void u.myMethod(Void) u.myMethod(Unit) u.myMethod(Nothing) Similar questions (like this one) suggest making a Java interface layer to let me get around the nullability rules. That works here, but I'd like to know if there's any way to call this without such an extra layer. I don't actually need to pass a null value, just to call the method. This question addresses a similar issue, but there they have control of the interface and can just use Void? as the type. Why do I want to do this? I don't really... However, I have some unit tests that intercept the addOnSuccessListener callback added to some Firebase methods and call onSuccess on the provided listener. The signature of that callback uses Void for its parameter type, and previously I could call listener.onSuccess(null) doAnswer { invocation -> val args = invocation.arguments @Suppress("UNCHECKED_CAST") val l = args[0] as OnSuccessListener<Void> l.onSuccess(null) mMockTask }.`when`(mMockTask).addOnSuccessListener(ArgumentMatchers.any()) After a recent update of Firebase libraries, it seems that either a @NonNull annotation was added to the parameter for onSuccess, or Kotlin changed to start enforcing it public interface OnSuccessListener<TResult> { void onSuccess(@NonNull TResult var1); } As a result, I can no longer call listener.onSuccess(null) - I get a build error about null being passed for a non-null parameter. I am able to make a VoidCaller Java interface to get around this, public class VoidCaller { static void callSuccessCallback(OnSuccessListener<Void> callback) { callback.onSuccess(null); } static void callFailureCallback(OnFailureListener callback) { callback.onFailure(null); } } which works, but only if I change my callbacks from fileRef.delete().addOnSuccessListener { onSuccess() } to fileRef.delete().addOnSuccessListener { _ : Void? -> onSuccess() } or I get an error attempting to set it of a non-null type to null. Parameter specified as non-null is null: method com.app.firebaseHelper.deleteImage$lambda-11$lambda-10, parameter it Ideally I would like to find a way to call such a method directly from Kotlin. A: If you only want to pass the Void object, but its constructor is private, you can use reflection. Constructor<Void> c = Void.class.getDeclaredConstructor(); c.setAccessible(true); Void v = c.newInstance(); then you can pass it. Since the question was about how to do this from Kotlin, here is the Kotlin version fun makeVoid(): Void { val c: Constructor<Void> = Void::class.java.getDeclaredConstructor() c.isAccessible = true return c.newInstance() } and val u = Uncallable() u.myMethod(makeVoid())
{ "language": "en", "url": "https://stackoverflow.com/questions/70343009", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: OSQP failed to find solution for max sharpe ratio I have provided my code. I have also provided the error it is throwing. And I have provided sample data. My actual data is too large to post but this gives you an idea of the data. I am trying to use the pypfopt module to calculate the efficient frontier maximum sharpe ratio solution. I'm using stock close price data for most of the s&p 500. for a smaller sample of stocks like 150 it will find a solution, but for the larger samples it throws this error. does anyone see what the issue might be? code: import numpy as np import pandas as pd import matplotlib.pyplot as plt import time import datetime import os import matplotlib.style from pandas.core.common import flatten from functools import partial, reduce import scipy.optimize as sco import math from pypfopt import EfficientFrontier from pypfopt import risk_models from pypfopt import expected_returns from pypfopt.discrete_allocation import DiscreteAllocation, get_latest_prices # Calculate expected returns and sample covariance mu = expected_returns.mean_historical_return(df) S = risk_models.sample_cov(df) # Optimise for maximal Sharpe ratio ef = EfficientFrontier(mu, S,verbose=True) raw_weights = ef.max_sharpe() error: ----------------------------------------------------------------- OSQP v0.6.0 - Operator Splitting QP Solver (c) Bartolomeo Stellato, Goran Banjac University of Oxford - Stanford University 2019 ----------------------------------------------------------------- problem: variables n = 394, constraints m = 789 nnz(P) + nnz(A) = 79388 settings: linear system solver = qdldl, eps_abs = 1.0e-05, eps_rel = 1.0e-05, eps_prim_inf = 1.0e-04, eps_dual_inf = 1.0e-04, rho = 1.00e-01 (adaptive), sigma = 1.00e-06, alpha = 1.60, max_iter = 10000 check_termination: on (interval 25), scaling: on, scaled_termination: off warm start: on, polish: on, time_limit: off iter objective pri res dua res rho time 1 0.0000e+00 1.00e+00 2.26e+03 1.00e-01 1.84e-02s 200 8.0697e+01 2.87e+01 1.04e-01 5.08e-05 6.78e-02s 400 1.1747e+02 4.23e+00 1.92e-02 5.08e-05 9.55e-02s 600 9.8811e+01 2.63e+00 5.59e-04 5.08e-05 1.23e-01s 800 9.4263e+01 2.06e+00 1.29e-03 5.08e-05 1.51e-01s 1000 9.0092e+01 1.62e+00 9.64e-04 5.08e-05 1.78e-01s 1200 8.6677e+01 1.43e+00 8.32e-04 5.08e-05 2.07e-01s 1400 8.3735e+01 1.33e+00 7.31e-04 5.08e-05 2.34e-01s 1600 8.1138e+01 1.24e+00 6.53e-04 5.08e-05 2.63e-01s 1800 7.8795e+01 1.16e+00 5.92e-04 5.08e-05 2.90e-01s 2000 7.6644e+01 1.09e+00 5.41e-04 5.08e-05 3.18e-01s 2200 7.4642e+01 1.03e+00 5.00e-04 5.08e-05 3.46e-01s 2400 7.2758e+01 9.76e-01 4.65e-04 5.08e-05 3.74e-01s 2600 7.0970e+01 9.32e-01 4.36e-04 5.08e-05 4.01e-01s 2800 6.9263e+01 8.93e-01 4.11e-04 5.08e-05 4.31e-01s 3000 6.7623e+01 8.59e-01 3.89e-04 5.08e-05 4.59e-01s 3200 6.6044e+01 8.40e-01 3.71e-04 5.08e-05 4.86e-01s 3400 6.4517e+01 8.36e-01 3.55e-04 5.08e-05 5.14e-01s 3600 6.3039e+01 8.30e-01 3.41e-04 5.08e-05 5.42e-01s 3800 6.1605e+01 8.24e-01 3.29e-04 5.08e-05 5.71e-01s 4000 6.0213e+01 8.17e-01 3.19e-04 5.08e-05 5.99e-01s 4200 5.8860e+01 8.09e-01 3.09e-04 5.08e-05 6.27e-01s 4400 5.7543e+01 8.01e-01 3.01e-04 5.08e-05 6.54e-01s 4600 5.6262e+01 7.92e-01 2.93e-04 5.08e-05 6.82e-01s 4800 5.5014e+01 7.83e-01 2.86e-04 5.08e-05 7.10e-01s 5000 5.3798e+01 7.74e-01 2.80e-04 5.08e-05 7.37e-01s 5200 5.2614e+01 7.65e-01 2.74e-04 5.08e-05 7.66e-01s 5400 5.1460e+01 7.56e-01 2.69e-04 5.08e-05 7.95e-01s 5600 5.0334e+01 7.46e-01 2.63e-04 5.08e-05 8.23e-01s 5800 4.9237e+01 7.37e-01 2.59e-04 5.08e-05 8.51e-01s 6000 4.8168e+01 7.28e-01 2.54e-04 5.08e-05 8.79e-01s 6200 4.7124e+01 7.18e-01 2.50e-04 5.08e-05 9.07e-01s 6400 4.6107e+01 7.09e-01 2.46e-04 5.08e-05 9.35e-01s 6600 4.5114e+01 7.00e-01 2.42e-04 5.08e-05 9.63e-01s 6800 4.4146e+01 6.91e-01 2.38e-04 5.08e-05 9.91e-01s 7000 4.3201e+01 6.82e-01 2.35e-04 5.08e-05 1.02e+00s 7200 4.2280e+01 6.73e-01 2.31e-04 5.08e-05 1.05e+00s 7400 4.1380e+01 6.64e-01 2.28e-04 5.08e-05 1.07e+00s 7600 4.0503e+01 6.55e-01 2.25e-04 5.08e-05 1.10e+00s 7800 3.9647e+01 6.46e-01 2.21e-04 5.08e-05 1.13e+00s 8000 3.8811e+01 6.37e-01 2.18e-04 5.08e-05 1.16e+00s 8200 3.7996e+01 6.29e-01 2.15e-04 5.08e-05 1.19e+00s 8400 3.7200e+01 6.20e-01 2.12e-04 5.08e-05 1.21e+00s 8600 3.6424e+01 6.12e-01 2.09e-04 5.08e-05 1.24e+00s 8800 3.5666e+01 6.04e-01 2.06e-04 5.08e-05 1.27e+00s 9000 3.4926e+01 5.96e-01 2.03e-04 5.08e-05 1.30e+00s 9200 3.4204e+01 5.88e-01 2.01e-04 5.08e-05 1.32e+00s 9400 3.3499e+01 5.80e-01 1.98e-04 5.08e-05 1.35e+00s 9600 3.2811e+01 5.72e-01 1.95e-04 5.08e-05 1.38e+00s 9800 3.2139e+01 5.64e-01 1.92e-04 5.08e-05 1.41e+00s 10000 3.1483e+01 5.57e-01 1.90e-04 5.08e-05 1.44e+00s status: maximum iterations reached number of iterations: 10000 run time: 1.44e+00s optimal rho estimate: 1.08e-04 --------------------------------------------------------------------------- SolverError Traceback (most recent call last) <ipython-input-62-c6bc50ed1e81> in <module> 7 # Optimise for maximal Sharpe ratio 8 ef = EfficientFrontier(mu, S,verbose=True) ----> 9 raw_weights = ef.max_sharpe() 10 # cleaned_weights = ef.clean_weights() ~/anaconda3/envs/pyopft/lib/python3.6/site-packages/pypfopt/efficient_frontier.py in max_sharpe(self, risk_free_rate) 224 ] + new_constraints 225 --> 226 self._solve_cvxpy_opt_problem() 227 # Inverse-transform 228 self.weights = (self._w.value / k.value).round(16) + 0.0 ~/anaconda3/envs/pyopft/lib/python3.6/site-packages/pypfopt/base_optimizer.py in _solve_cvxpy_opt_problem(self) 222 opt.solve(solver=self._solver, verbose=self._verbose) 223 else: --> 224 opt.solve(verbose=self._verbose) 225 except (TypeError, cp.DCPError) as e: 226 raise exceptions.OptimizationError from e ~/anaconda3/envs/pyopft/lib/python3.6/site-packages/cvxpy/problems/problem.py in solve(self, *args, **kwargs) 394 else: 395 solve_func = Problem._solve --> 396 return solve_func(self, *args, **kwargs) 397 398 @classmethod ~/anaconda3/envs/pyopft/lib/python3.6/site-packages/cvxpy/problems/problem.py in _solve(self, solver, warm_start, verbose, gp, qcp, requires_grad, enforce_dpp, **kwargs) 752 solution = solving_chain.solve_via_data( 753 self, data, warm_start, verbose, kwargs) --> 754 self.unpack_results(solution, solving_chain, inverse_data) 755 return self.value 756 ~/anaconda3/envs/pyopft/lib/python3.6/site-packages/cvxpy/problems/problem.py in unpack_results(self, solution, chain, inverse_data) 1066 raise error.SolverError( 1067 "Solver '%s' failed. " % chain.solver.name() + -> 1068 "Try another solver, or solve with verbose=True for more " 1069 "information.") 1070 self.unpack(solution) SolverError: Solver 'OSQP' failed. Try another solver, or solve with verbose=True for more information. data: print(df) MMM ABT ABBV ATVI AMD AAP \ 0 175.869995 107.610001 103.809998 76.190002 86.769997 150.009995 1 175.714996 107.355003 103.889999 76.690002 87.209999 149.005005 2 176.135696 107.330002 104.010002 76.870003 87.220001 148.613098 3 175.979996 107.415001 104.080002 77.010002 87.070000 148.529999 4 176.350006 107.500000 103.849998 76.900002 87.550003 148.865005 ... ... ... ... ... ... ... 1563 174.399994 108.360001 102.957497 90.779999 91.559998 160.789993 1564 174.679993 108.379997 103.140800 90.959999 91.645897 160.770004 1565 174.509995 108.349998 103.129997 90.919998 91.694901 160.904999 1566 174.520004 108.339996 103.309998 90.910004 91.800003 160.690002 1567 174.520004 108.349998 103.260002 90.959999 91.809998 160.679993 AES AFL A AKAM ... WMB \ 0 21.125000 45.455002 115.970001 102.639999 ... 21.580000 1 21.004999 45.139999 116.779999 102.930000 ... 21.510000 2 21.000000 45.209999 116.639999 102.722504 ... 21.559999 3 21.020000 45.209999 116.394997 102.750000 ... 21.610001 4 21.075001 45.200001 116.230003 103.400398 ... 21.590000 ... ... ... ... ... ... ... 1563 23.170000 43.840000 117.589996 107.214996 ... 20.684999 1564 23.190001 43.830002 117.410004 107.349998 ... 20.730000 1565 23.270000 43.775002 117.349998 107.370003 ... 20.760000 1566 23.270000 43.840000 117.309998 107.430000 ... 20.750000 1567 23.270000 43.840000 117.309998 107.459999 ... 20.740000 WYNN XEL XRX XLNX XYL YUM \ 0 100.320000 68.540001 23.430000 135.860001 96.665001 106.864998 1 99.935997 68.430000 23.389999 136.429993 96.440002 106.300003 2 100.199997 68.410004 23.420000 136.449997 96.254997 106.400002 3 100.459999 68.500000 23.320000 136.050003 96.559998 106.385002 4 99.745003 68.580002 23.299999 136.850006 96.449997 106.349998 ... ... ... ... ... ... ... 1563 113.654999 64.550003 22.610001 141.589996 100.099998 107.500000 1564 113.879997 64.599998 22.629999 141.699997 100.150002 107.589996 1565 114.150002 64.620003 22.600000 141.789993 100.230003 107.669998 1566 114.330002 64.680000 22.580000 141.990005 100.139999 107.550003 1567 114.389999 64.629997 22.580000 141.990005 100.250000 107.540001 ZBH ZION ZTS 0 149.675003 40.619999 161.639999 1 149.350006 40.860001 160.850006 2 148.925003 40.750000 161.169998 3 149.240005 40.669998 161.000000 4 149.770004 40.430000 160.979996 ... ... ... ... 1563 149.490005 43.174999 160.645004 1564 149.604996 43.285000 160.740005 1565 149.500000 43.360001 160.643204 1566 149.250000 43.330002 160.774994 1567 149.250000 43.340000 160.720001 [1568 rows x 393 columns]
{ "language": "en", "url": "https://stackoverflow.com/questions/65461301", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Authenticate desktop application with web application (mvc web app) I have an MVC application where users can authenticate and I developed a small desktop application that needs to authenticate to the web app at startup. I don't need to call APIs from my desktop application, I just need to authenticate. Any code samples will help taking in consideration that I am not a web developer yet. Thanks
{ "language": "en", "url": "https://stackoverflow.com/questions/42379419", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Java BeanUtils Unknown property with underscore (_) I cannot get the property with underscore (ex: User_Name) from a class using BeanUtils.getProperty(bean, property), it always throw error: "Unknown property 'User_Name' on class 'User'". But when I debug the bean, it has User_Name property. BeanUtils.getProperty(bean, propertyName); The User class is public class User { private String ID; private String User_Name; public void setID(String ID) { this.ID = ID; } public String getUser_Name() { return this.User_Name; } public void setUser_Name(String user_Name) { this.User_Name = user_Name; } } A: It is a matter of naming convention. You can refer to Where is the JavaBean property naming convention defined? for reference. From section 8.8 of JavaBeans API specification ... Thus when we extract a property or event name from the middle of an existing Java name, we normally convert the first character to lower case*case 1. However to support the occasional use of all upper-case names, we check if the first two characters*case 2 of the name are both upper case and if so leave it alone. So for example, 'FooBah" becomes 'fooBah' 'Z' becomes 'z' 'URL' becomes 'URL' We provide a method Introspector.decapitalize which implements this conversion rule Hence for your given class, the property deduced from getUser_Name() and setUser_Name() is "user_Name" instead of "User_Name" according to *case1. And calling getProperty(bean, "ID") is working according to *case 2. To solve the problem, please update the naming according to the Java naming convention, we should start with lower case for property and method, and use camelCase instead of snake_case to separate word. Keep in mind that following convention is really important in programming. The following is the updated class as an example. import java.lang.reflect.InvocationTargetException; import org.apache.commons.beanutils.BeanUtils; public class User { private String ID; private String userName; public String getID() { return ID; } public void setID(String ID) { this.ID = ID; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { User bean = new User(); bean.setUserName("name"); System.out.println(BeanUtils.getProperty(bean, "userName")); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/57068584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: why we need to use get method inside a java file @RequestMapping(method = RequestMethod.GET) In generally while sending form data from the ui pages we are using method="GET" or method="POST" in the form tag then what is the use of these methods in the server side programs. I am using these methods in spring while calling the methods in the controller @RequestMapping(method = RequestMethod.GET) Can anyone explain what is the real use of get or post methods in server side code A: Loosely speaking, if the purpose of your method is to retrieve data from the server use GET. e.g. getting information to display on the client. If you are sending data to the server use POST. e.g. sending information to the server to be saved on a database somewhere. There is a limit to the size of data you can send to the server with a GET request. A: The server side GET or POST is used to specify what the server expects to receive in order to accept the request. The client side GET or POST is used to specify what will be sent to the server. These two must match. You cannot send a GET request when server expects a POST and vice-versa. When you are building a server application, it is important to know the appropriate request type to use, which by itself is a whole big different topic which you should research if it is you the one that builds the server side part.
{ "language": "en", "url": "https://stackoverflow.com/questions/27147520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Group By dynamic list with Count I'm using a simple case statement to count the occurrences of breakcode in my data and grouping by Seller and SaleDate. However it seems like an inelegant solution. The breakcode could and quite possibly will expand and I would need to update my code when it does. How can this be done? Additionally, while using NULL gives me the right answers, I would like to know is there a better approach to how I am counting my instances of breakcode, putting 0 in place of NULL returns the incorrect results? SELECT seller, saledate, COUNT(CASE WHEN breakcode = 1 then 1 ELSE NULL END) as [Perfect], COUNT(CASE WHEN breakcode = 2 then 1 ELSE NULL END) as [Simple], COUNT(CASE WHEN breakcode = 3 then 1 ELSE NULL END) as [Medium], COUNT(CASE WHEN breakcode = 4 then 1 ELSE NULL END) as [Dual1], COUNT(CASE WHEN breakcode = 5 then 1 ELSE NULL END) as [Dual2], COUNT(CASE WHEN breakcode = 6 then 1 ELSE NULL END) as [Hard], COUNT(CASE WHEN breakcode = 7 then 1 ELSE NULL END) as [Difficult] FROM test GROUP BY seller, sale date Thanks. SQLFiddle: http://sqlfiddle.com/#!3/26f6d/2 A: Final version developed through comments: DECLARE @sql AS NVARCHAR(MAX) DECLARE @cols AS NVARCHAR(MAX) SELECT @cols= ISNULL(@cols + ',','') + QUOTENAME(case when breakname like 'Perfect%' then 'Perfect' else breakname end) FROM (select * from breaks where breakname not like 'Perfect - 90') a group by id, breakname order by id SET @sql = N'SELECT seller, saledate, ' + @cols + ' FROM (select seller, saledate, case when breakname like ''Perfect%'' then ''Perfect'' else breakname end breakname from test inner join breaks on case when breakcode = 8 then 1 else breakcode end = id) derived PIVOT(count(breakname) FOR derived.breakname IN (' + @cols + ')) AS PVTTable ORDER BY seller, saledate' EXEC sp_executesql @sql SQL Fiddle
{ "language": "en", "url": "https://stackoverflow.com/questions/26185905", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Printing variables with incrementing suffixes What I'm trying to do would be a lot easier to understand by looking at the code: suffix = 1 prefix1="success" prefix2="success" prefix3="success" prefix4="success" while suffix<5: temp = "prefix"+str(suffix) print temp suffix+=1 So what I'm trying to do is to print the value of prefix1, prefix2 etc which is "success" as opposed to "prefix1","prefix2" etc. I fully understand why my code is working how it is, but I want to know if there is a way to print the values of the variables prefix+suffix. A: I think using a dict would make more sense: d = { 'prefix1' : 'success', 'prefix2' : 'success', 'prefix3' : 'success', 'prefix4' : 'success' } for i in range(1,5): temp = "prefix%s" % i print d[temp]
{ "language": "en", "url": "https://stackoverflow.com/questions/17714130", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Copying text from RichTextBox to WebBrowser I am trying to copy text from a RichTextBox and paste it into a WebBrowser. I use this code: WebBrowser wb = new WebBrowser(); wb.Navigate("about:blank"); richTextBox1.SelectAll(); richTextBox1.Copy(); wb.Document.ExecCommand("Paste", false, null); wb.Document always shows an empty document. DocumentText gives <HTML> </HTML>\0 and Document.Body is null. What am I doing wrong? A: The content of a RichTextBox is not HTML, so an incompatible clipboard format may be part of the issue. If you are happy with the text only, try assigning the plain text to the clipboard: Clipboard.SetText(RichTextBox1.Text); If you want formatted text, you will need to convert the RTF to HTML. This article may help: http://www.codeproject.com/Articles/27431/Writing-Your-Own-RTF-Converter A: Because your page html is null,try this example public partial class Form1 : Form { public Form1() { InitializeComponent(); webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted); } private void Form1_Load(object sender, EventArgs e) { webBrowser1.DocumentText = "<html><body></body></html>"; } void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { webBrowser1.Document.Body.InnerText = richTextBox1.Text; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/16317613", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can i determine color my drawn line and my drawn image? I have the following code: private void DrawImage(PaintEventArgs e) { newImage = Image.FromFile(bmpPath); e.Graphics.DrawImage(newImage, new Rectangle(0, 0, 200, 200)); e.Graphics.DrawLine(new Pen(Color.Yellow, 20), 20, 20, 200, 200); } How can I find the intersection by color, I mean intersection with my drawn line and with my drawn image? private void Button2_Click(object sender, EventArgs e) { Bitmap b = new Bitmap(pictureBox1.ClientSize.Width, pictureBox1.Height); pictureBox1.DrawToBitmap(b, pictureBox1.ClientRectangle); int[,] pixels = new int[pictureBox1.Width, pictureBox1.Height]; for (int i = 0; i < pictureBox1.Width; i++) { for (int j = 0; j < pictureBox1.Height; j++) { if(Color.Black == b.GetPixel(i,j) && Color.Red == b.GetPixel(i,j)) { count++; } } } } A: Bitmap have array of every pixel which is an object that contains information about pixels. You can use it for your advantage. Pixel have 3 channels which contains informations about intensity of red, green, blue as channels. public Color GetPixel(int x, int y) { Color clr = Color.Empty; // Get color components count int cCount = Depth / 8; // Get start index of the specified pixel int i = ((y * Width) + x) * cCount; if (i > Pixels.Length - cCount) throw new IndexOutOfRangeException(); if (Depth == 32) // For 32 bpp get Red, Green, Blue and Alpha { byte b = Pixels[i]; byte g = Pixels[i + 1]; byte r = Pixels[i + 2]; byte a = Pixels[i + 3]; // a clr = Color.FromArgb(a, r, g, b); } if (Depth == 24) // For 24 bpp get Red, Green and Blue { byte b = Pixels[i]; byte g = Pixels[i + 1]; byte r = Pixels[i + 2]; clr = Color.FromArgb(r, g, b); } if (Depth == 8) // For 8 bpp get color value (Red, Green and Blue values are the same) { byte c = Pixels[i]; clr = Color.FromArgb(c, c, c); } return clr; }
{ "language": "en", "url": "https://stackoverflow.com/questions/58527839", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: local variable 'final_result' referenced before assignment I am making an django calculator web app and i got stuck with this error Currently, I am building a django powered UI Caculator app and I got stuck with this error.. I can't able to debug it. Whatever I'm to trying is not working at all. I mean i don't why it is telling me final result referenced before it gets assgined while i have already assigned final_result and then i have reference final_result Views.py def index(request): if request.method=="POST": values=request.POST['values'] print(values) vals=re.findall(r"(\d+)",values) operators=['+','x','÷','-','%'] opr=[] for v in values: for o in operators: if v==o: opr.append(o) print(opr) print(re.findall(r"(\d+)",values)) for o in opr: if o=='÷': i=opr.index(o) res=float(vals[i])/float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) elif o=='x': i=opr.index(o) res=float(vals[i])*float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) elif o=='+': i=opr.index(o) res=float(vals[i])+float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) else: i=opr.index(o) res=float(vals[i])-float(vals[i+1]) vals.remove(vals[i+1]) opr.remove(opr[i]) vals[i]=str(res) print(vals) print(opr) if(len(opr)!=0): if opr[0]=='÷': result = float(vals[0])/float(vals[1]) elif opr[0]=='x': result = float(vals[0])*float(vals[1]) elif opr[0]=='+': result = float(vals[0])+float(vals[1]) else : result = float(vals[0])-float(vals[1]) final_result=result print(final_result) res=render(request,'index.html'{'result':final_result,'values':values}) return res A: If request.method is not "POST", then final_result isn't assigned to before it is used the the call to render. A: You should initialize final_result before final_result = 0 if request.method == "POST": Just as @SLDem said. or else declare it in the function def index(request, final_result=0) This will also work.
{ "language": "en", "url": "https://stackoverflow.com/questions/65380251", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Pseudo-streaming in Flash - Apache and httpd.conf Setup? I installed and setup JW Player 6 plugin to my wordpress. I am using licensed mod. Anyway If I choose rendering mode:"Flash" i can't skip to time. I installed and activated Apache module h264_streaming and restart apache server, but nothing changed. Render Mode : "HTML5" is fine but i dont want to use html5. because video is loading slowly , i can skip to time in html5 but skip time is slow too in html5.
{ "language": "en", "url": "https://stackoverflow.com/questions/22884772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: three.js: How to get multiple materials working for one mesh I have a big problem with three.js: I want a simple cube with a different color on each face. I have tried this way: // set the scene size var WIDTH = jQuery('#showcase').width() - 20, HEIGHT = jQuery('#showcase').height(); // set some camera attributes var VIEW_ANGLE = 45, ASPECT = WIDTH / HEIGHT, NEAR = 0.1, FAR = 10000000; this.container = jQuery('#showcase'); this.renderer = new THREE.WebGLRenderer(); this.camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR); this.scene = new THREE.Scene(); this.scene.add(this.camera); // camera start position this.camera.position.z = this.model.radius; this.camera.position.y = this.model.cameraY; this.camera.position.x = 0; this.camera.lookAt(this.scene.position); this.renderer.setSize(WIDTH, HEIGHT); this.container.append(this.renderer.domElement); //Multiple Colors var materials = [new THREE.MeshBasicMaterial({ color : 0xFF0000 }), new THREE.MeshBasicMaterial({ color : 0x00FF00 }), new THREE.MeshBasicMaterial({ color : 0x0000FF }), new THREE.MeshBasicMaterial({ color : 0xAA0000 }), new THREE.MeshBasicMaterial({ color : 0x00AA00 }), new THREE.MeshBasicMaterial({ color : 0x0000AA })]; this.geometry = new THREE.CubeGeometry(100, 100, 100, materials); this.mesh = new THREE.Mesh(this.geometry, new THREE.MeshFaceMaterial()); this.scene.add(this.mesh); // create a point light this.pointLight = new THREE.PointLight(0xFFFFFF); this.pointLight.position = this.scene.position; this.scene.add(this.pointLight); this.renderer.render(this.scene, this.camera); But I get this error message: "Uncaught TypeError: Cannot read property 'map' of undefined" from line 19152 in three.js. To me it seems to be a problem of the webgl renderer. In most topics I have found here and somewhere else, they were using the canvas renderer. But I want to stay with the webgl renderer. Does anyone know something about this problem? Thanks a lot:-) A: Try this this.geometry = new THREE.CubeGeometry(100, 100, 100); this.mesh = new THREE.Mesh(this.geometry, new THREE.MeshFaceMaterial(materials)); A: maybe try to work with an array. With three.js 49 (dont of if it works with 57) i used this code for a skybox with different materials: var axes = new THREE.AxisHelper(); scene.add( axes ); var materialArray = []; materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) })); materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) })); materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) })); materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) })); materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) })); materialArray.push(new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture( 'textures/himmel.jpg' ) })); var skyboxGeom = new THREE.CubeGeometry( 5000, 5000, 5000, 1, 1, 1, materialArray ); var skybox = new THREE.Mesh( skyboxGeom, new THREE.MeshFaceMaterial() ); skybox.flipSided = true; scene.add( skybox ); A: Try this also, applying the vertexcolors. var geom = new THREE.BoxGeometry(20, 20, 20); var faceIndices = ['a', 'b', 'c']; var vertexIndex, point; mat = new THREE.MeshBasicMaterial({ vertexColors: THREE.VertexColors }); mesh = new THREE.Mesh(geom, mat); scene.add(mesh); geom.faces.forEach(function (face) { // loop through faces for (var i = 0; i < 3; i++) { vertexIndex = face[ faceIndices]; point = geom.vertices[vertexIndex]; color = new THREE.Color( point.x + 0.5, point.y + 0.5, point.z + 0.5 ); face.vertexColors[ i ] = [![the output will be as in the attached picture][1]][1]color; } });
{ "language": "en", "url": "https://stackoverflow.com/questions/15759447", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: Anchor Imageview at view bottom on scrollview layout I have a scrollview layout with several linear layouts inside. The last view of the scrollview is an ImageView which I need to appear always at the bottom of the screen. The content of the view is dynamic, and sometimes the screen does need to be scrolled and sometimes not. If the screen needs to be scrolled, the ImageView is shown correctly at the bottom. Take a look at the picture. This is an example of a scrolled screen, the imageView is the green bar. And this is an example of a screen that doesn't need to be scrolled, and as you can see, the image view is shown just below the textview. And here is my current XML file: <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" > <ImageView android:id="@+id/imagen_view11" android:layout_width="fill_parent" android:layout_height="60dp" android:scaleType="fitXY" android:src="@drawable/sector1" /> <ImageView android:id="@+id/imagen_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:scaleType="fitXY" android:src="@drawable/actpercusion" /> <TextView android:id="@+id/titulo_label" android:layout_width="fill_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:text="TextView TextView TextView TextView" android:textSize="25sp" android:textStyle="bold" /> <TextView android:id="@+id/lugar_label" android:layout_width="match_parent" android:layout_height="match_parent" android:text="TextView" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" > <RelativeLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:gravity="right" > <ImageButton android:id="@+id/boton_web" android:layout_width="80dp" android:layout_height="80dp" android:layout_alignParentRight="true" android:scaleType="fitXY" android:src="@drawable/web" android:text="Button web" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_toLeftOf="@+id/boton_web" android:orientation="vertical" > <ImageButton android:id="@+id/boton_mapa" android:layout_width="80dp" android:layout_height="80dp" android:scaleType="fitXY" android:src="@drawable/maps" android:onClick="openMapa" android:text="Button mapa" /> </LinearLayout> </RelativeLayout> </LinearLayout> <TextView android:id="@+id/descripcion_texto" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" android:text="TextView" /> <ImageView android:id="@+id/imagen_v" android:layout_width="fill_parent" android:layout_height="60dp" android:scaleType="fitXY" android:layout_alignParentBottom="true" android:src="@drawable/sector3" /> </LinearLayout> </ScrollView> I would need to change my layout file so that the image view always appears at the bottom of the screen, independently if the screen needs to be scrolled or not. Any help is welcome. A: You will need to use android:fillViewport <?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/scroller" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" > See this blog page written by Romain Guy.
{ "language": "en", "url": "https://stackoverflow.com/questions/27300523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Objective-C retain counts clarification I kind of understand what's retain counts for. But not totally. I looked on google a lot to try to understand but still I don't. And now I'm in a bit of code (I'm doing iPhone development) that I think I should use them but don't know totally how. Could someone give me a quick and good example of how and why using them? Thanks! A: If you haven't already I highly recommend you familiarize yourself with the Memory Management Programing Guide from Apple In there you will find a section specifically on retain counts A: The best explanation I ever heard was from Aaron Hillegass: Think of the object as a dog. You need a leash for a dog to keep it from running away and disappearing, right? Now, think of a retain as a leash. Every time you call retain, you add a leash to the dog's collar. You are saying, "I want this dog to stick around." Your hold on the leash insures that the dog will stay until you are done with it. Think of a release as removing one leash from the dog's collar. When all the leashes are removed, the dog can run away. There's no guarantee that the dog will be around any longer. Now, say you call retain and put a leash on the dog. I need the dog, too, so I walk along with you and start training him. When you are done with the dog, you call release and remove your leash. There are no more leashes and the dog runs away, even though I was still training him! If, instead, I call retain on the dog before I start training him, I have a second leash on the collar. When you call release and remove your leash, I still have one and the dog can't go away just yet. Different objects can "own" the dog by calling retain and putting another leash on its collar. Each object is making sure that the dog doesn't go away until it is done with it. The dog can't go away until all of the leashes have been removed. Autorelease pools get more complicated, but simplistically you can think of calling autorelease as handing your leash to a trainer. You don't need the dog anymore, but you haven't removed your leash right away. The trainer will take the leash off later; there is still no guarantee that the dog will be around when you need him.
{ "language": "en", "url": "https://stackoverflow.com/questions/2881880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Error on setting "user-type" type: org.jadira.usertype.dateandtime.joda.PersistentDateTime I am new on Grails (2.4.1). I am trying to use joda time (1.5). When I put the script below to my Config.groovy an error occurrs. grails.gorm.default.mapping = { "user-type" type: org.jadira.usertype.dateandtime.joda.PersistentDateTime, class: org.joda.time.DateTime "user-type" type: org.jadira.usertype.dateandtime.joda.PersistentLocalDate, class: org.joda.time.LocalDate // … define as many other user type mappings as you need } error: Error | 2014-07-12 23:45:31,632 [localhost-startStop-1] ERROR context.GrailsContextLoaderListener - Error initializing the application: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/engine/SessionImplementor Message: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/engine/SessionImplementor etc. A: I fixed the same error by upgrading the Jadira Usertype library dependency that the plugin was using. The Joda Time plugin recommends "org.jadira.usertype:usertype.jodatime:1.9", which only works for Hibernate 3. Try switching to "org.jadira.usertype:usertype.core:3.2.0.GA" when using Hibernate 4.
{ "language": "en", "url": "https://stackoverflow.com/questions/24719178", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Accessing a value from Server.R into .js file I think's it's quite an easy one but I can't find a way to solve it myself. I'd like to access the value of a variable in my Server.R file (I'm using Shiny) in my javascript file. My var "i" in myFile.js should take the value of my R variable "number". How should I proceed ? Example : Server.R ... number <- 5 ... myFile.js ... var i = ??? // var i = number *is not working* ... Thanks for your help, Matt A: Thanks to jdharrison, it works when I add the following code in myFile.js : Server.R number <- 5 observe({ session$sendCustomMessage(type='myCallbackHandler', number) }) myFile.js var i ; Shiny.addCustomMessageHandler("myCallbackHandler", function(number) { i = number; } ); var i now takes the value 5 in my javascript file.
{ "language": "en", "url": "https://stackoverflow.com/questions/24657590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQL JOB Output File - Remove Header I am trying to create a job that outputs the data into a file for manipulation later. I can easily output the file In the Job Type I have it set up for T-SQL for my query and this is the advanced tab for the Job step. It's working fine, except for the data that is being exported is coming out with a header, any ideas how I can get rid of this? A: Thanks to AlwaysLearning for pointing me in the right direction, went with the PowerShell solution Invoke-Sqlcmd Thanks again!!
{ "language": "en", "url": "https://stackoverflow.com/questions/64543039", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use 'strict' mode in Chrome 'JavaScript Console' I am practicing JavaScript on Chrome's 'JavaScript Console' ( version: 35.0) and I am unable to use the 'use strict' clause as expected. For the following code snippet : var obj={x:1,y:2} //Define new property with 'writable' flag as false. Object.defineProperty(obj, "z", {value:3, writable:false, enumerable:false, configurable:false}) // Try to change the property 'z', "use strict"; obj["z"]=4 Output: 4 As per my understanding, changing value of a 'non-writable' property will silently fail in non-strict mode and throw 'TypeError' in strict mode, But I don't see the exception. console.log(obj) Object {x: 1, y: 2, z: 3} Even though the property value is not changed but I am expecting a exception. Please correct if I am doing something wrong ? A: The easiest way to use strict mode is to use an IIFE (immediately Invoked Function Expression) like so: (function() { 'use strict'; var foo = 123;//works fine bar = 345;//ReferenceError: bar is not defined }()); To create a new-line in the console, use shift + enter, or write your code in a separate editor first, then copy-paste it to the console. Setting up a fiddle is all fine and dandy, but just test your code with the markup it was written for (ie: just clear the browser cache and test). However, I'd urge you to install node.js, still. It's a lot easier to test your code, or validate it (both syntactically and coding-style wise) using JSHint. There are also a lot of ways to examine and your code that run out of node.js, so it's a really good development tool to have
{ "language": "en", "url": "https://stackoverflow.com/questions/24369328", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "57" }