text
stringlengths
64
81.1k
meta
dict
Q: Cannot install ipython on rhel 5.8 using pip I am trying to install ipython on my rhel 5.8 server but it gives the below error. └──> sudo pip install ipython [sudo] password for ronak: Downloading/unpacking ipython Downloading ipython-0.13.tar.gz (6.1Mb): 6.1Mb downloaded Running setup.py egg_info for package ipython Traceback (most recent call last): File "<string>", line 14, in ? File "/usr/local/home/ronak/build/ipython/setup.py", line 23 from __future__ import print_function SyntaxError: future feature print_function is not defined Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 14, in ? File "/usr/local/home/ronak/build/ipython/setup.py", line 23 from __future__ import print_function SyntaxError: future feature print_function is not defined ---------------------------------------- Command python setup.py egg_info failed with error code 1 Storing complete log in /home/ronak/.pip/pip.log A: IPython ≥ 0.11 requires Python ≥ 2.6. That error suggests you have Python 2.5. If you must use Python 2.5, you can do: pip install ipython==0.10.2 Which is the last version that supported Python 2.5.
{ "pile_set_name": "StackExchange" }
Q: How to contact the 'akademio de esperanto' How to contact the 'AKADEMIO DE Esperanto' and suggest them to simplify/overhaul/revolutionise the Esperanto language by making plural forms, object agreement and other confusing language parts of the language optional? Can somebody rule a petition to convince the 'ADE' to make change to the language? A: I'm a member of the AdE, but I'm writing here as a private person. First, in order to answer the question in the title, here is the contact page of the Academy. Second, in order to react to your proposed reforms, here is my advice. From the content of your question I assume that you don't or hardly speak Esperanto. I urge you to learn the language first, for several reasons: It is good practice in the Esperanto community to discuss reforms in Esperanto only, as this a) keeps trolls away, b) shows that the proponent has an understanding of what they want to change, c) keeps quarrels away from the outside world. Discussing reforms in English will get you bunch of responses much less polite than mine. You will be able to read the Preface to the Fundamento de Esperanto, a document that fixes the core norms of the language (like all phenomena you mentioned in you question). You will get to know the way how Esperanto can evolve and you will understand that the Academy can add new rules to the Fundamento, but not as a replacement of older rules and only in case of indisputable need. The mere wish of a few beginners is not a sufficient reason to do so. See also the responses to this question. You will learn that Esperanto is a fully-fledged language with a community of speakers who are very reluctant to accept major changes, just because Esperanto is working well already. You will see that the chances of the reforms you propose are nil, so you will either live with the language as it is or leave it altogether instead of wasting energy fighting for a lost cause. You will have the chance to see from practice that some of the alleged flaws of Esperanto in fact are strengths. You will have access to a decent amount of cultural products like literature, music, and meetings not available in English, which make it worth learning the language independent of its role in international communication or structural details. It's fun, believe me. A: A quick search on Google will find their website where you can contact them. However I believe in general the Akademio doesn’t make sweeping changes like this. Rather they follow changes to the language as it used and make minor official recommendations when the usage diverges. Therefore if you want to make changes to the language your best bet is just to start using them yourself and try to convince others to do the same. If enough people do it then eventually the Akademio will officially recognise it. On the other hand if you propose extreme changes such as this then the resulting language probably isn’t Esperanto anymore and you are making a completely new constructed language. This has of course been done many times already and only time will tell if any of them will gain more support than Esperanto. Take a look at Ido, Toki Pona and Pandunia for example.
{ "pile_set_name": "StackExchange" }
Q: Can I count the number of pokes with the Facebook API? me/pokes returns only one poke I found this resource: http://developers.facebook.com/tools/explorer?method=GET&path=me%2Fpokes, but that only displays one poke. Can I get more pokes? I've also found this older question; Facebook FQL / Graph - Get all current pokes, which helped, but doesn't show the number of pokes ether. I want to show how often user x has poked user y. A: There is maximally one poke available. And if you poke back/delete poke, it is deleted from your profile (from API, too) SO you have no chance to see how often user x has poked user y
{ "pile_set_name": "StackExchange" }
Q: Is a PGP revocation certificate sensitive? In relation to an openpgp key on a smartcard: Besides revoking the key, is there anything else it can be (ab)used for? Can I just ensure it's reliably stored but not worry about it's confidentiality? A: What a Revocation Certificate is About Worst case in losing access to an OpenPGP key is that it probably is published on the key servers, and you have no chance in marking it as invalid any more, it will stay there forever, telling everybody "hey, that's my key, use it". A revocation certificate enables you to revoke your OpenPGP key if you lost access to your private key by publishing it on the key servers. Besides revoking the key, is there anything else it can be (ab)used for? Can I just ensure it's reliably stored but not worry about it's confidentiality? Whoever has access to it, can revoke your OpenPGP key. This cannot be undone once published. Using the revocation certificate, no further access can be obtained: it does not included the private key. If I had to guess a revocation certificate is "I declare revoked LET IT BE KNOWN! - Signed by " but I'd really like to know. In the end, that's exactly what it is. A revocation certificate is a special kind of signature on your OpenPGP key having some "revoke" bit set. How to Create a Revocation Certificate A revocation certificate can be created by using gpg --gen-revoke. From man gpg: --gen-revoke name Generate a revocation certificate for the complete key. To revoke a subkey or a signature, use the --edit command. I recommend to store it both digitally in a safe place, but also print it (qrencode for encoding the ASCII-armored revocation certificate can do a great job here if you don't want to use OCR) and deposit it with somebody you know very well and trust. Remember, even if you break up with that person, all he can do is revoking your key, not getting access to it. As you can add a description, you can even know which certificate was used for revoking your key and let the person know that to deter him.
{ "pile_set_name": "StackExchange" }
Q: Does "maximal submodule <=> simple quotient module" generalize to abelian categories? Does the statement "If $A$, $B$ are modules over a commutative ring $R$, then $B$ is a maximal submodule of $A$ if and only if $A/B$ is a simple module" generalize to the setting of abelian categories? That is, is it true to say "If C is an abelian category and $A, B \in$ C, then $B$ is a maximal subobject of $A$ if and only if $A/B$ is a simple object?" My hunch is that this statement does generalize, since I've seen it stated that the Jordan-Holder theorem for abelian categories is a "straightforward generalization" of the version for modules (wherein this fact is used), but I've had a lot of trouble finding anything on maximal subobjects at all and I haven't figured out the details yet. A: An attempt (everything happens inside abelian categories here and sorry for not being able to draw commutative diagrams with named arrows): $\textbf{Definition:}$ A monomorphism $\iota: B \rightarrow A$ is called a maximal subobject of $A$ if $\iota$ is not an isomorphism and the existence of two monomorphisms $B \rightarrow B'$ and $B' \rightarrow A$ sitting in a commutative diagram with $\iota$ implies that one of them is an isomorphism. $\textbf{Definition:}$ An object $S$ is called simple if $0 \rightarrow S$ is a maximal subobbject of $S$. $\textbf{Proposition:}$ Let $\iota: B \rightarrow A$ be a morphism with cokernel $\pi: A \rightarrow S$. If $\iota$ is a maximal subobject of $A$, then $S$ is simple. Proof. Note that since $\iota$ is not an isomorphism, we have $S \neq 0$ so we have the non-triviality condition. Let $\alpha: T \rightarrow S$ be a monomorphism. We want to show that either $\alpha = 0$ or $\alpha$ is an isomorphism. Form the pull-back along $\alpha$ and $\pi$, with parallel arrows to $\alpha$ and $\pi$ being $\alpha':P \rightarrow A$ and $\pi': P \rightarrow T$, respectively. First, $\alpha'$ is a monomorphism since pull-backs preserve kernels. Second, since $\pi$ is an epimorphism, the pull-back square is also a push-out; hence $\pi'$ is an epimorphism. Third, since $\iota$ is a monomorphism, it is a kernel, hence a kernel of its cokernel $\pi$. Again since pull-backs preserve kernels, there is a morphism $\iota' : B \rightarrow P$ which is a kernel of $\pi'$ and makes the relevant triangle commute ($\alpha' \circ \iota' = \iota$). Now, since $\iota$ is a maximal subobject, there are two possibilities: either $\iota'$ or $\alpha'$ is an isomorphism. The former yields $$\alpha \circ \pi' = \pi \circ \alpha' = \pi \circ \iota \circ (\iota')^{-1} = 0$$ hence $\alpha = 0$ as $\pi'$ is an epimorphism. And the latter yields that $\alpha$ is an isomorphism since $\alpha$ and $\alpha'$ are parallel in a push-out square. I haven't tried but I believe the converse statement can be proved similarly.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to get maven to accept maxerrs for its compiler plugin? I have a project where I am responsible for fixing some errors and another developer is responsible for other errors. The number of errors is well over a hundred, and as I'm fixing my errors, her errors are piling up. I'm at the point where I see 99 of her errors and one of mine, and I assume I will soon get to a point where it is 100 of hers. I looked into using this configuration for maven: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <compilerArgument>-Xmaxerrs 1000</compilerArgument> </configuration> </plugin> But no dice: Failure executing javac, but could not parse the error: javac: invalid flag: -Xmaxerrs 1000 Usage: javac <options> <source files> use -help for a list of possible options On the command line using javac, the maxerrs flag works as expected, but I can't seem to make the leap to maven with it. Any ideas? A: Using the "Map syntax" worked for me: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.1</version> <configuration> <fork>true</fork> <compilerArguments> <Xmaxerrs>1000</Xmaxerrs> </compilerArguments> </configuration> </plugin> The option is passed as expected: $ mvn clean compile -X ... [DEBUG] Using compiler 'javac'. [DEBUG] Source directories: [/home/pascal/Projects/stackoverflow/Q3358242/src/main/java] [DEBUG] Classpath: [/home/pascal/Projects/stackoverflow/Q3358242/target/classes] [DEBUG] Output directory: /home/pascal/Projects/stackoverflow/Q3358242/target/classes [DEBUG] Classpath: [DEBUG] /home/pascal/Projects/stackoverflow/Q3358242/target/classes [DEBUG] Source roots: [DEBUG] /home/pascal/Projects/stackoverflow/Q3358242/src/main/java [DEBUG] Command line options: [DEBUG] -d /home/pascal/Projects/stackoverflow/Q3358242/target/classes -classpath /home/pascal/Projects/stackoverflow/Q3358242/target/classes: -sourcepath /home/pascal/Projects/stackoverflow/Q3358242/src/main/java: /home/pascal/Projects/stackoverflow/Q3358242/src/main/java/com/stackoverflow/q3358242/App.java -g -nowarn -target 1.5 -source 1.5 -encoding UTF-8 -Xmaxerrs 1000 [INFO] Compiling 1 source file to /home/pascal/Projects/stackoverflow/Q3358242/target/classes [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ ... The odd part is that I get the exact same debug output (with the exact same Command line options) when using the alternative configuration you provided... except that it fails due to a Failure executing javac. You should raise a Jira issue, there is definitely something weird.
{ "pile_set_name": "StackExchange" }
Q: How To Prevent Direct Url Access In Codeigniter Let's said I have 2 pages "LowAdmin" and "Login" I want to prevent user from accesing "LowAdmin" directly from url. Instead, I want to redirect them to "Login" page. I have a problem explaining my pages to my teacher, because he access LowAdmin, instead of Login page. Anyone can help? I almost finish this final project. A: By analysing your project code in GitHub you can redirect by changing your constructor function of LowAdmin Controller like this. function __construct(){ parent::__construct(); $loginstatus = $this->session->userdata('status'); if($loginstatus!="login2"){ redirect(base_url("login")); } $this->load->model('project_model'); } Please comment below if you encountered any problem.
{ "pile_set_name": "StackExchange" }
Q: splitting multiple paths in string I have a command, which might resemble the following: SYNC C:\Users\Fox Mulder\SyncClient C:\Users\Fox Mulder\SyncServer This is a command that will be entered via a Console Application. It will be read by Console.ReadLine. How can I parse the command so that I can get the two seperate directory path's? I am unable to split on space, because that will result in a split at "Fox Mulder". How can I parse this easily? A: The command should be space delimited, with each path wrapped in quotes to properly include their embedded strings: SYNC "C:\Users\Fox Mulder\SyncClient" "C:\Users\Fox Mulder\SyncServer" If you can't require quotes then things become much more ugly--consider paths such as c:\documents and settings\mom and dad\documents\family vacations\2009\the bahama ramas\ String splitting on " " will be a headache. The brute force method would be to test the first portion of the path (c:\documents) on it's own, if it's invalid then append the next portion (c:\documents and), etc... of course it's ugly, non-performant, and full of potential issues (what if both "c:\documents" and "c:\documents and settings" are valid? Your code will end up very skittish and paranoid. A: Using " would solve it SYNC "C:\Users\Fox Mulder\SyncClient" "C:\Users\Fox Mulder\SyncServer" this will be interperted as two seperate strings in the argv A: How about this? string testString = @"SYNC C:\Users\Fox Mulder\SyncClient C:\Users\Fox Mulder\SyncServer"; int firstIndex = testString.IndexOf(Path.VolumeSeparatorChar); int secondIndex = testString.LastIndexOf(Path.VolumeSeparatorChar); string path1, path2; if (firstIndex != secondIndex && firstIndex != -1) { path1 = testString.Substring(firstIndex - 1, secondIndex - firstIndex); path2 = testString.Substring(secondIndex - 1); Console.WriteLine("Path 1 = " + path1); Console.WriteLine("Path 2 = " + path2); }
{ "pile_set_name": "StackExchange" }
Q: Edit does not save function in newly updated R 3.2.2 The more formal operator saves the changes to the function: function_I_want_to_edit <- edit() This opens the editing window and I can make changes which are there when I re-open it. However, if I simply try: edit(function_I_want_to_edit) It opens the editing window but it does not appear to have saved my changes when I re-open it. This is in RStudio, newly updated to Version 3.2.2. I can't tell if it always worked like this or not, because I believe I was able to change one thing, and then it stopped working. Has anyone noticed a similar problem with edit or fix? A: Yes, this appears to be the intended behavior. If you look at the help for edit: It is important to realize that edit does not change the object called name. Instead, a copy of name is made and it is that copy which is changed. Should you want the changes to apply to the object name you must assign the result of edit to name. (Try fix if you want to make permanent changes to an object.) fix does save the changes I make to a function.
{ "pile_set_name": "StackExchange" }
Q: How can I append string to y-axis data with tick and d3.format? I'm making a pretty simple Stacked Bar Chart using C3.js. https://c3js.org/samples/chart_bar_stacked.html . I want to be able to append text to the values, specifically +"Mb" so that my end users know that those numbers indicate Megabits, and not anything else. I've added a useful y-axis label, but for my question, I'm wondering how to utilize d3.js to perform the formatting of the values. I used d3.format which suggests I am able to append string, but haven't figured how to pull it off. var chart = c3.generate({ data: { columns: [ ['data1', 2000, 2000, 4000], ['data2', 1300, 1000, 500], ['data3', 2000, 2000, 2500] ], type: 'bar', groups: [ ['data1', 'data2'] ] }, axis: { y: { label: { text: 'Bandwidth Usage (Mb)', position: 'outer-middle' }, tick: { format: d3.format('') + "mb" } } } }); This isn't working as expected, I'm getting "TypeError: this.tickFormat is not a function". Wondering if there are any c3 gurus out there than can help me with this problem? Thanks!! A: You could write a tick function as follows: tick: { format: function (d) { if ((d) > 0) { d = d + "Mb"; } return d; } }, I have used >0 for d, so the "Mb" just gets appended to d if d is not 0, but you could also extend the code to automatically transform the input: tick: { format: function (d) { if (((d / 1000) >= 1) & ((d / 1000) < 1000)) { d = Math.round((d / 1000 )*100) / 100 + "Kb"; } else if ((d / 1000000) >= 1) { d = Math.round((d / 1000000 )*100) / 100 + "Mb"; } return d; } }, By doing this, you could use untransformed data as input, and it will transform it to either "Kb" or "Mb" unit. 100 sets 2 digits after decimal point.
{ "pile_set_name": "StackExchange" }
Q: How are maven surefire nested stacks controlled When I configure maven surefire plugin to print the full stack trace using <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.15</version> <configuration> <trimStackTrace>false</trimStackTrace> <failOnMissingWebXml>false</failOnMissingWebXml> <useFile>false</useFile> <redirectTestOutputToFile>false</redirectTestOutputToFile> </configuration> </plugin> It doesn't seem to influence the nested stacks as they're still cut, example: org.apache.openejb.OpenEjbContainer$AssembleApplicationException: org.apache.openejb.OpenEJBException: Creating application failed: /mnt/DATA/richter/NetBeansProjects/issue-openwebbeans: couldn't start owb context at org.apache.openejb.OpenEjbContainer$Provider.createEJBContainer(OpenEjbContainer.java:427) at javax.ejb.embeddable.EJBContainer.createEJBContainer(EJBContainer.java:56) at de.pgalise.issue.openwebbeans.TestUtils.getContainer(TestUtils.java:50) at de.pgalise.issue.openwebbeans.CityCtrlTest.setUp(CityCtrlTest.java:27) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42) at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) Caused by: org.apache.openejb.OpenEJBException: Creating application failed: /mnt/DATA/richter/NetBeansProjects/issue-openwebbeans: couldn't start owb context at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:901) at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:616) at org.apache.openejb.OpenEjbContainer$Provider.createEJBContainer(OpenEjbContainer.java:423) ... 20 more Caused by: org.apache.openejb.OpenEJBRuntimeException: couldn't start owb context at org.apache.openejb.cdi.ThreadSingletonServiceImpl.initialize(ThreadSingletonServiceImpl.java:161) at org.apache.openejb.cdi.CdiBuilder.build(CdiBuilder.java:40) at org.apache.openejb.assembler.classic.Assembler.createApplication(Assembler.java:803) ... 22 more Caused by: org.apache.openejb.OpenEJBRuntimeException: javax.enterprise.event.ObserverException: Caught Exception while handling event object with type : org.apache.webbeans.portable.events.discovery.AfterBeanDiscoveryImpl at org.apache.openejb.cdi.OpenEJBLifecycle.startApplication(OpenEJBLifecycle.java:187) at org.apache.openejb.cdi.ThreadSingletonServiceImpl.initialize(ThreadSingletonServiceImpl.java:159) ... 24 more Caused by: javax.enterprise.event.ObserverException: Caught Exception while handling event object with type : org.apache.webbeans.portable.events.discovery.AfterBeanDiscoveryImpl at org.apache.webbeans.event.NotificationManager.fireEvent(NotificationManager.java:501) at org.apache.webbeans.container.BeanManagerImpl.fireEvent(BeanManagerImpl.java:446) at org.apache.webbeans.container.BeanManagerImpl.fireLifecycleEvent(BeanManagerImpl.java:436) at org.apache.webbeans.config.BeansDeployer.fireAfterBeanDiscoveryEvent(BeansDeployer.java:362) at org.apache.webbeans.config.BeansDeployer.deploy(BeansDeployer.java:199) at org.apache.openejb.cdi.OpenEJBLifecycle.startApplication(OpenEJBLifecycle.java:184) ... 25 more Caused by: org.apache.webbeans.exception.WebBeansException: java.lang.reflect.InvocationTargetException at org.apache.webbeans.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:272) at org.apache.webbeans.event.NotificationManager.fireEvent(NotificationManager.java:482) ... 30 more Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.webbeans.event.ObserverMethodImpl.notify(ObserverMethodImpl.java:266) ... 31 more Caused by: java.lang.NoSuchMethodError: javax.enterprise.inject.spi.BeanManager.getInjectionTargetFactory(Ljavax/enterprise/inject/spi/AnnotatedType;)Ljavax/enterprise/inject/spi/InjectionTargetFactory; at com.sun.faces.util.cdi11.CDIUtilImpl.createHelperBean(CDIUtilImpl.java:76) at com.sun.faces.application.view.ViewScopeExtension.afterBeanDiscovery(ViewScopeExtension.java:130) ... 36 more I assume that the documentation for trimStackTrace "Whether to trim the stack trace in the reports to just the lines within the test, or show the full trace." isn't really sufficient as it doesn't make any distinction between stack and nested stacks. Does one have any possibility to control both? A: You already see the full stack trace here I guess ;) About the "... 24 more" patterns in the sample you provide, I don't know and don't think you can get them. About the role, and what you think of as uneffective, of the surefire configuration "trimStackTrace" property, I struggled a while, not understanding why I was seeing the exception root cause when running a test from IntelliJ, but not when ran from a maven command line. Here you'll see the property is truly effective for enabling the display of exceptions root causes. Without the "trimStackTrace" (default: false) surefire configuration property, I had this output: 2014-03-27 19:29:30,933 [main] DEBUG o.h.c.annotations.SimpleValueBinder - Starting fillSimpleValue for lastFetchTime 2014-03-27 19:29:30,933 [main] DEBUG org.hibernate.cfg.Configuration - Processing fk mappings (*ToOne and JoinedSubclass) Tests run: 2, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 5.032 sec (StorageHelper.java:35) at com.company.foobar.helper.StorageHelper.getInstance(StorageHelper.java:26) at com.company.foobar.StorageHelperTest.foo(StorageHelperTest.java:40) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:254) at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:149) at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124) at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200) at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153) at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103) Results : Tests in error: StorageHelperTest.foo:40 » Persistence [PersistenceUnit: default-persistence-u... Setting the "trimStackTrace" property, on "true", I now get the exceptions root causes: 2014-03-27 19:29:30,933 [main] DEBUG o.h.c.annotations.SimpleValueBinder - Starting fillSimpleValue for lastFetchTime 2014-03-27 19:29:30,933 [main] DEBUG org.hibernate.cfg.Configuration - Processing fk mappings (*ToOne and JoinedSubclass) Tests run: 2, Failures: 0, Errors: 2, Skipped: 0, Time elapsed: 5.032 sec (StorageHelper.java:35) at com.company.foobar.helper.StorageHelper.getInstance(StorageHelper.java:26) at com.company.foobar.StorageHelperTest.foo(StorageHelperTest.java:40) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27) at org.junit.runners.ParentRunner.run(ParentRunner.java:309) at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:254) at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:149) at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:124) at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:200) at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:153) at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103) Caused by: org.hibernate.AnnotationException: A Foreign key refering com.company.foobar.bean.FooBarItemCriterias from com.company.foobar.bean.FooBarOpportunity has the wrong number of column. should be 22 at org.hibernate.cfg.annotations.TableBinder.bindFk(TableBinder.java:450) at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:117) at org.hibernate.cfg.Configuration.processEndOfQueue(Configuration.java:1596) at org.hibernate.cfg.Configuration.processFkSecondPassInOrder(Configuration.java:1519) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1420) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850) ... 36 more Results : Tests in error: StorageHelperTest.foo:40 » Persistence [PersistenceUnit: default-persistence-u... By the way, this option is documented as "Whether to trim the stack trace in the reports to just the lines within the test, or show the full trace" which is ambiguous. At first, I thought "reports" were only the XML and text files you can find in "${basedir}/target/surefire-reports/", but it mainly designates the surefire console output, and also those files by extension.
{ "pile_set_name": "StackExchange" }
Q: laravel 5.2 if else to query database stuck on a form that allows the user to enter a value into a choice of two fields. I can query the database using one field but want to add more range to database queries. With the following code below when i try to access the page to query it just shows me a white screen. public function index() { $data = $request->all(); if(!empty($data['pstoreNum'])) { $pstoreNum = $data['pstoreNum']; $result = DB::table('perfumes')->where('StoreNumber','=',$pstoreNum) ->get(); return view('perfumes',compact('result')); } else if(!empty($data['pweekNum'])) { $pweekNum = $data['pweekNum']; $result = DB::table('perfumes')->where('WeekNumber','=',$pweekNum) ->get(); return view('perfumes',compact('result')); } } My routes file simple calls the index function. Any help would be appreciated. A: You can add query functions within your query like so public function index(Request $request) { $data = $request->all(); $result = \DB::table('perfumes')->where(function($query) use ($data) { if(!empty($data['pstoreNum'])) { $query->where('StoreNumber', '=', $data['pstoreNum']); } if(!empty($data['pweekNum'])) { $query->where('WeekNumber', '=', $data['pweekNum']); } })->get(); return view('perfumes',compact('result')); } You can then use the one query and add multiple wheres on various conditions. https://laravel.com/docs/5.2/queries#advanced-where-clauses
{ "pile_set_name": "StackExchange" }
Q: Removing ArrayList object issue I got an issue with deleting an object from ArrayList when working on the assignment If I use the "normal" for loop, it works as following public void returnBook(String isbn){ for (int i = 0; i < booksBorrowed.size(); i++){ if (booksBorrowed.get(i).getISBN() == isbn){ booksBorrowed.get(i).returnBook(); booksBorrowed.remove(i); } } } However, when I'm trying to simplify the code with enhanced for-loop, that doesn't work and showing java.util.ConcurrentModificationException error: public void returnBook(String isbn){ for (Book book: booksBorrowed){ if (book.getISBN() == isbn){ book.returnBook(); booksBorrowed.remove(book); } } } Hope you guys could lighten me up.. A: Your alternatives to avoid a ConcurrentModificationException are: List<Book> books = new ArrayList<Book>(); books.add(new Book(new ISBN("0-201-63361-2"))); books.add(new Book(new ISBN("0-201-63361-3"))); books.add(new Book(new ISBN("0-201-63361-4"))); Collect all the records that you want to delete on enhanced for loop, and after you finish iterating, you remove all found records. ISBN isbn = new ISBN("0-201-63361-2"); List<Book> found = new ArrayList<Book>(); for(Book book : books){ if(book.getIsbn().equals(isbn)){ found.add(book); } } books.removeAll(found); Or you may use a ListIterator which has support for a remove method during the iteration itself. ListIterator<Book> iter = books.listIterator(); while(iter.hasNext()){ if(iter.next().getIsbn().equals(isbn)){ iter.remove(); } } Or you may use a third-party library like LambdaJ and it makes all the work for you behind the scenes> List<Book> filtered = select(books, having(on(Book.class).getIsbn(), is(new ISBN("0-201-63361-2")))); A: You really shouldn't be doing either as they will cause problems in the end. Instead use the ArrayList's iterator to help you iterate through the list and then remove only with the iterator. This will help prevent pernicious concurrent modification errors.
{ "pile_set_name": "StackExchange" }
Q: implementation recursive function I am still very new to recursive and I want to return 3 from this array int arr[size] = {21, -6, 3, 5, 5, -3, 6, -21} for having same absolute value with recursive implementation. However, I get the value 0. I cant pinpoint out what is making this program not bringing desired value. #include <iostream> using namespace std; int additive_inverse_opposite_pairs_count(int* arr, int n) { int size = n; if (n == 0) { if (arr[n] == -1 * arr[size - 1 - n]) return 1; else return 0; } else { int count = additive_inverse_opposite_pairs_count(arr, n - 1) + count; if (arr[n] == -1 * arr[size - 1 - n]) { count += 1; } else count = 0; return count; } } int main() { int size = 8; int arr[size] = {21, -6, 3, 5, 5, -3, 6, -21}; int value = 0; value = additive_inverse_opposite_pairs_count(arr, size); cout << "value: " << value << endl; return 0; } A: Part of the problem is that you are accessing arr[n] where n is the size of the array. The valid indicies of an array are 0..n-1, so you need to change arr[n] to arr[n-1] in the else part of your if statement. One idea is to simply start at an index i, scan the rest of the array from that point on for the additive inverse, and if it is found, return that number, otherwise recurse further into the array. I wrote a helper function to do the work. int helper(int* arr, int i) { if (i == 0) { return 0; } for (int j = i - 1; j >= 0; j--) { if (arr[i] == -arr[j]) { return abs(arr[i]); } } return helper(arr, i - 1); } int additive_inverse_opposite_pairs_count(int* arr, int n) { return helper(arr, n - 1); }
{ "pile_set_name": "StackExchange" }
Q: Kill it with light mace: [windows-home-server] - or not? Before I blow through a day's worth of flags on this, perhaps there's a better way. I believe that virtually no question with the windows-home-server tag belongs here. Here's a discussion on the topic from two years ago: "How to deal with Windows Home Server questions on Serverfault?" Most people seem to want it dead yesterday. However, there is some dissent worth considering. The dissent highlites possible weaknesses in our FAQ and stated purpose. Let's use this as a time to refine our FAQ revision. Objections Oorang says: I personally know consultants currently selling WHS to small businesses. I don't see why you should make a differentiation just because MS marketed it with the name "home" in the title. I believe there might be outlying cases where someone that is defined as a "system administrator and/or desktop support professional" (slightly modified from our FAQ) can and should suggest WHS to a client. Those cases would be for "micro-businesses" of just a handful of people. Scott says: I think it's a big mistake to try and draw a line between corporate and residential IT. In my former career as an IT guy, I dealt with just as many residential customers as corporate customers. This would cause the word workplace to be in dispute. If a person's workplace is to consult within in the walls of a private home, then technically that's a workplace. I think the spirit of that word means that you are in floorspace that is leased or owned 100% for business purposes in an area zoned for commerce and not residence. Just because your profession calls you to someone's home, doesn't mean that the work falls within the scope of ServerFault. People who manage or maintain computers in a professional capacity would then include many of the questions that you see on SuperUser, like for instance this one that I asked in the capacity of someone who maintains computers in a professional capacity. Then again, Scott also says: Trying to separate corporate and residential IT is like trying to separate HTML and CSS; they're so closely related. I think SuperUser is fine for questions about how to do blah in Microsoft Word, but anything to do with adjusting system settings or system building is, in my opinion, most definitely sysadmin-related. If that's how we define "SysAdmin-related" then we've got some serious FAQ rewriting to do (and, of course, we are doing that. Yay!) Kev says: Isn't Windows Home Server a "server" and thus equally deserving of support by ServerFault? But the FAQ also says that you can't ask about home network related things. What happens when an unstoppable force collides with an immovable object? In the immortal words of Zorak: "Eh... chicken salad... maybe?" Since we have a history of closing questions that relate to a person putting a server on their home network, I believe that the "home" trumps the "server." Thus, no, Windows Home Server is not equally deserving of support by ServerFault. Conclusion Let's ban all WHS related questions regardless of if a consultant has implemented it on a small business network. By it's design, it is for home networks, regardless of how someone applies it. The converse reasoning is "Hey, this Juniper EX4500 is business class, so I should be able to ask about using it in my home network." Of course, we wouldn't allow that (except if the question made no reference to being in the home). Let's kill most if not all questions as off-topic. Let's migrate the rest and blackhole the tag. Let's charge for the guns! A: I agree with everything Mr David just said. If you're trying to do a port forward on a Belkin Home Router, I don't care if that router is sitting in a 10,000m2 datacenter of a Fortune 50 company - it's off topic. Additionally, if you're working from your home and you can't figure out why your TV won't authenticate against your AD so you can stream porn from your SAN in full 50" Full HD glory, that's off topic (because it's a freaking TV). So, if you've gone and deployed WHS, I don't give two hoots why, it's off topic. Regardless, it is actually quite a good product
{ "pile_set_name": "StackExchange" }
Q: viewForAnnotation detail disclosure changing current location as well as pins In my viewForAnnotation method I am adding a detail disclosure button to the right of the pin, however it changes the showsUserLocation to be a red pin, with a disclosure button to the right of the "Current Location" text. How can I stop the current location symbol from being a pin? Without the method it is fine. - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation { static NSString *identifier = @"MyLocation"; MKPinAnnotationView *annotationView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:identifier]; if (annotationView == nil) { annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier]; } else { annotationView.annotation = annotation; } annotationView.enabled = YES; annotationView.canShowCallout = YES; // Create a UIButton object to add on the UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; [rightButton setTitle:annotation.title forState:UIControlStateHighlighted]; [annotationView setRightCalloutAccessoryView:rightButton]; return annotationView; } A: add in the beginning of the method if (annotation == mapView.userLocation) { return nil; }
{ "pile_set_name": "StackExchange" }
Q: C# list of files name comparison I have a simple but yet very hard task for my coding skills. Basically I have a task to parse all file names in specific folder (this executed ok) but then I have to compare those file names and choose the one with the latest (biggest) number in a specific part of file name. An example: 0074-105-NVK.1.p7.ver.1.pdf 0074-105-NVK.1.p7.ver.2.pdf 0074-105-NVK.1.p7.ver.3.pdf The part that interests me is the one where "ver.1" from this the program should choose the highest one and remove other files. And I really don't know how to implement this filename comparison. A: I suggest extracting version info with a help of regular expressions and ordering by this version: string[] files = new string[] { "0074 - 105 - NVK.1.p7.ver.1.pdf", "0074 - 105 - NVK.1.p7.ver.2.pdf", "0074 - 105 - NVK.1.p7.ver.3.pdf", }; string pattern = @"ver\.(?<version>[0-9]+(\.[0-9]+)*)[^0-9]+$"; var result = files .Select(file => new { name = file, ver = new Version(Regex.Match(file, pattern).Groups["version"].Value + ".0") }) .OrderByDescending(item => item.ver) .Select(item => item.name) .FirstOrDefault();
{ "pile_set_name": "StackExchange" }
Q: What historical evidence do we have for the existence of Mohammed? I have been listening to a podcast, called "The History of Byzantium" and in one of the episodes there was a discussion about the lack of reference to Mohammad or Qur'an in the century after his death, and Muslims were referred as Ishmaelites, Saracens, etc. but never any reference to the prophet. It sounded like the Caliphate from Damascus somehow created an image of Mohammad. After that period, an Islam that is more similar to our days' version emerges, with references to its prophet, and the holy text. I haven't been able to find any sources on this discussion, what I have been able to find is a link to this book, which I haven't read yet: Robert Spencer: "Did Muhammad exist? : an inquiry into Islam's obscure origins", Isi Books, 2014 Can someone give a modern historic outlook of beginnings of Islam, and the existence of its prophet? Also please correct if there are any mistakes in this text. A: Your question touches on the problem how one would prove any historical fact when there is no living (and credible) witness or modern forensic analysis. Look at the sources, consider who wrote them, consider who would benefit from forging them, consider if multiple different sources give a coherent explanation. There seem to be fragmented non-Islamic sources from the 7th century AD. Naming differences are easily explained by exonyms and endonyms. The fact that the western chroniclers got the name wrong early on is only to be expected. (Consider that the French call the Germans Alemanni while the Slavic languages simply call them Nemec, mute ...) The preponderance of evidence seems to show that Mohammed did exist. I'd call it about as strong as the evidence for Jesus. What Mohammed did, what he wrote and what he taught is another matter, where faith enters the question. A: Well it seems likely that he existed if that's what you mean to ask. When you say "give a modern historic outlook and the existence of the prophet" what do you mean? Wikipedia has a large number of sources https://en.wikipedia.org/wiki/Muhammad I certainly don't think that somebody simply made him up if that's what you mean to imply. If you wish to read about the early days of Islam (i.e Mohammad's life) it would seem you would be well served by following the sources in the Wikipedia article. It seems that there were lots of reference amongst the Byzantines, Jews and the Europeans to Mohammad and Islam in general. I am no expert on the subject, but given the impact he had on the Middle East (prosecuting war in the Middle East, siring children etc.) I would say his existence was far more established than that that of, say, Jesus of Nazareth.
{ "pile_set_name": "StackExchange" }
Q: OpenCV frame capture from AVI I am working on a project with openCV 2.2. I need to do processing on each frame of an AVI file but when I run my code it only grabs the first frame of the file. The CV_CAP_PROP_POS_FRAMES does not seem to be working. Any ideas why not? CvCapture* capture = cvCaptureFromAVI("test1.avi"); IplImage *img = 0; if (!cvGrabFrame(capture)) { printf("Error: Couldn't open the image file.\n"); return 1; } int numFrames = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT); int posFrame = 1; for(int i =0; i <= numFrames; i++){ cvSetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES, i); posFrame = cvGetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES); img = cvGrabFrame(capture); cvNamedWindow("Image:", CV_WINDOW_AUTOSIZE); cvShowImage("Image:", img); printf("%i\n",posFrame); cvWaitKey(0); cvDestroyWindow("Image:"); } A: Why don't you try this way using OpenCV 2.3? I think it is more direct and efficient, and more clear to your eyes: VideoCapture _videoSource; if(!_videoSource.open("test1.avi")) { exit(1); // Exit if fail } _videoSource.set(CV_CAP_PROP_CONVERT_RGB, 1); Mat frame; namedWindow("Image"); int posFrame; while(1) { _videoSource >> frame; posFrame=_videoSource.get(CV_CAP_PROP_POS_FRAMES); imshow("output", frame); return 0; } Something like this should work.
{ "pile_set_name": "StackExchange" }
Q: Checkstyle plugin doesn't care what's in external configuration file I'm trying to use the Maven Checkstyle plugin with an external configuration file. The plugin works with or without specifying an external configuration file, and the checksytle warnings are different depending on if configLocation is set. So it seems like it should be working fine, but it's not. No matter what I enter in the external configuration file, the same warnings appear to be generated. In fact, I can clear out the file completely and nothing appears to change. In the pom: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <id>validate</id> <phase>validate</phase> <configuration> <configLocation>google_checks.xml</configLocation> <encoding>UTF-8</encoding> <consoleOutput>true</consoleOutput> <failsOnError>true</failsOnError> </configuration> <goals> <goal>check</goal> </goals> </execution> </executions> </plugin> Trying to use this file: https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/google_checks.xml In the pom, if I change the name to say "does_not_exist.xml" it will report it cannot find the file with the following message: Unable to find configuration file at location: does_not_exist.xml Since it does not print this message with the correct file name, it tells me it can find the file with the correct name (google_checks.xml). In the file: <module name="LineLength"> <property name="max" value="100"/> <property name="ignorePattern" value="^package.*|^import.*|a href|href|http://|https://|ftp://"/> </module> If I change the value to say 10, I still get the warning: Line is longer than 100 characters... I'm running: mvn clean verify I've tried putting the google_checks.xml file in the root of the project and in the src/main/resources directory. Same results either location. I'd ultimately like to change the rules for line length and indentation, but since it doesn't care what I enter in the file, I'm not sure how to do this. Any ideas on how to make it honor what's in the external file? A: Quite a dig but: The configLocation you've set the XML in your question gets injected into CheckstyleViolationCheckMojo#configLocation of the maven-checkstyle-plugin, since this variable is private it did not show up on their Javadoc but it is documented in source code. This description states that: This parameter is resolved as resource, URL, then file. If successfully resolved, the contents of the configuration is copied into the ${project.build.directory}/checkstyle-configuration.xml file before being passed to Checkstyle as a configuration. There are 2 predefined rulesets. sun_checks.xml: Sun Checks. google_checks.xml: Google Checks. What I think is happening is that it's not resolving the parameter the normal way, since google_checks.xml is a predefined ruleset and therefore the default google_checks.xml will be loaded. If you want to use your own custom configurator you should name it something other than google_checks.xml and sun_checks.xml
{ "pile_set_name": "StackExchange" }
Q: existence of a function such that it is equivalent to cosine. Prove there exist continuous functions $Cos : \mathbb{R} \to \mathbb{R}$ and $Sin : \mathbb{R} \to \mathbb{R}$ such that $Cos(q) = \cos(q)$ and $Sin(q) = \sin(q)$ for all $q \in \mathbb{Q}$. I have attempted this by noting that cosine and sine are continuous for all real numbers and therfore for the set of $q\in\mathbb{Q}$ we can hold that $Cos(q)=\cos(q)$ and that $Sin(q)=sin(q)$. I am not sure if this is sufficient however. Is correct or is there another way of showing this? A: Define $Cos(x):= \cos (x)$ and $Sin(x):= \sin (x)$ for $x \in \mathbb R$ and you are done.
{ "pile_set_name": "StackExchange" }
Q: How can I insert code from subclass constructor in superclass constructor? So I have this superclass which makes a JPanel with some components. Now I need the subclass to make some radiobuttons and have them displayed before the buttonMin. Now Is my question: how do I call the code from my subclass right there in the superclass where I need it (see code to see where code should be called)? My superclass public class RecordLine extends JPanel{ public RecordLine(Product product){ JTextField fieldName = new JTextField(); fieldName.setText(product.getName()); this.add(fieldName); Component horizontalStrut = Box.createHorizontalStrut(20); this.add(horizontalStrut); //Subclass code should be executed here Component horizontalStrut_1 = Box.createHorizontalStrut(20); this.add(horizontalStrut_1); JButton buttonMin = new JButton("-"); this.add(buttonMin); } } My subclass public class RecordLineDrinks extends RecordLine { public RecordLineDrinks(Product product) { super(product); JRadioButton rdbtnFles = new JRadioButton("Fles"); this.add(rdbtnFles); } } A: You will probably need to change your class structure, providing a method which can be used to create the UI (ie createView), from which it can access the other components via getters This way, you can change the way that createView works. The problem with this is, you will become responsible for re-creating the UI in your subclass completely, hence the reason you will need getter methods for the other UI components. Another choice is, if you know where you want to add new components, you could provide default implementations of methods which do nothing, but allow sub classes to modify public class RecordLine extends JPanel{ public RecordLine(Product product){ JTextField fieldName = new JTextField(); fieldName.setText(product.getName()); this.add(fieldName); Component horizontalStrut = Box.createHorizontalStrut(20); this.add(horizontalStrut); //Subclass code should be executed here Component horizontalStrut_1 = Box.createHorizontalStrut(20); this.add(horizontalStrut_1); addBeforeMinButton(); JButton buttonMin = new JButton("-"); this.add(buttonMin); } protected void addBeforeMinButton() { } } But this generally means you know before hand how you might like to modify the UI
{ "pile_set_name": "StackExchange" }
Q: How do the predefined interfaces in java work? This question is not about how to use interfaces, it is about how some of the predefined interfaces in java work. For example consider the ActionListener interface from java.awt.event package. When we implement the interface, then we must define the actionPerformed() method which will be called when an action occurs. What I want to know is how does this work. we aren't writing any code that checks for action occuring and which then calls actionPerformed. Neither is the code in the interface. It happens automatically. Who is actually doing this work? A: Interfaces such as ActionListener are an implementation of a callback. This means that there are other classes, such as JButton, which check for user action occurring, and know when it happens. Their task is to let your code know when it happens. They do it by means of calling back actionPerformed method of an ActionListener interface that you pass to them. This approach provides a very clean separation between the UI code, which knows when an action occurs, but does not know what exactly you want to do, and your code, which knows exactly what to do, but does not know when the action occurs.
{ "pile_set_name": "StackExchange" }
Q: now it is lost = that it is? How I escaped my certain fate by Stewart Lee I’ve, I’ve done this before when there’s been a kind of split in the room. Usually it creates an atmosphere of bonhomie. But tonight, it’s made it worse, hasn’t it? It’s made it worse. There’s a tension in the room that’s now ‘the gig is lost’, right? It’s lost. Full transcript Stewart Lee tries to "split" his audience during the stand-up show to create a tension. He writes that the tension created this time wasn't created as expected and the show now is lost. The part that confuses me is that's now 'the gig is lost'. Does "that's" mean "in other words" or "that it is"? There is no comma before it, so that why I'm not sure what "that's" connects to in this sentence. A: That's connects to the word "tension": tension that is. Because the passage is transcribed speech, it is more disjointed than written language, with incomplete sentences and imperfect sentence structure. The final sentence breaks abruptly from description into commentary via a pseudo-quotation. The speaker starts out observing that there was some tension in the room - but then breaks into an interjection: "the gig is lost!" He is inferring that someone (himself, not him, doesn't matter - someone) is crying "the gig is lost" due to the tension. This is a spoken colloquial structure that is a little bit similar to using phrases with "go" or "like" to indicate speech. For example: So I go, like: "how are you?" And she goes, "I am fine." The final sentence, then, broken down, means: There was a tension in the room that resulted in: (mimics someone else's voice) "the gig is lost!" Right? ("Right", as used in the example, is a way of saying: "Do you understand?" or "Do you agree?" - a common way of keeping one's audience engaged.)
{ "pile_set_name": "StackExchange" }
Q: wordpress social icon div not showing please help, i'm a newbie to wordpress. i am developing a website using wordpress CMS and fitness-lite theme (https://id.wordpress.org/themes/fitness-lite/). i edited the style.css, header.php, footer.php, and customize.php. it was just html and css editing. and then the problem comes. in the customization in admin mode, the social icon is shown just like the image below but in the public view mode, the social icon isn't shown just like this if checked by the inspect feature in Chrome browser, the respective div is there, but it isn't being displayed i haven't add any plugin, so it shouldn't be caused by one. do wordpress use different html or php file to show the web in admin mode and the public view mode? A: use css .social-icons{ display: block !important; }
{ "pile_set_name": "StackExchange" }
Q: Check for Valid User via Button Ok, so I have a form that has multiple views, some read only and some editable. Each form has buttons to open the other forms in either edit mode or read only mode based on a field being set to either 1 or 0 and the current status of the form (so if the status is 'Awaiting Purchasing' and the check field is 1, then clicking the purchasing button opens the purchasing view in edit mode. I have a button (Edit) to press that sets the check field to 1 on click and submitting the form sets the field back to 0. Now here comes the tricky part! I have a list that contains Department (text) and Editors (multi-select people field). I need, within the Edit button, to check the status of the form, then check if the current user exists in the Editors field from the other list based on that status. If they exists then the Edit button will set the check field to 1, otherwise it won't. Can anyone tell me a) if that is possible and b) if so, how to accomplish it? A: this is a simplified version i made for you but havent tested it! so might need some tweaking ;) You dont need to change the second method! for the first method, replace yourSiteGoesHere with your site name or leave blank. change ListName to the name of your list. you would call the method like so: //returns bool if the current user exists in department "marketing" (true=1 , false=0) bool isingroup = getAccessFromGroup("Marketing"); that would call the methods below! /// <summary> /// returns true if user is in field within list /// </summary> /// <returns></returns> public bool getAccessFromGroup(string department) { //open site from current site context using (SPSite site = new SPSite(SPContext.Current.Site.Url)) { //open specific site, leave blank if toplevel using (SPWeb web = site.OpenWeb("yourSiteGoesHere")) { //get splist collection but only return one row based on query SPListItemCollection currentUser = getListDetails("ListName", web, SPContext.Current.Web.CurrentUser.LoginName); //if null then user doesnt exist on any items if (currentUser != null) { //check if the user is in the department, loop if user exist in more than one place foreach (SPListItem item in currentUser) { //check to make sure the field department matches the one you want else loop through to end and return false (user doesnt exist) if (item["Department"] == department) { //return true as use exists in department return true; } } } } } return false; } this is called from the method above! no need to change anything unless i have the field name 'Editors' wrong? private SPListItemCollection getListDetails(string listName, SPWeb web, string passVal) { SPList List = web.Lists[listName]; SPQuery listABQuery = new SPQuery(); listABQuery.Query = "<Where><Eq><FieldRef Name='Editors'/>" + "<Value Type='Text'>" + passVal + "</Value></Eq></Where>"; SPListItemCollection item = List.GetItems(listABQuery); return item; }
{ "pile_set_name": "StackExchange" }
Q: jQuery Re initialize MagnificPopup after ajax loading I am running into a problem with this function and my Ajax pagination. On the first page of results, this popup works perfectly. But when I use the Ajax pagination, and the next set of results loads, this function no longer works. I guess it needs to be initialized with each ajax refresh? How do I alter the below code accordingly? jQuery(window).load(function(){ jQuery('.open-popup-link').magnificPopup({ type:'iframe', alignTop: true, overflowY: 'scroll', midClick: true }); }); Thank you!! :) Thank you MarkPlewis! I am using Search & Filter Pro. They provide the following snippet to use to reinitialize your jquery with ajax... How can I implement the first snippet of code I posted, with the following? `//detects the start of an ajax request being made https://gist.github.com/rmorse/b157004c68870dbd9fb9 ` $(document).on("sf:ajaxstart", ".searchandfilter", function(){ console.log("ajax start"); }); //detects when the ajax request has finished and the content has been updated // - add scripts that apply to your results here $(document).on("sf:ajaxfinish", ".searchandfilter", function(){ console.log("ajax complete"); //so load your lightbox or JS scripts here again }); //an event fired when S&F is initialised and S&F scripts have been loaded $(document).on("sf:init", ".searchandfilter", function(){ console.log("S&F JS initialised"); }); ` A: Yes, you're correct. You will need to re-execute that code every time new items are added to the DOM. I don't know which jQuery pagination plugin you're using, but here's a quick demo using "Infinite Ajax Scroll". You should be able to adapt this to whatever plugin you're using. The key is to call activatePopup(); inside the callback function that gets executed after new items have been added to the DOM: jQuery(window).load(function(){ activatePopup(); // Initialize the pagination plugin var ias = jQuery.ias({ container: '#posts', item: '.post', pagination: '#pagination', next: '.next' }); // Pagination plugin callback function ias.on('rendered', function(items) { activatePopup(); }); function activatePopup() { jQuery('.open-popup-link').magnificPopup({ type:'iframe', alignTop: true, overflowY: 'scroll', midClick: true }); } }); UPDATE Now that I know which plugin you're using, here's some updated code: jQuery(window).load(function(){ activatePopup(); // Plugin callback function jQuery(document).on("sf:ajaxfinish", ".searchandfilter", function(){ activatePopup(); }); function activatePopup() { jQuery('.open-popup-link').magnificPopup({ type:'iframe', alignTop: true, overflowY: 'scroll', midClick: true }); } });
{ "pile_set_name": "StackExchange" }
Q: Someone who constantly learns? I'm just trying to find a word that describes someone who's always in the process of learning. I'm talking more about a way of living than about someone like an apprentice etc. though. A: "Lifelong learner" is the term widely used to describe a person who actively engages in learning new things as a lifestyle choice. There is the single word "philomath" - lover of learning - but it is rarely seen and would not be understandable to 99+% of even native English users. Note that "philomath" was last seen in common usage as an honorific for almanac writers. Poor Richard being the most famous and possibly the last.
{ "pile_set_name": "StackExchange" }
Q: Code not working after little change I'm beginner in programming, I changed my code a little bit so that I can execute some def from the command line. After that change I got an error, but first my code: require 'faraday' @conn = Faraday.new 'https://zombost.de:8673/rest', :ssl => {:verify => false} @uid = '8978' def certificate res = conn.get do |request| request.url "acc/#{@uid}/cere" end end def suchen(input) @suche = input @res = @conn.get do |request| request.url "acc/?search=#{@suche}" end end puts @res.body Then I wrote into the console: ruby prog.rb suchen(jumbo) So, somehow i get the error: Undefined method body for Nilclass A: You're not invoking either of your methods, so @res is never assigned to. @res evaluates to nil, so you're invoking nil.body. RE: Your update: ruby prog.rb suchen(jumbo) That isn't how you invoke a method. You have to call it from within the source file. All you're doing is passing an argument to your script, which will be a simple string available in the ARGV array. RE: Your comment: It should go without saying that the solution is to actually invoke your method.
{ "pile_set_name": "StackExchange" }
Q: Using event handlers to update SQL Server I'm looking for a bit of advice if possible. I am using event handlers to update a WPF application, it works fine but I was wondering if this was the best way to go? Would it be better practice to use data binding using XAML? Thanks for your help as always. A: Personally I would use data binding to do this and the MVVM pattern. At the most basic you would bind your textbox to a property on your view model, in the setter you could call a method which executes your SQL query. Your View Model class would also need to implement INotifyPropertyChanged to allow the view model to update the UI if you wanted data to flow both ways. Although depending on what you're doing you may be better having something that triggers the SQL update rather than every time the text changes. If you have a lot of different fields to update and you use the text changed event you're going to fire off a lot more SQL updates than you need. Maybe a save button or something which detects when changes are finished and makes them all at once would be more efficient?
{ "pile_set_name": "StackExchange" }
Q: SQL creating a concatenated string of names from an array of ids I am developing reports using Streamtask with xReporter. Recently, our databases were updated to allow for multiple projects to be assigned to a single task. To achieve this, a string containing a a set of CSV index values was used to replace the old single index ie: '[1,2,3,4]' instead of 1. As a result we now have to update a slew of reports. To get around this, I replace the original selection statement: (select prj.name from project_table prj where prj.id=t.project_id) as project, with this line: (select prj.name from project_table prj where prj.id = ANY((string_to_array(btrim(task_table.projects, '[]'), ','))::integer[])) as project, which turns the string (successfully) into an array of integer values. The problem is that I must be able to take this array of indices and retrieve each project name associated with each index, and concatenate them together into a string containing a list of the project names. Because I have to implement this in an xReporter report, I believe I will need an SQL-only solution to my problem. A: Storing comma separated values in a relation database is a really horrible anti-pattern. Postgres has some really nifty functions to workaround this design-error which makes the query actually quite easy (but probably not really fast) select prj.name, tsk.id as task_id from project_table prj join ( select id, regexp_split_to_table(projects, ',')::int as pid from task_table ) tsk on tsk.pid = prj.id order by prj.id You original statement looks like you were really embedding that into a bigger statement, so I'm not sure how suitable the join is. But you could always create a normalized view on the mis-designed table using the above approach (the inner derived table). Here is a SQLFiddle: http://sqlfiddle.com/#!15/6f9bb/1
{ "pile_set_name": "StackExchange" }
Q: Dart Error: error: import of dart:mirrors with --enable-mirrors=false .yaml file bellow: dependencies: flutter: sdk: flutter cupertino_icons: ^0.1.2 fluttertoast: ^2.0.9 dio: ^1.0.6 json_serializable: ^2.0.0 dev_dependencies: build_runner: ^1.0.0 json_annotation: ^2.0.0 when I run: Launching lib/main.dart on Android SDK built for x86 in debug mode... Initializing gradle... Resolving dependencies... Gradle task 'assembleDebug'... Built build/app/outputs/apk/debug/app-debug.apk. D/OpenGLRenderer( 5350): HWUI GL Pipeline I/OpenGLRenderer( 5350): Initialized EGL, version 1.4 D/OpenGLRenderer( 5350): Swap behavior 1 D/ ( 5350): HostConnection::get() New Host Connection established 0xa12b3ec0, tid 5379 D/EGL_emulation( 5350): eglCreateContext: 0xa127cf60: maj 2 min 0 rcv 2 D/ ( 5350): SurfaceInterface::setAsyncMode: set async mode 1 D/EGL_emulation( 5350): eglMakeCurrent: 0xa127cf60: ver 2 0 (tinfo 0xa177fe80) E/flutter ( 5350): [ERROR:flutter/shell/common/shell.cc(188)] Dart Error: error: import of dart:mirrors with --enable-mirrors=false E/flutter ( 5350): [ERROR:flutter/shell/common/engine.cc(176)] Could not prepare to run the isolate. E/flutter ( 5350): [ERROR:flutter/shell/common/engine.cc(123)] Engine not prepare and launch isolate. E/flutter ( 5350): [ERROR:flutter/shell/platform/android/android_shell_holder.cc(167)] Could not launch engine in configuration. i know the problem is that 'json_serializable' but i didn't know how to resolve it. or is there any way to transform between model and json A: I did stumble across your post on my own search after solutions with your problem. I assume that you want to use json_serializable for your own sourceCode creation. If this is the case you should have json_serializable: ^2.0.0 under the dev_dependencies. Explanation json_serializable does use dartlang/source_gen internally. source_gen in turn does reference dart:mirrors, which is not supported in flutter (as told in this post). So long story in short: - through removing the dependency on json_serializable from your "build" dependencies you remove the dependency on mirrors which is stopping your flutterBuild. i know the problem is that 'json_serializable' but i didn't know how to resolve it. or is there any way to transform between model and json I did not really got that part. At least for me this is not enough information to provide help on your modelgeneration. Could try if you post a class in which you use json_serializable and the generated partial class.
{ "pile_set_name": "StackExchange" }
Q: How to find which consumer is assigned to which partition of a topic in kafka? I am building a kafka manager tool and I need to check which topic-partition is assigned to which consumer in a consumer group. Suppose there is consumer-Group group-A consuming topic topic-A with n partitions, so there can be multiple consumers in group-A hosted in different VM's. So how to find which partitioned is assigned to which consumer host? Is it possible in kafka 0.9.1? Thanks in advance. A: You can check how $KAFKA_HOME/bin/kafka-consumer-groups.sh works and integrate its implementation into your kafka manager tool, this tool will show you detailed group owner information(for example, partition assignment, lag, IP). GROUP TOPIC PARTITION CURRENT-OFFSET LOG-END-OFFSET LAG OWNER page_visits_10k 0 500 3333 2833 consumer-1_/10.139.176.190 page_visits_10k 1 0 3334 3334 consumer-1_/10.139.176.190 page_visits_10k 2 0 3333 3333 consumer-1_/10.139.176.190
{ "pile_set_name": "StackExchange" }
Q: VBA - Range Object Sets Only Once in Loop I am writing code which matches a date (from a file), puts this into a collection and then attempts to find this on a spreadsheet. Once it finds it, it puts the following two items in the collection in the two cells. When I run this I get the following error: "Object variable or With block variable not set". I have attempted to debug my code and it shows that after the first loop of the code below, the range object, "rthecell", changes to the proper value. Once the second iteration of the loop occurs the value of "rthecell" changes to "Nothing". Ex: Set rtheCell = Range("A:A").Find(What:=LineItem1) rtheCell.Offset(, 1).Value = LineItem3 rtheCell.Offset(, 2).Value = LineItem2 Set rtheCell = Nothing Again, everything works as intended on the first iteration of the loop but I receive the error once the second iteration occurs. Here is the full code: Sub InputData() 'Declare variables Dim sFilePath As String Dim sLineFromFile As String Dim saLineItems() As String Dim element As Variant Dim col As Collection Dim LineItem1 As String Dim LineItem2 As String Dim LineItem3 As String Dim rtheCell As Range Set col = New Collection 'Insert file path name here, this file will be overwritten each morning sFilePath = "P:\Billing_Count.csv" Open sFilePath For Input As #1 Do Until EOF(1) Line Input #1, sLineFromFile 'Split each line into a string array 'First replace all space with comma, then replace all double comma with single comma 'Replace all commas with space 'Then perform split with all values separated by one space sLineFromFile = Replace(sLineFromFile, Chr(32), ",") sLineFromFile = Replace(sLineFromFile, ",,", ",") sLineFromFile = Replace(sLineFromFile, ",", " ") saLineItems = Split(sLineFromFile, " ") 'Add line from saLineItem array to a collection For Each element In saLineItems If element <> " " Then col.Add element End If Next Loop Close #1 'Place each value of array into a smaller array of size 3 Dim i As Integer i = 1 Do Until i > col.Count 'Place each value of array into a string-type variable 'This line is the date LineItem1 = col.Item(i) i = i + 1 'This line should be the BW count make sure to check LineItem2 = col.Item(i) i = i + 1 'This line should be the ECC count make sure to check LineItem3 = col.Item(i) i = i + 1 'Find the matching date in existing Daily Billing File (dates on Excel must be formatted as 'general or text) and add ECC and BW counts on adjacent fields Set rtheCell = Range("A3:A37").Find(What:=LineItem1) rtheCell.Offset(, 1).Value = LineItem3 'This is LineItem3 since we can ECC data to appear before BW rtheCell.Offset(, 2).Value = LineItem2 Set rtheCell = Nothing LineItem1 = 0 Loop 'Format cells to appear as number with no decimals 'Format cells to have horizontal alignment Sheets(1).Range("B3:C50").NumberFormat = "0" Sheets(1).Range("C3:C50").HorizontalAlignment = xlRight End Sub A: when you use the Range.Find method, typically you would either use the After:= parameter in subsequent calls or use the Range.FindNext method which assumes After:= the last found item. Since you are not modifying the actual found cells' value(s) in any way, you need to record the original found cell (typically the address) because eventually you will loop back to the original. dim fndrng as range, fndstr as string set fndrng = Range("A:A").Find(What:=LineItem1, after:=cells(rows.count, "A")) if not fndrng is nothing then fndstr = fndrng.address do while True 'do stuff here set fndrng = Range("A:A").FindNext(after:=fndrng) if fndstr = fndrng.address then exit do loop end if That should give you the idea of looping through all the matching calls until you loop back to the original. tbh, it is hard to adequately expand on the small amount of code supplied.
{ "pile_set_name": "StackExchange" }
Q: Could I run a Zepp antenna from a telegraph pole underneath a mains cable? I'm new to the forum, and I've been advised that this is a good place to get experienced opinion. I lived in a three storey terraced house in Mid Wales. It is terraced on three sides with the house on one side being taller than mine. There are also two very tall solid chapels on each side of the road a few metres away. I have access to a small area at the rear which is about two and a half metres by 2 and a half metres. I have a vertical sandpiper on the roof but this has limited success because of the taller buildings around my house., I also have a 69ft zeppelin aerial which runs from the guttering at one corner of the roof, (about 30 ft high) passing above my neighbours smaller Cottage and garden to a plastic downpipe on one of the chapels at the bottom of my neighbour's garden (about 20ft up).. Unfortunately because of the proximity of the very old sound system the HF can interfere with the sound system in the chapel even on qrp There is a telegraph pole about 10 ft away from the chapel and the same distance from my house which is accessible. I could move the end of the Zeppelin to the telegraph pole. This would mean that it would be 3 or 4 ft down from a mains distribution cable that comes to my house. The Zeppelin and the mains cable would not be exactly parallel and over the length of the Zeppelin they would end up about 6 feet apart at the building.. I would only have to move the farthest end of the Zeppelin. At the moment the cables are about 10 feet apart at the far end and about 6 feet apart at the house end and I don't experience any interference. Would moving the Zepp to the pole present any interference problems for either my reception or the local dwellings via the electricity network please The attached pic is not too clear, but you can get an idea of the layout. Keith. A: I wouldn't do it. Power lines carry noise from all the houses attached to them, and with your antenna in such close proximity you'll probably hear all of it. Likewise, when transmitting you'll likely couple a fair bit of RF into the power line. That could cause even more interference with your neighbors. It's also a safety hazard. If that power line should fall and come into contact with the antenna you may be in for a surprise. It's probably also illegal.
{ "pile_set_name": "StackExchange" }
Q: Why is the cache busting rule declared in web.config being ignored? I'm trying to use the rewrite rule from the HTML 5 Boilerplate project to make circumventing browser cache (aka cache busting): <rewrite> <rules> <rule name="Cachebusting"> <match url="^(.+)\.\d+(\.(js|css|png|jpg|gif)$)" /> <action type="Rewrite" url="{R:1}{R:2}" /> </rule> <rule name="Remove WWW" stopProcessing="true"> <match url="^(.*)$" /> <conditions> <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" /> </conditions> <action type="Redirect" url="http://chewsy.com{PATH_INFO}" redirectType="Permanent" /> </rule> </rules> </rewrite> If i try to access my css with /css/all.123456.css, it fails to find the file with the error reporting that it's looking for /css/all.123456.css (no rewrite). I've tried commenting out the "Remove WWW" rule to see if that was a conflict, but same behavior. Any ideas why this rule isn't being applied and rewriting the URLs? Update: I'm using these settings for my web server in VS2010: A: <match url="^(.+)\.\d+\.(js|css|png|jpg|gif)$" /> <action type="Rewrite" url="{R:1}.{R:2}" /> I pressume you want to get /css/all.css, if not, post the desired result... EDIT: VS internal development server (Cassini) doesn't support IIS URL Rewriting Module, you would have to use IIS (Express) for that, or some third party component (http://urlrewriter.net/)...
{ "pile_set_name": "StackExchange" }
Q: Run my application without Qt on linux I wrote an application in Qt5 on Linux. How can I run this app on another Linux without using Qt and compile project again. I found this question: Run .EXE without Qt But it is related to Windows. I want to do that on Linux. A: It is basically the same, however, for Linux: Basic instructtion for static link: http://qt-project.org/doc/qt-5.0/qtdoc/deployment-x11.html Some note on deploying for Linux and licensing: http://qt-project.org/doc/qt-5.0/qtdoc/deployment.html If you need plug-ins: http://qt-project.org/doc/qt-4.8/deployment-plugins.html
{ "pile_set_name": "StackExchange" }
Q: How do I receive an http request with a Node.js server and then pass that request along to another server? There's a lot going on here so I'll simplify this into a pseudo example. Forget about security and whatnot for a minute here. The point is to understand the functionality. Let's say I'm running a local web server with node.js to dev a website. In the website, the user should be able to create a new account. The account information will be submitted via ajax to the node server. I then need the node server to take the incoming request and pass it along to another server that gives me access to a database. CouchDB, for example. So here's a pseudo example of what I'd like to happen. In the client's browser: $.ajax({ url: './database_stuff/whatever', // points to the node web server method: 'POST', data: {name: 'Billy', age: 24} }); In the Node web server: var http = require('http'), dbServer = 'http://127.0.0.1:5984/database_url'; http.createServer(function (req, res) { /* figure out that we need to access the database then... */ // magically pass the request on to the db server http.magicPassAlongMethod(req, dbServer, function (dbResponse) { // pass the db server's response back to the client dbResponse.on('data', function (chunk) { res.end(chunk); }); }) }).listen(8888); Make sense? Basically what's the best way to pass the original request along to another server and then pass the response back to the client? A: If the server at dbServer url supports streaming you could do something like var request = require('request'); req.pipe(request.post(dbServer)).pipe(res) where request is a module, for more info look here https://github.com/mikeal/request This is quite readable and easy to implement, if for whatever reason you cannot do this then you could take what you need from the request and manually POST it, then take the response and res.send it to the client. Sorry if there's an error in my code, I haven't tested it but my point should be clear, if it's not then ask away.
{ "pile_set_name": "StackExchange" }
Q: Session permission denied Laravel Forge and OAuth I can start by saying that I am not great on this server config stuff. I have had the social logins working with sessions and all that before, but then I edited the config file because I wanted to gzip the content that was sent to the browser. Now I am getting this. ErrorException (E_UNKNOWN) open(/var/lib/php5/sess_2fde40503711502d2a6fe148dfcee783, O_RDWR) failed: Permission denied (13) Open: /home/forge/default/vendor/lusitanian/oauth/src/OAuth/Common/Storage/Session.php public function __construct( $startSession = true, $sessionVariableName = 'lusitanian_oauth_token', $stateVariableName = 'lusitanian_oauth_state' ) { if ($startSession && !isset($_SESSION)) { session_start(); } session_start(); has red background in the error. I am not sure what the reason is for this error? Have anybody else got the same thing? It started happening after I added gzip to the config, but even if I remove it it won't go back to working for some reason. Worth to note is that the usual email + password login works fine even that they are using sessions. But not this OAuth stuff. Using Laravel 4.2. A: PHP doesn't have permission to write on the sessions folder. Given the ErrorException, I'm assuming your sessions were setup to use the folder "/var/lib/php5". So, you can do that: sudo chmod 777 /var/lib/php5/ Or you can open the php.ini file and edit the following line: session.save_path = "/path/to/your/folder" Otherwise, you can use: ini_set(session.save_path, '/path/to/your/folder')
{ "pile_set_name": "StackExchange" }
Q: Calculate roots of multiple polynomials Given a matrix A that represents polynomials in each column. How can the roots of each polynomial be calculated efficiently without loops? A: Here's a comparison between 3 methods: A simple loop through all the rows, using roots on each row. A completely loopless approach, based on YBE's idea of using a block-diagonal matrix, using sparse as an intermediate A simple loop through all the rows, but this time using "inlined" code from roots. The code: %// The polynomials m = 15; n = 8; N = 1e3; X = rand(m,n); %// Simplest approach tic for mm = 1:N R = zeros(n-1,m); for ii = 1:m R(:,ii) = roots(X(ii,:)); end end toc %// Completely loopless approach tic for mm = 1:N %// Indices for the scaled coefficients ii = repmat(1:n-1:m*(n-1), n-1,1); jj = 1:m*(n-1); %// Indices for the ones kk = bsxfun(@plus, repmat(2:n-1, m,1), (n-1)*(0:m-1).'); %' ll = kk-1; %// The block diagonal matrix coefs = -bsxfun(@rdivide, X(:,2:end), X(:,1)).'; %' one = ones(n-2,m); C = full(sparse([ii(:); kk(:)], [jj(:); ll(:)],... [coefs(:); one(:)])); %// The roots R = reshape(eig(C), n-1,m); end toc %// Simple loop, roots() "inlined" tic R = zeros(n-1,m); for mm = 1:N for ii = 1:m A = zeros(n-1); A(1,:) = -X(ii,2:end)/X(ii,1); A(2:n:end) = 1; R(:,ii) = eig(A); end end toc The results: %// m=15, n=8, N=1e3: Elapsed time is 0.780930 seconds. %// loop using roots() Elapsed time is 1.959419 seconds. %// Loopless Elapsed time is 0.326140 seconds. %// loop over inlined roots() %// m=150, n=18, N=1e2: Elapsed time is 1.785438 seconds. %// loop using roots() Elapsed time is 110.1645 seconds. %// Loopless Elapsed time is 1.326355 seconds. %// loop over inlined roots() Of course, your mileage may vary, but the general message should be clear: The old advice of avoiding loops in MATLAB is just that: OLD. It just no longer applies to MATLAB versions R2009 and up. Vectorization can still be a good thing though, but certainly not always. As in this case: profiling will tell you that most time is spent on computing the eigenvalues for the block-diagonal matrix. The algorithm underlying eig scales as N³ (yes, that is a three), plus it cannot take advantage of sparse matrices in any way (like this block-diagonal one), making the approach a poor choice in this particular context. Loops are your friend here ^_^ Now, this is of course based on eig() of the companion matrix, which is a nice and simple method to compute all roots in one go. There are of course many more methods to compute roots of polynomials, each with their own advantages/disadvantages. Some are a lot faster, but aren't so good when a few of the roots are complex. Others are a lot faster, but need a fairly good initial estimate for every root, etc. Most other rootfinding methods are usually a lot more complicated, which is why I left these out here. Here is a nice overview, and here is a more in-depth overview, along with some MATLAB code examples. If you're smart, you should only dive into this material if you need to do this computation millions of times on a daily basis for at least the next few weeks, otherwise, it's just not worth the investment. If you're smarter, you'll recognize that this will undoubtedly come back to you at some point, so it's worthwhile to do anyway. And if you're an academic, you master all the root-finding methods so you'll have a giant toolbox, so you can pick the best tool for the job whenever a new job comes along. Or even dream up your own method :)
{ "pile_set_name": "StackExchange" }
Q: Deploying JRuby/Rails to Glassfish: undefined method `bundle_path' for Bundler:Module The following error shows up in my Glassfish log when attempting to access my app: Caused by: org.jruby.exceptions.RaiseException: (NameError) method 'to_yaml' not defined in Object Looking through the log I see this: undefined method `bundle_path' for Bundler:Module I confirmed that warble is definitely putting the Bundler gem in my .war file. (using ruby 1.9, rails 3.1, glassfish 3.0 and 3.1) This also appears in the glassfish log: Policy Provider:Failed Permission Check: context (" myapp/myapp ") , permission (" (java.lang.reflect.ReflectPermission suppressAccessChecks) ") |#] However I've verified that the permission is granted in server.policy. EDIT: I fixed the permission problem and the first two errors persist. (That said, the premission problem required me to edit a file it specifically says not to edit. Attempting to grant this permission in server.policy in Glassfish did not work). Here is the relevant environment info from the Glassfish log file: https://gist.github.com/1245825 A: This affects some application servers but not others. See this thread for further information and a quick fix. https://github.com/jruby/warbler/issues/44#issuecomment-2809940
{ "pile_set_name": "StackExchange" }
Q: jQuery event handlers - memory usage I've been doing this: $('#id').on('click',function(e){myFunction(var1,var2);}); function myFunction(x,y){blah blah blah} I'm wanting to change to this: $('#id').on('click',function(e){blah blah blah}); If I do this with lots of different DOM elements, am I consuming more memory space because I'm multiplying the space taken up by myFunction with each closure? Or does it just use a pointer? A: The first code has the advantage of reuse, but has the disadvantage of defining an anonymous function just to call the real function. If it really matters, then the extra function is an overhead. The second one will take much less memory since you are passing only one function. Functions are also passed by reference. Meaning this function could be stored once and called by many different callers. However, the way you attach it also affects performance. If you do it like this: $('#id1').on('click',function(e){myFunction(var1,var2);}); $('#id2').on('click',function(e){myFunction(var1,var2);}); this one calls jQuery 4 times (2 $() and 2 on()), creates 2 anonymous functions and calls an external function twice. count: 6 calls, 3 functions just to execute your operation (not including internal jQuery calls). $('#id1').on('click',function(e){blah blah blah}); $('#id2').on('click',function(e){blah blah blah}); if you do it this way, the function isn't reusable anymore but you got 4 calls to jQuery, 2 functions but you are repeating the code. not good from a DRY perspective. $('#id1, #id2').on('click',function(e){blah blah blah}); this one, you have 2 calls, and 1 function. this one is better. $('#id1, #id2').on('click',function(e){myFunction(var1,var2);}); you could also do it this way, the function is reusable with a sacrifice of an additional anonymous function and call. count: 3 calls, 2 functions. You could harness the power of .on by attaching the handler to the "nearest common parent", nearest so that the bubble won't travel up very far. in comparison, live() attaches events to the document, making handlers available even to new elements. But attaching to the document makes it very far for deeply nested elements. $('nearest_common_parent').on('click','dynamic_element',function(){ //do stuff });
{ "pile_set_name": "StackExchange" }
Q: ViewModels Mediator with multiple generic callbacks I'm developing a mediator for an MVVM application. This application lets employees file tickets with IT support to ask for help. The mediator communicates messages and triggers callbacks between ViewModels. Here's a description of it's architecture : The messages between the ViewModels The messages are stored in an enumerator : public enum ViewModelMessages { UserCreated, ManagerChanged, TicketCreated, TicketDeleted, TicketRefusedByIT, CommentAppendedToTicket, TicketCompleted, StatisticsFileOutputted }; This list of messages could get a lot longer than that as I continue development. The Mediator The mediator is a singleton that can register multiple callbacks for each message and triggers them when the message is emitted. These callbacks can take no parameters or a single object parameter of any given type : public sealed class Mediator { #region Singleton definition private static readonly Lazy<Mediator> lazy = new Lazy<Mediator>(() => new Mediator()); public static Mediator Instance { get { return lazy.Value; } } private Mediator() { } #endregion private MultiDictionary<ViewModelMessages, Action> registeredCallbacksWithoutParameter = new MultiDictionary<ViewModelMessages, Action>(); private MultiDictionary<ViewModelMessages, Action<object>> registeredCallbacksWithParameter = new MultiDictionary<ViewModelMessages, Action<object>>(); public void Register(ViewModelMessages message, Action callback) { registeredCallbacksWithoutParameter[message] += callback; } public void Register<ParameterType>(ViewModelMessages message, Action<ParameterType> callback) { registeredCallbacksWithParameter[message] += (parameter) => callback((ParameterType)parameter); } public void Unregister(ViewModelMessages message, Action callback) { registeredCallbacksWithoutParameter[message] -= callback; } public void Unregister(ViewModelMessages message, Action<object> callback) { registeredCallbacksWithParameter[message] -= callback; } public void Notify(ViewModelMessages message) { foreach(Action callback in registeredCallbacksWithoutParameter[message]) { callback(); } } public void Notify(ViewModelMessages message, object parameter) { foreach(Action callback in registeredCallbacksWithoutParameter[message]) { callback(); } foreach(Action<object> callback in registeredCallbacksWithParameter[message]) { callback(parameter); } } } The MultiDictionary The callbacks are stored in a MultiDictionary: a regular dictionary where each entry can store a hashset : public class MultiDictionary<keyType, contentType> : IDictionary<keyType, AddableHashSet<contentType>> { private Dictionary<keyType, AddableHashSet<contentType>> dictionary = new Dictionary<keyType, AddableHashSet<contentType>>(); public AddableHashSet<contentType> this[keyType key] { get { EnsureKey(key); return dictionary[key]; } set { EnsureKey(key); dictionary[key] = value; if(dictionary[key].Count == 0) { dictionary.Remove(key); } } } private void EnsureKey(keyType key) { if(!ContainsKey(key)) { dictionary.Add(key, new AddableHashSet<contentType>()); } else { if(dictionary[key] == null) dictionary[key] = new AddableHashSet<contentType>(); } } #region IDictionary interface implementation via the dictionnary member variable public ICollection<keyType> Keys => dictionary.Keys; public ICollection<AddableHashSet<contentType>> Values => dictionary.Values; public int Count => dictionary.Count; public bool IsReadOnly => ((IDictionary<keyType, AddableHashSet<contentType>>)dictionary).IsReadOnly; public void Add(keyType key, AddableHashSet<contentType> value) => dictionary.Add(key, value); public void Add(KeyValuePair<keyType, AddableHashSet<contentType>> item) => throw new NotImplementedException(); public void Clear() => dictionary.Clear(); public bool Contains(KeyValuePair<keyType, AddableHashSet<contentType>> item) => throw new NotImplementedException(); public bool ContainsKey(keyType key) => dictionary.ContainsKey(key); public void CopyTo(KeyValuePair<keyType, AddableHashSet<contentType>>[] array, int arrayIndex) => throw new NotImplementedException(); public IEnumerator<KeyValuePair<keyType, AddableHashSet<contentType>>> GetEnumerator() => dictionary.GetEnumerator(); public bool Remove(keyType key) => dictionary.Remove(key); public bool Remove(KeyValuePair<keyType, AddableHashSet<contentType>> item) => throw new NotImplementedException(); public bool TryGetValue(keyType key, out AddableHashSet<contentType> value) => dictionary.TryGetValue(key, out value); IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException(); #endregion } The number of callbacks per message will potentially be between 0 and 10, but it could potentially go a lot higher than that. At this stage I still don't know how high so I preferred to use a hashet instead of a list to avoid it being a bottleneck later on. The hashset The AddableHashSet is a hashset with the + and - operators overloaded to simplify the syntax in the Mediator: using += and -= follows the event += eventhandler() pattern. public class AddableHashSet<Type> : HashSet<Type> { public static AddableHashSet<Type> operator +(AddableHashSet<Type> hashSet, Type value) { hashSet.Add(value); return hashSet; } public static AddableHashSet<Type> operator -(AddableHashSet<Type> list, Type value) { if(list.Contains(value)) { list.Remove(value); } return list; } public AddableHashSet() { } } What do you think? This is my first implementation of the mediator pattern ever. Any suggestions would be greatly appreciated! A: I don't feel like you should override + and -. Fine, it makes the syntax cuter, but it makes your code much less readable for someone who isn't you. Remember, you write code so that yourself in 5 years or someone else can read it properly, not so you can feel it better right now. Follow this guideline, and you'll see that your code will be much cleaner. By using the + operator, we loose the advantage of the bool Add(T value) that the Hashset<T> has. Following coding conventions, your generic types should be PascalCased. So keyType = KeyType and contentType = ContentType. You could make your dictionary variable readonly. The main purpose is to tell other programmers (or yourself in 5 years) that this variable should never be set somewhere else than at it's declaration. I'm wondering, why is there a s at the end of ViewModelMessages? Is it a list of view models? Your Mediator looks fine, though I feel like there might be a problem when it comes to Unregister. Imagine this : Mediator.Instance.Register(ViewModelMessages.UserCreated,() => someAction); //Later in a far far away block of code Mediator.Instance.Unregister(ViewModelMessages.UserCreated, () => someAction); Will it work? After all, the lambda isn't the same reference as before! Your dictionary might not find it. (Although I must say I'm not 100% sure) This is why, when you look at the IObservable/IObserver pattern, IObservable<T>.Subscribe returns IDisposable, which is the object responsible to Unsubscribe the Observer, you should implement something similar in my opinion because you might not always have the opportunity to Unregister your callback when you want (example if you need to do it in a DLL that has no reference to your Mediator. Last thing, I don't think it should be a Singleton. I think your Mediator should be backed by an interface (IMediator perhaps) so you can unit test your code more easily and create less dependance around your code. (If you need to understand why interfaces are nice, I'll post some articles in comment if you want) And you could use an IoC container to deal with the dependances. A: You should not be calling it a dictionary because you changed the expected behaviour of the IDictionary interface. The MSDN clearly states that the getter of the indexer should throw an exception if the key is not found. KeyNotFoundException - The property is retrieved and key is not found. this should not be adding new elements if the getter is used. The closest collection type that has a similar behaviour would be the ILookup but even this doesn't seem to be right in this case - a lookup returns an empty collection but does not change the lookup itself. I suggest naming it a MultiCollection and documenting the unexpected side effects of the getter. This collection does not need to implement the IDictionary interface because you use only the indexer anyway. IEnumerable would be enough so that you can use it a loop. You are also doing other things that are very unusual for C#. For example you use a plural name for the enum. We do this only if it is also decorated with the FlagsAttribute that indicates that the values can be combined. Another strange naming convention is the <keyType, contentType>. C# uses a T prefix for generic types so the correct names should be: <TKey, TContent>. A: I fully agree with TopinFrassi and t3chb0t. Some other points The MultiDictionary and the AddableHashSet are not required and complicate the solution. It is much simpler to use a dictionary with a List<TValue> as value. I understand the desire for simplifying the API to accessing the dictionary, but that can be also realized using extension methods or by sub-classing the dictionary. Using an enum as key may become a problem because the enum contains business related code (or values) and the Mediator is more a framework component - these parts should IMHO not be mixed. You could resolve that issue by using generics, or by using a more general type as key (e.g. object or string). The Lazy type is IMHO not required for singletons because it makes the code less readable and have no benefit. Considering the points above may result in the following implementaion: public sealed class Mediator<TMessageKey> { public static Mediator<TMessageKey> Instance { get; } = new Mediator<TMessageKey>(); private Mediator() { } private readonly KeyListDictionary<TMessageKey, Action> callbacks = new KeyListDictionary<TMessageKey, Action>(); private readonly KeyListDictionary<TMessageKey, Action<object>> callbacksWithParameter = new KeyListDictionary<TMessageKey, Action<object>>(); public void Register(TMessageKey key, Action action) => callbacks.AddListEntry(key, action); public void Register<ParameterType>(TMessageKey key, Action<object> action) => callbacksWithParameter.AddListEntry(key, action); public void Unregister(TMessageKey key, Action action) => callbacks.RemoveListEntry(key, action); public void Unregister(TMessageKey key, Action<object> action) => callbacksWithParameter.RemoveListEntry(key, action); public void Notify(TMessageKey key) => callbacks.ForEachListEntry(key, action => action()); public void Notify(TMessageKey key, object parameter) => callbacksWithParameter.ForEachListEntry(key, action => action(null)); } public class KeyListDictionary<TKey, TListEntry> : Dictionary<TKey, IList<TListEntry>> { public void AddListEntry(TKey key, TListEntry value) { IList<TListEntry> list; if (!TryGetValue(key, out list)) { list = new List<TListEntry>(); Add(key, list); } list.Add(value); } public bool RemoveListEntry(TKey key, TListEntry value) { IList<TListEntry> list; if (TryGetValue(key, out list)) return list.Remove(value); return false; } public void ForEachListEntry(TKey key, Action<TListEntry> action) { IList<TListEntry> list; if (TryGetValue(key, out list)) foreach (var value in list) action(value); } }
{ "pile_set_name": "StackExchange" }
Q: dhtmlx scheduler: display multiple months on single view I am using dhtmlx scheduler, Wanted to display multiple months on single view. I tried units view But nothing help. Is there any ideas to implement that without changing the source code? A: You can set year view in your app. Also, it's possible to set a required number of months displayed on the screen in this view. More info and demo: http://docs.dhtmlx.com/scheduler/year_view.html http://docs.dhtmlx.com/scheduler/samples/03_extensions/04_year_view.html There is way to create a timeline view with multiple months: http://docs.dhtmlx.com/scheduler/snippet/4774ef81 If you don't need sections in view, you can hide them: http://docs.dhtmlx.com/scheduler/snippet/b35f0aad Also, you can create a custom view. But if you need to display a large amount of time - this is not the most suitable way. http://docs.dhtmlx.com/scheduler/custom_views.html http://docs.dhtmlx.com/scheduler/snippet/aa263cdb
{ "pile_set_name": "StackExchange" }
Q: NHibernate - No Inverse on One-to-one my application has 2 entities called Event and Transaction. An Event may or may not have a transaction but can only have 1 Transaction. I thought the best way to map this was with a HasOne mapping. So far everything is fine but i want to make sure that when you delete an Event it won't delete it if has a Transaction. Normally on a HasMany relationship i would just set an Inverse and change Cascade to None. While Cascade exists, Inverse doesn't and the event deletes regardless of whether it has a Transaction or not. I'd appreciate it if someone could show me the correct way of doing this. Thanks A: You could always create your own custom delete behaviour using a DeleteEventListener: public class DeleteEventListener : DefaultDeleteEventListener { protected override void DeleteEntity(IEventSource session, object entity, EntityEntry entityEntry, bool isCascadeDeleteEnabled, IEntityPersister persister, ISet transientEntities) { Event event = entity as Event; if (event != null && event.Transaction != null) throw new Exception("You can't delete this Event! Look! It has a Transaction!"); CascadeBeforeDelete(session, persister, entity, entityEntry, transientEntities); CascadeAfterDelete(session, persister, entity, transientEntities); } } This DeleteEventListener would then need to be registered as part of your NHibernate setup configuration. Within the session factory element: <event type="delete"> <listener class="myNamespaces.DeleteEventListener, myAssembly" /> </event> I haven't tested this particular code but I have similar code in my app so I can help out if you get stuck.
{ "pile_set_name": "StackExchange" }
Q: How to play .mp4 video as a background video in Android? I have watched many tutorials but somethings wrong. I have simple mainactivity and there is a VideoView on the it's layout. I downloaded a video from youtube as a .mp4 file size is about 10 mb. I found a great sample about videoview on youtube as the following link. https://www.youtube.com/watch?v=tPeDn18FrGY&t=75s ublic class MainActivity extends AppCompatActivity { private VideoView bgVideo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bgVideo=(VideoView) findViewById(R.id.bg_videoview); Uri uri = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.bgvideo); bgVideo.setVideoURI(uri); bgVideo.start(); bgVideo.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { mp.setLooping(true); } }); } } I use genymotion emulator. While i run the app i take "can't play this" error. And at the android monitor things like this. 06-07 03:16:28.675 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648) 06-07 03:16:28.675 2146-2146/com.sample D/VideoView: Error: 1,-2147483648 06-07 03:16:28.692 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648) 06-07 03:16:28.692 2146-2146/com.sample D/VideoView: Error: 1,-2147483648 06-07 03:16:28.709 2146-2146/com.sample E/MediaPlayer: Error (1,-2147483648) 06-07 03:16:28.709 2146-2146/com.sample D/VideoView: Error: 1,-2147483648 06-07 03:16:28.742 2146-2146/com.sample E/MediaPlayer: Error (1,-32) 06-07 03:16:28.742 2146-2146/com.sample D/VideoView: Error: 1,-32 06-07 03:16:28.758 2146-2146/com.sample E/MediaPlayer: Error (1,-38) 06-07 03:16:28.758 2146-2146/com.sample D/VideoView: Error: 1,-38 06-07 03:16:29.526 2146-2146/com.sample I/Choreographer: Skipped 44 frames! The application may be doing too much work on its main thread. How can i fix it ? A: You can use MediaPlayer object and play in one service. here is the example code: public class Mp3PlayerService extends Service implements MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener { /** Android Built-in Media Player */ public MediaPlayer player; /** Binder for Mp3 Service */ private final IBinder iBinder = new Mp3PlayerService.BackgroundAudioServiceBinder(); @Override public void onCreate() { super.onCreate(); player = new MediaPlayer(); player.setOnCompletionListener(this); player = new MediaPlayer(); try { playSongLocal(); playSongNetwork(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } } private void playsongLocal() { AssetFileDescriptor afd; player.reset(); try { LogUtils.LOGE(TAG, "playing aaa.mp3"); afd = getApplicationContext().getAssets().openFd("aaa.mp3"); player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength()); player.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } } private void playsongNetwork() { player.reset(); try { player.setDataSource(networkUrlLink); player.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } } @Override public IBinder onBind(Intent intent) { return iBinder; } @Override public boolean onUnbind(Intent intent) { return super.onUnbind(intent); } public void onDestroy() { if (player.isPlaying()) { player.stop(); } player.release(); } /** return itself when beeing asked */ public class BackgroundAudioServiceBinder extends Binder { public Mp3PlayerService getService() { return Mp3PlayerService.this; } }
{ "pile_set_name": "StackExchange" }
Q: The root sign and it's relation with 1/2. $\sqrt{4}=2$ But is it same as writing... $4^{1/2}=2$? Basically I do not understand why $\sqrt{}$-sign equals $1/2$? A: Basically it is just a definition of the $\sqrt{}$-sign. Note, that the $\sqrt{}$-sign is one of the few examples (maybe the only one?) in mathematics, where you write "nothing" (since $\sqrt{x}=\sqrt[2]{x}$) and actually mean $2$. So yes. It is $\sqrt{4}=4^{1/2}=2$ To make it more clear, we have $\sqrt[n]{x}=x^{1/n}$, where $\sqrt[n]{x}$ notes the $n-th$ root of $x$. For example $\sqrt[3]{8}=2$, because $2\cdot 2\cdot 2=2^3=8$.
{ "pile_set_name": "StackExchange" }
Q: Specifying where clause format in Entity Framework with System.Data.SQLite I have an Entity Framwework 4.0 Model running against an SQLite database to which I connect via System.Data.SQLite. I have one field in the database which is typed "Date", and formatted as yyyy-MM-dd. (As we know, SQLite has no internal Date or DateTime type). The Entity Framework wizard happily translated that Date type to DateTime. When running queries against this date field, I was surprised to find out no results came. Suppose a table "MyTable": Create Table MyTable ( Id Integer Not Null Primary Key, ADate Date Not Null ); With System.Data.SQLite and LINQ: var date = new DateTime(2013, 1, 1); context.MyTables.AddObject(new MyTable { Id = 0, ADate = date }); context.SaveChanges(); context.MyTables.Where(r => r.ADate == date).Count; // -> returns 0 Looking further with ToTraceQuery, I found out that the query became: SELECT [Extent1].[Id] AS [Id], [Extent1].[ADate] AS [ADate] FROM [TestDate] AS [Extent1] WHERE [Extent1].[ADate] = @p__linq__0 With testing, I discovered that the mapped variable p__linq__0 was transformed to a fixed format of yyyy-MM-dd hh:mm:ss, so that asking for DateTime(2013,1,1) meant the query was looking for '2013-01-01 00:00:00' when all that was to be found was '2013-01-01'. If the folks who make 'System.Data.SQLite' had been nice about this, they'd have used the built in SQLite functions and done the comparison like: WHERE datetime([Extent1].[ADate]) = datetime(@p__linq__0) or even WHERE date([Extent1].[ADate]) = date(@p__linq__0) for just the date type. And indeed in System.Data.SQLite's SqlGenerator.cs, we find this formatting for all DateTime types: ((System.DateTime)e.Value).ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture), false /* IsUnicode */) All this to say, is there a way to specify the format for this where clause in this context? Notes: SQLite is what I'm stuck with, and the recorded format of 'yyyy-MM-dd' cannot be changed as other software relies on it. A: One alternative to ExecuteStoreQuery is to pass other where clauses first (if any) then force the query to run (for example with ToList()), and finally to apply standard LINQ filters on the special format Date field afterwards.
{ "pile_set_name": "StackExchange" }
Q: Memory leak on ruby gtk-3 I'm experiencing a memory leak on ruby 2.3.1 with gtk-3. On my system (Ubuntu 16-04) the following code consumes approximately 80 MB. The size of picture.jpg is 289kb. `require 'gtk3' def ptest i=0 j=0 loop { i += 1 j += 1 exit if j==50 @image = Gtk::Image.new newPixbuf = GdkPixbuf::Pixbuf.new(:file => "picture.jpg") @image.pixbuf = newPixbuf @image.clear @image=nil if i == 10 p "GC" GC.start i = 0 end } end ptest` According https://sourceforge.net/p/ruby-gnome2/mailman/message/8659687/ this shouldn't happen. What can I do to release the memory? A: Apparently there has been a bug in my Ruby gdk3-Gem. A gem update solved the problem.
{ "pile_set_name": "StackExchange" }
Q: How to use several splitters in Kivy? I'd like to use two splitters in a single screen, so that the user can have either one of the 3 parts to fill the whole screen (but leaving a bit for the splitters to be shown). I've tried doing it (see code below), but when I shrink part 3 to the minimum and then enlarge part 1 as much as I can, part 3 disappears, which is not the desired behavior (I'd like it to be symmetrical to all 3 parts). Does anyone have an idea? BoxLayout: id: all min_view_size: sp(30) strip_size: sp(13) Splitter: sizable_from: 'right' strip_size: all.strip_size max_size: all.width - (all.min_view_size + all.strip_size)*2 min_size: all.min_view_size + all.strip_size Label: text: '1' Splitter: sizable_from: 'right' strip_size: all.strip_size max_size: all.width - (all.min_view_size + self.strip_size)*2 min_size: all.min_view_size + self.strip_size Label: text: '2' BoxLayout: max_size: all.width - (all.min_view_size + all.strip_size)*2 min_size: all.min_view_size Label: text: '3' A: After some tweaking, here is a working example for 2 horizontal splitters, so the parts between them have a minimum size: BoxLayout: id: all min_view_size: sp(30) strip_size: sp(13) Splitter: id: splitter1 sizable_from: 'right' strip_size: all.strip_size max_size: all.width - (all.min_view_size + all.strip_size)*2 min_size: all.min_view_size + all.strip_size Label: text: '1' Splitter: id: splitter2 sizable_from: 'right' strip_size: all.strip_size max_size: (all.width - splitter1.width) - (all.min_view_size + self.strip_size) min_size: all.min_view_size + self.strip_size Label: text: '2' BoxLayout: Label: text: '3' The trick was to have the min_size rule for the second splitter depend on the size of the first one. EDIT: And here it is with auto-orientation-adjustment when the window is narrow/wide: BoxLayout: id: all min_view_size: sp(30) strip_size: sp(13) orientation: 'vertical' if self.width < self.height else 'horizontal' vertical: self.orientation == 'vertical' bigger_size: self.height if self.vertical else self.width default_part_size: (self.bigger_size - self.strip_size*2)/3 # Reset part sizes when orientation changes on_vertical: if args[1]: (splitter1.height, splitter2.height) = (self.default_part_size, self.default_part_size) if not args[1]: (splitter1.width, splitter2.width) = (self.default_part_size, self.default_part_size) Splitter: id: splitter1 strip_size: all.strip_size max_size: all.bigger_size - (all.min_view_size + all.strip_size)*2 min_size: all.min_view_size + all.strip_size sizable_from: 'bottom' if all.vertical else 'right' size_hint: (1, None) if all.vertical else (None, 1) size: (all.width, all.default_part_size) if all.vertical else (all.default_part_size, all.height) BoxLayout: Button: text: '1' Splitter: id: splitter2 strip_size: all.strip_size splitter1_bigger_size: splitter1.height if all.vertical else splitter1.width max_size: (all.bigger_size - self.splitter1_bigger_size) - (all.min_view_size + self.strip_size) min_size: all.min_view_size + self.strip_size sizable_from: 'bottom' if all.vertical else 'right' size_hint: (1, None) if all.vertical else (None, 1) size: (all.width, all.default_part_size) if all.vertical else (all.default_part_size, all.height) BoxLayout: Button: text: '2' BoxLayout: Button: text: '3'
{ "pile_set_name": "StackExchange" }
Q: difference between document.forms[0].onsubmit and jQuery("form").submit Why does #1 get called when the __doPostback (this dynamic JavaScript function created automatically by ASP.NET when HTML renders.. I think when Event Validation is turned on) is called, but #2 does not get called. Yet, both get called when a button is clicked? #1 document.forms[0].onsubmit = function() { alert("called submit 1"); jQuery("#<%=DDLUCSAddress.ClientID %>").children("option").each(function() { jQuery(this).remove(); }); }; #2 jQuery("form").submit(function() { alert("called submit 2"); jQuery("#<%=DDLUCSAddress.ClientID %>").children("option").each(function() { jQuery(this).remove(); }); }); Rendered HTML - If I do a Ctrl+K+D on this code, it exceeds the character limit for Stack Overflow, due to the spaces. If you'd like to look at it formatted, place into Visual Studio and press Ctrl+K+D <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <body> <div id="sessionRefresh" style="display:none"> <script language="JavaScript" type="text/javascript" /> <form id="Form1" onsubmit="javascript:return WebForm_OnSubmit();" action="EditSampleDetails.aspx?LabAccessioningNumber=20120401-1&SampleTypeContext=247" method="post" name="Form1"> <div> <script type="text/javascript" /> <script type="text/javascript" src="/WebResource.axd?d=EXaDJPTWpPG72bTbiKNh_OuYVox46idcF5L2FHTyi19FoknASLIR-iSOhjjdC3Xa0OCTSAQepXg5UpNN1TPkcREtvcQ1&t=634208598757546466" /> <script type="text/javascript" language="javascript" /> <script type="text/javascript" src="/WebResource.axd?d=4scrxOSLDbM-cgeLoXFnrTxM83c-T6NjCtRi_ghVZlXN0qjfjwNCtjtRWczFgkWux80g8Ip0p9JqPBJcPSlcT3N25CA1&t=634208598757546466" /> <script type="text/javascript" /> <div> <div id="mainMenu" class="droplinetabs"> <table cellspacing="0" cellpadding="0" border="0"> <table class="uIBoxStacked" width="100%" cellspacing="0" cellpadding="0" border="0"> <tbody> <tr> <tr> <td class="uIBoxInternal" colspan="2"> <table width="100%" cellspacing="0" cellpadding="0" border="0"> <tbody> <tr> <td> <div id="BxWizardTitle" style="border-color:LightSteelBlue;width:100%;"> <a href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00", "", true, "", "", false, true))'></a> <a href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl01", "", true, "", "", false, true))'></a> <a href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl02", "", true, "", "", false, true))'></a> <a href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl03", "", true, "", "", false, true))'></a> <table cellspacing="0" cellpadding="0" style="border-width:0px;"> <tbody> <tr> <td class="leftNavigationCell" style="vertical-align:top;"> <td> <td valign="top"> <table cellpadding="5"> <tbody> <tr> <tr> <td> <table cellpadding="5"> <tbody> <tr> <tr> <tr> <td> <script type="text/javascript" /> <table class="uIBoxStacked" width="100%" cellspacing="0" cellpadding="0" border="0"> <tbody> <tr> <tr> <td class="uIBoxInternal" colspan="2"> <table class="outerTableOfInputs" width="100%" cellspacing="0"> <tbody> <tr> <td> <table class="tableOfInputs" width="100%" cellspacing="0"> <tbody> <tr> <td> <div id="FullDataEntryEditor_UIBSampleInfo" style="border-color:LightSteelBlue;width:100%;"> <a href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("FullDataEntryEditor$ctl00", "", true, "", "", false, true))'></a> <a href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("FullDataEntryEditor$ctl01", "", true, "", "", false, true))'></a> <a href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("FullDataEntryEditor$ctl02", "", true, "", "", false, true))'></a> <a href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("FullDataEntryEditor$ctl03", "", true, "", "", false, true))'></a> <table> <script type="text/javascript" /> <tbody> <tr> <tr> <tr> <tr> <td>Additional Client Number</td> <td> <input id="FullDataEntryEditor_TxtAdditionalClientNumber" class="LIMSFormField" type="text" autocomplete="off" name="FullDataEntryEditor$TxtAdditionalClientNumber"> </td> </tr> <tr> <tr> <tr> <tr> <tr> <tr> <tr> <tr> <tr> </tbody> </table> </div> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <table class="saveCancelDeleteOuter" width="100%" cellspacing="0"> <table width="100%" cellspacing="0" cellpadding="0" border="0"> <tbody> <tr> <td> <input id="EditObjectId986257676" type="hidden" value="" name="EditObjectId986257676"> <input id="CommandName986257676" type="hidden" value="" name="CommandName986257676"> <table class="uIBoxStacked" width="100%" cellspacing="0" cellpadding="0" border="0"> <tbody> <tr> <tr> <tr> <td class="uIBoxInternal" colspan="2"> <table width="100%" cellspacing="0" cellpadding="0" border="0"> <tbody> <tr> <td> <div id="FullDataEntryEditor_NMNotes_List_ListBox" style="border-color:LightSteelBlue;width:100%;"> <a href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("FullDataEntryEditor$NMNotes$List$ctl00", "", true, "", "", false, true))'></a> <a href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("FullDataEntryEditor$NMNotes$List$ctl01", "", true, "", "", false, true))'></a> <a href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("FullDataEntryEditor$NMNotes$List$ctl02", "", true, "", "", false, true))'></a> <a href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("FullDataEntryEditor$NMNotes$List$ctl03", "", true, "", "", false, true))'></a> <table id="FullDataEntryEditor_NMNotes_List_ListGrid" cellspacing="0" cellpadding="4" border="1" style="width:100%;border-collapse:collapse;" rules="all"> <tbody> <tr class="columnHeader"> <tr style="background-color:Yellow;"> <td> <a href="javascript:listCustomPostback(986257676,'Edit',129285);">bbbbbbbbbbbbbb</a> </td> <td> </tr> </tbody> </table> </div> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <div id="pdfDisplay"></div> <script language="javascript" type="text/javascript" /> </td> </tr> <tr> </tbody> </table> <script type="text/javascript" /> <input id="FullDataEntryEditor_HiddenSampleType" type="hidden" value="247" name="FullDataEntryEditor$HiddenSampleType"> <input id="FullDataEntryEditor_HiddenAJAXUCSAddressValue" type="hidden" value="7533" name="FullDataEntryEditor$HiddenAJAXUCSAddressValue"> <input id="FullDataEntryEditor_HiddenAJAXUCSAddressText" type="hidden" value="[7533] A1's Primary address, a1_primary_address, madison wi, usa 53719" name="FullDataEntryEditor$HiddenAJAXUCSAddressText"> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </div> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> <table class="saveCancelDeleteOuter" width="100%" cellspacing="0"> <script type="text/javascript" /> <script type="text/javascript" /> <script type="text/javascript" /> </form> <table class="copyright" align="center"> </body> </html> A: __doPostback does the following: theform.onsubmit(); This is taking the value of the onsubmit attribute and executing it. Submit handlers attached with jquery are not set as attributes on the element so they will not fire when this is done. EDIT: The relevant piece of code from the jQuery source: if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } This is how jquery attaches its events, not with the onsubmit attribute.
{ "pile_set_name": "StackExchange" }
Q: Problems with image adaptive resizing + Javascript Good evening to all!! I'm facing some problems with image resizing & Javascript. I wrote a function to resize an image maintaining aspect ratio. Here's the function: function computeRatio () { var el_image = document.getElementById("div_image"); var newImg = new Image(); newImg.src = document.getElementById("image").src; // GET IMAGE REAL DIMENSIONS var image_height = newImg.height; var image_width = newImg.width; // SET WINDOW DIMENSIONS var window_height = 762; var window_width = 600; // COMPUTE DIMENSION RATIOS var height_ratio = image_height / window_height; var width_ratio = image_width / window_width; // RESET IMAGE POSITION el_image.style.left = "0px"; el_image.style.top = "0px"; if (height_ratio > width_ratio) { var width = window_height/(image_height/image_width); // SET NEW DIMENSIONS (MAX HEIGHT & NEW WIDTH) el_image.style.width = width+"px"; el_image.style.height = window_height+"px" // SET NEW POSITION TO CENTER IMAGE var scroll_x = (window_width-width)/2; el_image.style.left = scroll_x+"px"; } else { var height = window_width*(image_height/image_width); // SET NEW DIMENSIONS (MAX WIDTH & NEW HEIGHT) el_image.style.width = window_width+"px" el_image.style.height = height+"px"; var scroll_y = (window_height-height)/2; el_image.style.top = scroll_y+"px"; } } This is the relevant part in HTML: <div id="div_image" style="display: block;"> <img src="" alt="0" id="image" onLoad="computeRatio ()"/> </div> It works really fine except when handling a not-so-small image (i.e size > 1MB). When this occours, the function computes the correct dimensions, but then the image is displayed in full screen (W=600px, H=762px) and, obviously, it isn't centered! I really can't understand why this happens!! Any help? Thanks to all A: To maintain aspect ratio for an image in a container, just set the image to display:block and add a width:100%. The effect is that the image will fill the to the width of the containing element, and height will automatically adjust. #image { display:block; width:100%; }
{ "pile_set_name": "StackExchange" }
Q: Output each string inside .txt file Made a program retrieving .txt files from a folder. Each .txt files contains 1 or 2 lines of word. I get the output of each filenames of .txt files from a folder: Donatello Galileo Leonardo Michael Rafael ex. codes i have so far: import java.io.*; import java.util.*; public class Liarliar { public static void main(String args[])throws IOException{ File listofnames = new File("C:\\List of names"); File[] names = listofnames.listFiles(); for(File person : names){ int index = person.getName().lastIndexOf("."); if(index>0&& index <= person.getName().length()-2){ System.out.println(person.getName().substring(0, index)); } } } } This are all filenames, but that is not I want to be the output. The output I want is: Donatello 2 Hi Hello Galileo 2 Fine Thanks Leonardo 1 Hi Michael 1 Hello Rafael 1 Hi Explanation: The example output given above e.g. Donatello 2, the number 2 after space and the name Donatello, the 2 correspond to the numbers of words inside the filename Donatello.txt. 2 because there are 2 lines of words. I hope you get my point. Any help would be greatly much appreciated. Thank you... A: Finally, I got your point. Donatello(file name) 2(containing line number) Hi Hello (above two lines are content in Donatello.txt, right? Solution: If file size is at most two lines, you can generate a new class to meet your requirement: class FileInfo { String fileName; int lineNum; String[] content; } Then read file line by line to fill information for your FileInfo. At last, print out all information you need. Hope this help.
{ "pile_set_name": "StackExchange" }
Q: Javascript: How to get .tgz MIME type from HTML file input? I am able to get most file MIME types by checking the file in a HTML file element, however when choosing a .tgz file I do not get a type. Here is a jsfiddle showing the file type when a file is selected from the HTML file input: http://jsfiddle.net/chrisabrams/cTJKf/ A: According to the spec it's up to the browser to attempt to determine the content-type and if it fails, it should return an empty string. type The ASCII-encoded string in lower case representing the media type of the Blob, expressed as an RFC2046 MIME type [RFC2046]. On getting, conforming user agents MUST return the MIME type of the Blob, if it is known. If conforming user agents cannot determine the media type of the Blob, they MUST return the empty string. A string is a valid MIME type if it matches the media-type token defined in section 3.7 "Media Types" of RFC 2616 [HTTP]. So whatever browser you're using doesn't recognise what a .tgz file is - this could vary both per-browser and also per-operating-system however. I'm using Opera on Linux and it recognises .tgz but - for example - doesn't recognise .xcf
{ "pile_set_name": "StackExchange" }
Q: MongoDB full text search with haskell driver Is there a possibility to use the full text search of mongoDB with the haskell driver? I found the 'runCommand' in the haskell API, but it expects a Document as parameter. That's fine for all the other commands that mongodb can run, but the syntax for a text command is: db.collection.runCommand( "text", {search : "something"}) So I don't know how I'll get the "text" as first parameter in front of the Document. Thanks A: The text-command can be written in another structure: { text: your_collection , search: your_text , filter: your_filter , limit: your_limit , project: your_projection } I had my suspicion, since all "runCommand"-action have the same structure. So I tried to apply that structure to the text-command - but without success. Then I remembered that aggregate has another structure too and tried that, but that didn't work either. Finally, I found the answer in a google group entry of the Java driver.
{ "pile_set_name": "StackExchange" }
Q: Silverlight - GestureService & GestureListner in code-behind I want to do the following XAML code in code behind and not sure how to add the GestureService and GestureListner onto the Image. Xaml code: <Image Grid.Row="1" x:Name="img" VerticalAlignment="Center" HorizontalAlignment="Center" Width="200"> <toolkit:GestureService.GestureListener> <toolkit:GestureListener/> </toolkit:GestureService.GestureListener> </Image> Code behind equivalent: Image image = new Image(); //how do I add GestureService and GestureListner? ContentPanel.Children.Add(image); A: Do this: GestureService.GetGestureListener(image); Normal approach would be doing it this way: GestureService.SetGestureListener(image, new GestureListener()); But GetstureService developers have marked SetGestureListener method as obsolete: "Do not add handlers using this method. Instead, use GetGestureListener, which will create a new instance if one is not already set, to add your handlers to an element."
{ "pile_set_name": "StackExchange" }
Q: Why has SpaceX changed Starship from carbon fiber composite to stainless steel? Recently, there was news that SpaceX changed the material used for the BFS/Starship (upper stage of the BFR) from initially planned carbon fiber to metal which seems quite counter-intuitive as carbon fiber has a few desirable physical properties and, more importantly, low weight. (source) What were the main reasons for choosing stainless steel over carbon fiber composite? A: According to tweets from Elon, at least part of the decision is due to their design for dealing with the reentry heat: instead of adding ablators to cool the craft on reentry, Starship is going to actively cool the hot side with liquid methane. Steel is better at coping with this than carbon fiber. Tweet 1: Usable strength/weight of full hard stainless at cryo is slightly better than carbon fiber, room temp is worse, high temp is vastly better Tweet 2: Leeward side needs nothing, windward side will be activity cooled with residual (cryo) liquid methane, so will appear liquid silver even on hot side (Also: Skin will get too hot for paint. Stainless mirror finish. Maximum relfectivity. [sic])
{ "pile_set_name": "StackExchange" }
Q: Spring NoClassDefFoundError: wrong name I have the following class: package com.spring.domain; @Document(collection = "sportactions") // for my mongodb collection @JsonInclude(JsonInclude.Include.NON_NULL) public class SportAction extends Action { //code logic } When I compile it, it gives me the following error: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler processing failed; nested exception is java.lang.NoClassDefFoundError: com/spring/domain/Sportaction (wrong name: com/spring/domain/SportAction)] with root cause java.lang.NoClassDefFoundError: com/spring/domain/Sportaction (wrong name: com/spring/domain/SportAction) I was confused as I can see my class is called SportAction with a capital A and not a small letter a so then I attempted to refactor my class name to see if it will work with a small letter a. I got the following error: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler processing failed; nested exception is java.lang.NoClassDefFoundError: com/spring/domain/SportAction (wrong name: com/spring/domain/Sportaction)] with root cause java.lang.NoClassDefFoundError: com/spring/domain/SportAction (wrong name: com/spring/domain/Sportaction) The spring application will compile perfectly but this will appear at run time when I try to use the class. I also did several clean and then build on gradle and it still doesn't work. Does anyone know what is wrong with the code? The error arose in this line of my java code when I try to fetch a list of Sportaction from mongodb: List<Sportaction> sportactions = mongoTemplate.find(query, Sportaction.class); A: I don't know why this error occurred, but my build.gradle file required me to build a jar like so: task stage(type: Copy, dependsOn: [clean, build]) { from jar.archivePath into project.rootDir rename { 'app.jar' } } stage.mustRunAfter(clean) clean << { project.file('app.jar').delete() } When I ran it and pushed it onto my repo, I got a very strange error where my filename was now SportAction but my class name inside my java file was: public class Sportaction This caused a mismatch, and I tried refactoring the name to match the filename SportAction but the same wrong name error arose. I then decided to refactor the name to something else like SportEvents and then rerun the code and then it worked. This isn't the best solution but it will have to do for now. I suspect it has something to do with the way the jar was built but I'm not sure as the app.jar was never run. The Application.main() was the class that ran when I ran my Spring app. I'm also confused as to why my SportAction class on bitbucket does not seem to have a commit at all - see those 3 dots next to my Action file - it doesn't have a date and neither does it have a description.
{ "pile_set_name": "StackExchange" }
Q: Fetch complex format data in list with dart language I'm just trying to fetch data via api in list but getting exception while debugging Class '_InternalLinkedHashMap<String, dynamic>' has no instance method 'cast' with matching arguments. Here is my demo json_api. First I created model class for data which I'm getting then decleared variables according to api data. Then created method to fetch data in the type of list of Model class objects. then created Widget tree and add StreamBuilder with the list type model class objects, to display data. CODE: Model Class: class Results { String kind; List<Item> items; int totalItems; Results({ this.kind, this.items, this.totalItems, }); factory Results.fromJson(Map<String, dynamic> json) => new Results( kind: json["kind"], items: new List<Item>.from(json["items"].map((x) => Item.fromJson(x))), totalItems: json["totalItems"], ); Map<String, dynamic> toJson() => { "kind": kind, "items": new List<dynamic>.from(items.map((x) => x.toJson())), "totalItems": totalItems, }; } class Item { String id; String kind; String selfLink; Item({ this.id, this.kind, this.selfLink, }); factory Item.fromJson(Map<String, dynamic> json) => new Item( id: json["id"], kind: json["kind"], selfLink: json["selfLink"], ); Map<String, dynamic> toJson() => { "id": id, "kind": kind, "selfLink": selfLink, }; } Method for get data in list of Model class objects: Future<List<Results>> fetchData()async{ List<Results> results = new List<Results>(); final response = await http.get(url); if(response.statusCode == 200 || json !=null){ List jsonParsed = json.decode(response.body).cast<Map<String, dynamic>>(); for (int i = 0; i < jsonParsed.length; i++) { results.add(new Results.fromJson(jsonParsed[i])); } return results; }else{ print('Request failed with status: ${response.statusCode}'); Fluttertoast.showToast(msg: "Request failed with status: ${response.statusCode}"); throw Exception('Failed to load post'); } } My Widget Tree with StreamBuilder: body: Center( child:FutureBuilder<List<Results>>( future:fetchData(), builder: (context, snapshot){ if(snapshot.hasData){ return //Center(child:Text(snapshot.data.items[0].id) ,); ListView.builder( itemCount: snapshot.data.length, itemBuilder: (context, int i){ return Column( children: <Widget>[ ListTile( leading: CircleAvatar( child: Text(snapshot.data[i].items[i].id), ), title: Text(snapshot.data[i].totalItems.toString()), subtitle: Text(snapshot.data[i].kind) , ), Divider(color: Colors.grey,) ], ); }, ); }else if(snapshot.hasError){ return Center(child: Text("${snapshot.error}"),); }else{ return Center(child: CircularProgressIndicator(),); } }, ), ), Where Am i doing wrong. A: try this, Future<Results> fetchData() async { Results results = new Results(); final response = await http .get('https://www.googleapis.com/books/v1/volumes?q=%7Bhttp%7D'); if (response.statusCode == 200 || json != null) { Map jsonParsed = json.decode(response.body); results = Results.fromJson(jsonParsed); return results; } else { print('Request failed with status: ${response.statusCode}'); throw Exception('Failed to load post'); } } @override void initState() { // TODO: implement initState super.initState(); fetchData(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Tiitle'), ), body: Center( child: FutureBuilder<Results>( future: fetchData(), builder: (context, snapshot) { if (snapshot.hasData) { return //Center(child:Text(snapshot.data.items[0].id) ,); ListView.builder( itemCount: snapshot.data.items.length, itemBuilder: (context, int i) { return Column( children: <Widget>[ ListTile( leading: CircleAvatar( child: Text(snapshot.data.totalItems.toString()), ), title: Text(snapshot.data.items[i].id), subtitle: Text(snapshot.data.items[i].kind), ), Divider( color: Colors.grey, ) ], ); }, ); } else if (snapshot.hasError) { return Center( child: Text("${snapshot.error}"), ); } else { return Center( child: CircularProgressIndicator(), ); } }, ), )); }
{ "pile_set_name": "StackExchange" }
Q: Como setar um token no header? Bom eu uso o jwt para gerar um token só que pelo exemplo que estava seguindo não mostrava exatamente como colcoar o token no header da aplicação. Alguém saberia como? Obs.: Estou usando o express. app.js //parte do arquivo principal app.use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST'); res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization'); next(); }); A: Tens de criar uma palavra passe e inserir um middleware que faça a verificação e depois fazer o pedido http com esse token algures. No lado do servidor: Há um exemplo bom neste link com os passos principais são: fazer require do jwt e configurar uma palavra passe var express = require('express'); var app = express(); var jwt = require('jsonwebtoken'); // inserir o módulo jwt app.set('superSecret', 'minha palavra passe'); // criar uma palavra passe de controlo gerar um token Dentro da função/path que tem a lógica de login, ou seja quando quiseres retornar um token a um utilizador que já esteja verificado podes fazer assim: var token = jwt.sign('nome do utilizador ou objeto', app.get('superSecret'), { expiresInMinutes: 1440 // validade de 24 horas }); // mostrar o token ao utilizador com um JSON res.json({ success: true, message: 'Enjoy your token!', token: token // este token é para guardar! }); configurar um middleware para verificar o token Por fim tens de defenir um middleware que corra em todas as path que precisas, ou seja nos url que devem estar protegidos. Essa parte é defenida na ultima linha deste código, primeiro tempos de defenir o router: // ir buscar uma instância do router do Express.js var apiRoutes = express.Router(); // middleware apiRoutes.use(function(req, res, next) { // procurar a propriedade token em partes diferentes do pedido var token = req.body.token || req.query.token || req.headers['x-access-token']; // descodificar caso haja um valor no request if (token) { // verifies secret and checks exp jwt.verify(token, app.get('superSecret'), function(err, decoded) { if (err) { // erro! return res.json({ success: false, message: 'Failed to authenticate token.' }); } else { // tudo ok! vamos passar esse valor para o req.decoded para ser usado no resto da aplicação req.decoded = decoded; next(); } }); } else { // se não houver token no pedido/request, retornar erro return res.status(403).send({ success: false, message: 'No token provided.' }); } }); // defenir quais os caminhos que devem estar protegidos app.use('/api', apiRoutes); No lado do cliente Há várias opções: via formulário/POST neste caso é só fazer um input escondido com o token: <input type="hidden" name="token" value="eyJhbGciOiJIUzI1NiJ9.dXNlcg.EvNc9eWXXeAjpMTMzV4xoW2EjtEcLeSwJwY5_8vE6X8" /> e o express vai ser encontrado com o req.body.token. (Não esquecer de juntar o middleware body parser) via url/query string Neste caso é só juntar no url uma query string com ?token=xxxxx, exemplo: http://localhost:3000/api?token=eyJhbGciOiJIUzI1NiJ9.dXNlcg.EvNc9eWXXeAjpMTMzV4xoW2EjtEcLeSwJwY5_8vE6X8 para ir buscar no Node pode usar-se req.query.token via request header/AJAX Neste caso é só passar via request header do AJAX assim: <script type="text/javascript"> function reqListener () { console.log(this.responseText); } var oReq = new XMLHttpRequest(); oReq.addEventListener("load", reqListener); oReq.open("GET", 'http://localhost:3000/api'); oReq.setRequestHeader('x-access-token', 'eyJhbGciOiJIUzI1NiJ9.dXNlcg.EvNc9eWXXeAjpMTMzV4xoW2EjtEcLeSwJwY5_8vE6X8'); oReq.send(); </script> e no Node ir buscar com req.headers['x-access-token'] Exemplo: Criei um exemplo com 3 ficheiros aqui: https://gist.github.com/SergioCrisostomo/445e4e37a6972c8493e8
{ "pile_set_name": "StackExchange" }
Q: Vue.js v2.0 delimeters I'm migrating from Vue.js v1 to v2. Before i was assigning vue delimiters in vue.config, but in version 2 it doesn't work (in components I mean). So how to globally declare delimiters? A: There is a migration guide on the VueJS documentation : https://vuejs.org/v2/guide/migration.html You can find information about delimiters (the options has been replaced) : https://vuejs.org/v2/guide/migration.html#Vue-config-delimiters-replaced You need to declare delimiters in your vue component : new Vue({ delimiters: ['${', '}'] })
{ "pile_set_name": "StackExchange" }
Q: Question on How to Separate Meshes Into Multiple, Disconnected Meshes So I'm very new to Blender and was looking to use it to create some sword fight/lightsaber fight actions scenes. However, I'm running into issues with separating body parts for models. For example, let's say Luke's hand gets cut off by Darth Vader. How do I go about detaching his hand from the rest of his body so that it can be lying on the ground, separate from the rest of his model? I believe that essentially I'd be creating a new model or mesh, but I'm not certain how to do this from an existing mesh. Any help or links to tutorials would be appreciated. Thanks! A: Enter in edit mesh, deselect all, move the mouse over the object that you want to separate, use "L" as a shortcut and you will have a select option. After you select what you want to separate use "P" as shortcut and click on separate. Repeat this for every object that you want to separate.
{ "pile_set_name": "StackExchange" }
Q: insert row in tableview and set textfield first responder i have an nstableview with 3 columns and a custom cell view. with this code i add a new row to my table: tableView.beginUpdates() tableView.insertRows(at: IndexSet(integer: tableView.numberOfRows), withAnimation: .effectFade) tableView.endUpdates() let view = tableView.view(atColumn: 1, row: tableView.numberOfRows-1, makeIfNecessary: false) as! CustomCell view.txtName.becomeFirstResponder() this works nearly perfect, but the problem is: The Row will insert, the textfield become the first Responder, i can write a value in it but if i change to focus to another textfield of this row my app crashs: 2017-06-14 09:20:13.282076+0200 Programm[2206:105520] [General] An uncaught exception was raised 2017-06-14 09:20:13.282112+0200 Programm[2206:105520] [General] Row -1 out of row range [0-0] for rowViewAtRow:createIfNeeded: 2017-06-14 09:20:13.289941+0200 Programm[2206:105520] [General] ( 0 CoreFoundation 0x00007fffb49ac57b __exceptionPreprocess + 171 1 libobjc.A.dylib 0x00007fffc9bf01da objc_exception_throw + 48 2 AppKit 0x00007fffb25329fb -[NSTableRowData rowViewAtRow:createIfNeeded:] + 690 3 AppKit 0x00007fffb25fdb11 -[NSTableView viewAtColumn:row:makeIfNecessary:] + 28 4 Programm 0x000000010002019a _TFC8Programm18DokumentController7controlfTCSo9NSControl20textShouldEndEditingCSo6NSText_Sb + 394 5 Programm 0x00000001000227cf _TToFC8Programm18DokumentController7controlfTCSo9NSControl20textShouldEndEditingCSo6NSText_Sb + 79 6 AppKit 0x00007fffb25e7ba7 -[NSTextField textShouldEndEditing:] + 161 7 AppKit 0x00007fffb25d5f1f -[NSTextView(NSSharing) resignFirstResponder] + 483 8 AppKit 0x00007fffb24d7923 -[NSWindow _realMakeFirstResponder:] + 235 9 AppKit 0x00007fffb24d77e4 -[NSWindow makeFirstResponder:] + 123 10 AppKit 0x00007fffb2773fef -[NSTextView(NSPrivate) _giveUpFirstResponder:] + 261 11 AppKit 0x00007fffb25d42b7 -[NSTextView doCommandBySelector:] + 192 12 AppKit 0x00007fffb25d41d1 -[NSTextInputContext(NSInputContext_WithCompletion) doCommandBySelector:completionHandler:] + 118 13 AppKit 0x00007fffb25b1e00 -[NSKeyBindingManager(NSKeyBindingManager_MultiClients) interpretEventAsCommand:forClient:] + 2218 14 AppKit 0x00007fffb2df37b1 __84-[NSTextInputContext _handleEvent:options:allowingSyntheticEvent:completionHandler:]_block_invoke.1096 + 355 15 AppKit 0x00007fffb2df35e5 __84-[NSTextInputContext _handleEvent:options:allowingSyntheticEvent:completionHandler:]_block_invoke_3 + 80 16 AppKit 0x00007fffb25b9f59 -[NSTextInputContext tryHandleEvent_HasMarkedText_withDispatchCondition:dispatchWork:continuation:] + 93 17 AppKit 0x00007fffb2df3560 __84-[NSTextInputContext _handleEvent:options:allowingSyntheticEvent:completionHandler:]_block_invoke.1086 + 262 18 HIToolbox 0x00007fffb3eb689f __TSMProcessRawKeyEventWithOptionsAndCompletionHandler_block_invoke_5 + 70 19 HIToolbox 0x00007fffb3eb56e2 ___ZL23DispatchEventToHandlersP14EventTargetRecP14OpaqueEventRefP14HandlerCallRec_block_invoke + 108 20 AppKit 0x00007fffb2dec4f8 __55-[NSTextInputContext handleTSMEvent:completionHandler:]_block_invoke.314 + 2874 21 AppKit 0x00007fffb25b3835 __55-[NSTextInputContext handleTSMEvent:completionHandler:]_block_invoke_2 + 80 22 AppKit 0x00007fffb25b37b4 -[NSTextInputContext tryHandleTSMEvent_HasMarkedText_withDispatchCondition:dispatchWork:continuation:] + 93 23 AppKit 0x00007fffb25b319f -[NSTextInputContext handleTSMEvent:completionHandler:] + 2221 24 AppKit 0x00007fffb25b2883 _NSTSMEventHandler + 321 25 HIToolbox 0x00007fffb3e5bd85 _ZL23DispatchEventToHandlersP14EventTargetRecP14OpaqueEventRefP14HandlerCallRec + 1708 26 HIToolbox 0x00007fffb3e5aff6 _ZL30SendEventToEventTargetInternalP14OpaqueEventRefP20OpaqueEventTargetRefP14HandlerCallRec + 428 27 HIToolbox 0x00007fffb3e5ae3f SendEventToEventTargetWithOptions + 43 28 HIToolbox 0x00007fffb3eb26d6 SendTSMEvent_WithCompletionHandler + 408 29 HIToolbox 0x00007fffb3eb2bb1 __SendUnicodeTextAEToUnicodeDoc_WithCompletionHandler_block_invoke + 400 30 HIToolbox 0x00007fffb3eb2a12 __SendFilterTextEvent_WithCompletionHandler_block_invoke + 215 31 HIToolbox 0x00007fffb3eb2727 SendTSMEvent_WithCompletionHandler + 489 32 HIToolbox 0x00007fffb3eb2511 SendFilterTextEvent_WithCompletionHandler + 236 33 HIToolbox 0x00007fffb3eb21d6 SendUnicodeTextAEToUnicodeDoc_WithCompletionHandler + 284 34 HIToolbox 0x00007fffb3eb1f8c __utDeliverTSMEvent_WithCompletionHandler_block_invoke_2 + 296 35 HIToolbox 0x00007fffb3eb1e32 __utDeliverTSMEvent_WithCompletionHandler_block_invoke + 439 36 HIToolbox 0x00007fffb3eb1bf9 TSMKeyEvent_WithCompletionHandler + 632 37 HIToolbox 0x00007fffb3eb1948 __TSMProcessRawKeyEventWithOptionsAndCompletionHandler_block_invoke_4 + 251 38 HIToolbox 0x00007fffb3eb1775 __TSMProcessRawKeyEventWithOptionsAndCompletionHandler_block_invoke_3 + 281 39 HIToolbox 0x00007fffb3eb148b __TSMProcessRawKeyEventWithOptionsAndCompletionHandler_block_invoke_2 + 308 40 HIToolbox 0x00007fffb3eb11c2 __TSMProcessRawKeyEventWithOptionsAndCompletionHandler_block_invoke + 300 41 HIToolbox 0x00007fffb3eb073a TSMProcessRawKeyEventWithOptionsAndCompletionHandler + 3604 42 AppKit 0x00007fffb2df33d1 __84-[NSTextInputContext _handleEvent:options:allowingSyntheticEvent:completionHandler:]_block_invoke.1077 + 116 43 AppKit 0x00007fffb2df2689 __204-[NSTextInputContext tryTSMProcessRawKeyEvent_orSubstitution:dispatchCondition:setupForDispatch:furtherCondition:doubleSpaceSubstitutionCondition:doubleSpaceSubstitutionWork:dispatchTSMWork:continuation:]_block_invoke.1003 + 121 44 AppKit 0x00007fffb2df24f3 -[NSTextInputContext tryTSMProcessRawKeyEvent_orSubstitution:dispatchCondition:setupForDispatch:furtherCondition:doubleSpaceSubstitutionCondition:doubleSpaceSubstitutionWork:dispatchTSMWork:continuation:] + 285 45 AppKit 0x00007fffb2df2e1b -[NSTextInputContext _handleEvent:options:allowingSyntheticEvent:completionHandler:] + 1515 46 AppKit 0x00007fffb2df2362 -[NSTextInputContext _handleEvent:allowingSyntheticEvent:] + 114 47 AppKit 0x00007fffb25b128b -[NSView interpretKeyEvents:] + 232 48 AppKit 0x00007fffb25b10a1 -[NSTextView keyDown:] + 704 49 AppKit 0x00007fffb2d132cc -[NSWindow(NSEventRouting) _reallySendEvent:isDelayedEvent:] + 4086 50 AppKit 0x00007fffb2d11f0a -[NSWindow(NSEventRouting) sendEvent:] + 541 51 AppKit 0x00007fffb2b974a8 -[NSApplication(NSEvent) sendEvent:] + 4768 52 AppKit 0x00007fffb2411427 -[NSApplication run] + 1002 53 AppKit 0x00007fffb23dbe0e NSApplicationMain + 1237 54 Programm 0x000000010001388d main + 13 55 libdyld.dylib 0x00007fffca4d1235 start + 1 56 ??? 0x0000000000000003 0x0 + 3 ) A: Problem solved!! in the EndEditing i expected an selected row. but if i add a row, this row isn't selected. i add the following line to my addRow function and now it works: tableView.selectRowIndexes(IndexSet(integer: tableView.numberOfRows-1), byExtendingSelection: false)
{ "pile_set_name": "StackExchange" }
Q: invoke an instance of a class by its type I am trying to write a generic method that will accept any type and create its instance so that I can use it later: Example of a class that I want to dynamically generate: public class bb_ColorScaleCriteriaTypes { public Dictionary<string, int> Types { get; set; } public bb_ColorScaleCriteriaTypes() { this.Types = new Dictionary<string, int>() { {"LowestValue", 1}, {"Number", 0}, {"Percent", 3}, {"Formula", 4}, {"Percentile", 5}, {"HighestValue", 2}, {"AutomaticMax", 7}, {"AutomaticMin", 6}, {"None", -1} }; } public static int byName(string name) { if (name == null) { throw new ArgumentException("name"); } int intValue = new bb_ColorScaleCriteriaTypes().Types[name]; return intValue; } } Normally I have another class that I can call like this: public class bb_ColorScaleCriteriaTypesUI : DSDropDownBase { private const string NO_FAMILY_TYPES = "No types were found."; public bb_ColorScaleCriteriaTypesUI() : base("Color Scale Criteria Type") { } // Get Data Class that holds dictionary public static bb_ColorScaleCriteriaTypes cscTypes = new bb_ColorScaleCriteriaTypes(); protected override SelectionState PopulateItemsCore(string currentSelection) { Items.Clear(); Dictionary<string, int> d = new Dictionary<string, int>(cscTypes.Types); } As you can see I am instantiating a class of bb_ColorScaleCriteriaTypes and then calling Types on it. However, I want to write a more generic implementation where I could just do something similar to this: public abstract class bb_ColorScaleCriteriaTypesUI : DSDropDownBase { public bb_ColorScaleCriteriaTypesUI (string name, Type elementType) : base(name) { this.ElementType = elementType; PopulateItems(); } private const string noTypes = "No Types available."; public Type ElementType; // how to instantiate an instance of ElementType here? protected override SelectionState PopulateItemsCore(string currentSelection) { if (this.ElementType != null) { Dictionary<string, int> d = new Dictionary<string, int>(myTypeInstance.Types); //so I can call it here } Looks like this got a little out of hand in the comments really quick. Anyways, I don't mind using the Activator.CreateInstance() but how can I create an instance of type and cast it back to the type so its not a generic object? A: Activator.CreateInstance() as the others have said. The return type is not a generic object, its the actual type you requested, its just returned as an object because that's the base class of everything. If you want to do it "the right way", you'd define an interface or base class that all your classes derive / implement from and have the common methods that you need to call generically defined in the interface / base class. Then you can either use Activator.CreateInstance() or the factory pattern to new up the objects and return them as the interface / base class.
{ "pile_set_name": "StackExchange" }
Q: How to pass a closure to send in Ruby as an argument I use send like this: [:last, :first].map { |sym| [0,1,2].send(sym) } #=> [2, 0] I am trying to pass to send a symbol of index and rindex, and a closure for their execution: [:rindex, :index].map { |sym| [0,1,2].send(sym, { |x| x %2 == 0 }) } I get an error message: SyntaxError: (irb):4: syntax error, unexpected '|', expecting '}' ...p { |sym| [0,1,2].send(sym, { |x| x %2 == 0 }) } What am I doing wrong? A: To pass the closure, one should instruct the ruby parser, that it’s a block, using an ampersand character: [ :rindex, :index ].map do |sym| [0,1,2].send(sym, &->(x){ x % 2 == 0 }) end #⇒ [2, 0] A: What am I doing wrong? In Ruby, blocks are being passed after the argument list instead of inside it: foo(1, { puts 'Hello' }) # wrong foo(1) { puts 'Hello' } # right So, your code should look like: [:rindex, :index].map {|sym| [0, 1, 2].send(sym) {|x| x %2 == 0 }} Note: you should always prefer public_send over send. send does two things at once: allow the name of the message to be dynamic, and break encapsulation. If you use send, people who read your code are never quite sure which of the two features you are actually using. In this case, you are not breaking encapsulation at all, you are only using the dynamic message name. That's exactly what public_send does. %i[rindex index].map {|meth| [0, 1, 2].public_send(meth, &:even?)} This would be a more idiomatic way to write your code.
{ "pile_set_name": "StackExchange" }
Q: FileSavePicker and deprecated ApplicationViewState In the documentation for the FileSavePicker, it states: Warning If you try to show the file picker while your app is snapped the file picker will not be shown and an exception will be thrown. You can avoid this by making sure your app is not snapped or by unsnapping it before you call the file picker. I'm currently checking to see if the app is snapped or not, and my app responds differently in each case. My default behavior isn't showing the FileSavePicker, either, so I can't just try and then fall back to something else. Nor do I want to force the app to unsnap. However, ApplicationViewState is deprecated post-8.1. In that documentation and related searching, developers are advised to access the window size directly in order to determine proper behavior. However, if the view state is no longer available, how do I know if the file picker will throw an exception or not? At what size is the app considered 'snapped'? Also, I'm using C++, so an answer compatible with C++ would be splendid. I wouldn't mind seeing the C# solution, too. A: In regards to the FileSavePicker documentation - I believe that it is just an oversight. The text you quote was from the Windows 8 version, and to me it looks like it didn't get updated for Windows 8.1. If you look at the FileOpenPicker documentation, you see that it was updated: Important In Windows 8 if you attempt to display the file picker while your app is snapped, the file picker will not be shown and an exception will be thrown. You can avoid this by making sure your app is not snapped, or by unsnapping it before you call the file picker. ...Note that Windows 8.1 does not define a specific snapped window size. Instead, users can resize apps to any width, down to the minimum. Therefore, if your app will deploy only on Windows 8.1, you can ignore the EnsureUnsnapped function and calls to it in this topic's example code. The last sentence (in bold) above essentially says that you can ignore state and safely open the file dialogs if you are running under Windows 8.1. To test the above, I used VS 2012 to create a Windows 8 application with a file save picker (in C#). I believe the outcome will be the same with C++, but I am not 100% certain. I should note that my test application does not check for view state and always tries to open a file dialog. When the application is run under Windows 8 in the snapped state, the application causes an error. That same application (same binary) when run under Windows 8.1 allows the file save dialog to open without issue. As mentioned previously there is no snapped state in Windows 8.1, so the way I tested the application was to open the application to the minimum width (320 pixels). To summarize: If you are targeting Windows 8.0, you will have to make sure the application is unsnapped prior to opening the file picker dialogs. If you are targeting Windows 8.1, you do not have to worry about state, as the file picker dialogs no longer throw any exceptions.
{ "pile_set_name": "StackExchange" }
Q: std::for_each, calling member function with reference parameter I have a container of pointers which I want to iterate over, calling a member function which has a parameter that is a reference. How do I do this with STL? My current solution is to use boost::bind, and boost::ref for the parameter. // Given: // void Renderable::render(Graphics& g) // // There is a reference, g, in scope with the call to std::for_each // std::for_each( sprites.begin(), sprites.end(), boost::bind(&Renderable::render, boost::ref(g), _1) ); A related question (from which I derived my current solution from) is boost::bind with functions that have parameters that are references. This specifically asks how to do this with boost. I am asking how it would be done without boost. Edit: There is a way to do this same thing without using any boost. By using std::bind and friends the same code can be written and compiled in a C++11-compatible compiler like this: std::for_each( sprites.begin(), sprites.end(), std::bind(&Renderable::render, std::placeholders::_1, std::ref(g)) ); A: This is a problem with the design of <functional>. You either have to use boost::bind or tr1::bind.
{ "pile_set_name": "StackExchange" }
Q: does jdbcConnection have ExceptionListener support, similar to jmsConnection? We use XA/distributed transaction, and I'm trying to notify/update global transaction status, should a participating xaResource-branch throw an exception. A good example can be found in JMS Connection#setExceptionListener(), (ref.link), which offers notification hook in the ExceptionListener. I'm looking for something similar in JDBC specification, but I haven't been able to find any. XA Transaction processing is single-threaded in our application, and a given global transaction can touch multiple xaResource-branches. Assuming UOW happens in the order of rA, rB and rC, it happens we might have a slow query running on rB, causing rA timeout before rC starts. Because of the single threaded nature (and the limitation of the TM we use), rC still proceeds while the fate of the global transaction has already been determined (to rollback). We are trying to notify the global transaction of the fact rA has already been rolled back so that rC can be skipped. If the JDBC specification doesn't offer something similar to JMS's ExceptionListener, one option I can think of would be using async thread(s) to test the JDBC connection with a certain frequency. The closest example I've found so far is described in this PostgreSQL documentation (ref.link), which uses asynchronous thread(s) to test/poll JDBC connection. It probably satisfies my need, but wondering if there's any other option I missed in the JDBC specification. A: JDBC doesn't provide this for normal connections, so that is why you can't find it. JDBC does support listeners on PooledConnection (and XAConnection) objects (ConnectionEventListener and StatementEventListener), but those listeners are for communication from the pooled connection to the pool manager (or transaction manager), and are not for general use. If you want something like this, you would need to write it yourself. For example wrap the connection in a proxy, and decorate it with something that catches exceptions, notifies a listener and rethrows the exception. Alternatively, check if your resource manager already provides support for this. However, given the single-threaded nature of your handling, I guess it would be impossible for you to detect that rA timed out while you are handling rB through something like an exception listener: the resource will be waiting for the commit, and won't communicate the timeout until you actually try to commit. Asynchronously checking connections sounds like a big race condition waiting to happen, and that even assumes that the error you are checking for is something that is verifiable in that way. A logical exception might leave the connection in a working state.
{ "pile_set_name": "StackExchange" }
Q: Forcing Stored Procedure to check before inserting data into table I created this Stored Procedure, Now what I want to do is, to always replace if a similiar type of record exists within table, here's the sp, USE [DBName] GO CREATE procedure [dbo].[InsertDD] ( @ColumnA varchar(1000), @ColumnB varchar(1000), @CurrentDateAndTime datetime ) AS INSERT Into TableName ( ColumnA, ColumnB, CurrentDateAndTime ) Values ( @ColumnA, @ColumnB, @CurrentDateAndTime ) Now If table already has Column B value (regardless of difference in letters e.g. capital or lower case) then just update CurrentDateAndTime value. If not then simply add three of the values. A: Do the update, and if it didn't find any record to update, do the insert: update TableName set CurrentDateAndTime = @CurrentDateAndTime where ColumnB = @ColumnB if (@@rowcount = 0) begin insert into TableName ( ColumnA, ColumnB, CurrentDateAndTime ) values ( @ColumnA, @ColumnB, @CurrentDateAndTime ) end
{ "pile_set_name": "StackExchange" }
Q: Como mudar estilo da DIV usando AJAX sem atualizar a pagina Estou fazendo uma atividade complementar na faculdade, e tenho que fazer um sistema para mudar o estilo da div se o problema do usuario já for resolvido ou não. Quando clicar em resolvido se a div já estiver com a class alert-danger, essa class vai mudar para alert-success. Em seguida a minha pagina e onde eu estou parado. <!DOCTYPE html> <html lang="en"> <head> <title>Formulário </title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="css/stylee.css"> <script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.js"></script> </head> <body> <?php try { $pdo = new PDO('mysql:host=localhost;dbname=agenda', 'root', ''); // define para que o PDO lance exceções caso ocorra erros $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (Exception $exc) { echo "Algum erro foi cometido".$exc->getTraceAsString(); } // pega ID via GET $id = $_GET['id']; $buscasegura= $pdo->prepare("SELECT * FROM pessoa WHERE id = :id"); $vertel = $pdo->prepare("SELECT * FROM `contatos` WHERE id_pessoa = :id"); // Busca variavel ID $buscasegura->bindValue(":id", $id); $vertel->bindValue(":id", $id); $buscasegura->execute(); $vertel->execute(); // percorre a variavel para mostrar os resultados while($linharesp=$buscasegura->fetch(PDO::FETCH_ASSOC)){ ?> <div class="container body321"> <div class="row"> <div class="jumbotron" > <h4>Ver informações de: <?php echo $linharesp["nome"];}?> </h4> <?php $consultainfo = $pdo->prepare("SELECT * FROM pessoa where id = :id"); $verregistro = $pdo->prepare('SELECT * FROM `registro` WHERE id_pessoa = :id'); $consultainfo->bindParam(':id', $id); $verregistro->bindParam(':id',$id); $consultainfo->execute(); $verregistro->execute(); while ($linha = $consultainfo->fetch(PDO::FETCH_ASSOC)) { $id = $linha['id']; $nomee = $linha['nome']; $cpff = $linha['cpf']; $empresa = $linha['empresa']; $tipo = $linha['tipo']; $ob = $linha['ob']; } ?> <h4>CPF: <?php echo "$cpff"; ?><br><br> Empresa: <?php echo "$empresa"; ?><br><br> Tipo: <?php echo "$ob"; ?></h4> </div> <br> <div class="col-md-6"> <h4>&nbsp;&nbsp;&nbsp;Informações de registros</h4> <?php //definição da variavel que ira mostrar os resultados while($linharesp=$verregistro->fetch(PDO::FETCH_ASSOC)){ // define qual a class que vai ser usada danger ou sucess $solucao = $linharesp['resolvido']; if(strcasecmp( $solucao, 'sim' ) == 0){ $class = "alert-success"; }else{ $class = "alert-danger"; } //atribui o nome da class para as divs ?> <div class="info2 <?php echo $class; ?>"> <span class="p">Forma de Comunicação:</span> <?php echo $linharesp['info']; ?><br> <span class="p">Assunto:</span> <?php echo $linharesp['assunto']; ?><br> <span class="p">Descrição:</span> <?php echo $linharesp['descricao']; ?><br> <span class="p">Resolvido?</span> <?php echo $solucao;?> </div> <div class="text-right"> <span class="p">Data/Hora:</span> <?php // aqui eu separei a data da hora $dataHoraArray = explode(" ", $linharesp['data']); // vamos separar os valores da data $dataArray = explode("-", $dataHoraArray[0]); // vamos re organizar a data $data = $dataArray[2]."-".$dataArray[1]."-".$dataArray[0]; // mostra a data completa echo $data." ".$dataHoraArray[1]; ?> <a class="label label-success text-right" href="#">Resolvido</a> </div> <hr> <?php } ?> </div> <div class="col-md-6"> <h4>Telefone(s) para contato:</h4> <div class="info2 alert-success"> <?php $linhatel = $vertel->fetchAll(PDO::FETCH_ASSOC); foreach ($linhatel as $listar){ //as faz uma variavel receber os valores de outra variavel ?> <span class="p">Número:</span><?php echo $listar["telefone"]; ?>&nbsp;&nbsp;&nbsp; <span class="p">Operadora:</span><?php echo $listar["operadora"]. "<br><br>"; } ?> </div> <br> </div> </div> <div class="row text-center"> <br><a class="btn btn-primary" href="index.php">Voltar ao inicio</a> </div> </div> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </body> </html> A: Use $('seletor_da_div').removeClass('class_antiga).addClass('nova_class)
{ "pile_set_name": "StackExchange" }
Q: $\left\lVert x \right\rVert_p$ = ($\sum_{i=1}^{n} |x_i|^p$)$^{1/p}$ and triangle inequality How can I prove that for $0 < p < 1$ the defined function $\left\lVert x \right\rVert_p$ = ($\sum_{i=1}^{n} |x_i|^p$)$^{1/p}$ for $n \geq 2$ does not fulfill the triangle inequality anymore? I know that in one dimension, the norm is simply the absolute value and the triangle inequality holds. So here I could take two unit vectors. For example, $\vec{a}$ = $(0, 1, 0)$ and $\vec{b}$ = $(2/3, 2/3, 1/3)$ But I don't really know how I can put the unit vectors into the sum above to show, that $\left\lVert a + b \right\rVert$ $\leq$ $\left\lVert a\right\rVert$ + $\left\lVert b \right\rVert$ does not hold. I have read this question yesterday night here, but it seems to be deleted, that's why I ask A: You cannot add vectors in different dimensions. Your $a$ is in $\mathbb R^{2}$ and $b$ is in $\mathbb R^{3}$ so $a+b$ has no meaning. What you are asked to show is that if you fix $n \geq 2$ then we can have vectors $a$ and $b$ in $\mathbb R^{3}$ such that $\|a+b\| >\|a\|+\|b\|$. This is very easy: take the vectors $(1,0,0,...,0)$ and $(0,1,0,...,0)$ and verify that $\|a+b\|=2^{1/p}$, $\|a\|+\|b\|=2$. Since $p<1$ we have $2^{1/p} >2$.
{ "pile_set_name": "StackExchange" }
Q: How to add reference to a non primary key column of a table in rails5 I am using Rails 5.0.1 for web development and deploying my app on Heroku. I am using postgreSQL as my database for Heroku and sqlite3 for my local development database. I need to link to an account_number column of an Accounts table to two columns in a Transactions table. The account_number column is not the primary key of Accounts table. And, the Transactions table has a column from_account, which I want to link to the account_number column in Accounts table and another column - to_account that I want to link to the same account_number column of Accounts table. The account_number is not the primary key of accounts table but it is unique. I am trying to do something like this in my migration file: create_table :transactions do |t| t.string :from_account, foreign_key: true t.string :to_account, foreign_key: true t.timestamps end add_foreign_key :transactions, column: :from_account, :accounts, column: :account_number add_foreign_key :transactions, column: :to_account, :accounts, column: :account_number and my model file looks like this: class Transaction < ApplicationRecord belongs_to :from_account, :foreign_key => 'from_account', :class_name => 'Account' belongs_to :to_account, :foreign_key => 'to_account', :class_name => 'Account' end But this gives error on both my local sqlite3 database and also on the Heroku's PostgreSQL database. How do I model something like this in Rails5. So far all the tutorials I found online only tell how to link to the primary key of the referenced table. EDIT: Maybe it is unclear from my question above, but the account_number field is already unique in the Accounts table in my database. This is the schema of my Accounts table: create_table :accounts do |t| t.string :account_number, :unique => true # Other fields t.timestamps end A: Try primary_key: class Transaction < ApplicationRecord belongs_to :from_account, :foreign_key => 'from_account', :class_name => 'Account', :primary_key => 'account_number' belongs_to :to_account, :foreign_key => 'to_account', :class_name => 'Account', :primary_key => 'account_number' end A: As Arcana's answer says, give the referenced column via :primary_key: class Transaction < ApplicationRecord belongs_to :from_account, :foreign_key => 'from_account', :class_name => 'Account', :primary_key => 'account_number' belongs_to :to_account, :foreign_key => 'to_account', :class_name => 'Account', :primary_key => 'account_number' end The language :primary_key in the belongs_to is misleading. It should really be :candidate_key or :references or :unique or primary_key_or_unique. But it isn't. It doesn't affect what the primary key in the referenced class is. Active Record Associations 4 Detailed Association Reference 4.1 belongs_to Association Reference 4.1.2 Options for belongs_to 4.1.2.6 :primary_key By convention, Rails assumes that the id column is used to hold the primary key of its tables. The :primary_key option allows you to specify a different column. (In the relational model, a foreign key references a candidate key, which is some unique (not null) column set that doesn't contain a smaller unique (not null) column set, and is some set of columns you could have picked as primary key. But in (Active Record and) SQL a PRIMARY KEY actually declares a UNIQUE NOT NULL (that might contain a smaller UNIQUE NOT NULL) and a FOREIGN KEY REFERENCES a UNIQUE NOT NULL.)
{ "pile_set_name": "StackExchange" }
Q: Quicksand how to make it dynamic with ajax load more items and then filter? I have taken script from this link: http://mode87.com/untame/demo/filteredgallery/ Now what I want is I want to make it dynamic. In my site ,when pages loads, it shows some items, and there is a button below to load more items via ajax, when more items are loaded, the filtration does not work properly. For example, pages loads with 4 item,now I click Load more, and when I again click 'all' it just shows me 4 items, but I want all the items to be displayed which have been loaded via ajax. waiting your answers my code here index.php <ul class="filter nav nav-pills"> <li data-value="all">All</li> <li data-value="1">OPENING CEREMONIES</li> <li data-value="2">PRODUCT LAUNCHES</li> <li data-value="3"> MALL SHOWS </li> <li data-value="4">FAMILY FESTIVALS</li> <li data-value="5">CULTURAL FESTIVALS</li> <li data-value="6">WORLD CLASS SHOWS</li> <li data-value="7">SPORTS EVENTS</li> <li data-value="8">GALA DINNERS</li> </ul> <ul class="thumbnails" id="loading_more"> <?php $_SESSION["page_load"] = 1; portfolioItems($_SESSION["page_load"]); ?> </ul> <div class="row-fluid"> <div class="span12 portfolio-load-more-wrapper"> <h1><span class="caption_heading">WANT TO</span> SEE MORE?</h1> <h2><span class="icon-down-open-2 gray" onClick="javascript:showMore();"></span></h2> </div> </div> When click , showMore() function: function showMore() { var data = 'load_more='+'load_more'; $.ajax({ url:'process.php', type:'post', data:data, success:function(html) { $('.thumbnails').html(html); } }); } process.php function portfolioItems($page_load) { if( $page_load == 1 ) { global $con; $item_list = ""; //Query to get the items $sql_item_details = mysqli_query($con , "SELECT * FROM portfolio_items LIMIT 4"); $count = mysqli_num_rows($sql_item_details); //If records found if( $count > 0 ) { while($row = mysqli_fetch_array($sql_item_details)) { $id = $row["id"]; $title = $row["title"]; $category = $row["category_id"]; $date = $row["date"]; $detail = $row["detail"]; $thumbnail = $row["thumbnail"]; $item_list .= '<li data-type="'.$category.'" data-id="id-1" class="span3 fancybox fancybox.iframe portfolio-iframe" onClick="javascript:showPortfolioDetail('.$id.');"> <img src="images/portfolios/portfolio_thumbs/'.$thumbnail.'" width="295" height="295" border="0"> <div class="img_hover_box"> <div class="portfolio_title"> <div class="portfolio-cpation"> <h2> <div class="arrow_icon"> <i class="icon-right-circled-1"></i> </div> <span>'.$title.'</span> </h2> </div> </div> </div> <div class="clock_year"> <span class="icon-clock-alt"></span><span class="year">'.$date.'</span> </div> </li>'; } echo $item_list; } } else { //Get the pagination value. $page_no = $page_load; $one_page = $page_no * 4; $start_from = $one_page - 4; $limit = 4; global $con; $item_list = ""; //Query to get the items $sql_item_details = mysqli_query($con , "SELECT * FROM portfolio_items LIMIT 0,".$one_page); $count = mysqli_num_rows($sql_item_details); //If records found if( $count > 0 ) { while($row = mysqli_fetch_array($sql_item_details)) { $id = $row["id"]; $title = $row["title"]; $category = $row["category_id"]; $date = $row["date"]; $detail = $row["detail"]; $thumbnail = $row["thumbnail"]; $item_list .= '<li data-type="'.$category.'" data-id="id-1" class="span3 fancybox fancybox.iframe portfolio-iframe" onClick="javascript:showPortfolioDetail('.$id.');"> <img src="images/portfolios/portfolio_thumbs/'.$thumbnail.'" width="295" height="295" border="0"> <div class="img_hover_box"> <div class="portfolio_title"> <div class="portfolio-cpation"> <h2> <div class="arrow_icon"> <i class="icon-right-circled-1"></i> </div> <span>'.$title.'</span> </h2> </div> </div> </div> <div class="clock_year"> <span class="icon-clock-alt"></span><span class="year">'.$date.'</span> </div> </li>'; } echo $item_list; } } } A: Ok i think i get it. If you look at the js code , after function gallery(){} youre gonna see the codes for filtering operations like this: var $itemsHolder = $('ul.thumbnails'); var $itemsClone = $itemsHolder.clone(); var $filterClass = ""; $('ul.filter li').click(function(e) { e.preventDefault(); $filterClass = $(this).attr('data-value'); if($filterClass == 'all'){ var $filters = $itemsClone.find('li'); } else { var $filters = $itemsClone.find('li[data-type='+ $filterClass +']'); } $itemsHolder.quicksand( $filters, { duration: 1000 }, gallery ); }); Now this is setting filters when the page was first load so since new added items arent gonna be in $itemsHolder list, further filtering is not gonna involve new added items. What you need to do is wrap this code in a function like: function gallery_filter() { var $itemsHolder = $('ul.thumbnails'); ..... } And then call this function after ajax succes: success:function(html) { $('.thumbnails').html(html); gallery_filter(); // here }
{ "pile_set_name": "StackExchange" }
Q: EF Core "no migrations found" despite Migrations folder containing migration files We have a .NET Core project set up with a Migrations folder containing several migrations that we were able to successfully run in our Development database in the past by executing dotnet ef database update. However, we are now trying to apply those changes to our Staging database and it isn't working. We've set our ASPNETCORE_ENVIRONMENT env variable to Staging and when we attempt to run the migrations, it seems like it is targeting Staging properly. A dbo.__EFMigrationsHistory table is created in our Staging database, but there are no entries in it. Also, when we run dotnet ef migrations list, we get a message that says "No migrations were found." Even if we set the ASPNETCORE_ENVIRONMENT variable back to Development, we get the same result. We've run all the above dotnet ef commands with the verbose flag and haven't gotten any errors. The only output that seems like it could be suspicious is No referenced design-time services were found and No design-time services were found, but we weren't able to determine what we need to do to fix these issues. When we run dotnet ef migrations add <migration name>, it successfully generates a migration file in the Migrations folder, and when we run dotnet ef migrations list that new migration shows up, so it seems like our older migrations are in the correct place. They just aren't being detected by dotnet ef for some reason. We have the following packages in our .csproj: <PackageReference Include="FlexLabs.EntityFrameworkCore.Upsert" Version="3.1.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.0"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="3.1.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.0" /> <PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.0" /> <PackageReference Include="Newtonsoft.Json" Version="9.0.1" /> <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.113"> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <PrivateAssets>all</PrivateAssets> </PackageReference> <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.0" /> Any thoughts on why we can't get our existing migrations to run? A: It turns out this error was because of the lack of Designer.cs files. We deleted them due to the response in this post, but EF was not able to find our migrations without them. If you plan on running your migrations in any other environments, don't delete your Designer files!
{ "pile_set_name": "StackExchange" }
Q: Redirecting page if client doesn't have silverlight runtime I want to identify, whether the client accessing a silverlight web application have silverlight runtime installed, if not i want to redirect to an aspx page showing reasons for failing to run the application ( instead of the messagebox telling missing silverlight plugin). How to do this ? A: This Javascript provides a warning I am sure it can be changed to redirect user instead function hasSilverlightPlugin() { var slplugin = false; var browser = navigator.appName; // Get the browser type if (browser == 'Microsoft Internet Explorer') { try { var slControl = new ActiveXObject('AgControl.AgControl'); if (slControl) { slplugin = true; } } catch (e) { } } else { // Netscape, FireFox, Google chrome etc try { if (navigator.plugins["Silverlight Plug-In"]) { slplugin = true; } } catch (e) { } } return slplugin; } /** This function checks the browser to see if Silverlight has been installed. * The display informing the user that his/her browser is lacking the plugin * is shown in the Announcements section of the desktop tab. */ function silverlightAnnouncementWarning() { var elem = null; var hasPlugin = hasSilverlightPlugin(); elem = document.getElementById("SilverlightWaringElem"); if (!hasPlugin) { if (elem) { elem.style.display = ""; var warningMsg = "WARNING THE SILVERLIGHT PLUGIN IS NOT INSTALLED ON THIS MACHINE" elem.innerHTML = warningMsg; } } //64 bit silverlight warning if (navigator.platform == "Win64") { if (elem) { var warningMsg = "64 bit browser has been detected which is currently incompatible with Silverlight" elem.style.display = ""; var msg = elem.innerHTML; if (msg && msg.length > 0) { warningMsg = msg + " (also a " + warningMsg + ")"; } else { warningMsg = "A " + warningMsg; } elem.innerHTML = warningMsg; } } } function popupSilverlightWarning() { var hasPlugin = hasSilverlightPlugin(); if (!hasPlugin) { var warningMsg = "THE SILVERLIGHT PLUGIN IS NOT INSTALLED ON THIS MACHINE!\n"; warningMsg += "This page requires the Silverlight plugin in order to work.\n"; warningMsg += "Please contact your Systems Administrator to have the Silverlight plugin installed on this computer.\n"; warningMsg += "Thank you . . ."; alert(warningMsg); } }
{ "pile_set_name": "StackExchange" }
Q: Dropdown at the end of Model dialog Edit: Opening up a dropdown (placed right at bottom of dialog) in JDialog (with modal behavior), doesn't display the entire dropdown. I have tried z-index, but still not working. A: Try to use style="height: 50px;" Alsom can you please post some code? maybe we can help better! try THIS and THIS and THIS
{ "pile_set_name": "StackExchange" }
Q: How to add dynamic sql query in JPA query annotation in spring boot? I want to add a sorting column in the query at run time. I have used query annotation for build query. I have used param "sortCol" for adding a sort column in the query. But somehow query annotation not recognize the "sortCol" parma and hence not using it. Not giving any error as well. SELECT * FROM request r WHERE r.asset_type IN ( ?, ?, ? ) AND r.request_type IN ( ?, ? ) AND r.status IN ( ?, ?, ?, ? ) AND r.assign_to = ? AND ( r.request_custom_id LIKE ? OR r.project_name LIKE ? OR r.asset_type LIKE ? OR r.request_type LIKE ? ) ORDER BY ? limit ?" In this after the order by column name is missing, which I have added. At the run time: @Query(value ="SELECT * FROM request r WHERE r.asset_type IN (:assetType) AND r.request_type IN (:requestType) AND r.status IN (:statusList) AND r.assign_to = :assignTo AND ( r.request_custom_id LIKE %:searchTerm% OR r.project_name LIKE %:searchTerm1% OR r.asset_type LIKE %:searchTerm2% OR r.request_type LIKE %:searchTerm3% ) ORDER BY :sort",nativeQuery = true) Page<Request> findRequestdata(Pageable pageable, @Param("assetType") List<String> assetType, @Param("requestType") List<String> requestType, @Param("statusList") List<Integer> statusList, @Param("assignTo") Long assignTo, @Param("searchTerm") String searchTerm, @Param("searchTerm1") String searchTerm1, @Param("searchTerm2") String searchTerm2, @Param("searchTerm3") String searchTerm3, @Param("sort") String sortCol); All parma is setting properly except "sortCol". Please suggest where am missing anything. A: You are already passing a Pageable object to your method. So when you create the paging you can also add sorting: Pageable sortedByName = PageRequest.of(0, 3, Sort.by("name")); findRequestdata(sortedByName, ...) Read more here: https://www.baeldung.com/spring-data-jpa-pagination-sorting
{ "pile_set_name": "StackExchange" }
Q: Inverting without actual inverse? I'm reading Ash's "Basic Abstract Algebra" and been trying to understand the following: For which I guess the problem lies when we try to take an element $hk\in HK$, it's inverse is $k^{-1}h^{-1}$ but $k^{-1}h^{-1}\in HK$ only if $k^{-1}h^{-1}=h^{-1} k^{-1}$. My problem is the following, taking the definition of subgroup, we have: If $a,b\in H$, then $ab^{-1}\in H$. Then, all the elements $k\cdot1=k$ and $1\cdot h=h$ are in $HK$, that is: We have all the elements of both $H,K$ in $HK$. By the definition, suppose we have $hk\in HK$, then we must have $(hk)(k^{-1})$ and $(hkk^{-1})(h^{-1})$. Isn't this very similar to having the inverse of $hk$ in $HK$? It's a bit odd because it seems we can actually invert $hk$ by performing the two operations I mentioned before but $(hk)^{-1}$ is not actually in $HK$. A: $\newcommand{\Span}[1]{\left\langle #1 \right\rangle}$Allow me first of all to question your statement when we try to take an element $hk\in HK$, its inverse is $k^{-1}h^{-1}$ but $k^{-1}h^{-1}\in HK$ only if $k^{-1}h^{-1}=h^{-1} k^{-1}$. This is not true. Take for instance $G = S_{3}$, $H = \Span{(1 2)}$, $K = \Span{(1 2 3)}$, $h = (1 2)$, $k = (1 2 3)$. Then $h^{-1} k^{-1} = (2 3) \ne (1 3) = k^{-1} h^{-1} \in H K = S_{3}$. As to your second statement suppose we have $hk\in HK$, then we must have $(hk)(k^{-1})$ and $(hkk^{-1})(h^{-1})$. Isn't this very similar to having the inverse of $hk$ in $HK$? I fail to see the point. Sure, $h k$ has an inverse $k^{-1} h^{-1}$ in $G$, and that's what you are checking. But to show that $H K$ is a subgroup you will have to show that (under suitable conditions) this inverse lies precisely in $H K$.
{ "pile_set_name": "StackExchange" }
Q: Difference between onActivated and onHighlighted? I'm having trouble understanding the difference between the two. onActivated: Fires when the active tab in a window changes. http://developer.chrome.com/extensions/tabs.html#event-onActivated onHighlighted: Fired when the highlighted or selected tabs in a window changes. http://developer.chrome.com/extensions/tabs.html#event-onHighlighted A: In Chrome, the user can 'highlight' more than one tab by holding the Shift or Ctrl keys and clicking on the tabs (the usual rules apply, Shift extends the selection, Ctrl toggles it). When there is more than one tab highlighted, the context menu for the tabs changes so that some actions are in plural (for instance, 'Close tabs' instead of 'Close tab'). In contrast, there is always exactly one active tab per window, which in addition is always highlighted. The different events refer to these two different concepts.
{ "pile_set_name": "StackExchange" }
Q: How can I implement complicated macros like `format_args!` in user space? I like that Rust comes with a lot of macros which moves computation to compile-time instead of repeatably to run-time. print! and all its variants using format_args! See source code are great examples. Unfortunately, in the source code you see the comment /* compiler built-in */ instead of a implementation direct in the source file. Does Rust have the capability to let the user write such complex logic as a macro as well? If so, how can I do so? A: Complex macros are usually implemented as procedural macros, which you can learn more about in The Rust Programming Language or in The Rust Reference books. You can also achieve very complex things with the so called declarative macros, look at the excellent The Little Book of Rust Macros. There are several talks about these on YouTube, but you may find the following in particular very interesting, which was given at the RustConf 2018, My Little Procedural Macro by Chris Wong:
{ "pile_set_name": "StackExchange" }
Q: Find global minimum of equation with many local minima How can I find global minimum for the function: (what is the function name?) ff[x_] := 0.01*(x + 20) + 0.001*(x + 20)^2 + Sin[(x + 20)] + 20 Plot[ff[x],{x,-222,222}] A: As a supplement to the solution of rhermans ff[x_]= 0.01*(x + 20) + 0.001*(x + 20)^2 + Sin[(x + 20)] + 20; tab = Table[{x, ff[x]}, {x, -222, 222, 0.001}]; {x, ff} = MinimalBy[tab, Last] // Flatten {-27.848, 18.9831} A: Your function is a parabola plus a sinusoidal. The parabola has minimum at x-> -25 that you can find like this Minimize[0.01*(x + 20) + 0.001*(x + 20)^2 + 20, x] {19.975, {x -> -25.}} or Solve[D[0.01*(x + 20) + 0.001*(x + 20)^2 + 20, x] == 0, x] {{x -> -25.}} For your particular function, there will be many local minima, so the initial guess is important. here I use FindMinimum with an initial guess given by the minimum of the parabola. {x, ff[x]} /. FindMinimum[ff[x], {x, -25}][[2]] {-27.8483, 18.9831} Or you could use Minimize giving constrains around x->-25. Notice that without constrains it will not find the global minimum. Minimize[{ff[x], -50 < x < 0}, x] {18.9831, {x -> -27.8483}} you can see the result in a Plot by placing a Point in an Epilog Plot[ff[x], {x, -50, 0}, Epilog -> {Red, PointSize[Large], Point[{x, ff[x]} /. FindMinimum[ff[x], {x, -25}][[2]]]}]
{ "pile_set_name": "StackExchange" }
Q: Can enum parameter be optional in c#? I've used this helpful post to learn how to pass a list of Enum values as a parameter. Now I would like to know whether I can make this parameter optional? Example: public enum EnumColors { [Flags] Red = 1, Green = 2, Blue = 4, Black = 8 } I want to call my function that receives the Enum param like this: DoSomethingWithColors(EnumColors.Red | EnumColors.Blue) OR DoSomethingWithColors() My function should then look like what? public void DoSomethingWithColors(EnumColors someColors = ??) { ... } A: Yes it can be optional. [Flags] public enum Flags { F1 = 1, F2 = 2 } public void Func(Flags f = (Flags.F1 | Flags.F2)) { // body } You can then call your function with or without parameter. If you call it without any parameter you'll get (Flags.F1 | Flags.F2) as the default value passed to the f parameter If you don't want to have a default value but the parameter to be still optional you can do public void Func(Flags? f = null) { if (f.HasValue) { } } A: An enum is a value type, so you could use a nullable value type EnumColors?... void DoSomethingWithColors(EnumColors? colors = null) { if (colors != null) { Console.WriteLine(colors.Value); } } and then set the default value of EnumColors? to null Another solution is to set EnumColors to an unused value... void DoSomethingWithColors(EnumColors colors = (EnumColors)int.MinValue) { if (colors != (EnumColors)int.MinValue) { Console.WriteLine(colors); } }
{ "pile_set_name": "StackExchange" }
Q: Is there a way to get loan for Retired people in India to buy a house? Is there a way to get loan for Retired people in India to buy a house? Can their working son or daughter being a NRI co-sign for surety purposes? Any bank or institution that you can suggest? A: Getting a loan only in the name of the retired person is not quite impossible but is very difficult and most banks will reject your application on one pretext or another. That said, if the property is co-owned (in your case with your son/daughter) you can get loan but the loan amount cap will be mostly that of the co-owner. Your best bet to get this kind of loan is State Bank of India (SBI), in case it is an apartment project approved by SBI it would be slightly faster, however, SBI takes long to approve loans but their rate is also the least. Hope this helps
{ "pile_set_name": "StackExchange" }
Q: Increasing the size of axis labels in a Wireframe Plot I want to adjust the size of the text in the axis labels of the wireframe method in R (found in the lattice package). It seems like it should just be a matter of specifying cex.lab=2 as is the case with most other plots. However, this does not increase the font size. For example: some_data <- expand.grid(c(1:10), c(1:10)) some_data$z <- sin(some_data$Var1 + some_data$Var2) wireframe(z~Var1*Var2, some_data, scales=list(arrows=FALSE, cex=1.5), xlab='blah1', ylab='blah2', zlab='blah3') wireframe(z~Var1*Var2, some_data, scales=list(arrows=FALSE, cex=1.5), xlab='blah1', ylab='blah2', zlab='blah3', cex.lab=4) should produce a second plot with axis labels 4 times larger than the ones in the first. Instead they are identical. A: Two ways, there might be others: wireframe(z~Var1*Var2, some_data, trellis.par.set(list(axis.text=list(cex=2))), scales=list(arrows=FALSE), xlab='blah1', ylab='blah2', zlab='blah3') The canonical reference for this is Sarkar's "Lattice" text and this is described in the Parameter System chapter on pages 126-128. It also appears that you can use nested arguments within scales. Drop the par.settings call and use this instead: ..., scales=list(arrows=FALSE, axis=list(text=list(cex=2))), ...
{ "pile_set_name": "StackExchange" }
Q: How does CAS instructions guarantee atomicity According to Wiki, CAS do something like this: function cas(p : pointer to int, old : int, new : int) returns bool { if *p ≠ old { return false } *p ← new return true } Well, it seems for me that if several processors will try to execute CAS instruction with the same arguments, there can be several write attempts at the same time so it's not safe to do it anyway. Where am I wrong? A: Atomic read-compare-write instructions from multiple cores at the same time do contend with each other, but it's up to hardware to sort that out. Hardware arbitration of atomic RMW instructions is a real thing in modern CPUs, and provides some degree of fairness so that one thread spinning on lock cmpxchg can't totally block other threads doing the same thing. (Although that's a bad design: better to spin on an acquire-load and only do the CAS if it should succeed) There's no guarantee what order they happen in, which is why you need to carefully design your algorithm so that correctness only depends on that compare-and-exchange being atomic. (The ABA problem is a common pitfall). BTW, that entire block of pseudocode happens as a single atomic operation. Making a read-compare-write or read-modify-write happen as a single atomic operation is much harder for the hardware than just stores, which MESIF/MOESI handle just fine. are you sure? I thought that it's unsafe to do that because, for example, x86 doesn't guarantee atomicity of writes for non-aligned DWORDs lock cmpxchg makes the operation atomic regardless of alignment. It's potentially a lot slower for unaligned, especially on cache-line splits where atomically modifying a single cache line isn't enough. See also Atomicity on x86 where I explain what it means for an operation to be atomic.
{ "pile_set_name": "StackExchange" }
Q: How to handle signals when a Qt object isn't created through Designer? Hi I've got a spare moment so decided to look at Qt and how easily I can port my windows applications to Qt. My only real problem is a couple of controls that will need re-implementing under Qt. I've already handled the basic drawing of the control but my control creates a child scroll bar. The problem is that this scrollbar is created dynamically as part of my new Widget (i.e. m_Scrollbar is a member of the widget). How can I then respond to movement of the scrollbar. Under other circumstances this is easy as I'd just create an on_myscrollbar_sliderMoved function under my protected slots and handle it there. This does however rely on the QScrollBar being called myscrollbar. As I've created the object dynamically (i.e. not through designer) how do I capture this signal? I'm guessing this is really simple and I'm missing the obvious :) A: connect( myScrollbar, SIGNAL( <signal signature>), this, SLOT( <slot signature>)); Call connect after creating the scroll bar (I presume that you need this signal handling immediately after creating the scroll bar). I assumed myScrollbar is of type QScrollBar* and that the slot is defined as a member in your class. When myScrollbar is destroyed, the connection is removed (disconnect is called). See the documentation of QObject::connect and QObject::disconnect methods. Later edit - to be more concrete, in your code it could be: myScrollbar = new QScrollBar; // Create the scroll bar // ... add it to the layout, etc. // ... and connect the signal to your slot connect( myScrollbar, SIGNAL( sliderMoved( int)), this, SLOT( handleSliderMoved( int))); where handleSliderMoved is the slot method of your class.
{ "pile_set_name": "StackExchange" }
Q: What is easiest way to create multithreaded applications with C/C++? What is the easiest way to create multithreaded applications with C/C++? A: There is no easy way to create a multithreaded application in any language. A: unfortunately there is no easy way. Couple of options: pthread on linux, win32 api threads on windows or boost::thread library A: Just to mention it because it hasn't been mentioned: a compiler with OpenMP support (http://openmp.org/wp/)
{ "pile_set_name": "StackExchange" }
Q: How to make adjust a recipe for red velvet cake when increasing the quantity? If I'm quadrupling the recipe for a red velvet cake do I still add four times the baking soda and powder? A: I know some disagree, but I always have learned that recipes can start breaking down if more than doubling or halving. Ratios can start changing and need adjusted, and then there is the cooking time components. If I have a recipe I am happy with, and I want to greatly increase it, I normally will instead make multiple instances of the base recipe. If I want to make a cake recipe times 4 or times 6 for a large event for instance, I would instead make 4 or 6 instances and build the larger cake from them rather than risk disaster making a single large cake that did not come out right. If I had a bread recipe I like, but wanted to use it for an event, I would not try to make a loaf 6 times as large, I would make 6 loafs, and so on. Here is a discussion that gets into some of the issues of what can go wrong when trying to scale recipes and why for instance someone making a wedding cake does not make one giant cake, they make a bunch of smaller ones and build that cake. http://kitchenscience.sci-toys.com/scaling
{ "pile_set_name": "StackExchange" }
Q: What are the advantages/disadvantages of configuring JS libraries in resource files vs package.json? JavaScript libraries like Babel, Nyc, Eslint and many others allows its configurations in resources files or in package.json. For instance, babel can be configured in .babelrc file or in a babel entry in the package.json file. What are the advantages / disadvantages of each approach? A: Pros of .babelrc (or any .*rc file): Separation of concerns in files Easier to find and modify your settings (depending on how stuffed your package.json is) Some people prefer using a runcom file // personal preference Pros of package.json: Limit file bloat (you could have other .*rc files, test config files, task runner files, readmes, etc.) "Single source of truth" for app configuration Some people prefer using a package.json hack // personal preference Via - my_ledge_ends
{ "pile_set_name": "StackExchange" }
Q: headers already sent by ... Why my code is not working? I have the following code to get the number of online visitors and members: session_save_path($_SERVER['DOCUMENT_ROOT'] . '/sessions/' . (isset($_COOKIE['uid']) ? "members/" : "guests/")); if(isset($_COOKIE['uid'])){ session_id($_COOKIE['uid']); } session_start(); define("MAX_IDLE_TIME", 15); $online_guests = 0; $directory = opendir($_SERVER['DOCUMENT_ROOT'] . '/sessions/guests/'); while(false !== ($file = readdir($directory))){ $online_guests++; } $online_guests -= 2; $online_members = array(); $directory = opendir($_SERVER['DOCUMENT_ROOT'] . '/sessions/members/'); while(false !== ($file = readdir($directory))){ if($file != '.' && $file != '..'){ $online_members[] = intval(substr($file,5)); } } I tested the code from my wamp server and it worked, but when I uploaded the code to my host it gives me the following error: Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/csabi/public_html/index.php:9) in /home/csabi/public_html/track-online-users.php on line 6 A: That message means your program had some output before you called session_start. You can't send anything to the browser before that since setting the session cookie has to happen in the HTTP headers, which come before the response body. If both index.php and track-online-users.php are the same on both servers, check for blank lines before the opening <?php in both files, byte-order-marks at the start of the file, etc.
{ "pile_set_name": "StackExchange" }
Q: Access polymer-elements variables with jquery I am trying to change page with jQuery but I do not know how to access the "selected" variable. Here is what I am trying do achieve with jQuery: var tabs = document.querySelector('paper-tabs'); var pages = document.querySelector('core-animated-pages'); tabs.addEventListener('core-select', function(){ pages.selected = tabs.selected; }); And I have tried something like this: $(document).ready(function(){ $('paper-tabs').on('core-select', function(){ $('core-animated-pages').attr('selected',$(this).attr('selected')); }); }); So how do I get pages.selected and tabs.selected with jQuery? EDIT: This worked for me, but I don't believe it is the optimal answer $(document).ready(function(){ $('paper-tabs').on('core-select', function(){ $('core-animated-pages').find('section').removeClass('core-selected'); $('core-animated-pages').find('section:eq('+($(this).find('.core-selected').index())+')').addClass('core-selected'); }); }); A: I guess a hybrid will do.. $(document).on('core-select','paper-tabs', function(){ document.querySelector('core-animated-pages').selected = this.selected; });
{ "pile_set_name": "StackExchange" }
Q: Java reg exp match pattern against file names Pattern.compile("# Match a valid Windows filename (unspecified file system). \n" + "^ # Anchor to start of string. \n" + "(?! # Assert filename is not: CON, PRN, \n" + "(?: # AUX, NUL, COM1, COM2, COM3, COM4, \n" + "CON|PRN|AUX|NUL| # COM5, COM6, COM7, COM8, COM9, \n" + "COM[1-9]|LPT[1-9] # LPT1, LPT2, LPT3, LPT4, LPT5, \n" + " ) # LPT6, LPT7, LPT8, and LPT9... \n" + " +([.]txt) # followed by .txt \n" " $ # and end of string \n" + ") # End negative lookahead assertion. \n" + "[^<>:\"/\\\\|?*\\x00-\\x1F.]* # Zero or more valid filename chars.\n" + "[^<>:\"/\\\\|?*\\x00-\\x1F\\ .] # Last char is not a space or dot. \n" + " +([.]txt) # followed by .txt \n" + "$ # Anchor to end of string. ", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE| Pattern.COMMENTS); I am trying to use this pattern check to validate file names(only .txt text files), but this pattern doesn't allow file names which contain periods, eg: "a.b". Does any one suggest what i am missing? A: I think the 4th last line commented with "# Zero or more valid filename chars." should be without dot (.): + "[^<>:\"/\\\\|?*\\x00-\\x1F]* # Zero or more valid filename chars.\n" (And I'm not sure what the quantifier + in the second to last line is here for). See also Validate a file name on Windows
{ "pile_set_name": "StackExchange" }
Q: Problem while displaying activity from BroadcastReceiver Hi I have a Broadcast receiver with following code. 1. Intent i = new Intent(context, A.class); 2. i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 3. context.startActivity(i); This works fine and my activity does start, but it starts on top of my main activity i.e. B. What I want is that from my broadcast receiver I should be able start an Activity A, such that it does not start on top of B. Why B is always starting in background. What I am doing wrong. Also, to mention by activity A has Theme.Dialog. Please let me know your thoughts. A: A new activity is supposed to start on top of existing activities. If you want to start something without appearing in the activity history stack, maybe this something shouldn't be an Activity but a Service instead? Edit: I think you can change this behaviour with FLAG_ACTIVITY_NEW_TASK in conjunction with android:launchMode="singleTask" in the Manifest. (see documentation on launch mode)
{ "pile_set_name": "StackExchange" }
Q: Should the information from tags be present in the question body? For example when I'm asking a question about regex, should the question body contain information like what language I'm using or is a tag indicating that enough? I saw this question over on the RPG meta with which I agree, but I want to see if the SO community thinks otherwise. A: The tag itself is enough. There is no need to add the tag itself to the question's body, also. A: Don't force tags into body/title but don't make effort to avoid them either. While tags are enough to convey the information it is perfectly fine to have them essentially repeated in title or body of the post if natural language of either calls for it - "C# regular expression … behaves differently than PHP" is reasonable title. Definitely don't force tags into title ("[regex] [php] [validation] e-mail validation " is not acceptable) or body. On SO questions require to show your research and in most cases it means showing some code that likely will cover at least language tag and possibly one more. In case of regex posting question without regex that you believe should work is asking for downvotes/closure. As result I expect that most (if not all) tags would be naturally incorporated into the body (even if not explicitly called out). Side note: on mobile view tags are at the top of the post. If your post is really long having TL;DR section at the bottom that reiterates tags (as a proper sentence) could be beneficial.
{ "pile_set_name": "StackExchange" }
Q: ACTION_SEND Intent with custom extras causing other apps to crash I'm implementing an option for sharing content from my app. When the user presses the share button the following code is executed. public static void openShareIntent(Context context, String text, Wish wish) { Intent share = new Intent(Intent.ACTION_SEND); share.setType("text/plain"); share.putExtra(Intent.EXTRA_TEXT, text); share.putExtra("share_wish", wish); startIntent(context, share); } I'm setting one special extra for my Intent, that is object wish witch implements the Parcelable interface. This object contains some extra information. I want to use this information if the user selects my app (current app actually sharing content) from the available apps for sharing text/plain. But the problem is that all other popular apps (Facebook, Twitter, ...) and built-in apps (Messaging) crash when I include my Parcable object. It's not my applications that crashes, other apps are throwing quit unexpectedly error. When I call my SharingActivity with some extra name that is not known to this Activity, it does not crash. It just ignore that extra. Wish object source code Am I doing something wrong or what? Is this not possible because other apps don't know my Wish object? A: But the problem is that all other popular apps (Facebook, Twitter, ...) and built-in apps (Messaging) crash when I include my Parcable object. Never pass a custom Parcelable object to an app that lacks your Parcelable class definition. Is this not possible because other apps don't know my Wish object? Correct. Instead, pass an identifier (string, int, whatever) that SharingActivity can use to find your Wish from your central data model. Or, instead of creating a custom Wish, use a Bundle to represent the "wish", as Bundle has a common class definition across all apps.
{ "pile_set_name": "StackExchange" }
Q: Juntar 2 Programas - Python (3) Criei 2 programas separadamente para converter Reais em Dólares e outro para converter Dólares em reais, o que eu gostaria de fazer é criar uma espécie de menu ou input, onde estaria escrito: "Digite 1 para converter Reais em Dólares ou 2 para converter Dólares em reais" quando o usuário digitar 1, o programa inicia a variável que trabalha essa conversão, se digitar 2, outra variável é chamada na tela do usuário. Segue abaixo os 2 programas: #------------Reais P/ Dolar------------------------ Reais = float (input("Quantos reais? R$: ")) Cotação = float (input("Cotação de hoje é? ")) conversão = Reais/Cotação print("Você possui US$" , ("%.2f" % conversão)) #-----------Dolar P/ Reais------------------------- Dolar = float(input("Quantos Dolares? US$: ")) Cotação = float(input("Cotação de hoje é? ")) Conversão = Cotação*Dolar print("Você possui: R$", ("%.2f" % Conversão)) A: É uma ideia boa, e podes aplicar alguns conceitos de programação como a criação de funções para cada uma das tuas conversões Aprender sobre funções. Exemplo: def reaisParaDolar(reais, cotacao): conversao = reais / cotacao return conversao De seguida para construir o teu menu podes fazer algo deste tipo: if __name__ == '__main__': Reais = float (input("Quantos reais? R$: ")) Cotação = float (input("Cotação de hoje é? ")) operacao = int(input('1 - Reais para Dolar; 2 - Dolar para Reais') if operacao == 1: resultado = reaisParaDollar(Reais, Cotação) print("Você possui US$" , ("%.2f" % conversão)) elif operacao == 2: resultado = dolarParaReais(Reais, Cotação) print("Você possui: R$", ("%.2f" % Conversão)) else: print("Operação Inválida")
{ "pile_set_name": "StackExchange" }
Q: Onclick function not working on input elements I'm trying to 'listen' to clicks on any input field using the snippet below document.getElementsByTagName('input').onclick = function(){ console.log('clicked an input field'); } But nothing happens when I click on the input fields. I double checked to make sure that input fields are being detected with getElementsByTagName using this snippet and it shows 200 objects elems = document.getElementsByTagName('input'); console.dir(elems); Screenshot from console: Is there a reason why this would not work? I tried moving code to different sections to make sure that document is loaded when it runs. Plain javascript, not using jquery A: getElementsByTagName returns a html collection.So you need to retrieve individual element and then attach event to it. [...document.getElementsByTagName('input')].forEach((item) => { item.addEventListener('click', function() { console.log('clicked an input field'); }) }) The three dots ... is spread syntax to convert the collection to array so that array methods like forEach can be used Alternatively you can use normal for loop to attach event to the element let inputs = document.getElementsByTagName('input'); for (let i = 0; i < inputs.length; i++) { inputs[i].addEventListener('click', function() { console.log(this.id); }) } <input type='text' id='1'> <input type='text' id='2'> <input type='text' id='3'>
{ "pile_set_name": "StackExchange" }
Q: Making statements wait before being executed i have this code, which has an animation and some other statements (they are like resetting the TextBoxs and other UI Controls). what is happening is that the animation is starting with the statements at he same time, it looks weird that the users sees that the text in the TextBoxs suddenly disappers, so i want these other statements to wait some time (the animation duration) before being executed. //this is an Animation that takes me back to the home view switching = (Storyboard)this.FindResource("view_Copy1"); switching.Begin(); //I want these statments to wait until the animation is finished st1.Children.Clear(); st2.Children.Clear(); st3.Children.Clear(); st4.Children.Clear(); name.Text = lname.Text = fname.Text = mname.Text = sex.Text = bplace.Text = bday.Text = idcard.Text = socal.Text = region.Text = location.Text = telephone.Text = mobile1.Text = mobile2.Text = email1.Text = email2.Text = ctype.Text = cyear.Text = emergname1.Text = emergrelation1.Text = emergloc1.Text = emergphone1.Text = emergname2.Text = emergrelation2.Text = emergloc2.Text = emergphone2.Text = ""; region.Items.Clear(); New.IsEnabled = true; id = ""; bt_del.Visibility = Visibility.Collapsed; A: There is a Completed event that you can use and on completion you execute your code. switching.Begin(); switching.Completed += Storyboard_Completed; ... private void Storyboard_Completed(object sender, EventArgs e) { // Your code to execute after the animation completed. }
{ "pile_set_name": "StackExchange" }
Q: How do I make this div extend to 100% of the screen on mobile/tablet? EDITED FOR CLARITY Currently I have 2 divs that are side by side on DESKTOP "kt_mobile_left" and "kt_mobile_right" -- each div is 47% of the page wide. I want it so that on mobile AND tablet, the left div ("kt_mobile_left") stretches to 100% of the page and pushes "kt_mobile_right" underneath it. Right now it stays at only 47% of the page. I set a media query to make the width 100%, but it doesn't seem to be adding it to the div. Is my media query correct for this? Here's my code. <style type="text/css"> /*desktop css */ .kt_mobile_left { width: 47%; display: inline-block; vertical-align: text-top; margin-right:25px; padding: 10px; } .kt_mobile_right { width: 47%; display: inline-block;vertical-align: text-top; max-width: 457px; } /* #### Tablets or mobile css */ @media screen and (max-device-width: 867px){ .kt_mobile_left { width: 100% !important; min-width: 800px; display: block !important; margin-right: 0px; } .kt_mobile_right { width: 100% !important; float: none !important; display: block !important; } } </style> <div style="margin: 0 auto; text-align: center; margin-top: 25px; padding: 25px; width: 100%"> <div class="kt_mobile_left"> <p style="font-size: 40px; line-height: 45px; margin: 0 0 40px; position: relative; text-align: center; font-weight: 300; color: #000; text-align: left">Learn more about who may be calling or texting your teen</p> <p style="font-size: 15px; line-height: 150%; text-align: left"> TeenSafe has partnered with BeenVerified, a one-stop bakground check service, to help you learn more about the people who are calling or texting your child. Try it for just $1 for 5 days. </p> </div> <div class="kt_mobile_right"> <img src="http://storage.googleapis.com/instapage-user-media/ce3c4430/5232032-0-BeenVerified.png"> </div> </div> Here's my JSfiddle: https://jsfiddle.net/kn4xrue5/ Can anyone help? A: You have just messed up the code. I have cleaned some of your code and it seems that media queries works fine. .kt_mobile_left { background: red; width: 47%; display: inline-block; vertical-align: text-top; margin-right:25px; padding: 10px; } .kt_mobile_right { background: green; width: 47%; display: inline-block;vertical-align: text-top; max-width: 457px; } @media screen and (min-width: 320px) and (max-width: 1024px) { .kt_mobile_left { width: 100%; } .kt_mobile_right { width: 100%; } } Check out the fiddle https://jsfiddle.net/mgautam1408/xjdcqvu3/
{ "pile_set_name": "StackExchange" }
Q: How can I tag Sharepoint Documents with CRM atttributes? I have a requirement to display a SharePoint 2010 document library in an IFrame which will be hosted in a MS Dynamics CRM 4 entity form. Through the IFrame to the document library, I want to be able to add new and upload existing documents. These documents need to be tagged in SharePoint 2010 with certain CRM entity attributes. It is proposed these tags will be passed to SharePoint via the IFrame url i.e. ID1=123&ID2=456 etc. I'm thinking an application page to capture the parameters and an event receiver to tag the documents. I'm able to extract the parameters from the URL in the app page and add them to a helper class but I can't think how I can join this up with the event receiver - the event receiver can't get access to the existing instance of the helper class and using a static wont support more than 1 update at a time. The other option that comes to mind is to code all of the required New document and upload functionality and thereby have the paramrters to hand. I think I'd need to throw up a dialog when a document was being created / uploaded that the user would need to close so that I can update the metadata. I'm open to other solutions ..... A: @Robert, I tried the constructor idea and found that this: I use this url to get to a document library (note the parameter wortony=1): http://sps2010servername/Docs/Forms/AllItems.aspx?wortony=1&InitialTabId=Ribbon%2EDocument&VisibilityContext=WSSTabPersistence When I use the New document process from SharePoint the constructor fires and the HttpContext is NOT available for either the ItemAdding or ItemAdded events. This means there is no way to get at the parameters from the url. When I use the upload a document process from SharePoint the constructor fires and the HttpContext IS available, however, the current.Request.Url.AbsoluteUri is set to this http://sps2010servername/_layouts/UploadEx.aspx?List=%7bF6996215-B603-438B-BE72-4E658DFF3292%7d&RootFolder=&IsDlg=1 As you can see the result is that the url no longer resembles the url and the point is that the wortony=1 is missing from the url. In the end I went for an additionalpagehead delegate control which is included on every site page (via the masterpage). The control can get at and parse the query string and pops the params into the HttpRuntimeCache under the users login id. The event receiver then pops the params out via the ListItem["Created By"] property and sets them accordingly. This seems to be a solution.
{ "pile_set_name": "StackExchange" }