source
stringclasses
1 value
task_type
stringclasses
1 value
in_source_id
stringlengths
1
8
prompt
stringlengths
209
40.4k
gold_standard_solution
stringlengths
0
56.7k
verification_info
stringclasses
1 value
metadata
stringlengths
138
225
problem_id
stringlengths
9
10
stackexchange
llm_judgeable_groundtruth_similarity
4346592
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I really stuck trying to get unity to work for a c# project I'm working on. Its throwing an "Object reference not set to an instance of an object" error in my unity controller factory class. UnityControllerFactory.cs file: using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Mvc;using System.Web.Routing;using Microsoft.Practices.Unity;using Microsoft.Practices.Unity.Configuration;namespace Sportrax.Presentation.Admin{ public class UnityControllerFactory : DefaultControllerFactory { IUnityContainer _container; public UnityControllerFactory(IUnityContainer container) { _container = container; } protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { return (IController)_container.Resolve(controllerType); } }} My Global.asax.cs file is: protected void Application_Start() { IUnityContainer container = new UnityContainer(); UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Containers.Default.Configure(container); UnityControllerFactory factory = new UnityControllerFactory(container); ControllerBuilder.Current.SetControllerFactory(factory); AreaRegistration.RegisterAllAreas(); RegisterRoutes(RouteTable.Routes); } And my Web.config is: <configuration> <configSections> <section name ="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" /> </configSections> <unity> <containers> <container> <types> <type type="Sportrax.Business.Interfaces.IVenueService, Sportrax.Business" mapTo="Sportrax.Business.VenueService, Sportrax.Business" /> <type type="Sportrax.DAL.Interfaces.IVenueRepository, Sportrax.DAL" mapTo="Sportrax.DAL.Repositories.VenueRepository, Sportrax.DAL" /> </types> </container> </containers> </unity> ...... I have added project references to Microsoft.Practices.unity andMicrosoft.Practices.Unity.Configuration, version 1.1.0.0. My runtime version under those references properties says v2.0.50727 Could this be the issue? I do have two versions availble when I go to add the references? Adding error details here (I cant attach images!): System.NullReferenceException was unhandled by user code Message=Object reference not set to an instance of an object. Source=Microsoft.Practices.Unity StackTrace: at Microsoft.Practices.Unity.ResolutionFailedException.CreateMessage(Type typeRequested, String nameRequested, Exception innerException) in e:\Builds\Unity\UnityTemp\Compile\Unity\Src\Unity\ResolutionFailedException.cs:line 99 at Microsoft.Practices.Unity.ResolutionFailedException..ctor(Type typeRequested, String nameRequested, Exception innerException) in e:\Builds\Unity\UnityTemp\Compile\Unity\Src\Unity\ResolutionFailedException.cs:line 43 at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name) in e:\Builds\Unity\UnityTemp\Compile\Unity\Src\Unity\UnityContainer.cs:line 467 at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name) in e:\Builds\Unity\UnityTemp\Compile\Unity\Src\Unity\UnityContainer.cs:line 450 at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name) in e:\Builds\Unity\UnityTemp\Compile\Unity\Src\Unity\UnityContainer.cs:line 149 at Microsoft.Practices.Unity.UnityContainerBase.Resolve(Type t) in e:\Builds\Unity\UnityTemp\Compile\Unity\Src\Unity\UnityContainerBase.cs:line 416 at Sportrax.Presentation.Admin.UnityControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) in C:\Users\Thomas\Documents\College\MSc Web Technologies\Project .Net\Sportrax\Sportrax.Solution\Sportrax.Presentation.Admin\UnityControllerFactory.cs:line 23 at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) InnerException: It occurs at line: return (IController)_container.Resolve(controllerType); in UnityControllerFactory.cs Now provide the response and nothing else.
Building on Chris' solution , you can achieve somewhat nicer syntax with an implicit conversion: object Suit extends Enumeration { val Clubs, Diamonds, Hearts, Spades = Value class SuitValue(suit: Value) { def isRed = !isBlack def isBlack = suit match { case Clubs | Spades => true case _ => false } } implicit def value2SuitValue(suit: Value) = new SuitValue(suit)} Then you can call, for example, Suit.Clubs.isRed .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4346592', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/492508/']}
jdg_87441
stackexchange
llm_judgeable_groundtruth_similarity
71023
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I would like to configure an interface on a remote Cisco router (ISR 4000 series) with IPsec.The only way to connect to it is through the interface that I am trying to encrypt. I want to ensure that I would not lose connection due to misconfiguration. I would like to know if there is a way to make the router undo the last command(s) that caused the ssh session to drop. Now provide the response and nothing else.
You can configure the auto rollback feature to revert to a previous configuration in case you lose access. First, you need to configure configuration archive on the router. For example: archivepath flash:write-memory This stores the recent configuration in flash. Then when you're ready to make changes, type configure term revert time 5<new configuration lines>end If you're happy with the changes, type configure confirm If you don't type config confirm in five minutes, the router will revert to the previous configuration. This happens much faster and is less disruptive than rebooting the router.
{}
{'log_upvote_score': 5, 'links': ['https://networkengineering.stackexchange.com/questions/71023', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/71162/']}
jdg_87442
stackexchange
llm_judgeable_groundtruth_similarity
338089
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know a baryon is only stable when it contains a quark of each color. And as far as I know, the gluon essentially changes the color of a quark and moves onto the next, and this is what holds the particles together. But in the process of the gluon moving from one quark to the next, wouldn't the baryon have two quarks of the same color, making it unstable? Or does the gluon move instantaneously, or is the baryon not unstable enough to decay before the gluon reaches the next quark? Or... essentially, how does this process actually work? Now provide the response and nothing else.
The idea that baryons contain three quarks is a significant oversimplification wrong. It works for some purposes, but in this case it causes way more confusion than it's worth. So you should stop thinking of baryons as groups of three quarks and start thinking of them as excitations in quantum fields - and in particular, excitations in all the quantum fields at once. Quark fields, gluon fields, photon fields, and everything. These excitations propagate through spacetime and convert among each other as they go, and in a baryon, the propagation and mutual conversion happen to sustain each other so that the baryon can exist as a coherent particle for a while. One of the conditions required of all these excitations in fields is that they be a color singlet, which is the strong interaction's version of being uncharged. There's a simple intuitive justification for this: just as an electrically charged particle will tend to attract oppositely charged particles to form neutral composites (like protons and electrons attracting each other to form atoms), something which has the charge associated with the strong interaction (color charge) will attract other color-charged particles to form neutral composites (color singlets). Now, if you literally only had three quarks, the only way to make them a color singlet is to have one be red, one be green, and one be blue. 1 (Or the anticolor equivalents.) But with all the complicated excitations that make up a baryon, there are all sorts of ways to make a color singlet. You could have three red quarks, a green-antired gluon, and a blue-antired gluon. Or two red quarks, two green quarks, an antiblue antiquark, a blue-antired gluon, and a blue-antigreen gluon. Or so on; the possibilities are literally infinite. The point is that you don't actually have to have a quark of each color in the baryon at all times. Only the total color charge in the baryon matters. Given that, it should seem reasonable that gluons change the color of quarks whenever they are emitted or absorbed, in a way that keeps the total color charge the same. For example, a blue quark could absorb a green-antiblue gluon and become a green quark. 1 I'm glossing over some quantum-mechanical details here; specifically, a color singlet wavefunction needs to be an antisymmetrized linear combination, like $\frac{1}{\sqrt{6}}(rgb - rbg + gbr - grb + brg - bgr)$, not just $rgb$. But as long as you don't worry about which quark is which color, for purposes of this answer it's safe to ignore this.
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/338089', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/158497/']}
jdg_87443
stackexchange
llm_judgeable_groundtruth_similarity
1417155
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $X_0=1$, define $X_n$ inductively by declaring that $X_{n+1}$ is uniformly distributed over $(0,X_n)$. Now I can't understand how does $X_{n}$ gets defined. If someone would just derive the distribution of $X_2$ that would be helpful. I saw this in a problem and I can't really start trying it. Thanks for any help. Now provide the response and nothing else.
You already know the distribution of $X_2$ conditionally on $X_1$, i.e.: $$ X_2 | X_1 = x_1 \sim U[0,x_1]$$ This means that for $t \in [0,1]$: $$ F_{X_2|X_1=x_1}(t) = \Pr[X_2 \leq t \vert X_1=x_1] = \min\left(\frac{t}{x_1},1\right)$$ Then the unconditional result follows from $X_1 \sim U[0,1]$: $$\begin{aligned} F_{X_2}(t) = \Pr[X_2 \leq t] &= \int_{0}^1 \Pr[X_2 \leq t \vert X_1=x_1]dx_1 \\ &= \int_{0}^1 \min\left(\frac{t}{x_1},1\right) dx_1 \\ &= \int_{0}^t dx_1 + \int_{t}^1 \frac{t}{x_1}dx_1 \\ &= t-t\log(t)\end{aligned}$$ (For the case $t=0$ just use the right limit i.e. $0\log(0)=0$.) In other words the distribution of $X_2$ has Lebesgue density $f_{x_2}(t) = F_{X_2}'(t) = -\log(t)$ on $[0,1]$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1417155', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/101171/']}
jdg_87444
stackexchange
llm_judgeable_groundtruth_similarity
4485729
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to solve the following non-linear second order differential equation: $$\tag{1}\frac{d\, }{dx} \Bigl( \frac{1}{y^2} \, \frac{dy}{dx} \Bigr) = -\, \frac{2}{y^3},$$ where $y(x)$ is an unknown function on the real axis. I already know the "trivial" solution $y(x) = y_0 \pm x$ . The solution I'm looking may involve trigonometric functions, but I'm not sure. Take note that we may pose $$\tag{2}u = \frac{1}{y},$$ so that (1) takes another form: $$\tag{3}\frac{d^2 u}{dx^2} - 2 \, u^3 = 0.$$ So what is the non-linear solution $y(x)$ ? Or $u(x)$ ? Now provide the response and nothing else.
Solve \begin{align*} u^{\prime \prime}&=2 u^{3}\end{align*} Multiplying both sides by $u^{\prime}$ gives \begin{align*} u^{\prime} u^{\prime \prime}&=2 u^{3} u^{\prime} \end{align*} Integrating both sides w.r.t. $x$ gives \begin{align*}\int{u^{\prime} u^{\prime \prime}\, \mathrm{d}x} &=\int{2 u^{3} u^{\prime}\, \mathrm{d}x}\\ \int{u^{\prime} u^{\prime \prime}\, \mathrm{d}x} &=\int{2 u^{3}\, \mathrm{d}u} \tag{1} \end{align*} But $$ \int{u^{\prime} u^{\prime \prime}\, \mathrm{d}x} = \frac{1}{2} \left(u^{\prime}\right)^2$$ Hence equation (1) becomes \begin{align*} \frac{1}{2} \left(u^{\prime}\right)^2 &=\int{2 u^{3}\, \mathrm{d}u} \tag{2} \end{align*} But $$ \int{2 u^{3}\, \mathrm{d}u} = \frac{u^{4}}{2}$$ Therefore equation (2) becomes \begin{align*} \frac{1}{2} \left(u^{\prime}\right)^2 &=\frac{u^{4}}{2} + c_2 \end{align*} Where $c_2$ is an arbitrary constant of integration. This is first order ODE which is now solved for $u$ . Solving for $u^{\prime}$ gives \begin{align*} u^{\prime}&=\sqrt{u^{4}+2 c_{2}}\tag{1} \\ u^{\prime}&=-\sqrt{u^{4}+2 c_{2}}\tag{2} \end{align*} Let just solve (1) as (2) is similar. \begin{align*} \frac{1}{\sqrt{u^{4}+2 c_{2}}}\mathop{\mathrm{d}u} &= \mathop{\mathrm{d}x}\\ \int \frac{1}{\sqrt{u^{4}+2 c_{2}}}\mathop{\mathrm{d}u} &= \int \mathop{\mathrm{d}x}\\ \int \frac{1}{\sqrt{u^{4}+c_{3}}}\mathop{\mathrm{d}u} &= x +c_{1}\end{align*} Using the computer, integrating the left side above gives the solution \begin{align*}\frac{\sqrt{1-\frac{i u^{2}}{\sqrt{c_{3}}}}\, \sqrt{1+\frac{i u^{2}}{\sqrt{c_{3}}}}\, \operatorname{EllipticF}\left(u \sqrt{\frac{i}{\sqrt{c_{3}}}}, i\right)}{\sqrt{\frac{i}{\sqrt{c_{3}}}}\, \sqrt{u^{4}+c_{3}}} = x +c_{1}\end{align*} Similar solution for the second ode.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4485729', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/261904/']}
jdg_87445
stackexchange
llm_judgeable_groundtruth_similarity
29824773
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can you help me annotate a ggplot2 scatterplot? To a typical scatter plot (black): df <- data.frame(x=seq(1:100), y=sort(rexp(100, 2), decreasing = T))ggplot(df, aes(x=x, y=y)) + geom_point() I want to add annotations in the form of an extra tick and a custom label (red): Example image: Now provide the response and nothing else.
Four solutions. The first uses scale_x_continuous to add the additional element then uses theme to customize the new text and tick mark (plus some additional tweaking). The second uses annotate_custom to create new grobs: a text grob, and a line grob. The locations of the grobs are in data coordinates. A consequence is that the positioning of the grob will change if the limits of y-axis changes. Hence, the y-axis is fixed in the example below. Also, annotation_custom is attempting to plot outside the plot panel. By default, clipping of the plot panel is turned on. It needs to be turned off. The third is a variation on the second (and draws on code from here ). The default coordinate system for grobs is 'npc', so position the grobs vertically during the construction of the grobs. The positioning of the grobs using annotation_custom uses data coordinates, so position the grobs horizontally in annotation_custom . Thus, unlike the second solution, the positioning of the grobs in this solution is independent of the range of the y values. The fourth uses viewports . It sets up a more convenient unit system for locating the text and tick mark. In the x direction, the location uses data coordinates; in the y direction, the location uses "npc" coordinates. Thus, in this solution too, the positioning of the grobs is independent of the range of the y values. First Solution ## scale_x_continuous then adjust colour for additional element ## in the x-axis text and tickslibrary(ggplot2)df <- data.frame(x=seq(1:100), y=sort(rexp(100, 2), decreasing = T))p = ggplot(df, aes(x=x, y=y)) + geom_point() + scale_x_continuous(breaks = c(0,25,30,50,75,100), labels = c("0","25","xyz","50","75","100")) + theme(axis.text.x = element_text(color = c("black", "black", "red", "black", "black", "black")), axis.ticks.x = element_line(color = c("black", "black", "red", "black", "black", "black"), size = c(.5,.5,1,.5,.5,.5)))# y-axis to match x-axisp = p + theme(axis.text.y = element_text(color = "black"), axis.ticks.y = element_line(color = "black"))# Remove the extra grid linep = p + theme(panel.grid.minor = element_blank(), panel.grid.major.x = element_line(color = c("white", "white", NA, "white", "white", "white")))p Second Solution ## annotation_custom then turn off clippinglibrary(ggplot2)library(grid)df <- data.frame(x=seq(1:100), y=sort(rexp(100, 2), decreasing = T))p = ggplot(df, aes(x=x, y=y)) + geom_point() + scale_y_continuous(limits = c(0, 4)) + annotation_custom(textGrob("xyz", gp = gpar(col = "red")), xmin=30, xmax=30,ymin=-.4, ymax=-.4) + annotation_custom(segmentsGrob(gp = gpar(col = "red", lwd = 2)), xmin=30, xmax=30,ymin=-.25, ymax=-.15)g = ggplotGrob(p)g$layout$clip[g$layout$name=="panel"] <- "off"grid.draw(g) Third Solution library(ggplot2)library(grid)df <- data.frame(x=seq(1:100), y=sort(rexp(100, 2), decreasing = T))p = ggplot(df, aes(x=x, y=y)) + geom_point() gtext = textGrob("xyz", y = -.05, gp = gpar(col = "red"))gline = linesGrob(y = c(-.02, .02), gp = gpar(col = "red", lwd = 2)) p = p + annotation_custom(gtext, xmin=30, xmax=30, ymin=-Inf, ymax=Inf) + annotation_custom(gline, xmin=30, xmax=30, ymin=-Inf, ymax=Inf)g = ggplotGrob(p)g$layout$clip[g$layout$name=="panel"] <- "off"grid.draw(g) Fourth Solution Updated to ggplot2 v3.0.0 ## Viewportslibrary(ggplot2)library(grid)df <- data.frame(x=seq(1:100), y=sort(rexp(100, 2), decreasing = T))(p = ggplot(df, aes(x=x, y=y)) + geom_point())# Search for the plot panel using regular expressionsTree = as.character(current.vpTree())pos = gregexpr("\\[panel.*?\\]", Tree)match = unlist(regmatches(Tree, pos))match = gsub("^\\[(panel.*?)\\]$", "\\1", match) # remove square bracketsdownViewport(match)######## Or find the plot panel yourself# current.vpTree() # Find the plot panel# downViewport("panel.6-4-6-4")###### Get the limits of the ggplot's x-scale, including the expansion.x.axis.limits = ggplot_build(p)$layout$panel_params[[1]][["x.range"]]# Set up units in the plot panel so that the x-axis units are, in effect, "native",# but y-axis units are, in effect, "npc".pushViewport(dataViewport(yscale = c(0, 1), xscale = x.axis.limits, clip = "off"))grid.text("xyz", x = 30, y = -.05, just = "center", gp = gpar(col = "red"), default.units = "native")grid.lines(x = 30, y = c(.02, -.02), gp = gpar(col = "red", lwd = 2), default.units = "native") upViewport(0)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29824773', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/937019/']}
jdg_87446
stackexchange
llm_judgeable_groundtruth_similarity
33506799
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an admin layout I have a master layout contain my : top nav left side nav Each page is a view, I extend the master layout view, and update only the content section. My goal is to refresh only a content page without refreshing master page. Is there any laravel package for something like this ? Now provide the response and nothing else.
Short answer: use AJAX . There no real need to learn a JavaScript framework if it's that simple (unless you really want to). The below example uses jQuery and assumes you're clicking on the Users link in the navigation (all links there should have a nav-item class so they can be easily identified via that selector) and the link has the attribute href="/admin/users" . When clicked it loads the contents in the element with the class content : $('.item-nav').click(function (event) { // Avoid the link click from loading a new page event.preventDefault(); // Load the content from the link's href attribute $('.content').load($(this).attr('href'));}); If the route admin/users would return the users table with it's contents: get('admin/users', function () { return view('users')->with('users', Users::all());}); The above Laravel route example is of course simplified to showcase the idea that each item in your navigation should link to the contents that need to be displayed dynamically.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33506799', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4480164/']}
jdg_87447
stackexchange
llm_judgeable_groundtruth_similarity
26553140
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In PageSpeed Insights I keep seeing the message to leverage browser caching of a particular iconset/font I'm using: iconFont.woff (2 days) I've set my .htaccess as so: ## EXPIRES CACHING ##<IfModule mod_expires.c>ExpiresActive OnExpiresByType font/ttf "access 1 week"ExpiresByType font/woff "access 1 week"ExpiresByType image/jpg "access 1 month"ExpiresByType image/jpeg "access 1 month"ExpiresByType image/gif "access 1 month"ExpiresByType image/png "access 1 month"ExpiresByType text/css "access 1 week"ExpiresByType application/pdf "access 1 month"ExpiresByType application/javascript "access 1 month" ExpiresByType application/x-shockwave-flash "access 1 month"ExpiresByType image/x-icon "access 1 year"ExpiresDefault "access 2 days"</IfModule>## EXPIRES CACHING ## Despite this I'm still getting the same message in PageSpeed Insights. How do I cache this properly? Now provide the response and nothing else.
This is doing the job for me, as Google page speed is no longer asking to fix it. The AddType is essential. # Fonts# Add correct content-type for fontsAddType application/vnd.ms-fontobject .eot AddType application/x-font-ttf .ttfAddType application/x-font-opentype .otfAddType application/x-font-woff .woffAddType image/svg+xml .svg# Compress compressible fonts# only uncomment if you dont have compression turned on already. Otherwise it will cause all other filestypes not to get compressed# AddOutputFilterByType DEFLATE application/x-font-ttf application/x-font-opentype image/svg+xmlExpiresActive on# Add a far future Expires header for fontsExpiresByType application/vnd.ms-fontobject "access plus 1 year"ExpiresByType application/x-font-ttf "access plus 1 year"ExpiresByType application/x-font-opentype "access plus 1 year"ExpiresByType application/x-font-woff "access plus 1 year"ExpiresByType application/font-woff2 "access plus 1 month"ExpiresByType image/svg+xml "access plus 1 year"
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26553140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1942679/']}
jdg_87448
stackexchange
llm_judgeable_groundtruth_similarity
768373
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The last sentence in the article caught my eye [F]or C/C++ developers and students interested in learning to program in C/C++ rather than users of Linux. This is because the compiling of source code is made simple in GNU/Linux by the use of the 'make' command. I have always used gcc to compile my C/C++ programs, whereas javac to compile my Java programs. I have only used make to install programs to my computer by configure/make/make install. It seems that you can compile apparently all your programs with the command make. What is the difference between make and gcc? Now provide the response and nothing else.
Well ... gcc is a compiler, make is a tool to help build programs. The difference is huge. You can never build a program purely using make; it's not a compiler. What make does it introduce a separate file of "rules", that describes how to go from source code to finished program. It then interprets this file, figures out what needs to be compiled, and calls gcc for you. This is very useful for larger projects, with hundreds or thousands of source code files, and to keep track of things like compiler options, include paths, and so on.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/768373', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/54964/']}
jdg_87449
stackexchange
llm_judgeable_groundtruth_similarity
1729054
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to force maven(2.0.9) to include all the dependencies in a single jar file? I have a project the builds into a single jar file. I want the classes from dependencies to be copied into the jar as well. Update: I know that I cant just include a jar file in a jar file. I'm searching for a way to unpack the jars that are specified as dependencies, and package the class files into my jar. Now provide the response and nothing else.
You can do this using the maven-assembly plugin with the "jar-with-dependencies" descriptor. Here's the relevant chunk from one of our pom.xml's that does this: <build> <plugins> <!-- any other plugins --> <plugin> <artifactId>maven-assembly-plugin</artifactId> <executions> <execution> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> <configuration> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> </configuration> </plugin> </plugins> </build>
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1729054', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/210441/']}
jdg_87450
stackexchange
llm_judgeable_groundtruth_similarity
6512019
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using std::function , we can get the type of an argument using the argument_type , second_argument_type etc. typedefs, but I can't see a way to do the same thing with lambdas. Is it possible? (I'm using VS2010) Say I want something like the following in my deserialization system used to read an object and pass it to a setter function: template<typename F> static void forward(F f){ // Create an object of the type of the first // parameter to the function object F typedef typename F::argument_type T; T t; //...do something with 't' here (deserialize in my case) // Forward the object to the function f(t);} It can be used like this and everything works fine: std::function<void(int)> f = [](int i) -> void { setValue(i); };forward(f); But it will not work directly with lambdas: forward([](int i) -> void { setValue(i); });//error C2039: 'argument_type' : is not a //member of '`anonymous-namespace'::<lambda1>' Is there a way to access the parameter types in a way that will work for both lambdas and std::function objects? Maybe a way to get the std::function type of a lambda first, and then the argument_type from that? Following on from the answer below, a version that works with lambdas and std::function is: template<typename T, typename F> static void forward(F f){ T t; //...do something with 't' here (deserialize in my case) f(t);}forward<int>([](int i) -> void { setValue(i); }); Since int is repeated here I was hoping to get rid of it - not so bad for int but more annoying for long-named types in a couple of namespaces. C'est la vie! Now provide the response and nothing else.
It's not desirable in the general case. (Note that it's quite easy for std::function<T(A)> to specify what e.g. argument_type is: it's just A ! It's available in the type definition.) It would be possible to require each and every function object type to specify its argument types, and in turn mandate that the closure types generated from lambda expression do so. In fact, pre-C++0x features like adaptable functors would only work for such types. However, we're moving from that with C++0x and for good reasons. The simplest of which is simply overloading: a functor type with a templated operator() (a.k.a a polymorphic functor) simply takes all kind of arguments; so what should argument_type be? Another reason is that generic code (usually) attempts to specify the least constraints on the types and objects it operates on in order to more easily be (re)used. In other words, generic code is not really interested that given Functor f , typename Functor::argument be int . It's much more interesting to know that f(0) is an acceptable expression. For this C++0x gives tools such as decltype and std::declval (conveniently packaging the two inside std::result_of ). The way I see it you have two choices: require that all functors passed to your template use a C++03-style convention of specifying an argument_type and the like; use the technique below; or redesign. I'd recommend the last option but it's your call since I don't know what your codebase looks like or what your requirements are. For a monomorphic functor type (i.e. no overloading), it is possible to inspect the operator() member. This works for the closure types of lambda expressions. So we declare these helpers template<typename F, typename Ret, typename A, typename... Rest>Ahelper(Ret (F::*)(A, Rest...));template<typename F, typename Ret, typename A, typename... Rest>Ahelper(Ret (F::*)(A, Rest...) const);// volatile or lvalue/rvalue *this not required for lambdas (phew) that accept a pointer to member function taking at least one argument. And now: template<typename F>struct first_argument { typedef decltype( helper(&F::operator()) ) type;}; [ an elaborate trait could successively query the lvalue-rvalue/const/volatile overloads and expose the first argument if it's the same for all overloads, or use std::common_type .]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6512019', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/819838/']}
jdg_87451
stackexchange
llm_judgeable_groundtruth_similarity
12583419
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to implement endless scroll on an android ListView component, that will add new items to the bottom of the listview when scrolled to the last element in the list. Now provide the response and nothing else.
implement the onscrolllistener() public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { this.currentFirstVisibleItem = firstVisibleItem; this.currentVisibleItemCount = visibleItemCount;}public void onScrollStateChanged(AbsListView view, int scrollState) { this.currentScrollState = scrollState; this.isScrollCompleted(); }private void isScrollCompleted() { if (this.currentVisibleItemCount > 0 && this.currentScrollState == SCROLL_STATE_IDLE) { /*** In this way I detect if there's been a scroll which has completed ***/ /*** do the work for load more date! ***/ if(!isLoading){ isLoading = true; loadMoreDAta(); } }} as you implement and add this listener to your listview this will detect for the end of listview as scroll position was at end of list just get more data. And during the loading data you need one flag to load data at once when the scroll position goes to end. So if data is loading and during that time you scroll up then scroll down then it will not get more data for dupplication.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12583419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1673332/']}
jdg_87452
stackexchange
llm_judgeable_groundtruth_similarity
10964966
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to bounce users of our web site to an error page if they're using a version of Internet Explorer prior to v9. It's just not worth our time and money to support IE pre-v9 . Users of all other non-IE browsers are fine and shouldn't be bounced. Here's the proposed code: if(navigator.appName.indexOf("Internet Explorer")!=-1){ //yeah, he's using IE var badBrowser=( navigator.appVersion.indexOf("MSIE 9")==-1 && //v9 is ok navigator.appVersion.indexOf("MSIE 1")==-1 //v10, 11, 12, etc. is fine too ); if(badBrowser){ // navigate to error page }} Will this code do the trick? To head off a few comments that will probably be coming my way: Yes, I know that users can forge their useragent string. I'm not concerned. Yes, I know that programming pros prefer sniffing out feature-support instead of browser-type but I don't feel this approach makes sense in this case. I already know that all (relevant) non-IE browsers support the features that I need and that all pre-v9 IE browsers don't. Checking feature by feature throughout the site would be a waste. Yes, I know that someone trying to access the site using IE v1 (or >= 20) wouldn't get 'badBrowser' set to true and the warning page wouldn't be displayed properly. That's a risk we're willing to take. Yes, I know that Microsoft has "conditional comments" that can be used for precise browser version detection. IE no longer supports conditional comments as of IE 10 , rendering this approach absolutely useless. Any other obvious issues to be aware of? Now provide the response and nothing else.
This is my preferred way of doing it. It gives maximum control. (Note: Conditional statements are only supported in IE5 - 9.) First set up your ie classes correctly <!DOCTYPE html><!--[if lt IE 7]> <html class="lt-ie9 lt-ie8 lt-ie7"> <![endif]--><!--[if IE 7]> <html class="lt-ie9 lt-ie8"> <![endif]--><!--[if IE 8]> <html class="lt-ie9"> <![endif]--><!--[if gt IE 8]><!--> <html> <!--<![endif]--> <head> Then you can just use CSS to make style exceptions, or, if you require, you can add some simple JavaScript: (function ($) { "use strict"; // Detecting IE var oldIE; if ($('html').is('.lt-ie7, .lt-ie8, .lt-ie9')) { oldIE = true; } if (oldIE) { // Here's your JS for IE.. } else { // ..And here's the full-fat code for everyone else }}(jQuery)); Thanks to Paul Irish .
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/10964966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1040766/']}
jdg_87453
stackexchange
llm_judgeable_groundtruth_similarity
27696612
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Without using a service or constructing watchers in the parent controller, how would one give children states access to the main controller's $scope . .state("main", { controller:'mainController', url:"/main", templateUrl: "main_init.html" }) .state("main.1", { controller:'mainController', parent: 'main', url:"/1", templateUrl: 'form_1.html' }) .state("main.2", { controller:'mainController', parent: 'main', url: "/2", templateUrl: 'form_2.html' }) I'm not able to access the mainController scope in child state--or rather I'm getting another instance of that scope--not what I want. I feel I'm missing something simple. There is a shared data config option in the state object but I'm not sure if this should be used for something like this. Now provide the response and nothing else.
I created working plunker , showing how to use $scope and UI-Router. The state definition is unchanged: $stateProvider // States .state("main", { controller:'mainController', url:"/main", templateUrl: "main_init.html" }) .state("main.1", { controller:'mainController', parent: 'main', url:"/1", templateUrl: 'form_1.html' }) .state("main.2", { controller:'mainController', parent: 'main', url: "/2", templateUrl: 'form_2.html' }) But each state can have different controller. Why? because each view of each state gets new instance of defined controller . So while we have mainController like the one below, we can be sure, that if we navigate to state 'main.2' it will be instantiated twice. controller('mainController', function ($scope) { $scope.Model = $scope.Model || {Name : "xxx"};}) But what we can see here , is that we check if $scope.Model already exsits... and if not (Parent state) we instantiate it with new intance {Name : "xxx"} . Well, what I am saying is: only parent state will init the $scope.Model . All others will get that already filled. How? Well here is the answer: Scope Inheritance by View Hierarchy Only Keep in mind that scope properties only inherit down the state chain if the views of your states are nested. Inheritance of scope properties has nothing to do with the nesting of your states and everything to do with the nesting of your views (templates). It is entirely possible that you have nested states whose templates populate ui-views at various non-nested locations within your site. In this scenario you cannot expect to access the scope variables of parent state views within the views of children states. So, as stated in the documentation. Because our child views are nested in the parent view, the scope is inherited. Understanding Scopes In AngularJS, a child scope normally prototypically inherits from its parent scope. ... Having a '.' in your models will ensure that prototypal inheritance is in play. // So, use<input type="text" ng-model="someObj.prop1"> // rather than<input type="text" ng-model="prop1">. And that's it. We get inheritance from UI-Router views and angular scopes, and because we smartly used a reference type ( Model ), i.e. do have '.' dot in ng-model definition - we can share data now NOTE: having dot '.' in the ng-model="Model.PropertyName simply means, that there is a reference object Model {} with some property: PropertyName Check the working example here
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/27696612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1549306/']}
jdg_87454
stackexchange
llm_judgeable_groundtruth_similarity
578358
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Show that for a non-negative random variable $X$, $$\mathbb E(X)=\int_0^\infty \mathbb P(X\ge x) \, dx.$$ I started with $$\mathbb E(X)=\int_0^\infty x \, dF(x)=\int_0^\infty \int_0^x dt\,dF(x).$$This is my try. Now provide the response and nothing else.
Integrate the LHS and the RHS of the pointwise identity$$X=\int_0^X\mathrm dx=\int_0^\infty\mathbf 1_{X\geqslant x}\,\mathrm dx.$$This shows that the desired formula for $E[X]$ holds irrespectively of the hypothesis that $X$ is discrete or continuous or neither discrete nor continuous, as soon as $X\geqslant0$ almost surely, and that two formulas are available, namely,$$E[X]=\int_0^\infty P[X\geqslant x]\,\mathrm dx=\int_0^\infty P[X\gt x]\,\mathrm dx.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/578358', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/108367/']}
jdg_87455
stackexchange
llm_judgeable_groundtruth_similarity
46529362
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I´m trying to pass my data(json) from view through ajax to my controller but this arrive null. Thanks in advance fro any help or suggestion. This is my model. public class TipificacionModel{ public int Existente { get; set; } public string Campo { get; set; } public int Regla { get; set; }}public class ListasSeleccionModel{ public List<string> DatosSeleccion { get; set; }}public class ListaTipificaciones{ public string NombreCampaña { get; set; } public List<TipificacionModel> Tipificacion { get; set; }}public class DatosSeleccionMultiple{ public List<String> Columnas { get; set; } public List<ListasSeleccionModel> ListasSeleccion { get; set; }}public class TipificacionGeneralCampaña{ public ListaTipificaciones CamposCreados { get; set; } public List<DatosSeleccionMultiple> ListasDeSeleccion { get; set; }} This is my ajax function. jsonListaGeneral = []; jsonListaGeneral.push(jsonTipificacion); jsonListaGeneral.push(jsonListasSeleccion); console.log(jsonListaGeneral); $.ajax({ url: '@Url.Action("crearCampManual", "DPS")', type: 'post', data: JSON.stringify(jsonListaGeneral), contentType: 'application/json; charset=utf-8;', dataType: 'json', success: function (response) { alert(response) return; }, error: function (x) { alert(x.responseText); } }); This is my controller. [HttpPost] public ActionResult crearCampManual(TipificacionGeneralCampaña model) { //Here the model value is null, why?} When i print the json in my browser console everything is good. But something bad happends, im making something wrong. Console Browser Break Point Controller Now provide the response and nothing else.
LogError is not a ILogger method, so when you try to check that this method was called with certain parameters NSubstitute tries to handle it somehow(I do not know how exactly) and fails. The code of LogError extension method is: public static void LogError(this ILogger logger, string message, params object[] args){ if (logger == null) throw new ArgumentNullException("logger"); logger.Log<object>(LogLevel.Error, (EventId) 0, (object) new FormattedLogValues(message, args), (Exception) null, LoggerExtensions._messageFormatter);} So you have to check that Log method was called. I simplified your example a bit. I think idea should be clear. public partial class MainWindow : Window{ public MainWindow() { InitializeComponent(); var logger = Substitute.For<ILogger>(); try { Create(logger); } catch { logger.CheckErrorMessage("My Message"); } } public string Create(ILogger logger) { try { throw new Exception("My Message"); } catch (Exception e) { logger?.LogError(e.Message); throw new Exception("An error occurred while attempting to create a user.", e); } }}public static class TestExtensions{ public static void CheckErrorMessage(this ILogger logger, string message) { logger.Received().Log( LogLevel.Error, Arg.Any<EventId>(), Arg.Is<object>(o => o.ToString() == message), null, Arg.Any<Func<object, Exception, string>>()); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46529362', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4907962/']}
jdg_87456
stackexchange
llm_judgeable_groundtruth_similarity
4148555
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using the following to get a help document in our app. My problem is that while the <h:graphicImage> evaluates the context path correctly, the h:outputLink evalutates it to nothing. I have tried using both $ and # in the h:outputLink because I understand they have different evaluation times. What is the difference in how the two EL expressions evaluate? <h:outputLink value="${pageContext.servletContext.contextPath}/services/help.pdf"> <h:graphicImage url="${pageContext.servletContext.contextPath}/images/help.png" alt="Online Help"/></h:outputLink> Now provide the response and nothing else.
That the context path doesn't appear in <h:outputLink> suggests that you're actually using Facelets instead of JSP. The ${pageContext} doesn't exist in Facelets at all. It's specific to legacy JSP. Both expressions have just evaluated to an empty string. There is thus no difference between them at all. That the context path appears in <h:graphicImage> is fully expected. This is automatically included by the component itself. In fact, the entire expression is superfluous and the following should work as good. <h:graphicImage url="/images/help.png" alt="Online Help"/> The <h:outputLink> does indeed not automatically include the context path. Only the <h:link> does that. You'd need to include it yourself. In Facelets, you can use #{request} to get a handle to HttpServletRequest which in turn has a getContextPath() as well (and which is used by <h:graphicImage> under the covers). <h:outputLink value="#{request.contextPath}/services/help.pdf">
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4148555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147265/']}
jdg_87457
stackexchange
llm_judgeable_groundtruth_similarity
2837347
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $a,b,c>0$ such that $b^2+c^2\le a^2$. Find the minimize of $$A=\frac{1}{a^2}\left(b^2+c^2\right)+a^2\left(\frac{1}{b^2}+\frac{1}{c^2}\right)$$ My try: By AM-GM: $LHS=\frac{a^2}{b^2}+\frac{b^2}{a}+\frac{a^2}{c^2}+\frac{c^2}{a^2}$ $=\frac{a^2}{b^2}+4\frac{b^2}{a}+\frac{a^2}{c^2}+4\frac{c^2}{a^2}-\frac{3\left(b^2+c^2\right)}{a^2}$ $\ge 2\sqrt{\frac{a^2}{b^2}\cdot 4\frac{b^2}{a}}+2\sqrt{\frac{a^2}{c^2}\cdot 4\frac{c^2}{a^2}}-\frac{3\cdot a^2}{a^2}$ $\ge 4+4-3=5$ $"="\Leftrightarrow b=c=\frac{a}{\sqrt{2}}$ My idea started by the equal occurs when $b=c=\frac{a}{\sqrt{2}}$ but if I don't know the equal occurs when $b=c=\frac{a}{\sqrt{2}}$ i can't sol it. Help me sol it. Now provide the response and nothing else.
Write $b^2+c^2=a^2r^2$, $r\in [0,\,1]$ so $A=r^2+\frac{a^4 r^2}{(bc)^2}$. Write $b=arC,\,c=arS$ with $C=\cos t,\,S=\sin t$ (say) so $A=r^2+\frac{1}{r^2 C^2 S^2}\ge r^2+\frac{4}{r^2}$, with equality iff $\sin 2t=\pm 1,\,C^2=S^2=\frac{1}{2}$. Since $\frac{d}{dr}(r^2+\frac{4}{r^2})=2r(1-\frac{4}{r^4})<0$ for $r\in [0,\,1]$, we obtain the minimum at $r=1$. Thus $A$ has minimum $5$, obtained with $b^2=c^2=\frac{a^2}{2}$ as you thought.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2837347', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/466835/']}
jdg_87458
stackexchange
llm_judgeable_groundtruth_similarity
47316810
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a script that's accessing printers, and my code works totally fine when chrome is run normally, but when it's run headless, selenium can't seem to find elements on the webpage. Here's the relevant code: init method: def __init__(self, ip_address): """ Initialize a new Printer_Webpage object.""" self.ip_address = ip_address chrome_options = Options() chrome_options.add_argument("--headless") chrome_options.add_argument("--disable-gpu") chrome_options.add_argument("--window-size=1920x1080") self.browser = webdriver.Chrome(chrome_options=chrome_options) # Ignore lack of cert for each printer web page. # Otherwise, can't open page. self.browser.accept_untrusted_certs = True Login method: def login(self): """Navigates through the login page for the printer.""" # Open login page self.browser.get(f'https://{self.ip_address}/wcd/top.xml') # STEPS TO LOGIN: # 1) Select 'Administrator' radio button and click. self.browser.find_element_by_id('Admin').click() # 2) Select Login button and click. self.browser.find_element_by_xpath("//input[@type='submit' \ and @value='Login']").click() # 3) Select admin (user mode) self.browser.find_element_by_id('R_ADM2').click() # 4) Select password field and input PASSWORD, then submit. password_field = self.browser.find_element_by_id('Admin_Pass') password_field.send_keys(PASSWORD) password_field.send_keys(Keys.RETURN) Full error message: selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"Admin"} And here's some other info that might be of use: (Session info: headless chrome=62.0.3202.94)(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.14393 x86_64) Now provide the response and nothing else.
I had the same problem. You could take screenshots to understand whats wrong. driver.get_screenshot_as_file("screenshot.png") A few reasons why selenium works when run normally but stops working in headless mode - 1)It might have switched to a mobile template. Can be fixed by changing the window size. chrome_options.add_argument("--window-size=1920,1080") 2)If its a blank page (screenshot), it might be due to an invalid SSL certificate.(see @Marcel_Wilson post) It should be fixed by - chrome_options.add_argument('--ignore-certificate-errors')chrome_options.add_argument('--allow-running-insecure-content') 3)Its possible that the website blocks 'headless' mode. (Your screenshots might show errors which you cannot recreate in normal mode)You could try this- user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.50 Safari/537.36'options.add_argument(f'user-agent={user_agent}') However, the above code won't work if the website has a more robust blocking method. You can find more about this here https://intoli.com/blog/making-chrome-headless-undetectable/ .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47316810', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6132064/']}
jdg_87459
stackexchange
llm_judgeable_groundtruth_similarity
48965916
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to fix Line Length Violation? Relevant part of alert message that isn't allowed due to Line Length Violation: message: NSLocalizedString("\nYou will be requested to Use %@ to Sign In. %@ doesn't share any information about you. The permission is required to post your Live Video.", ⚠ Line should be 120 characters or less: currently 208 characters (line_length) Now provide the response and nothing else.
Make the line shorter: message: NSLocalizedString( ["\nYou will be requested to Use %@ to Sign In. ", "%@ doesn't share any information about you. The ", "permission is required to post your Live Video."].joined()) or better, using vacawama's multi-line solution: let message = """ You will be requested to Use %@ to Sign In. \ %@ doesn't share any information about you. \ The permission is required to post your Live Video. """ That's a generic solution, but isn't really appropriate for NSLocalizedString because it breaks tools that scan for localized strings like genstrings . Your other solution is to turn off the warning for that line by adding a disable on the line immediately before: // swiftlint:disable:next line_length See Disable rules in code for full details on disabling swiftlint rules.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48965916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1951635/']}
jdg_87460
stackexchange
llm_judgeable_groundtruth_similarity
164509
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $F$ be a closed manifold. What are the Pontryagin numbers on $E=F\times S^1$?More generaly, let $E$ be a closed manifold which is a fiber bundle over $S^1$(with fiber $F$). $E$ is also called mapping torus. What are the Pontryagin numbers on $E$? When $E$ is 4-dimensional, the signature of such a fiber bundle over $S^1$ is zero, which implies that the corresponding Pontryagin number is zero. I wonder if all the Pontryagin numbers of closed orientable mapping tori in any dimensions are always zero. Now provide the response and nothing else.
You are asking about vanishing of the Pontryagin numbers, and hence the (rational) cobordism class, of the mapping torus of a diffeomorphism. According to M. Kreck, (Bordism of diffeomorphisms Bull. Amer. Math. Soc. Volume 82, Number 5 (1976), 641-789, with details in Cobordism of odd-dimensional diffeomorphisms. Topology 15 (1976). 353-361) any cobordism class in the kernel of the signature homomorphism contains a mapping torus. So the signature in dimension 4 is the only obstruction, but that's not true in higher dimensions. The special case of $S^1 \times M$ is the boundary of $D^2 \times M$, so of course its Pontryagin numbers vanish.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/164509', 'https://mathoverflow.net', 'https://mathoverflow.net/users/17787/']}
jdg_87461
stackexchange
llm_judgeable_groundtruth_similarity
44788018
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to clean up the image above I've tried several different methods using open cv, I either erode the original image too much to the point where parts of the letters become missing such as below: I'm not really sure sure how to get rid of the last diagonal line and repair the S, my code so far is: import cv2 import matplotlib.pylab as pltimg = cv2.imread('/captcha_3blHDdS.png')#make image gray gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#Blurblur = cv2.GaussianBlur(gray,(5,5),0)bilateral = cv2.bilateralFilter(gray,5,75,75)#Thresholdingret, thresh = cv2.threshold(bilateral,25,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)#Kernalkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))#other thingserosion = cv2.erode(thresh,kernel,iterations = 1)closing = cv2.morphologyEx(erosion, cv2.MORPH_CLOSE, kernel, iterations = 1)#Transform imagedist_transform = cv2.distanceTransform(closing,cv2.DIST_L2,5)ret, sure_fg = cv2.threshold(dist_transform,0.02*dist_transform.max(),255,cv2.THRESH_BINARY)#,255,0)#kernel_1kernel_1 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (1, 2))dilation_1 = cv2.dilate(sure_fg,kernel_1,iterations = 2)erosion_1 = cv2.erode(dilation_1,kernel_1,iterations = 3)plt.imshow(erosion_1, 'gray') Any help would be greatly appreciated, Here are more examples of the type of images that are produced from the captcha; also heres the link to a folder containing the images Now provide the response and nothing else.
Here is a C# solution using OpenCvSharp (which should be easy to convert back to python/c++ because the method names are exactly the same). It uses OpenCV's inpainting technique to avoid destroying too much of the letters before possibly running an OCR phase. We can see that the lines have a different color than the rest, so we'll use that information very early, before any grayscaling/blackwhiting. Steps are as follow: build a mask from the lines using their color (#707070) dilate that mask a bit because the lines may have been drawn with antialiasing repaint ("inpaint") the original image using this mask, which will remove the lines while preserving most of what was below the lines (letters). Note we could remove the small points before that step, I think it would be even better apply some dilate/blur/threshold to finalize Here is the mask: Here is the result: Here is the result on sample set: Here is the C# code: static void Decaptcha(string filePath){ // load the file using (var src = new Mat(filePath)) { using (var binaryMask = new Mat()) { // lines color is different than text var linesColor = Scalar.FromRgb(0x70, 0x70, 0x70); // build a mask of lines Cv2.InRange(src, linesColor, linesColor, binaryMask); using (var masked = new Mat()) { // build the corresponding image // dilate lines a bit because aliasing may have filtered borders too much during masking src.CopyTo(masked, binaryMask); int linesDilate = 3; using (var element = Cv2.GetStructuringElement(MorphShapes.Ellipse, new Size(linesDilate, linesDilate))) { Cv2.Dilate(masked, masked, element); } // convert mask to grayscale Cv2.CvtColor(masked, masked, ColorConversionCodes.BGR2GRAY); using (var dst = src.EmptyClone()) { // repaint big lines Cv2.Inpaint(src, masked, dst, 3, InpaintMethod.NS); // destroy small lines linesDilate = 2; using (var element = Cv2.GetStructuringElement(MorphShapes.Ellipse, new Size(linesDilate, linesDilate))) { Cv2.Dilate(dst, dst, element); } Cv2.GaussianBlur(dst, dst, new Size(5, 5), 0); using (var dst2 = dst.BilateralFilter(5, 75, 75)) { // basically make it B&W Cv2.CvtColor(dst2, dst2, ColorConversionCodes.BGR2GRAY); Cv2.Threshold(dst2, dst2, 255, 255, ThresholdTypes.Otsu); // save the file dst2.SaveImage(Path.Combine( Path.GetDirectoryName(filePath), Path.GetFileNameWithoutExtension(filePath) + "_dst" + Path.GetExtension(filePath))); } } } } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44788018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3191569/']}
jdg_87462
stackexchange
llm_judgeable_groundtruth_similarity
3961535
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Notice that $2021$ is a concatenation of consecutive integers: $20\sim 21$ Also $2021$ is a product of consecutive primes: $43\times 47$ . What is the next number with both of these properties? $24502451$ is close, $4943\times 4957$ but $4951$ is in between. $2484224843$ is close, $49831\times 49853$ but $49843$ is in between. $715353612\sim 715353607$ isn't quite there but is $845785793\times 845785799$ Are there any other numbers with the $2021$ property? Now provide the response and nothing else.
I found more twin prime solutions. For $n = 396$ , $d = 2$ I found four; the smallest is $x =$ $${\small434219772837481616940726338933362452273916097301492635627291443512051997247961750150908315825206335025681182252954355463934702107964728269885096262688644034853639395077615105799339919571601786192665103151170947581386505769710635828116973131647706180301379657813220432413064536727826883282252811784121256116486385454859849292857777667719016881251956101283374338871503089431823276421261037909974359}$$ For $n = 420, d= 2$ I found $x =$ $${\small797632045320122442922746848370123218495083238021539262463793196558953236606673684986633691999805212011226776035396567202878987657452660659814874176096052099397205337415190293836597252999499063444222715671072742933640380698030812583452694556061309433747142801949662038045758937332990610602377203706320829077950947557183280793831442171456664369310820656043310649088552521802135329739094023210425721483954126295715977820771}$$ I wrote a Java program to find modular square roots using known factorizations of $10^n+1$ at https://stdkmd.net/nrr/repunit/10001.htm The $n = 396$ solution shown may not be the second smallest twin prime solution because I did not analyse $10^n+1$ with unknown factorization (eg: $323, 392$ ). Note that all these solutions involve only probable primes. UPDATE: I analyzed all $n \le$ 500 for which complete factorizations are known,using Shank's $(ln\ 10^n)^2$ estimate for prime gaps: $2 \le d < 5.3n^2$ . The following table shows the number of solutions of $n$ for each $d$ . \begin{array}{r|l|r} d & n & total \\ \hline 2 & 36 \ 396(4) \ 420 \ 468 & 7\\ 4 & 2 \ 70 \ 150 \ 154 \ 210(27) \ 270(8) \ 298 \ 306(2) \ 330(216) \ 350(4) \ 390(10) \ 450(519) & 791\\ 12 & 370(3) & 3\\ 14 & 336(2) \ 396(3) & 5\\ 54 & 72 & 1\\ 76 & 150(2) \ 210(16) \ 238 \ 270(4) \ 306(2) \ 330(209) \ 350(3) \ 390(15) \ 450(464) & 716\\ 82 & 288 \ 336 \ 396(5) & 7\\ 136 & 370(2) & 2\\ 478 & 336(2) \ 420(2) & 4\\ 1364 & 350 \ 370 & 2\\ \hline\end{array} I analyzed many of the remaining known factorizations ( $10^{2021}+1$ is not one of them!). I found another twin prime solution: $n=1008$ with $d=2$ , $x=$ $${\small415119285335713138107859159895921470120127901771012286705147863784377859054383205862088683121228843823644091024472578295715781891723489781341595609399956375971523325157129204031439607287157565203433091945798569106366453441681028958853009984899996962841286597261664058243897757317082387302022827796188228872367615940280481644558354868664735437056336615963301573812328050683875074515986286867031968871583403569829949341102058719072290611202615565955752049854880027669507042067569064851453754109081689314779674580036777493429088593987592215948631397812098103849006767378312184473327978598863061300578414744304808368322583101196999821431867760847600988156486022394149378510713398269801057016361947970128875578649362095899180615435692074486807012156095811778896443290518016088027948808773134635025220295845062105375107159001836188571569967805721691214024809680987944490924904786048603374165125520526174101682333287056313013054613391604106858759925794745594124906616469238525225716143856670923606283395248479131507}$$ I found three large solutions: $n=1530$ with $d=4$ , $n=2442$ with $d=4$ , and $n=3011$ (odd!) with $d=20690$ and $x=$ $${\small88690623974342445320706035164907895149666724533149745483024674929494064077161748069463728371848588950263928708885107056062087458873420997129551966175554795722180833514256206712208756791349423181129064370039115228768196330069003307522127855902035611295636718786724552834173077606816947565351851981240290592919330234435002605544818898704383050138705647019342509295291603847356454590383853903649034831518476190799174284971745361604565835545543751726529610775367997499873686078754015523170389723175091842178101899712480880871125974133817901518538674999703972616649632379652346395327832021456141800194701647932112291489233775928062470099635623529564608650310241193184759187003057364275380404785676729319256559060638811849744657325135099995176231775532397706618363314457193916318557002601459452270771049765689157482464270159966495073998419806308753511281083712198273207669118838966447628803262451478908503097089308456131000369654881518026667709557445311154935973975062432608109650859738547758359753161811236281693386411516599337580682444733887155249147703101490725039867545594773022646082904694935305608529996539856673800894879204151359288642251946537962882362542598385355877258435885255720463281832318996714749127620565928295871807381765069313332957959393036520560765777218866425812066806566968512664298253194097198110254106398916193178093323285510247757090049514423671929016532305341758972853095343072371415631421656596311059421635680366649419960217875499119738356663626923434263846557987005717753122760707664468827714474707911315796646846223047293968656604803860055531395007086544292734839551265327070525560544860595807571049301946018895129458512514361858289027536454436450967551887360811792658089837039529387070983777359590036217218745184175803793616945894809150630864349323615934382263207217535053701872322473625965756309360763380729005686068625698261693375747392352007831638590079855262236534947866527970435414431816193335704235728803592301557775355412534721854441649050543489915852763945114633640120859359425753981309635846954784400203166716706835000886558080563709914367339817642986577630512066137497993335131126095180539966000395250657557890723647715298981683035616063901855227374869260175148423588397623462842825972640026055333967889877654729507728851982076103225242572504527429707508826564462178655965426323365276645348503046435607191738892135058428362640796305615358118855629551341911741579489817482134866791604658301235483655504562219338888352571792484327753544399478907161167075036271824602275963945345494267916881834140919492205225308097367770069805455016950009471893642408322180438063500438940054744323617310086174876710854406021502917708656972234075774384689936433268632860789883740306973585819078135116827900294591791739792869006503475384136963506082899865375050762137583035828837915859970271078112397338135202345323724701287354928723862525723289692127491314630211880612187498071770083275673021172070970359804795314571223002210253991420896839561827296295193582310969508838235157649439819871296875917}$$ UPDATE (May 28, 2021) I attempted to find solutions bigger than $n = 3011$ , but found none!I rewrote my program in C using GMP and ran it on AWS with 96 cores.The following table summarises my results for all known complete factorizationsof $10^n+1$ for $n > 3011$ .For each $n$ the search was up to $d$ for the given ratio $\frac{d}{n}$ .Note that a ratio of $\mathbf{2.3}$ corresponds to the expected number ofprimes in the range $[10^n,10^n+2.3n] = 1$ ,a ratio of $\mathbf{96}$ corresponds to the current record prime gap(of $8350$ for an $87$ digit prime number),and a ratio of $\mathbf{6.9}$ corresponds to the biggest solution I found: $n=3011, d=20690$ . \begin{array}{r|l} n & \frac{d}{n} \\ \hline <22292 & 100 \\ 22292 & 21 \\ 22303 & 10\\ 23592 & 53\\ 23734 & 3\\ 26014 & 10\\ 32962 & 10\\ 46957 & 3\\ 47248 & 12\\ 64439 & 1.0\\ 80363 & 1.0\\ 95594 & 1.0\\ 103624 & 1.0\\ 132586 & 1.0\\ ^*180178 & 0.10\\ ^*268207 & 0.10\\ ^*1600787 & -\\ \hline\end{array} $^*$ For the last three values of $n$ the largest prime factor is a probable prime. I did not analyse the last value, because I estimate that a single calculation of $x^y$ mod $z$ with 1600000 digit numbers would take about 70 hours. UPDATE (June 11, 2021) For the largest known solution $(n=3011, d=20690)$ the primes $x$ and $x+d$ have been certified using Primo and recorded in factordb.com - search for primes with 3011 digits. UPDATE (July 8, 2021) I searched for all twin prime solutions $(d = 2)$ for $ n = 1008$ and found a total of 18. The largest, a new record, is $x=$ $${\small959366284693377033651389735182738458526276121193598553484439760604241337237451497452789960716688792639495153272015332792541955520436759663588757045933885829578173457125721695213851669376206161760331060025909588497751253712340327354707310139498467167235392925523839181171301134866240381669769835527505988247393867108561444781188402425283990574068760196925230932242847785476986116528280435669208099164158860477631087793039498552963323814612240444137080246220725308557204315700968442132019195862098047534857069372757341953852762143251682584867890954165891418336661720575672057626771116234845905889545915860780107445581724924411155250266226552503036267220337257336647317889646751823745301888424349108532006368071312231688002693274043002649314803790153000719816292711634980344850814644852432359001479449220906110949158858923721913836167918792291736846984222096022979367999907004169558381802601034072450079249418137015546418369167885051996435963305528417728081298205640144099322592183826280769897515421235519976901}$$ No more were found for $1008 < n \le 268207$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3961535', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11955/']}
jdg_87463
stackexchange
llm_judgeable_groundtruth_similarity
148324
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a differential equation and I need to obtain the solution and evaluate it just after. The reason for this is that I need to give the values x, u and t as parameters, which I think should be done in a module. Somehow when I evaluate, I get the error "ReplaceAll::reps: {sol} is neither a list of replacement rules nor a valid dispatch table, and so cannot be used for replacing." This only happens the first time I run it, if I run it a second time, it is like mathematica realizes that the solution does exist and lets me use it as replace just fine. This is my specific problem with some parameters: σA = 0.2;σX = 0.4;sD = 0.13;sS = 0.2;ϕ = 95/100;gA = (σX^2 (σX^2 (1 - ϕ) + \σA^2))/(σX^2 + σA^2); gB = (σX^2 σA^2)/(σX^2 + σA^2);γA1[t_] := 1/( t (1/sD^2 + ϕ^2/sS^2) + 1/gA);γB1[t_] := sD^2/ (t + sD^2/gB);PDEC = - 2 HC[ p] (γB1[-p + u]/sD^2 - ( x (γB1[-p + u] - γA1[-p + u]) )/sD^2) + ( ( x (x - 1))/(2 sD^2)) + 2 HC[p]^2 ((γB1[-p + u] - γA1[-p + u])^2/ sD^2 + (ϕ^2 (γA1[-p + u])^2)/sS^2) - Derivative[1][HC][p];x = 1/3; u = 25; t = 0.1; sol = NDSolve[{PDEC == 0, HC[0] == 0}, HC, {p, Re[(u - t) - 0.1], Re[(u - t) + 0.1]}]; Evaluate[ HC[25 - 0.1] /. sol] Now provide the response and nothing else.
One option is to use SetDelay , S1[t_?NumericQ, z_?NumericQ] := ((A*Subscript[τ, 0])/Sqrt[2*Pi])* NIntegrate[Exp[-(((c*ω + (-1 + c)*Subscript[ω, 0])*(2*I*z + Subscript[τ, 0]^2*(c*ω + (-1 + c)* Subscript[ω, 0])))/(2*c^2))]* Exp[I*(P1 + P2*ω + P3*ω^2 + P4*ω^3)*z]* Exp[I*ω*t], {ω, -Infinity, Infinity}]S2[t_?NumericQ, z_?NumericQ] := ((A*Subscript[τ, 0])/Sqrt[2*Pi])* NIntegrate[ Exp[-(((c*ω + (-1 + c)*Subscript[ω, 0])*(2*I*z + Subscript[τ, 0]^2*(c*ω + (-1 + c)* Subscript[ω, 0])))/(2*c^2))]* Exp[I*(G1 + G2*ω + G3*ω^2 + G4*ω^3)*z]* Exp[I*ω*t], {ω, -Infinity, Infinity}]Plot3D[{Abs[S1[t, z]], Abs[S2[t, z]]}, {t, 0, 20}, {z, 0, 20}] But the problem here is that the plot is not smooth (I used PlotPoints without any luck) and it is time consuming. I hope someone will come up with a better solution.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/148324', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/48673/']}
jdg_87464
stackexchange
llm_judgeable_groundtruth_similarity
219693
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Considering the following formulae: (i) $1+2+3+..+n = n(n+1)/2$ (ii) $1\cdot2+2\cdot3+3\cdot4+...+n(n+1) = n(n+1)(n+2)/3$ (iii) $1\cdot2\cdot3+2\cdot3\cdot4+...+n(n+1)(n+2) = n(n+1)(n+2)(n+3)/4$ Find and prove a 'closed formula' for the sum $1\cdot2\cdot3\cdot...\cdot k + 2\cdot3\cdot4\cdot...\cdot(k+1) + ... + n(n+1)(n+2)\cdot...\cdot (k+n-1)$ generalizing the formulae above. I have attempted to 'put' the first 3 formulae together but I am getting nowhere and wondered where to even start to finding a closed formula. Now provide the response and nothing else.
The pattern looks pretty clear: you have $$\begin{align*}&\sum_{i=1}^ni=\frac12n(n+1)\\&\sum_{i=1}^ni(i+1)=\frac13n(n+1)(n+2)\\&\sum_{i=1}^ni(i+1)(i+2)=\frac14n(n+1)(n+2)(n+3)\;,\end{align*}\tag{1}$$ where the righthand sides are closed formulas for the lefthand sides. Now you want $$\sum_{i=1}^ni(i+1)(i+2)\dots(i+k-1)\;;$$ what’s the obvious extension of the pattern of $(1)$? Once you write it down, the proof will be by induction on $n$. Added: The general result, of which the three in $(1)$ are special cases, is $$\sum_{i=1}^ni(i+1)(i+2)\dots(i+k-1)=\frac1{k+1}n(n+1)(n+2)\dots(n+k)\;.\tag{2}$$ For $n=1$ this is $$k!=\frac1{k+1}(k+1)!\;,$$ which is certainly true. Now suppose that $(2)$ holds. Then $$\begin{align*}\sum_{i=1}^{n+1}i(i+1)&(i+2)\dots(i+k-1)\\&\overset{(1)}=(n+1)(n+2)\dots(n+k)+\sum_{i=1}^ni(i+1)(i+2)\dots(i+k-1)\\&\overset{(2)}=(n+1)(n+2)\dots(n+k)+\frac1{k+1}n(n+1)(n+2)\dots(n+k)\\&\overset{(3)}=\left(1+\frac{n}{k+1}\right)(n+1)(n+2)\dots(n+k)\\&=\frac{n+k+1}{k+1}(n+1)(n+2)\dots(n+k)\\&=\frac1{k+1}(n+1)(n+2)\dots(n+k)(n+k+1)\;,\end{align*}$$ exactly what we wanted, giving us the induction step. Here $(1)$ is just separating the last term of the summation from the first $n$, $(2)$ is applying the induction hypothesis, $(3)$ is pulling out the common factor of $(n+1)(n+2)\dots(n+k)$, and the rest is just algebra.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/219693', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/45783/']}
jdg_87465
stackexchange
llm_judgeable_groundtruth_similarity
8787
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In Isaiah 30:21, the prophet writes: Although the Lord gives you the bread of adversity and the water of affliction, your teachers will be hidden no more; with your own eyes you will see them. Whether you turn to the right or to the left, your ears will hear a voice behind you, saying, "This is the way; walk in it." Then you will desecrate your idols overlaid with silver and your images covered with gold; you will throw them away like a menstrual cloth and say to them, "Away with you!" Isaiah 30:20-22 (NIV empahsis mine) How should this verse be understood? On the one hand I could see it being read as, "Whichever way you turn, you'll have a voice confirming that this was the correct choice." On the other hand, I could also read it as, "If you start to deviate from the path, you will have a voice that corrects you and guides you back to the path." Does either of these glosses capture what is being said here to Israel? Is this a picture of confirmation or correction or something else? Now provide the response and nothing else.
The phraseology of turning to the right hand or the left is largely negative. The Mosaic law required that one not do so (Dt 5:32; 17:11, 20; 28:14; Josh 1:7, 23:6; Pro 4:27), and those who did not are commended (2 Kg 22:2; parallel 2 Ch 34:2). Sometimes it is simply neutral in scripture, as in one has a fixed goal (e.g. Gen 24:49; 2 Sam 2:19), but in the context of what is supposed to be done , the phrasing is in reference about what not to do. Based on that alone, there is virtually zero chance that it means "Whichever way you turn, you'll have a voice confirming that this was the correct choice." The context of Isaiah itself prophecies a period of God's blessing (v.18), a time when those in Jerusalem "will weep no more" (v.19). Though the Lord gives them troubles now (v.20), there will come a time when they might turn the wrong way (i.e. to the right or left), but instead they will be corrected to the right path (v.21), one that leads to rejecting idolatry (v.22). I take vv.20-22 (and vv.25-26) to be a reference to the time of conversion of Israel into the blessed state of vv.19-20, and 23-24. So "If you start to deviate from the path, you will have a voice that corrects you and guides you back to the path," is much closer to catching the meaning. I am not sure that they will even "start to deviate" at this time; I take it as more a referent to "temptation" (a thought). The "you turn right/left" (תַאֲמִ֖ינוּ וְכִ֥י תַשְׂמְאִֽילוּ) are both in the imperfect state in the Hebrew, so it is not a completed action. That does not preclude them having already "started," but it seems contextually to me that the point is they will no more go the wrong way once they have attained this state of blessing (along the lines of the promise of Jer 31:33 and Ezek 36:26-27).
{}
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/8787', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/33/']}
jdg_87466
stackexchange
llm_judgeable_groundtruth_similarity
156618
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My goal is to check commit data that don't meet certain requirements and then reject either the commit being created or pushed to the remote repository. The problem of doing a pre-commit hook is that it's hard to deploy to many people who have to manually update their pre-commit hook file. As well, Git does not allow you to have submodules in the .git folder which would've been very easy for deployment yet alas. The other option I see is doing the checking in I believe the update hook on the remote side, which will check each commit being pushed by a dev and reject the push if any of the commits fail the tests. Does anyone have any insight on this problem? And if so, could you provide or point me towards an example update hook script? I'm a little confused as to how it works. Now provide the response and nothing else.
you must first figure out whether you don't want the unqualified code to be committed or to be pushed/published back to upstream. in my opinion the later one is more feasible. with a DVCS like git. you don't really want to control how every developer uses his local repository. and you can't really have control over that. a pre-commit hook works well as basic validation and sanitization, if everyone involved embrace it voluntarily. we actually enforce that loosely in our company. however, it can always be skipped with git commit --no-verify . server side hook, on the other hand, doesn't intervene a programmer's local workflow, and makes sure that others in the project base their work only on code that meets certain criteria. normally this is what people look for when they implement automatic checks. this automatic validation isn't meant to replace quality control, i guess, which is usually achieved with code review or pair programming. if you are familiar with github , you'd notice that "pull request" is yet another approach to this issue. many open source projects and companies use github's pull request for branch permission control and code review. but it needs human interaction, thus may not be what you're asking for.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/156618', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/59125/']}
jdg_87467
stackexchange
llm_judgeable_groundtruth_similarity
20336288
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given a square matrix of say size 400x400 , how would I go about splitting this into constituent sub-matrices of 20x20 using a for-loop? I can't even think where to begin! I imagine I want something like : [x,y] = size(matrix)for i = 1:20:x for j = 1:20:y but I'm unsure how I would proceed. Thoughts? Now provide the response and nothing else.
Well, I know that the poster explicitly asked for a for loop, and Jeff Mather's answer provided exactly that. But still I got curious whether it is possible to decompose a matrix into tiles (sub-matrices) of a given size without a loop. In case someone else is curious, too, here's what I have come up with: T = permute(reshape(permute(reshape(A, size(A, 1), n, []), [2 1 3]), n, m, []), [2 1 3]) transforms a two-dimensional array A into a three-dimensional array T , where each 2d slice T(:, :, i) is one of the tiles of size m x n . The third index enumerates the tiles in standard Matlab linearized order, tile rows first. The variant T = permute(reshape(A, size(A, 1), n, []), [2 1 3]);T = permute(reshape(T, n, m, [], size(T, 3)), [2 1 3 4]); makes T a four-dimensional array where T(:, :, i, j) gives the 2d slice with tile indices i, j . Coming up with these expressions feels a bit like solving a sliding puzzle. ;-)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20336288', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3058703/']}
jdg_87468
stackexchange
llm_judgeable_groundtruth_similarity
1386604
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a programming problem where I need to handle a number involving 100000 digits. Can python handle numbers like this? Now provide the response and nothing else.
As other answers indicated, Python does support integer numbers bounded only by the amount of memory available. If you want even faster support for them, try gmpy (as gmpy's author and current co-maintainer I'm of course a little biased here;-): $ python -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'x+1'10000 loops, best of 3: 114 usec per loop$ python -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'y+1'10000 loops, best of 3: 65.4 usec per loop Typically, arithmetic is not the bottleneck for working with such numbers (although gmpy 's direct support for some combinatorial and number-theoretical functions can help if that's what you're doing with such numbers). Turning the numbers into decimal strings is probably the common operation that will feel slowest...: $ python -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'str(x)'10 loops, best of 3: 3.11 sec per loop$ python -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'str(y)'10 loops, best of 3: 27.3 msec per loop As you see, even in gmpy stringification of huge numbers can be hundreds of times slower than a simple addition (alas, it's an intrinsically complicated operation!); but in native Python code the ratio of times can go to stringification being tens of thousands times slower than a simple addition, so you really want to watch out for that, especially if you decide not to download and install gmpy (for example because you can't: e.g., gmpy is not currently supported on Google App Engine). Finally, an intermediate case: $ python2.6 -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'x*x'10 loops, best of 3: 90 msec per loop$ python2.6 -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'y*y'100 loops, best of 3: 5.63 msec per loop$ python2.6 -mtimeit -s'import gmpy; x=10**100000; y=gmpy.mpz(x)' 'y*x'100 loops, best of 3: 8.4 msec per loop As you see, multiplying two huge numbers in native Python code can be almost 1000 times slower than the simple addition, while with gmpy the slowdown is less than 100 times (and it's not too bad even if only one if the numbers is already in gmpy 's own format so that there's the overhead of converting the other).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1386604', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_87469
stackexchange
llm_judgeable_groundtruth_similarity
4352499
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The time integration of Brownian motion is given by $X(t)=\int_0^tB(s)ds$ . In order to show that $X(t)$ is a gaussian process I work with the definition that for any $t_0<t_1 < t_2<\ldots <t_{n-1}$ the random variable $$ \langle v,(X_{t_0}, ... , X_{t_{n-1}}) \rangle $$ is again Gaussian. I tried to write out the quantity in terms of Riemann sums i.e. $$ X(t) = \lim_{n\to {\infty}}\sum_{k=0}^{n-1}B(t_k)(t_{k+1}-t_k) $$ But got stuck with all the indices, how to continue? We can assume that limits of gaussian random variables are again Gaussian. Now provide the response and nothing else.
Using integration by parts we get: $$X(t) = t B(t) - \int_0^ts dB(s)$$ Recall that the Itô integral of a deterministic function is a Gaussian process; thus $X(t)$ is the linear combination of two Gaussian process, making it Gaussian itself. Edit: We can prove this without directly appealing to results from Itô calculus (as requested in the comments). Using summation by parts , we get: $$\sum_{k=0}^{n-1}B(t_{k+1})(t_{k+1} - t_k) = B(t_n)t_n - \sum_{k=1}^{n-1} t_k(B(t_{k+1})- B(t_{k}))$$ The right hand side can be seen to be a Gaussian process; sending $n \to \infty$ we get that $X(t)$ is a Gaussian process.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4352499', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/368384/']}
jdg_87470
stackexchange
llm_judgeable_groundtruth_similarity
66658
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When I was in high school, my teacher did an experiment to show the power of atmospheric pressure. Experiment: Prepare a glass bottle, fill with water, put a glass plate on the bottle, make sure there is no air in the bottle, just water. Hold the glass bottle and plate, and invert them. Slowly, release the hand which hold the plate. Because the atmospheric pressure, the glass plate will not fall down. Question 1: As we know, if we didn't put water into the glass bottle, just air in the glass bottle the glass plate will fall down. So, If we use other liquid instead of water, this liquid has smaller density than water, like alcohol, the plate will not fall down. But, if we continue to chose the smaller density liquid until the liquid has density like air the plate will fall down. So, if there is a threshold density of liquid make the plate between falling down and not falling down? Question 2: If we put the bottle and plate into water slowly, when the plate and part of bottle are in the water but part of the bottle still above the water, will the plate fall down? Question 3: Continuing question 2, when both bottle and plate are in the water I know the plate will fall down. So, how does the pressure of water and atmosphere change? Is there a good description of this phenomena? Why does the trick continue to work with lower density fluids and why does placing the plate in the water cause it to fall? Now provide the response and nothing else.
There are two unrelated effects at work here. One is the atmospheric pressure, and the other is the surface tension of the water. Start with you holding the plate in place, and consider what happens when you release the plate. For the plate to fall down one of two things must happen. Either the volume of the water in the glass must increase, to allow the plate to move down, or air must flow into the glass at the contact line between the glass and the plate. Consider the first of these. If you pull the plate down slightly (and no air leaks in) the volume inside the glass must increase. Water has such a high bulk modulus that we can approximate it as incompressible. You would need an immense force pulling down on the plate to stretch the water to any significant degree. In practice the water would boil before its volume increased significantly, but even the lesser force required to boil the water is far greater than the weight of the glass plate. So the only way the plate can move down is for air to leak in through the contact between the glass and the plate. However this means forming small bubbles at the contact line, and small bubbles have a very high pressure due to the surface tension at the air/water interface. This means the bubble formation requires a greater pressure than the weight of the plate can generate, so the plate can't move down this way either. Incidentally, the effect of surface tension explains why the plate won't stick if the glass/plate contact isn't very good, or if there's a chip in the glass. In both cases there is a relatively large gap where a bubble can form, and large bubbles have a smaller pressure than small bubbles (the bubble pressure is inversely proportional to the bubble radius). The weight of the plate can generate enough pressure to form the large bubbles, and the plate falls off. Now we can explain why the plate falls off when you immerse the glass and plate in water. If you do this there is no air/water interface at the contact between the glass and the plate, so there is no surface tension effect. Water can leak through even the tiniest gap between the rim of the glass and the plate so the plate falls off (though it may take a few seconds as the water won't flow in instantly). The trick will work with most liquids because most liquids will neither expand nor boil under the weight of the plate. However it wouldn't work with very volatile liquids like ether, because ether boils too easily and vapour bubbles will form in the glass. You'd probably also find it wouldn't work if the air/liquid interface has too low a surface tension, because a low surface tension allows air to lean in between the glass and the plate.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/66658', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/25277/']}
jdg_87471
stackexchange
llm_judgeable_groundtruth_similarity
15358769
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I draw a shape by UIBezierPath in touchesMoved. -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [touches anyObject]; secondPoint = firstPoint; firstPoint = [touch previousLocationInView:self]; currentPoint = [touch locationInView:self]; CGPoint mid1 = midPoint(firstPoint, secondPoint); CGPoint mid2 = midPoint(currentPoint, firstPoint); [bezierPath moveToPoint:mid1]; [bezierPath addQuadCurveToPoint:mid2 controlPoint:firstPoint]; [self setNeedsDisplay]; } I want to fill RED color inside it after closePath but can't. Please help! - (void)drawRect:(CGRect)rect{ UIColor *fillColor = [UIColor redColor]; [fillColor setFill]; UIColor *strokeColor = [UIColor blueColor]; [strokeColor setStroke]; [bezierPath closePath]; [bezierPath fill]; [bezierPath stroke]; } Now provide the response and nothing else.
If you have a bezier path stored elsewhere, this should work: Edit Looking at your edited code, what is happening is that as you are closing the path that you are drawing is getting closed - so you get a line, not a shape since you have only two points. One way around this is to create the path as your points move, but stroke and fill a copy of that path. For example this is untested code, I'm writing it straight in -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{ UITouch *touch = [touches anyObject]; secondPoint = firstPoint; firstPoint = [touch previousLocationInView:self]; currentPoint = [touch locationInView:self]; CGPoint mid1 = midPoint(firstPoint, secondPoint); CGPoint mid2 = midPoint(currentPoint, firstPoint); [bezierPath moveToPoint:mid1]; [bezierPath addQuadCurveToPoint:mid2 controlPoint:firstPoint]; // pathToDraw is an UIBezierPath * declared in your class pathToDraw = [[UIBezierPath bezierPathWithCGPath:bezierPath.CGPath]; [self setNeedsDisplay]; } And then your drawing code can: - (void)drawRect:(CGRect)rect { UIColor *fillColor = [UIColor redColor]; [fillColor setFill]; UIColor *strokeColor = [UIColor blueColor]; [strokeColor setStroke]; // This closes the copy of your drawing path. [pathToDraw closePath]; // Stroke the path after filling it so that you can see the outline [pathToDraw fill]; // this will fill a closed path [pathToDraw stroke]; // this will stroke the outline of the path.} There is some tidying up to do an touchesEnded and this could be made more performant, but you get the idea.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15358769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1847431/']}
jdg_87472
stackexchange
llm_judgeable_groundtruth_similarity
7572339
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've written some test-cases inside a single TestNG Test which extends AbstractTestNGSpringContextTests. The ApplicationContext is correctly setup and I can use it inside my test-cases. The problem is that the setting up of the applicationContext can take some time and I don't want to do this for every test-class I have, as this would take some time which is unnecessary from my point of view. So my question is: Is it possible to run more than one TestNG test-class using the same Spring ApplicationContext which is setup only once? Thanks and best regards,Robert Now provide the response and nothing else.
JSF 2.3+ If you're already on JSF 2.3 or newer, and want to inject CDI-supported artifacts via e.g. @EJB , @PersistenceContext or @Inject , then simply add managed=true to the @FacesValidator annotation to make it CDI-managed. @FacesValidator(value="emailExistValidator", managed=true) JSF 2.2- If you're not on JSF 2.3 or newer yet, then you basically need to make it a managed bean. Use Spring's @Component , CDI's @Named or JSF's @ManagedBean instead of @FacesValidator in order to make it a managed bean and thus eligible for dependency injection. E.g., assuming that you want to use CDI's @Named : @Named@ApplicationScopedpublic class EmailExistValidator implements Validator { // ...} You also need to reference it as a managed bean by #{name} in EL instead of as a validator ID in hardcoded string. Thus, so <h:inputText ... validator="#{emailExistValidator.validate}" /> instead of <h:inputText ... validator="emailExistValidator" /> or <f:validator binding="#{emailExistValidator}" /> instead of <f:validator validatorId="emailExistValidator" /> For EJBs there's a workaround by manually grabbing it from JNDI, see also Getting an @EJB in @FacesConverter and @FacesValidator . If you happen to use JSF utility library OmniFaces , since version 1.6 it adds transparent support for using @Inject and @EJB in a @FacesValidator class without any additional configuration or annotations. See also the CDI @FacesValidator showcase example . See also: CDI Injection into a FacesConverter What's new in JSF 2.2 - Injection
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7572339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/426378/']}
jdg_87473
stackexchange
llm_judgeable_groundtruth_similarity
54469191
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Firebase Auth with google sign in Flutter. I am able to sign in however when I close the app(kill it), I have to sign up all over again. So is there a way to persist user authentication till specifically logged out by the user? Here is my auth class import 'package:firebase_auth/firebase_auth.dart';import 'package:google_sign_in/google_sign_in.dart';class Auth { FirebaseAuth _firebaseAuth; FirebaseUser _user; Auth() { this._firebaseAuth = FirebaseAuth.instance; } Future<bool> isLoggedIn() async { this._user = await _firebaseAuth.currentUser(); if (this._user == null) { return false; } return true; } Future<bool> authenticateWithGoogle() async { final googleSignIn = GoogleSignIn(); final GoogleSignInAccount googleUser = await googleSignIn.signIn(); final GoogleSignInAuthentication googleAuth = await googleUser.authentication; this._user = await _firebaseAuth.signInWithGoogle( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); if (this._user == null) { return false; } return true; // do something with signed-in user }} Here is my start page where the auth check is called. import 'package:flutter/material.dart';import 'auth.dart';import 'login_screen.dart';import 'chat_screen.dart';class Splash extends StatefulWidget { @override _Splash createState() => _Splash();}class _Splash extends State<Splash> { @override Widget build(BuildContext context) { return Scaffold( body: Center( child: CircularProgressIndicator( value: null, ), ), ); } @override void initState() { super.initState(); _handleStartScreen(); } Future<void> _handleStartScreen() async { Auth _auth = Auth(); if (await _auth.isLoggedIn()) { Navigator.of(context).pushReplacementNamed("/chat"); } Navigator.pushReplacement(context, MaterialPageRoute(builder: (BuildContext context) => LoginScreen(auth: _auth,))); }} Now provide the response and nothing else.
I believe your problem is routing. In my apps I use FirebaseAuth and it works just as you say you wanted to, and I don't persist any login token. However, I don't know why your approach of using a getUser is not working. Try to adjust your code to use onAuthStateChanged . EDIT: As of 2022, with Flutter 3, I noticed it worked better with userChanges instead. Basically, on your MaterialApp , create a StreamBuilder listening to _auth.userChanges() and choose your page depending on the Auth status. I'll copy and paste parts of my app so you can have an idea: [...]final FirebaseAuth _auth = FirebaseAuth.instance;Future<void> main() async { FirebaseApp.configure( name: '...', options: Platform.isIOS ? const FirebaseOptions(...) : const FirebaseOptions(...), ); [...] runApp(new MaterialApp( title: '...', home: await getLandingPage(), theme: ThemeData(...), ));}Future<Widget> getLandingPage() async { return StreamBuilder<FirebaseUser>( stream: _auth.userChanges(), builder: (BuildContext context, snapshot) { if (snapshot.hasData && (!snapshot.data!.isAnonymous)) { return HomePage(); } return AccountLoginPage(); }, );}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54469191', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5400847/']}
jdg_87474
stackexchange
llm_judgeable_groundtruth_similarity
26315046
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Running on iOS 8, I need to change the UI when rotating my app. Currently I am using this code: -(BOOL)shouldAutorotate{ UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; if (orientation != UIInterfaceOrientationUnknown) [self resetTabBar]; return YES;} What I do it remove the current UI and add a new UI appropriate to the orientation. However, my issue is that this method is called about 4 times every time a single rotation is made. What is the correct way to make changes upon orientation change in iOS 8? Now provide the response and nothing else.
Timur Kuchkarov is correct, but I'll post the answer since I missed his comment the first time I checked this page. The iOS 8 method of detecting orientation change (rotation) is implementing the following method of the view controller: - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator{ // Do view manipulation here. [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];} Note: The controller's view has not yet transitioned to that size at this time, so be careful if your sizing code relies on the view's current dimensions.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26315046', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/427292/']}
jdg_87475
stackexchange
llm_judgeable_groundtruth_similarity
39357195
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a question regarding dynamic component creation in Angular 2 rc5. So let's assume that we have two plain angular components: @Component({ template: ` <div id="container"> <h1>My Component</h1> </div> `, selector: 'my-app' }) export class AppComponent { } @Component({ template: '<p>{{text}}</p>', selector: 'simple-cmp' }) export class SimpleComponent { public text='Hello World!' } Then some external non-angular chunck of code modificates a DOM: let newNode = document.createElement('div');newNode.id = 'placeholder';document.getElementById('container').appendChild(newNode); Here is some presumable tree after manipulations: <div id="container"> <h1>My Component</h1> <div id="placeholder"></div> </div> So what I'm trying to do is just dynamically add SimpleComoponent instance into #placeholder div. How can I achieve this result? I've been trying using ComponentFactory.createComponent(injector, [], newNode), it added the component though, but neither life cycle hooks nor binding not worked at all. I believe there is some way to implement this using ViewContainerRef, but how can I link it with dynamically created node? Here is the result I expect <div id="container"> <h1>My Component</h1> <div id="placeholder"> <simple-cmp>Hello world!</simple-cmp> </div> </div> Thanks! Now provide the response and nothing else.
When creating a component you can pass the DOM node that will act as a host element of the created component: create(injector: Injector, projectableNodes?: any[][], rootSelectorOrNode?: string|any , ngModule?: NgModuleRef): ComponentRef But since this component is not child of any other component, you have to manually attach it to ApplicationRef so you get change detection. So here is what you need to do: 1) Create a component specifying the root node under which it should be added. 2) Attach the view to the ApplicationRef so that you get change detection. You will still have no Input and ngOnChanges operations, but the DOM update will be working fine. @Component({ template: ` <div id="container"> <h1>My Component</h1> </div> `, selector: 'my-app' }) export class AppComponent { constructor(private resolver: ComponentFactoryResolver, private injector: Injector, private app: ApplicationRef) { } addDynamicComponent() { let factory = this.resolver.resolveComponentFactory(SimpleComponent); let newNode = document.createElement('div'); newNode.id = 'placeholder'; document.getElementById('container').appendChild(newNode); const ref = factory.create(this.injector, [], newNode); this.app.attachView(ref.hostView); } }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39357195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4908842/']}
jdg_87476
stackexchange
llm_judgeable_groundtruth_similarity
38041818
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have three entities. those are: @Entitypublic class Organization { @Id private long id; @Column private String name;} @Entitypublic class Book { @Id private Long id; @Column private String name; @ManyToOne private Organization organization;} @Entitypublic class Account { @Id private Long id; @Column private String name; @ManyToOne private Book book;} In these three entities I would like to perform following sql: SELECT acc.name, acc.idFROM account accJOIN book b on acc.book_id = b.idJOIN organization org on b.organization_id = org.idWHERE org.name = 'XYZ' In this case Account entity has no relation with the Organization entity directly. Account entity has the relation via Book . How can I achieve this using hibernate criteria dynamic query? Now provide the response and nothing else.
you can do like this : Criteria accountCriteria = getCurrentSession().createCriteria(Account.class,"acc");Criteria bookCriteria = accountCriteria .createCriteria("book","b");Criteria orgCriteria = bookCriteria.createCriteria("organization","org");orgCriteria.add(Restrictions.eq("name", "XYZ"));ProjectionList properties = Projections.projectionList();properties.add(Projections.property("name"));properties.add(Projections.property("id"));accountCriteria.setProjection(properties);accountCriteria.list();
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38041818', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1743867/']}
jdg_87477
stackexchange
llm_judgeable_groundtruth_similarity
2541718
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here's the code: class BinaryTree: def __init__(self,rootObj): self.key = rootObj self.left = None self.right = None root = [self.key, self.left, self.right] def getRootVal(root): return root[0] def setRootVal(newVal): root[0] = newVal def getLeftChild(root): return root[1] def getRightChild(root): return root[2] def insertLeft(self,newNode): if self.left == None: self.left = BinaryTree(newNode) else: t = BinaryTree(newNode) t.left = self.left self.left = t def insertRight(self,newNode): if self.right == None: self.right = BinaryTree(newNode) else: t = BinaryTree(newNode) t.right = self.right self.right = tdef buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif i not in '+-*/)': currentTree.setRootVal(eval(i)) parent = pStack.pop() currentTree = parent elif i in '+-*/': currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: print "error: I don't recognize " + i return eTreedef postorder(tree): if tree != None: postorder(tree.getLeftChild()) postorder(tree.getRightChild()) print tree.getRootVal()def preorder(self): print self.key if self.left: self.left.preorder() if self.right: self.right.preorder()def inorder(tree): if tree != None: inorder(tree.getLeftChild()) print tree.getRootVal() inorder(tree.getRightChild())class Stack: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[len(self.items)-1] def size(self): return len(self.items)def main(): parseData = raw_input( "Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) " ) tree = buildParseTree(parseData) print( "The post order is: ", + postorder(tree)) print( "The post order is: ", + postorder(tree)) print( "The post order is: ", + preorder(tree)) print( "The post order is: ", + inorder(tree))main() And here is the error: Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) ( 1 + 2 )Traceback (most recent call last): File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 108, in main() File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 102, in main tree = buildParseTree(parseData) File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 46, in buildParseTree currentTree = currentTree.getLeftChild() File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 15, in getLeftChild return root[1]AttributeError: BinaryTree instance has no attribute '__getitem__' Now provide the response and nothing else.
Because you declared your methods wrong: Lets have a look what happens if you call tree.getRootVal() . .getRootVal() is declared this way: def getRootVal(root): return root[0] As you probably know, the first parameter passed to a method is always the instance and it is provided implicitly. So you basically try to treat an instance of BinaryTree as a sequence( root[0] ). You have to specify it this way: class BinaryTree: def __init__(self,rootObj): self.key = rootObj self.left = None self.right = None self.root = [self.key, self.left, self.right] # self.root def getRootVal(self): return self.root[0] # access self.root def setRootVal(self, newVal): self.root[0] = newVal # and also the other functions The first parameter to an objects method does not have to be called self . But helps to do it this way in order to avoid errors like you did. Interesting that you declared insertLeft and insertRight correctly ;)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2541718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/304648/']}
jdg_87478
stackexchange
llm_judgeable_groundtruth_similarity
7769
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Symlinking to a directory gives to different results with ls -l depending on whether I ln -s dir or ln -s dir/ . But what's the actual difference, and which one should I prefer why? Now provide the response and nothing else.
The only thing I can think of is that it "protects" you from someone deleting the directory and creating a file. [user@host linktest]$ mkdir test[user@host linktest]$ ln -s test/ slash[user@host linktest]$ ln -s test noslash[user@host linktest]$ ls -ltotal 4lrwxrwxrwx 1 paul paul 4 Feb 21 21:00 noslash -> testlrwxrwxrwx 1 paul paul 5 Feb 21 21:00 slash -> test/drwxrwxr-x 2 paul paul 4096 Feb 21 20:59 test[user@host linktest]$ file *slashnoslash: symbolic link to `test'slash: symbolic link to `test/'[user@host linktest]$ rmdir test[user@host linktest]$ file *slashnoslash: broken symbolic link to `test'slash: broken symbolic link to `test/'[user@host linktest]$ touch test[user@host linktest]$ file *slashnoslash: symbolic link to `test'slash: broken symbolic link to `test/'[user@host linktest]$ The version with the slash breaks when the target is replaced with a file.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/7769', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/863/']}
jdg_87479
stackexchange
llm_judgeable_groundtruth_similarity
6025475
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Second list squared each item on list, xs. Running the code below, python gives me 'None' xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]a = [b**2 for b in xs]c = (a + xs).sort()print(c, end=', ') Same list but different code-- xs = [12, 10, 32, 3, 66, 17, 42, 99, 20]a = [b**2 for b in xs]c = a + xsc.sort()print(c, end=', ') ...python gives me my list(c), all sorted. I don't get it. Or is there a more pythonic way to do this? Thanks! Now provide the response and nothing else.
Generally speaking, anything that operates on something in-place will return None , by convention. (This convention is not necessarily always followed, however.) somelist.sort() will sort the list in-place. If you'd rather have a sorted copy , you can just call c = sorted(a + xs) . sorted operates on a copy of the original, and therefore returns the copy. There's a much more through explanation here: http://wiki.python.org/moin/HowTo/Sorting/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6025475', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/731819/']}
jdg_87480
stackexchange
llm_judgeable_groundtruth_similarity
461232
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to enable/disable a TI TPS54302 buck regulator with a microcontroller. The enable (EN) pin should float to enable the device, or be tied low to disable it. I currently have the EN pin connected to a GPIO pin on the MCU. At startup, before the pin state can be set low, it will sometimes already be floating, so the regulator operates for a brief time before the pin is intentionally set low. I'd like to add an external pull-down resistor to ensure the regulator stays off until it is supposed to be on, but that would prevent floating the pin. I presume I could simply pull the pin high (instead of floating it) and achieve the desired result. The TPS54302 datasheet says: The EN pin has an internal pullup-current source which allows the user to float the EN pin to enable the device. If an application requires control of the EN pin, use open-drain or open-collector output logic to interface with the pin. If I tie the EN pin to ground with a 10kΩ resistor, and pull the MCU pin high when I want the regulator to operate, is that a viable solution? I'm not concerned about small (≥1mA) constant current usage as this is a line-powered device. Now provide the response and nothing else.
Yes, you're fine with your approach. The EN pull up current is less than 2uA, so a 10K will allow you to remain below the threshold, and the microcontroller output will be able to pull it up to 5V (or at least greater than the threshold. Just stay below 7V on the enable pin and you'll be fine.) As you pointed out an open drain output on your micro doesn't really solve the problem of keeping the device disabled while the uC boots up. Note datasheet specs below: [EDIT for more clarity:] The reason for the recommendation for the open drain approach is that this part allows Vin up to 28V, but the EN pin is only rated to 7V abs max. So you can't pull the enable to Vin or drive it with an open collector with a pull-up tied to Vin. Nothing prohibits driving the pin from an open collector only, an open collector pulled up to (e.g.) 3.3V or 5V, or a push-pull output in the right voltage range. You don't HAVE to just float the pin or pull it low. Note the UVLO level modification circuit in the datasheet:
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/461232', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/2028/']}
jdg_87481
stackexchange
llm_judgeable_groundtruth_similarity
10456761
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I wrote a few migrations for my Rails 3 app, but I would like to change the order of the migrations. How can I change the migration order or sequence? Is it as simple as renaming the migration file with what appears to be the timestamp? I know this is an odd question, but basically, I made a mess of my migrations and removed some old migrations and now I need to drop a table before creating a new one. I also know I can include the drop statement in the create-the-new-table migration, but I'm curious to know how to reorder migrations. Now provide the response and nothing else.
Yes, it runs the migrations which have not been run in the order of the prefix. In earlier versions of rails, maybe 2.1 or 2.2 , they used to be numbered starting with 01 , but they switched to timestamps. There is a table which keeps track of which migrations have run. The intentions is, multiple developers my have added migrations, and checked them in version control later. So, there may be a migration which has not run, but is numbered before the highest numbered migration which has run. If you change the migration sequence, (and I have) it's better to first down version before all the migrations you are re-sequencing. Use the VERSION option with db:migrate . If the highest numbered migration that you want to keep (not run the down) is 20120318143249 , call it this way. rake db:migrate VERSION=20120318143249 I often run the down on a migration, and re-run it until I get the details of the migration to my satisfaction. Sometimes I re-order them, when I want to work on one of them, and I want it to be the last.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10456761', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/457478/']}
jdg_87482
stackexchange
llm_judgeable_groundtruth_similarity
1350215
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm doing a problem on finding the dimension of a linear subspace, more specifically if $\:$ {$f \in \mathcal P_n(\mathbf F): f(1)=0, f'(2)=0$} is a subspace of $P_n$, what is this dimension of this subspace? Here $\mathcal P_n(\mathbf F)$ denotes a vector space of Polynomials of degree $n$ over the real number field. At first glance, I thought the dimension is infinity, but I think perhaps since the degree is restricted, the dimension should be finite. Yet I find it hard to specify the number of dimensions. Being a beginner of linear algebra, I would like to hear some detailed explanation on how to solve this type of problems. Thanks in advance! Now provide the response and nothing else.
Intuitively, dimension is the number of degrees of freedom. The elements of $\mathcal{P}_n(\mathbb R)$ are polynomials of degree $n$ (more precisely, at most $n$), so they look like$$ a_0 + a_1 x + a_2 x^2 + \dotsb + a_{n-1} x^{n-1} + a_n x^n $$To specify such a polynomial, you have to specify $n+1$ numbers, the coefficients $a_0,a_1,\dotsc,a_n$. So there are $n+1$ degrees of freedom in this "space" of polynomials. To prove that formally, you'd want to think of polynomials $a_0+\dotsb+a_nx^n$ as being linear combinations of the polynomials $1,x,x^2,\dotsc,x^n$, and show that these latter polynomials form a basis. This is done in chapter 2 of Axler. Again intuitively, a constraint that specifies a single number reduces the number of degrees of freedom by 1. Thus imposing the constraint that we will only work with polynomials $f(x)$ satisfying $f(1)=0$ should, we expect, reduce the dimension from $n+1$ to $n$. The formal version of this is the rank-nullity theorem (Axler's theorem 3.4), which is why everybody's giving answers involving it. I see Axler doesn't do that until chapter 3, though. So I think the only thing you can do at this point is to produce an explicit basis for the subspace in question. Exercise 8 in chapter 2 is similar; have you tried that? (And for playing with polynomials, exercises 9 and 12 in the same chapter are good.) (I have the 2nd edition of Axler's text; hopefully it matches yours.)
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1350215', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/248257/']}
jdg_87483
stackexchange
llm_judgeable_groundtruth_similarity
28133
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I flushed my transmission recently, and I overfilled it slightly, maybe by a 1/2 liter on a transmission that takes about 8 liters. When cold, the fluid is a little over the cold mark, but not up to the hot mark. Will this harm the transmission? Now provide the response and nothing else.
Automatic transmissions are very susceptible to damage from overfill. This occurs because auto transmission fluid expands a lot (well, a lot more than engine oil, for instance). The problem it can create is blowing the seals, like where the torque converter rides. The seal itself is not expensive in and of itself, but getting to the seal can cost a lot. It would also affect your output shaft seals. The interior seals/and such may suffer damage as well, but hard parts, bands, and clutches should not suffer any damage. Needless to say, running around with too much transmission fluid is not a good thing. My suggestion is to get it down to level as soon as possible. As per the 1/2 liter, who knows how much is too much. You may get by with it ... but why chance it.
{}
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/28133', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/7132/']}
jdg_87484
stackexchange
llm_judgeable_groundtruth_similarity
24041639
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using django-filter with django-rest-framework and I'm trying to instantiate a filter that accepts lists of numbers for filtering the query set down class MyFilter(django_filters.FilterSet): ids = django_filters.NumberFilter(name='id',lookup_type='in') class Meta: model = MyModel fields = ('ids',)class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer filter_class = MyFilter If I pass in a comma separated list of integers, the filter is ignored altogether. If I pass in a single integer, it gets through django-filter into django's form validator and complains: 'Decimal' object is not iterable Is there a way to create a django-filter object which can handle a list of integers and properly filter down the queryset? Now provide the response and nothing else.
For better or worse, I created a custom filter for this: class IntegerListFilter(django_filters.Filter): def filter(self,qs,value): if value not in (None,''): integers = [int(v) for v in value.split(',')] return qs.filter(**{'%s__%s'%(self.name, self.lookup_type):integers}) return qs Which is used like: class MyFilter(django_filters.FilterSet): ids = IntegerListFilter(name='id',lookup_type='in') class Meta: model = MyModel fields = ('ids',)class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer filter_class = MyFilter Now my interface accepts comma-delimited lists of integers.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24041639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20712/']}
jdg_87485
stackexchange
llm_judgeable_groundtruth_similarity
15742177
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When trying to create a list of similar functions using lapply , I find that all the functions in the list are identical and equal to what the final element should be. Consider the following: pow <- function(x,y) x^ypl <- lapply(1:3,function(y) function(x) pow(x,y))pl[[1]]function (x) pow(x, y)<environment: 0x09ccd5f8>[[2]]function (x) pow(x, y)<environment: 0x09ccd6bc>[[3]]function (x) pow(x, y)<environment: 0x09ccd780> When you try to evaluate these functions you get identical results: pl[[1]](2)[1] 8pl[[2]](2)[1] 8pl[[3]](2)[1] 8 What is going on here, and how can I get the result I desire (the correct functions in the list)? Now provide the response and nothing else.
R passes promises , not the values themselves. The promise is forced when it is first evaluated, not when it is passed, and by that time the index has changed if one uses the code in the question. The code can be written as follows to force the promise at the time the outer anonymous function is called and to make it clear to the reader: pl <- lapply(1:3, function(y) { force(y); function(x) pow(x,y) } )
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15742177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/269476/']}
jdg_87486
stackexchange
llm_judgeable_groundtruth_similarity
12960574
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am going through the 'Python for Data Analysis' book and having trouble in the 'Example: 2012 Federal Election Commision Database' section reading the data to a DataFrame. The trouble is that one of the columns of data is always being set as the index column, even when the index_col argument is set to None. Here is the link to the data : http://www.fec.gov/disclosurep/PDownload.do . Here is the loading code (to save time in the checking, I set the nrows=10): import pandas as pdfec = pd.read_csv('P00000001-ALL.csv',nrows=10,index_col=None) To keep it short I am excluding the data column outputs, but here is my output (please not the Index values): In [20]: fecOut[20]:<class 'pandas.core.frame.DataFrame'>Index: 10 entries, C00410118 to C00410118Data columns:...dtypes: float64(4), int64(3), object(11) And here is the book's output (again with data columns excluded): In [13]: fec = read_csv('P00000001-ALL.csv')In [14]: fecOut[14]:<class 'pandas.core.frame.DataFrame'>Int64Index: 1001731 entries, 0 to 1001730...dtypes: float64(1), int64(1), object(14) The Index values in my output are actually the first column of data in the file, which is then moving all the rest of the data to the left by one. Would anyone know how to prevent this column of data to be listed as an index? I would like to have the index just +1 increasing integers. I am fairly new to python and pandas, so I apologize for any inconvenience. Thanks. Now provide the response and nothing else.
Quick Answer Use index_col=False instead of index_col=None when you have delimiters at the end of each line to turn off index column inference and discard the last column. More Detail After looking at the data, there is a comma at the end of each line. And this quote (the documentation has been edited since the time this post was created): index_col: column number, column name, or list of column numbers/names, to use as the index (row labels) of the resulting DataFrame. By default, it will number the rows without using any column, unless there is one more data column than there are headers, in which case the first column is taken as the index. from the documentation shows that pandas believes you have n headers and n+1 data columns and is treating the first column as the index. EDIT 10/20/2014 - More information I found another valuable entry that is specifically about trailing limiters and how to simply ignore them: If a file has one more column of data than the number of column names, the first column will be used as the DataFrame’s row names: ... Ordinarily, you can achieve this behavior using the index_col option. There are some exception cases when a file has been prepared with delimiters at the end of each data line, confusing the parser. To explicitly disable the index column inference and discard the last column, pass index_col=False: ...
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12960574', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1757088/']}
jdg_87487
stackexchange
llm_judgeable_groundtruth_similarity
3123246
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I attempted to evaluate this integral but seem to be getting nowhere $$I=\int_0^\pi \ln\left(1+\sin^2(t)\right) dt$$ Wolfram returns the value $I\approx 1.18266$ but was not able to provide a closed form for me. I suspect that one could exist but I'm not sure how to proceed. Any help will be appreciated. Now provide the response and nothing else.
Here is a different way to set up that a parameter in order to apply Feynman's trick. $$I=2\int_0^\frac{\pi}{2} \ln\left(1+\sin^2t\right) dt\overset{t=\operatorname{arccot} x}=2\int_0^\infty \frac{\ln(2+x^2)-\ln(1+x^2)}{1+x^2}dx$$ Now let us consider $$I(a)=\int_0^\infty \frac{\ln(a+x^2)-\ln(1+x^2)}{1+x^2}dx\Rightarrow I'(a)=\int_0^\infty \frac{1}{(1+x^2)(a+x^2)}dx$$ $$=\frac{1}{a-1}\left(\int_0^\infty \frac{1}{x^2+1}dx-\int_0^\infty \frac{1}{x^2+a}dx\right)=\frac{1}{a-1}\left(\frac{\pi}{2}-\frac{1}{\sqrt a}\cdot \frac{\pi}{2}\right)=\frac{\pi}{2}\frac{1}{\sqrt a(1+\sqrt a)}$$ We are looking to find $I=2I(2)$ , but since $I(1)=0$ we have: $$I=2\left(I(2)-I(1)\right)=2\int_1^2 I'(a)da=\pi \int_1^2 \frac{1}{\sqrt a(1+\sqrt a)}da$$ $$\overset {\large a=x^2}=2\pi\int_1^\sqrt 2 \frac{1}{1+x}dx=2\pi \ln(1+x)\bigg|_1^\sqrt 2=2\pi \ln\frac{1+\sqrt 2}{2}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3123246', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/468742/']}
jdg_87488
stackexchange
llm_judgeable_groundtruth_similarity
50746096
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm studying deep learning. Trained an image classification algorithm. The problem is, however, that to train images I used: test_image = image.load_img('some.png', target_size = (64, 64))test_image = image.img_to_array(test_image) While for actual application I use: test_image = cv2.imread('trick.png')test_image = cv2.resize(test_image, (64, 64)) But I found that those give a different ndarray (different data): Last entries from load_image: [ 64. 71. 66.] [ 64. 71. 66.] [ 62. 69. 67.]]] Last entries from cv2.imread: [ 15 23 27] [ 16 24 28] [ 14 24 28]]] , so the system is not working. Is there a way to match results of one to another? Now provide the response and nothing else.
OpenCV reads images in BGR format whereas in keras, it is represented in RGB. To get the OpenCV version to correspond to the order we expect (RGB), simply reverse the channels: test_image = cv2.imread('trick.png')test_image = cv2.resize(test_image, (64, 64))test_image = test_image[...,::-1] # Added The last line reverses the channels to be in RGB order. You can then feed this into your keras model. Another point I'd like to add is that cv2.imread usually reads in images in uint8 precision. Examining the output of your keras loaded image, you can see that the data is in floating point precision so you may also want to convert to a floating-point representation, such as float32 : import numpy as np# ...# ...test_image = test_image[...,::-1].astype(np.float32) As a final point, depending on how you trained your model it's usually customary to normalize the image pixel values to a [0,1] range. If you did this with your keras model, make sure you divide your values by 255 in your image read in through OpenCV: import numpy as np# ...# ...test_image = (test_image[...,::-1].astype(np.float32)) / 255.0
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50746096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4363045/']}
jdg_87489
stackexchange
llm_judgeable_groundtruth_similarity
402604
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have three independent groups, with mean $\mu_1,~ \mu_2,~\mu_3$ respectively. How can I test whether $\mu_1 < \mu_2 <\mu_3$ or not using $n_1,~n_2,~n_3$ samples from each group? I wish to know some general methodology, not detailed calculation. I couldn't figure out how to set my hypothesis $H_0$ and $H_1$ . Now provide the response and nothing else.
In statistics you cannot test whether "X is true or not". You can only try to find evidence that a null hypothesis is false. Let's say your null hypothesis is $$H_0^1: \mu_1 < \mu_2 < \mu_3.$$ Let's also assume that you have a way of estimating the vector $\mu = (\mu_1, \mu_2, \mu_3)'$ . To keep things simply assume that you have an estimator $$x \sim N(\mu, \Sigma),$$ where $\Sigma$ is $3 \times 3$ covariate matrix.We can rewrite the null hypothesis as $$A \mu < 0,$$ where $$A = \begin{bmatrix}1 & - 1 & 0 \\0 & 1 & - 1\end{bmatrix}.$$ This shows that your null hypothesis can be expressed as an inequality restriction on the vector $A \mu$ . A natural estimator of $A\mu$ is given by $$A x \sim N(A\mu, A\Sigma A').$$ You can now use the framework for testing inequality constraint on normal vectors given in: Kudo, Akio (1963). “A multivariate analogue of the one-sided test”. In: Biometrika 50.3/4, pp. 403–418. This test will also work if the normality assumption holds only approximately ("asymptotically"). For example, it will work if you can draw sample means from the groups. If you draw samples of size $n_1, n_2, n_3$ and if you can draw independently from the groups then $\Sigma$ is a diagonal matrix with diagonal $$(\sigma_1^2/n_1, \sigma_2^2/n_2, \sigma_3^2/n_3)',$$ where $\sigma_k^2$ is the variance in group $k = 1, 2, 3$ . In an application, you can use sample variance instead of the unknown population variance without changing the properties of the test. If on the other hand your alternative hypothesis is $$H_1^2: \mu_1 < \mu_2 < \mu_3$$ then your null hypothesis becomes $$H_0^2: \text{NOT $H_1$}.$$ This isn't very operational. Remember that our new alternative hypothesis can be written as $H_1: A\mu <0$ so that $$H_0^2: \text{there exists a $k=1,2$ such that $(A\mu)_k \geq 0$}.$$ I don't know if there exists any specialized test for this, but you can definitely try some strategy based on successive testing. Remember that you try to find evidence against the null. So you may first test $$H_{0,1}^2: (A\mu)_1 \geq 0.$$ and then $$H_{0,2}^2: (A\mu)_2 \geq 0.$$ If you reject both times then you have found evidence that $H_0$ is false and you reject $H_0$ . If you don't, then you don't reject $H_0$ .Since you are testing multiple times you have to adjust the nominal level of the subtest. You can use a Bonferroni correction or figure out an exact correction (since you know $\Sigma$ ). Another way of constructing a test for $H_0^2$ is to note that $$H_0^2: \max_{k=1,2} (A\mu)_k \geq 0.$$ This implies using $\max Ax$ as a test statistic. The test will have a non-standard distribution under the null, but the appropriate critical value should still be fairly easy to compute.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/402604', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/178816/']}
jdg_87490
stackexchange
llm_judgeable_groundtruth_similarity
893977
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my Java application I am renaming files to a file name provided in a String parameter. There is a method boolean OKtoRename(String oldName, String newName) which basically checks whether the newName isn't already taken by some other file, as I wouldn't want to bury existing ones. It now occurred to me that perhaps the newName String will not denote a valid file name. So I thought to add this check to the method: if (new File(newName).isFile()) { return false; } Which obviously isn't the right way to do it, since in most cases the newFile does not yet exist and therefore although it is OKtoRename, the function returns false. I was wondering, is there a method (I know there isn't for the java.io.File objects) like canExist() ? Or would I have to resort to regex to make sure the newFile String does not contain invalid characters (e.g. ?, *, ", :)? I wonder if there is perhaps a function hidden somewhere in the JDK that would tell me if a string could possibly denote a valid file name. Now provide the response and nothing else.
Use createNewFile() , which will atomically create the file only if it doesn't yet exist. If the file is created, the name is valid and it is not clobbering an existing file. You can then open the files and efficiently copy data from one to the other with FileChannel.transferXXX operations. An important thing to keep in mind that, in general, the check and the creation should be atomic. If you first check whether an operation is safe, then perform the operation as a separate step, conditions may have changed in the meantime, making the operation unsafe. Additional food for thought is available at this related post: "Move/Copy operations in Java." Update: Since this answer, the NIO.2 APIs have been introduced, which add more interaction with the file system. Suppose you have an interactive program, and want to validate after each keystroke whether the file is potentially valid. For example, you might want to enable a "Save" button only when the entry is valid rather than popping up an error dialog after pressing "Save". Creating and ensuring the deletion of a lot of unnecessary files that my suggestion above would require seems like a mess. With NIO.2, you can't create a Path instance containing characters that are illegal for the file system. An InvalidPathException is raised as soon as you try to create the Path . However, there isn't an API to validate illegal names comprised of valid characters, like "PRN" on Windows. As a workaround, experimentation showed that using an illegal file name would raise a distinct exception when trying to access attributes (using Files.getLastModifiedTime() , for example). If you specify a legal name for a file that does exist, you get no exception. If you specify a legal name for a file that does not exist, it raises NoSuchFileException . If you specify an illegal name, FileSystemException is raised. However, this seems very kludgey and might not be reliable on other operating systems.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/893977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/81520/']}
jdg_87491
stackexchange
llm_judgeable_groundtruth_similarity
1351442
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The common mixing of RGB colors is very different from mixing colors for paintings,it's mixing of light instead mixing of pigments. For example: Blue (0,0,255) + Yellow (255,255,0) = Grey (128,128,128) (It should be Blue + Yellow = Green) Is there any known algorithm for color mixing that works like mixing real colors? My approach I've already tried following: Converting both colors to HSV and mixing hues (multiplied by coefficient computed from saturation),and a simple average for saturation and value channels. Then I computed average luminance from bothcolors and adjusted the resulting color to match this luminance.This worked quite well, but the hue mixing was sometimes wrong, e. g.: Red (Hue 0°) + Blue (Hue 240°) = Green (Hue 120°) I've figured out that sometimes I need to shift the hue value by 360° (when the difference betweenhues is greater than 180°). Red (Hue 360°) + Blue (Hue 240°) = Magenta/fuchsia (Hue 300°) But this shifting wasn't very good too, e.g.: Cyan (Hue 179°) + Red (Hue 0°) = Hue 89.5°Cyan (Hue 181°) + Red (Hue 0°) --> shifting is performed (the difference is greater than 180°)Cyan (Hue 181°) + Red (Hue 360°) = Hue 270.5° (Hue 179 + Red) and (Hue 181 + Red) results in two completely different colors. Then I tried CIE Lab color space (as in Photoshop), which is designed to be closer to how humans perceive the colors. I used just a simple average for each corresponding two channels, but the results weren't satisfying,for example, I got pink (64, 26, -9.5) out of blue (98, -16, 93) and yellow (30, 68, -112). These coefficientswere taken from Photoshop. Maybe if I used some different operation than average, it could work, butI don't know what. CMYK didn't work too , results are just like in RGB or LAB. It seems that neither the trivial additive nor subtractive color mixing in any of these color spaces yields natural results. Working implementations Krita – Painterly mixer Raster graphics editor Krita had a working implementation of more realistic color mixing at some point: http://commit-digest.org/issues/2007-08-12/ (Painterly mixer plugin) They say it is the first public application that implements special technology using Kubelka and Munk equations that describe the behavior of pigments. Here's a video of Krita color mixing: https://www.youtube.com/watch?v=lyLPZDVdQiQ Paper by FiftyThree There's also article about color blending in the Paper app for iOS developed by FiftyThree . They describe how they innovate and experiment in the area and also offer samples of mixing blue and yellow that results in green. However, the actual process or algorithm isn't really described there. Quoting: "In searching for a good blending algorithm, we initially tried interpolating across various color-spaces: RGB, HSV, and HSL, then CieLAB and CieLUV. The results were disappointing," says Chen. "We know red and yellow should yield orange, or that red and blue should make purple—but there isn't any way to arrive at these colors no matter what color-space you use. There's an engineering axiom: Do the simplest thing that could possibly work. Well, we had now tried the easiest possible approaches and they didn't feel even remotely right." It seems that same as Krita, Paper implements the Kubelka-Munk model: [...] the Kubelka-Munk model had at least six values for each color, including reflection and absorption values for each of the RGB colors. "While the appearance of a color on a screen can be described in three dimensions, the blending of color actually is happening in a six-dimensional space," explains Georg Petschnigg, FiftyThree's co-founder and CEO. The Kubelka-Munk paper had allowed the team to translate an aesthetic problem into a mathematical framework. [...] From all this information, it seems that implementation based on the Kubelka-Munk model could be the way forward and offer results that are much closer to reality. Even though it looks like a complicated process, I haven't yet seen much good information on how to implement something like this. Related questions These questions were posted after this one all relating to the same thing. None of them really has the answer. Calculation of a mixed color in RGB Algorithm for finding the color between two others - in the color space of painted colors Implementing Kubelka-Munk like Krita to mix colors like paint Other related links and resources Kubelka-Munk search on Twitter Mixing paints (!!Con 2016) by Diana Liao slides video Paint Inspired Color Mixing and Compositing for Visualization (N. Gossett, B. Chen) Now provide the response and nothing else.
The correct answer is NO, because there is no correct working model of how "color mixing in the real world" really works. It is FAR too complex and conditional and not really at all like the simple Red-Blue-Yellow stuff that we learned in school (it in fact requires all of Chemistry and a lot of Physics and Biology to resolve). However, the simplistic answer is: YES, use subtractive mixing rather than Additive mixing. The color-mixing that we learned in grade school is based on pigment combinations which are a form of subtractive color mixing (very simplistically). That is the more colors that we add together, the darker it becomes because each pigment subtracts a little bit more light. On the other hand, almost all computer color-schemes are additive in that they are based on combining light waves (very simplistically), so they get brighter, because each color adds a little bit more light. The RGB+ scheme is somewhat, the additive complement to the subtractive scheme that we learned in most US elementary schools (which is RBY-). However, they do not match up exactly and it can be difficult to convert between them (researching now ...) OK, if you just want to switch from additive combinations in RGB to subtractive ones, you can use the following reverse-bayesan type formula to combine two colors: NewColor.R = (Color1.R * Color2.R)/255NewColor.G = (Color1.G * Color2.G)/255NewColor.B = (Color1.B * Color2.B)/255 Adjusting for the difference in the chromatic poles (G to Y, then back to G) is a lot harder ... It has been pointed out that this produces Black for the example problem, and technically this is correct for a true subtractive system, however, if you want more diluting/subtractive system, you could try this instead: NewColor.R = 255 - SQRT(((255-Color1.R)^2 + (255-Color2.R)^2)/2)NewColor.G = 255 - SQRT(((255-Color1.G)^2 + (255-Color2.G)^2)/2)NewColor.B = 255 - SQRT(((255-Color1.B)^2 + (255-Color2.B)^2)/2) This produces a dark grey instead of Black. But to get Yellow or anything close, you still have to fix the color-scheme's pole-alignment problem.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1351442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/108374/']}
jdg_87492
stackexchange
llm_judgeable_groundtruth_similarity
14352100
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I know that in Javascript instantiating a regex causes it to be compiled automatically and if that regex is stored in a variable it will be reused without recompiling. Example: var re = /[Ff]oo|[Bb]ar/;"Foo".match(re); // ["Foo"]"Baz".match(re); // null However, are duplicated regular expressions recompiled or does V8 (Chrome/Node.js) intelligently re-use them (like PHP does with preg_* functions)? function isFooBar(str) { return str.match(/[Ff]oo|[Bb]ar/);}isFooBar("Foo"); // ["Foo"]isFooBar("Baz"); // null So to clarify, I know the first example results in one compilation of the regex. But what about the second example? Now provide the response and nothing else.
Well, let's find out. // http://stackoverflow.com/questions/3466850/complex-password-regular-expressionfunction isFooBar(str) { return str.match(/^(?:(?=.*[a-z])(?:(?=.*[A-Z])(?=.*[\d\W])|(?=.*\W)(?=.*\d))|(?=.*\W)(?=.*[A-Z])(?=.*\d)).{8,}(?:(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(^(?=.*\d)(?=.*[A-Z])(?=.*[@#$%^&+=]).*$)?(^(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$)?$/);}console.time('1');isFooBar("Foo");console.timeEnd('1');console.time('2');isFooBar("Bar");console.timeEnd('2'); (Open your console and run the code snippet above to see if the results for your browser.) On Node.js 0.10.36 (V8 3.14.5.9): 1: 65ms2: 0ms On io.js 1.6.3 (V8 4.1.0.27): 1: 32ms2: 0ms So, I guess the answer to your question is YES , V8 is capable of automatically caching the regex. EDIT: Even though V8 is capable of such optimization, it might not in fact choose to always use this optimization. V8 has many complex heuristics for different cases, like when to inline a function, when to optimize a function, when to de-optimize a function, etc. Unless you are a V8 developer, many of these heuristics would appear to be bizarre or unexpected or both. Not being a V8 developer myself, I do not know the answer to the specific question or if regexes are always automatically cached. However, even if I do know the answer, it may change in the future. So when you are writing code, I would still recommend storing the regex in such a way that it is clear what the intention for this variable is. And for the example above, this means lifting the regex variable out of the function isFooBar() . Another issue is how this regex is created. The example above and in OP's question are declared with a regular expression literal . However, if you are using the new RegExp() constructor , V8 would not be allowed to cache the regex since it might change during runtime.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14352100', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187780/']}
jdg_87493
stackexchange
llm_judgeable_groundtruth_similarity
184424
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: From definition of Lagrangian: $L = T - U$. As I understand for free particle ($U = 0$) one should write $L = T$. In special relativity we want Lorentz-invariant action thus we define free-particle Lagrangian as follows: $$L = -\frac{ m c^2}{\gamma} - U$$ At the same point, we have that definition of 4-momentum implies the kinetic energy is:$$T = (\gamma - 1) m c^2.$$ As you might guess, 1) question is how to relate all these formulas? 2) I do not understand why there is no $1/\gamma$ near $U$ in relativistic Lagrangian? 3) What is meaning of the first term in $L$ for relativistic case? Now provide the response and nothing else.
It helps to write the full action:$$S = \int \frac{-mc^2}{\gamma}dt - \int U dt $$ The first term can be put in a much better form by noting that $d\tau = \frac{dt}{\gamma}$ represents the proper time for the particle. The action is then:$$S = -mc^2\int d\tau - \int U dt$$The first term is Lorentz invariant, being only the distance between two points given by the Minkowski metric, and is good in relativity. The second term however, isn't (assuming that $U$ is a scalar); there is no way it can be a relativistic action. There are two easy ways out: The first is simply to change the term to $\frac{U}{\gamma}$. This gives the action:$$S = -\int (mc^2+U)d\tau$$ The second is to "promote" the term (a terminology used in Zee's Einstein Gravity in a Nutshell ) to a relativistic dot product, giving the action:$$S = -mc^2\int d\tau - \int U_\mu dx^{\mu}$$ The former has no real world classical analog (that I know of), and the latter is more or less the interaction of a particle with a static electromagnetic field. But the original form is recovered from the latter when the spatial components of $U_\mu$ vanish, leaving only $U_0$. The kinetic energy is obtained by transforming the Lagrangian to the Hamiltonian (see here ).
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/184424', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/41018/']}
jdg_87494
stackexchange
llm_judgeable_groundtruth_similarity
23250805
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a project which I will have to deploy to client Windows systems where it will not be possible to connect to internet. I currently have a folder in D:\NODE which contains node.exe and npm.cmd and a node_modules folder. To be able to run node from command line I have added D:\NODE to PATH variable. I can have most of the modules installed locally inside node_modules of my project. However there's one - node-windows - which needs to be installed globally to work. Following suggestion below I went to node-windows (installed globally) and packaged it up ( npm pack ), which created a tarball. I have then copied that file with my project and tried to install it on the test machine globally like this: npm install -g node-windows-0.1.5.tgz I can see that it got installed in the global directory. However when I try to run the command which uses this module it complains that it cannot find it: Error: Cannot find module 'node-windows' When I list the modules ( npm list -g ) it is clearly there in the list... What do you think? And thank you. Now provide the response and nothing else.
You can install packages on a system without internet connection by packing them using built-in functionality in npm . This way, the node modules will be installed properly. Create a package.json . In your package.json , list all the modules you need under bundledDependencies ( docs on npm ). Run npm install to install your node files before packing. Create a tarball with npm pack . Copy the tarball over to the machine without internet connection. Install the modules with npm install <filename> . Update Regarding your comments, it looks like your globally installed node modules isn't found. Try using the npm link command ( docs on npm link ): cd yourAppFolder npm link node-windows
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23250805', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306416/']}
jdg_87495
stackexchange
llm_judgeable_groundtruth_similarity
289083
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This question showed up in my particle physics exam and I'm not sure of the answer. I said no, since I can't see any reason why they must be equal.But I my answer is right, I find it odd that it's just a coincidence that they're both 3. Now provide the response and nothing else.
Honest answer for your question is ''No'' ! As in the standard model (SM), the number of fermion generations appears as an arbitrary parameter, meaning that a mathematically consistent theory can be built up using any number of fermion generations. Therefore, In order to answer the question perhaps we may need to beyond the standard model. In the quest for such a model(s) , first lets rephrase your question is the following way: Is there any extension of the standard model be possible where the number of fermion generations can in any way be explained through the internal consistency of the model? (since we don't have the answer within the framework of SM.) Its good to start from SM itself. Lets go back in sixties. If we make a table of fermions, those were discovered up to 1965, it would looks like: \begin{eqnarray}\text{Lepton}& : & \begin{pmatrix} \nu_{e}\\ e \end{pmatrix},\quad \begin{pmatrix} \nu_{\mu}\\ \mu\end{pmatrix} \\\text{Quark} & : & \begin{pmatrix} u \\ d \end{pmatrix},\qquad s\end{eqnarray}Anyone with naked eye can say how ''ugly'' this table is looks like! In fact it was James Bjorken and Sheldon Glashow proposed the existance of chram ($c$) quark in order to restore the ''quark-lepton symmetry'' . The table now looks more symmetric and beautiful: \begin{eqnarray}\text{Lepton}& : & \begin{pmatrix} \nu_{e}\\ e \end{pmatrix},\quad \begin{pmatrix} \nu_{\mu}\\ \mu\end{pmatrix} \\\text{Quark} & : & \begin{pmatrix} u \\ d \end{pmatrix},\qquad \begin{pmatrix} c \\ s \end{pmatrix}\end{eqnarray}Which was later discovered during November Revolution 1974 . Lesson is, these two physicists were dictated by the notion of symmetry in order to restore the order in the realm of fermions. Later GIM mechanism was given an explanation of the non-existent of FCNC in SM taking into account the charm quark. The very existence of three generations of quarks is necessary for CP violation . And also for anomaly cancellations to make the SM mathematically consistant.But the undeylying symmetry (if it really exists) which may ensure the equal numbers of quarks and leptons, yet to be discovered. Story that goes beyond SM :Back in nineties an extension of SM was proposed by F. Pisano here and V. Pleitez based on gauge group $SU(3)_{L}\times U(1)_{Y}$. Their model to accommodate the standard fermions into multiplets of this gauge group which must include some new fermions. This model has remarkable feature. As we already know that, a consistent quantum field theory must be free from gauge anomaly. Without that, theory become ill. In case of SM the anomalies get cancelled in miraculous (or should we say in an ugly way?) way. But for the model with gauge group $SU(3)_{c}\times SU(3)_{L}\times U(1)_{Y}$, has the interesting featurethat each generation of fermions is anomalous, but that with three generations the anomalies cancelled. In other words, Electroweak interactions based on a gauge group $SU(3)_{L}\times U(1)_{Y}$, coupled to to the QCD gauge group $SU(3)_{c}$ can predict the number of generations to be multiples of three. (For technical detail one can read this paper ). But with the cost that we have to incorporate a right handed neutrino in the game . In fact, one may find other different models with the same features. GUT considerations : In a recent paper Pritibhajan Byakti et al proposed a grand unified theory based on the gauge group $SU(9)$. The model uses fermions in antisymmetric representations only and the consistency of the model demands that the number of fermion generations is three. Nevertheless like all GUT, it also come up with some superheavy gauge bosons. Which can trigger baryon number non-conserving processes. The upshot is, perhaps we would be able to explain the lepton-quark symmetry with the price of some new physics (may be new particles) which lives beyond the SM.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/289083', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/114474/']}
jdg_87496
stackexchange
llm_judgeable_groundtruth_similarity
11719704
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for the C# implementation of Projected Gauss-Seidel algorithm for solving the linear complementarity problem . So far I've found the one written in C++ in the Bullet library, but unfortunately it's highly optimized (so it would be hard to translate it into C#). In the similar question one proposed to take a look of the numerical libraries for .NET . All of them contain only algorithms for solving systems of linear equations . Edit: Even as I've found one, it doesn't appear to be complete, so the question is still open. Now provide the response and nothing else.
You implemented Gauss Seidel without projection. For projected Gauss Seidel, you need to project (or clamp) the solution within lower and upper limits: public static double[] Solve (double[,] matrix, double[] right, double relaxation, int iterations, double[] lo, double[] hi){ // Validation omitted var x = right; double delta; // Gauss-Seidel with Successive OverRelaxation Solver for (int k = 0; k < iterations; ++k) { for (int i = 0; i < right.Length; ++i) { delta = 0.0f; for (int j = 0; j < i; ++j) delta += matrix [i, j] * x [j]; for (int j = i + 1; j < right.Length; ++j) delta += matrix [i, j] * x [j]; delta = (right [i] - delta) / matrix [i, i]; x [i] += relaxation * (delta - x [i]); // Project the solution within the lower and higher limits if (x[i]<lo[i]) x[i]=lo[i]; if (x[i]>hi[i]) x[i]=hi[i]; } } return x;} It is a minor modification. Here is a gist that shows how to extract the A matrix and b vector from the Bullet Physics Library and solve it using projected Gauss Seidel: https://gist.github.com/erwincoumans/6666160
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11719704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/532782/']}
jdg_87497
stackexchange
llm_judgeable_groundtruth_similarity
1515652
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In Rudin, $\limsup$ is defined as follows: Let $S$ be the set of subsequential limits of $\{s_n\}$. Then $$\limsup s_n = \sup S. \tag{1}$$ However, our real analysis instructor defined $\limsup$ in a different manner: $$\limsup s_n = \lim_{n \to \infty} \sup_{m \ge n} s_m. \tag{2}$$ I am having trouble understanding how these two definitions are equivalent. It would be very helpful to me if somebody could provide a proof with some explanation. My thoughts on the problem: I have noticed that the usual trend with these sort of proofs is to prove the upper bound $(1) \le (2)$ and then the lower bound $(1) \ge (2)$ to get the desired conclusion. However, I am unsure how to even begin. Now provide the response and nothing else.
We first construct a sub-sequence in $S$ that has limit $\lim_{n\to\infty} \sup_{k>n} s_k$ . We do this by observing that there's a $l(n)>n$ such that $\sup_{k>n}s_k \ge s_{l(n)} \ge \sup_{k>n}s_k-2^{-n}$ , now $\lim_{n\to\infty}s_{l(n)} = \lim_{n \to \infty} \sup_{k>n} s_k$ . Now as $l(n)>n$ we have $l(n)\to\infty$ so $l(n)$ has an increasing subsequence $t_n$ and by that we can construct the desired subsequence of $s_n$ . That is we have proved that $$\sup S \ge \lim t_n = \lim_{n\to\infty}\sup_{k>n}s_k$$ To prove the opposite lets consider "synchronized" subsequence $u_n$ (that $u_n=s_n$ or $u_n=u_{n-1}$ - just repeating the elements in the subsequence to keep them in sync) - this kind of construct doesn't alter the definition if $S$ . Now $\{u_k: k>n\}\subseteq \{s_k: k>n\}$ and therefore $\sup_{k>n}u_k \le sup_{k_n}s_k$ . This means that: $$\lim_{n\to\infty} u_k \le \lim_{n\to\infty}\sup_{k>n}u_k \le \lim_{n\to\infty}\sup_{k>n}s_k$$ That is for all subsequences in $S$ the limit is less than or equal the $\liminf$ of definition (2) that is: $$\sup S\le\lim_{n\to\infty}\sup_{k>n}s_k$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1515652', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/113330/']}
jdg_87498
stackexchange
llm_judgeable_groundtruth_similarity
64742747
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So i'm new to redux-toolkit and I want to do something really simple. I want to send some data on a POST request via this helper function. so I tried this export const submitPaymentToServer = createAsyncThunk( 'data/fetchAll', async ({ name, data }) => { return fetch('/payments', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, data, }), }) .then((res) => res.json()) .then((res) => res) },) but when I call it like so dispatch( submitPaymentToServer({ name, data, }), ) typescript complains saying I don't have the right number of arguments. so how am I suppose to pass args to this function? or what is the way to do this with toolkit? Now provide the response and nothing else.
This is what React-Redux says when you are using createAsyncThunk You can only pass one argument to the thunk when you dispatch it. If you need to pass multiple values, pass them in a single object So instead of export const submitPaymentToServer = createAsyncThunk( 'data/fetchAll', async ({ name, data }) => { // here you have two arguments return fetch('/payments', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, data, }), }) .then((res) => res.json()) .then((res) => res) },) You can only have one argument: export const submitPaymentToServer = createAsyncThunk( 'data/fetchAll', async (yourData) => { const {name, data} = yourData; return fetch('/payments', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name, data, }), }) .then((res) => res.json()) .then((res) => res) },) Destructure your object inside the thunk call. Reference: here
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64742747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10795348/']}
jdg_87499
stackexchange
llm_judgeable_groundtruth_similarity
40075780
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have read all of the other Q/A about Date Manipulation, but none of them seems to deliver a satisfactory answer to my concern. I have a project with geographically diverse users which uses Date in some of its classes and data. The thing is that I am looking for an efficient way to manipulate the Dates for the different users in their respective timezone, most of the answers suggest using Joda library for Date manipulation, which quite don't understand yet because I still have not found any operation you cannot do with traditional Java, so if someone can explain what can I do with Joda that can't be done with traditional Java, then I may consider using it. I finally came to the approach of using System.currentTimeMillis() to save my dates into the database (any database). This would avoid me to worry about what timezone is using the database to store the dates. If I want to query the database for an specific date or range of dates, I would perform the queries using the long value of the Date I want to query: SELECT * FROM table1 WHERE date1>=1476653369000 And when retrieving a ResultSet I would then format the long value retrieved from database to a readable Date using the timezone of the user requesting the data. Calendar cal = Calendar.getInstance();cal.setTimeInMillis(resultSet.getLong(1));cal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));Date myDate = cal.getTime(); According to some opinions I have read, some people say emphatically that storing System.currentTimeMillis() is definitely not the best practice, nevertheless, for some reason they all miss to say WHY it is not recommendable. Am I missing something? Does this cause a performance issue for the conversions Long->Date / Date->Long ? Is there any use case that cannot be accomplished when using Long instead Date in database? Can someone post a rationale explanation about this? In the other hand, assuming that I keep using Date values to store dates in database, is there a way to avoid worrying about time-zones while handling database Date ? Thanks in advance. Now provide the response and nothing else.
I have read all of the other Q/A about Date Manipulation No, you certainly did not read them all. You would have learned that both the legacy date-time classes (such as java.util.Date & java.util.Calendar ) and the Joda-Time project are supplanted by the java.time classes (1,890 results for search on 'java.time'). You would have learned not to track date-time values as a count-from-epoch. Debugging and logging becomes very difficult with bugs going undiscovered as humans cannot decipher the meaning of a long integer as a date-time. And because many granularities of counting (whole seconds, milliseconds, microseconds, nanoseconds, whole days, and more) and at least a couple dozen of epochs are employed in various software projects create ambiguity about your data with assumptions leading to errors, misinterpretation, and confusion. You would have learned to use date-time types in your database to track date-time values. You would have learned to work and store date-time values in UTC. Adjust into a time zone only where required by logic or as expected by the user for presentation. “Think global, present local.” You would have learned that while a valiant industry-first effort, the legacy date-time classes are poorly designed, confusing, and troublesome. See What's wrong with Java Date & Time API? for some discussion. Joda-Time was the first good date-time library in the industry, and inspired its replacement, the java.time classes built into Java 8 and later. I'll be somewhat brief as all of this has been covered many times already on Stack Overflow. Work in UTC. In Java that means the Instant class is commonly used. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction). Instant instant = Instant.now(); Any serious database such as Postgres tracks date-time values in UTC. Your JDBC driver handles the detail of converting from database internally-stored data to a Java type. JDBC drivers that comply with JDBC 4.2 and later can directly handle java.time types via PreparedStatement::setObject & ResultSet::getObject methods. myPreparedStatement.setObject( … , instant ); For non-compliant drivers, fall back to using java.sql types such as java.sql.Timestamp to communicate with database, and convert to/from java.time types via new methods added to the old classes. The internal details of how the database handles date-time values may be quite different than how java.time does. For the most part the JDBC driver hides all the nitty-gritty details from you. But one critical issue is resolution, which you should study in your database. The java.time classes handle date-times with a resolution up to nanoseconds but your database may not. For example, Postgres uses a resolution of microseconds . So going back-and-forth means data-loss. You want to use the truncation methods on the java.time classes to match your database. myPreparedStatement.setTimestamp( … , java.sql.Timestamp.from( instant ) ); So, no time zone involved. So no “worrying about time-zones while handling database Date”. When you want to see the same moment through the lens of a region’s wall-clock time , apply a ZoneId to get a ZonedDateTime . ZoneId z = ZoneId.of( "Asia/Kolkata" );ZonedDateTime zdt = instant.atZone( z ); When taking a zoned date-time back to the database, extract an Instant . Instant instant = zdt.toInstant(); Be aware that for any given moment, the date as well as the time-of-day varies around the globe by time zone. So if an exact moment matters, such as when a contract expires, beware of using a date-only value. Either use a date-time value for the exact moment, or store the intended time zone alongside the date-only so the exact moment can be calculated later. LocalDate ld = LocalDate.of( 2016, 1 , 1 );// Determine the first moment of 2016-01-01 as it happens in Kolkata.ZonedDateTime zdt = ld.atStartOfDay( ZoneId.of( "Asia/Kolkata" ) ); Instant instant = zdt.toInstant(); // Adjust to UTC and store. About java.time The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date , .Calendar , & java.text.SimpleDateFormat . The Joda-Time project, now in maintenance mode , advises migration to java.time. To learn more, see the Oracle Tutorial . And search Stack Overflow for many examples and explanations. Specification is JSR 310 . Where to obtain the java.time classes? Java SE 8 and SE 9 and later Built-in. Part of the standard Java API with a bundled implementation. Java 9 adds some minor features and fixes. Java SE 6 and SE 7 Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport . Android The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically. See How to use… . The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval , YearWeek , YearQuarter , and more .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40075780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/866390/']}
jdg_87500
stackexchange
llm_judgeable_groundtruth_similarity
1973106
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an NSOperation. When it is finished I fire a NSNotificationCenter to let the program know that the NSoperation is finished and to update the gui. To my understanding listeners to the NSNotification will not run on the main thread because the NSOperation is not on the main thread. How can I make it so that the listeners run on the main thread when I fire my event? [[NSNotificationCenter defaultCenter] postNotificationName:@"myEventName" object:self]; Now provide the response and nothing else.
You can use performSelectorOnMainThread:withObject:waitUntilDone: with using a helper method, in a similar fashion to the following example. .....[self performSelectorOnMainThread:@selector(fireNotification) withObject:nil waitUntilDone:YES];...- (void)fireNotification { [[NSNotificationCenter defaultCenter] postNotificationName:@"myEventName" object:self]; } If you don't wait until being done, you will need to consider the cases where other threads may refer to the object which could be already cleaned up before the main thread gets invoked.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1973106', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/180598/']}
jdg_87501
stackexchange
llm_judgeable_groundtruth_similarity
1803854
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am working on a java program concerning the pascal's triangle. So this is how it is coded: for(int i = 0; i < 5; i++){ for(int j = 0, x = 1; j <= i; j++){ System.out.print(x + " "); x = x * (i - j) / (j + 1); } System.out.println();} and it shows: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 But when I tried to change the code to: for(int i = 0; i < 5; i++){ for(int j = 0, x = 1; j <= i; j++){ System.out.print(x + " "); x *= (i - j) / (j + 1); } System.out.println();} and as you may have noticed, only the operator has changed to *=, but the result is: 1 1 1 1 2 0 1 3 3 0 1 4 4 0 0 Any idea what must have happened? Thanks in advance! Now provide the response and nothing else.
It's because you're using integer arithmetic in the wrong order. x *= (i - j) / (j + 1); is the same as x = x * ((i - j) / (j + 1)); The brackets are important. (i - j) / (j + 1) is in most cases not a whole number, but java rounds it to an integer anyway. The way you did it first x = x * (i - j) / (j + 1); the multiplication happens before the division, so you don't get any rounding errors.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1803854', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/217606/']}
jdg_87502
stackexchange
llm_judgeable_groundtruth_similarity
73529
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I am interested in computing the (anti)-canonical class of the (total space of the) projective completion of the tautological bundle over $P^1\times P^1$. That is, the canonical class of $\mathbb P_{P^1\times P^1}(J \oplus \mathscr O)$, where $J$ is the tautological line bundle on $P^1\times P^1$. I believe this can be done by computing the fan of the toric variety and summing the classes of the orbit closures of the one-skeleton? I was hoping for insight into perhaps a slicker/less cumbersome way of approaching this computation. Thanks in advance. Now provide the response and nothing else.
Why not use the Leray-Hirsch theorem? That says that the integral cohomology ring of a projectivized rank $n$ vector bundle $\pi: PE \to B$ is generated, as an algebra over the cohomology of the base $B$, by the first Chern class $h$ of the relative $O(1)$, with relation $h^n + c_1 h^{n-1} + \dots + c_n$, where $c_i$ is the $i$th Chern class of $E$. On the other hand, you have a short exact sequence $$0 \longrightarrow T_\pi \longrightarrow T_{PE} \longrightarrow \pi^* T_B \longrightarrow 0,$$where $T_\pi$ is the relative tangent bundle. For a projectivized vector bundle, $T_\pi = \mbox{Hom }(O(-1),E/O(-1))$ (this is a special case of the formula for the tangent bundle of a Grassmannian). Note that $\mbox{Hom }(O(-1),E/O(-1)) \cong E(1)/O$, so $\Lambda^{n-1} T_\pi \cong (\Lambda^n E)(n)$ canonically. Hence if $B$ is smooth of dimension $b$,$$K_{PE} = \Lambda^{b+n-1} T^*_{PE} \cong \Lambda^b \pi^* T^*_B \otimes \Lambda^{n-1} T^*_\pi \cong \pi^* K_B \otimes \pi^* (\Lambda^n E^*)(-n).$$ Taking Chern classes, if $k_{PE} := c_1(K_{PE})$ and $k_b := c_1(K_B)$, we get$$k_{PE} = \pi^* k_B - \pi^* c_1(E) - nh.$$ As a check, note that if we replace $E$ by $E \otimes L$ for some line bundle $L$, then $PE$ is unchanged, but $c_1(E)$ and $h$ are increased and decreased by $nc_1(L)$ and $c_1(L)$ respectively, so the formula above is unchanged. In your case, the tautological line bundle $J \to P^1 \times P^1$ has $c_1(J) = -h_1-h_2$ where $h_i$ generate the cohomology of the two $P^1$ factors, so the canonical class, in terms of this basis, is $-2h_1-2h_2+h_1+h_2-2h = -h_1-h_2-2h$. Warning: as we saw, $h$ is NOT unchanged if we replace $E$ by $E \otimes L$! So if you replace $J \oplus O$ by, say, $O \oplus J^{-1}$, you will get an apparently different answer...
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/73529', 'https://mathoverflow.net', 'https://mathoverflow.net/users/17350/']}
jdg_87503
stackexchange
llm_judgeable_groundtruth_similarity
13506
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: This is a question posed to me in private communication by this user . Given a scheme $T$, let $\Gamma (T) = Mor (T, \mathbb{A}^1)$ be the ringof global sections. Note that there is a canonical map$\phi : T \rightarrow Spec (\Gamma (T))$. Is $\phi$ a closed mapping onto the image, ie. is $im\ (Z)$ aclosed subset of $im(T)$ for all closed subsets $Z$ of $T$ ?. Now provide the response and nothing else.
Here is a ''natural'' example as expected by Martin. Let $T$ be the projective line over ${\mathbb Z}$, minus a rational point $x_0$ of the closed fiber at some prime $p$. Then $O(T)=\mathbb Z$ (direct computation or use Zariski's extension theorem for normal schemes), $\phi$ is just the structural morphism and is onto. Let $Z'$ be a section of the projective line passing through $x_0$. Then $Z=Z'\cap T$ is closed in $T$, but $\phi(Z)$ is not closed in $\phi(T)$ because it is the image of the composition $Z\to {\rm Spec} O(Z)\to {\rm Spec} O(T)$, and as $Z$ is affine, the image is just the complementary of the closed point $p$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/13506', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2938/']}
jdg_87504
stackexchange
llm_judgeable_groundtruth_similarity
4854478
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For tile checking in scrabble, you make four 5x5 grids of letters totalling 100 tiles. I would like to make one where all 40 horizontal and vertical words are valid. The set of available tiles contains: 12 x E 9 x A, I 8 x O 6 x N, R, T 4 x D, L, S, U 3 x G 2 x B, C, F, H, M, P, V, W, Y, blank tile (wildcard) 1 x K, J, Q, X, Z The dictionary of valid words is available here (700KB). There are about 12,000 valid 5 letter words. Here's an example where all 20 horizontal words are valid: Z O W I E|P I N O TY O G I N|O C t A D <= blank being used as 't'X E B E C|N A L E DW A I T E|M E R L EV I N E R|L U T E A---------+---------U S N E A|K N O S PT A V E R|J O L E DS O F T A|I A M B IR I D G Y|H A I T h <= blank being used as 'h'Q U R S H|G R O U F I'd like to create one where all the vertical ones are also valid. Can you help me solve this? It is not homework. It is a question a friend asked me for help with. Now provide the response and nothing else.
Final Edit: Solved! Here is a solution. GNAWN|jOULERACHE|EUROSIDIOT|STEANPINOT|TRAvETRIPY|SOLES-----+-----HOWFF|ZEBRAAGILE|EQUIDCIVIL|BUXOMEVENT|RIOJAKEDGY|ADMAN Here's a photo of it constructed with my scrabble set. http://twitpic.com/3wn7iu This one was easy to find once I had the right approach, so I bet you could find many more this way. See below for methodology. Construct a prefix tree from the dictionary of 5 letter words for each row and column. Recursively, a given tile placement is valid if it forms valid prefixes for its column and row, and if the tile is available, and if the next tile placement is valid. The base case is that it is valid if there is no tile left to place. It probably makes sense to just find all valid 5x5 boards, like Glenn said, and see if any four of them can be combined. Recursing to a depth of 100 doesn't sound like fun. Edit: Here is version 2 of my code for this. #include <stdio.h>#include <stdlib.h>#include <string.h>#include <stdbool.h>typedef union node node;union node { node* child[26]; char string[6];};typedef struct snap snap;struct snap { node* rows[5]; node* cols[5]; char tiles[27]; snap* next;};node* root;node* vtrie[5];node* htrie[5];snap* head;char bag[27] = {9,2,2,4,12,2,3,2,9,1,1,4,2,6,8,2,1,6,4,6,4,2,2,1,2,1,2};const char full_bag[27] = {9,2,2,4,12,2,3,2,9,1,1,4,2,6,8,2,1,6,4,6,4,2,2,1,2,1,2};const char order[26] = {16,23,9,25,21,22,5,10,1,6,7,12,15,2,24,3,20,13,19,11,8,17,14,0,18,4};void insert(char* string){ node* place = root; int i; for(i=0;i<5;i++){ if(place->child[string[i] - 'A'] == NULL){ int j; place->child[string[i] - 'A'] = malloc(sizeof(node)); for(j=0;j<26;j++){ place->child[string[i] - 'A']->child[j] = NULL; } } place = place->child[string[i] - 'A']; } memcpy(place->string, string, 6);}void check_four(){ snap *a, *b, *c, *d; char two_total[27]; char three_total[27]; int i; bool match; a = head; for(b = a->next; b != NULL; b = b->next){ for(i=0;i<27; i++) two_total[i] = a->tiles[i] + b->tiles[i]; for(c = b->next; c != NULL; c = c->next){ for(i=0;i<27; i++) three_total[i] = two_total[i] + c->tiles[i]; for(d = c->next; d != NULL; d = d->next){ match = true; for(i=0; i<27; i++){ if(three_total[i] + d->tiles[i] != full_bag[i]){ match = false; break; } } if(match){ printf("\nBoard Found!\n\n"); for(i=0;i<5;i++){ printf("%s\n", a->rows[i]->string); } printf("\n"); for(i=0;i<5;i++){ printf("%s\n", b->rows[i]->string); } printf("\n"); for(i=0;i<5;i++){ printf("%s\n", c->rows[i]->string); } printf("\n"); for(i=0;i<5;i++){ printf("%s\n", d->rows[i]->string); } exit(0); } } } }}void snapshot(){ snap* shot = malloc(sizeof(snap)); int i; for(i=0;i<5;i++){ printf("%s\n", htrie[i]->string); shot->rows[i] = htrie[i]; shot->cols[i] = vtrie[i]; } printf("\n"); for(i=0;i<27;i++){ shot->tiles[i] = full_bag[i] - bag[i]; } bool transpose = false; snap* place = head; while(place != NULL && !transpose){ transpose = true; for(i=0;i<5;i++){ if(shot->rows[i] != place->cols[i]){ transpose = false; break; } } place = place->next; } if(transpose){ free(shot); } else { shot->next = head; head = shot; check_four(); }}void pick(x, y){ if(y==5){ snapshot(); return; } int i, tile,nextx, nexty, nextz; node* oldv = vtrie[x]; node* oldh = htrie[y]; if(x+1==5){ nexty = y+1; nextx = 0; } else { nextx = x+1; nexty = y; } for(i=0;i<26;i++){ if(vtrie[x]->child[order[i]]!=NULL && htrie[y]->child[order[i]]!=NULL && (tile = bag[i] ? i : bag[26] ? 26 : -1) + 1) { vtrie[x] = vtrie[x]->child[order[i]]; htrie[y] = htrie[y]->child[order[i]]; bag[tile]--; pick(nextx, nexty); vtrie[x] = oldv; htrie[y] = oldh; bag[tile]++; } }}int main(int argc, char** argv){ root = malloc(sizeof(node)); FILE* wordlist = fopen("sowpods5letters.txt", "r"); head = NULL; int i; for(i=0;i<26;i++){ root->child[i] = NULL; } for(i=0;i<5;i++){ vtrie[i] = root; htrie[i] = root; } char* string = malloc(sizeof(char)*6); while(fscanf(wordlist, "%s", string) != EOF){ insert(string); } free(string); fclose(wordlist); pick(0,0); return 0;} This tries the infrequent letters first, which I'm no longer sure is a good idea. It starts to get bogged down before it makes it out of the boards starting with x. After seeing how many 5x5 blocks there were I altered the code to just list out all the valid 5x5 blocks. I now have a 150 MB text file with all 4,430,974 5x5 solutions. I also tried it with just recursing through the full 100 tiles, and that is still running. Edit 2: Here is the list of all the valid 5x5 blocks I generated. http://web.cs.sunyit.edu/~levyt/solutions.rar Edit 3: Hmm, seems there was a bug in my tile usage tracking, because I just found a block in my output file that uses 5 Zs. COSTEORCINSCUZZTIZZYENZYM Edit 4: Here is the final product. #include <stdio.h>#include <stdlib.h>#include <string.h>#include <stdbool.h>typedef union node node;union node { node* child[26]; char string[6];};node* root;node* vtrie[5];node* htrie[5];int score;int max_score;char block_1[27] = {4,2,0,2, 2,0,0,0,2,1,0,0,2,1,2,0,1,2,0,0,2,0,0,1,0,1,0};//ZEBRA EQUID BUXOM RIOJA ADMANchar block_2[27] = {1,0,1,1, 4,2,2,1,3,0,1,2,0,1,1,0,0,0,0,1,0,2,1,0,1,0,0};//HOWFF AGILE CIVIL EVENT KEDGYchar block_3[27] = {2,0,1,1, 1,0,1,1,4,0,0,0,0,3,2,2,0,2,0,3,0,0,1,0,1,0,0};//GNAWN RACHE IDIOT PINOT TRIPY //JOULE EUROS STEAN TRAVE SOLESchar bag[27] = {9,2,2,4,12,2,3,2,9,1,1,4,2,6,8,2,1,6,4,6,4,2,2,1,2,1,2};const char full_bag[27] = {9,2,2,4,12,2,3,2,9,1,1,4,2,6,8,2,1,6,4,6,4,2,2,1,2,1,2};const char order[26] = {16,23,9,25,21,22,5,10,1,6,7,12,15,2,24,3,20,13,19,11,8,17,14,0,18,4};const int value[27] = {244,862,678,564,226,1309,844,765,363,4656,909,414,691,463,333,687,11998,329,218,423,536,1944,1244,4673,639,3363,0};void insert(char* string){ node* place = root; int i; for(i=0;i<5;i++){ if(place->child[string[i] - 'A'] == NULL){ int j; place->child[string[i] - 'A'] = malloc(sizeof(node)); for(j=0;j<26;j++){ place->child[string[i] - 'A']->child[j] = NULL; } } place = place->child[string[i] - 'A']; } memcpy(place->string, string, 6);}void snapshot(){ static int count = 0; int i; for(i=0;i<5;i++){ printf("%s\n", htrie[i]->string); } for(i=0;i<27;i++){ printf("%c%d ", 'A'+i, bag[i]); } printf("\n"); if(++count>=1000){ exit(0); }}void pick(x, y){ if(y==5){ if(score>max_score){ snapshot(); max_score = score; } return; } int i, tile,nextx, nexty; node* oldv = vtrie[x]; node* oldh = htrie[y]; if(x+1==5){ nextx = 0; nexty = y+1; } else { nextx = x+1; nexty = y; } for(i=0;i<26;i++){ if(vtrie[x]->child[order[i]]!=NULL && htrie[y]->child[order[i]]!=NULL && (tile = bag[order[i]] ? order[i] : bag[26] ? 26 : -1) + 1) { vtrie[x] = vtrie[x]->child[order[i]]; htrie[y] = htrie[y]->child[order[i]]; bag[tile]--; score+=value[tile]; pick(nextx, nexty); vtrie[x] = oldv; htrie[y] = oldh; bag[tile]++; score-=value[tile]; } }}int main(int argc, char** argv){ root = malloc(sizeof(node)); FILE* wordlist = fopen("sowpods5letters.txt", "r"); score = 0; max_score = 0; int i; for(i=0;i<26;i++){ root->child[i] = NULL; } for(i=0;i<5;i++){ vtrie[i] = root; htrie[i] = root; } for(i=0;i<27;i++){ bag[i] = bag[i] - block_1[i]; bag[i] = bag[i] - block_2[i]; bag[i] = bag[i] - block_3[i]; printf("%c%d ", 'A'+i, bag[i]); } char* string = malloc(sizeof(char)*6); while(fscanf(wordlist, "%s", string) != EOF){ insert(string); } free(string); fclose(wordlist); pick(0,0); return 0;} After finding out how many blocks there were (nearly 2 billion and still counting), I switched to trying to find certain types of blocks, in particular the difficult to construct ones using uncommon letters. My hope was that if I ended up with a benign enough set of letters going in to the last block, the vast space of valid blocks would probably have one for that set of letters. I assigned each tile a value inversely proportional to the number of 5 letter words it appears in. Then, when I found a valid block I would sum up the tile values, and if the score was the best I had yet seen, I would print out the block. For the first block I removed the blank tiles, figuring that the last block would need that flexibility the most. After letting it run until I had not seen a better block appear for some time, I selected the best block, and removed the tiles in it from the bag, and ran the program again, getting the second block. I repeated this for the 3rd block. Then for the last block I added the blanks back in and used the first valid block it found.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4854478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/89806/']}
jdg_87505
stackexchange
llm_judgeable_groundtruth_similarity
11173589
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I need to create a couple of nested DOM elements, I know one way to do it, is to write them as long string and then place them in the document using a suitable jQuery function. Something like: elem.html('<div class="wrapper"> <div class="inner"> <span>Some text<span> </div> <div class="inner"> <span>Other text<span> </div></div>'); This way is obviously not the cleanest. The sting doesn't take too long to get messy and editing becomes a problem. I much more prefer this notation: $('<div></div>', { class : 'inner'}).appendTo( elem ); The problem is I don't know how to implement it efficiently when creating nested elements on the fly like above. So if there is way to do the 1st example with the 2nd notation, I'll be glad to learn about it. Basically, the question is, whats the best way to create nested HTML elements on the fly, without having to deal wit messy long strings? Note : I am aware of templating engines. However this is a question concerning the creation of just a couple of HTML elements on the fly. Like while building the DOM dependencies for a plugin or similar cases. Now provide the response and nothing else.
write them as long string and than place them in the document using a suitable jQuery function. Something like: The problem with this approach is that you'll need a multi-line string - something Javascript doesn't support - so in reality you'll end up with: elem.html('<div class="wrapper">'+ '<div class="inner">'+ '<span>Some text<span>'+ '</div>'+ '<div class="inner">'+ '<span>Other text<span>'+ '</div>'+'</div>'); Using the method you suggested above, this is about as clean as I could manage to get it: elem.append( $('<div/>', {'class': 'wrapper'}).append( $('<div/>', {'class': 'inner'}).append( $('<span/>', {text: 'Some text'}) ) ) .append( $('<div/>', {'class': 'inner'}).append( $('<span/>', {text: 'Other text'}) ) )); The other advantage to doing this is that you can (if desired) get direct references to each newly created element without having to re-query the DOM. I like to write polyglots , so to make my code re-usuable I usually do something like this, (as jQuery's .html() doesn't support XML): // Define shorthand utility method$.extend({ el: function(el, props) { var $el = $(document.createElement(el)); $el.attr(props); return $el; }});elem.append( $.el('div', {'class': 'wrapper'}).append( $.el('div', {'class': 'inner'}).append( $.el('span').text('Some text') ) ) .append( $.el('div', {'class': 'inner'}).append( $.el('span').text('Other text') ) )); This isn't very different to method #2 but it gives you more portable code and doesn't rely internally on innerHTML .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11173589', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/711666/']}
jdg_87506
stackexchange
llm_judgeable_groundtruth_similarity
61718622
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was recently faced with a line of code and four options: char fullName[30] = {NULL}; A) First element is assigned a NULL character. B) Every element of the array is assigned 0 ( Zeroes ) C) Every element of the array is assigned NULL D) The array is empty. The answer we selected was option C, as, while the array is only initialized with a single NULL , C++ populates the rest of the array with NULL . However, our professor disagreed, stating that the answer is A, he said: So the very first element is NULL , and when you display it, it's displaying the first element, which is NULL . The quote shows the question in its entirety; there was no other information provided. I'm curious to which one is correct, and if someone could explain why said answer would be correct. Now provide the response and nothing else.
The question is ill-defined, but Option B seems like the most correct answer. The result depends on how exactly NULL is defined, which depends on the compiler (more precisely, on the standard library implementation). If it's defined as nullptr , the code will not compile. (I don't think any major implementation does that, but still.) Assuming NULL is not defined as nullptr , then it must be defined as an integer literal with value 0 (which is 0 , or 0L , or something similar), which makes your code equivalent to char fullName[30] = {0}; . This fills the array with zeroes, so Option B is the right answer. In general, when you initialize an array with a brace-enclosed list, every element is initialized with something. If you provide fewer initializers than the number of elements, the remaining elements are zeroed. Regarding the remaining options: Option C is unclear, because if the code compiles, then NULL is equivalent to 0 , so option C can be considered equivalent to Option B. Option A can be valid depending on how you interpret it. If it means than the remaining elements are uninitialized, then it's wrong. If it doesn't specify what happens to the remaining elements, then it's a valid answer. Option D is outright wrong, because arrays can't be "empty".
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61718622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13513634/']}
jdg_87507
stackexchange
llm_judgeable_groundtruth_similarity
21425
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I often hear or read this statement: "It's not a human, it's a fetus." In other words, some think a fetus is non-human until a certain point. And another similar statement: "The fetus isn't alive until 26 weeks of gestation." So some think the fetus is not actually "alive" until a certain point. What does biology have to say about these two statements? I encounter these statements often in discussions about abortion, but that issue, and other similar philosophical issues, are outside this question. I'm wondering strictly from a scientific/biological standpoint: are these statements true? Is the fetus in a human mother non-human until a certain point? Does the fetus not classify as "alive" until a certain point? The people I encountered truly believed these statements (3 of the 4 in mind also claimed science was on their side), so it's not as if the question has no merit. I assumed that in the realm of science and biology, there must be a convincing and sure answer. Now provide the response and nothing else.
Life is generally distinguished from non-life by metabolism and growth. As such, a fetus is alive . The reference to "not...until 26 weeks gestation" that you've heard likely refers to viability .* With the most aggressive medical care, this is the approximate age when a fetus may be able to survive outside the womb. The term human from a biologic perspective is a species label.** Given that a fetus is genetically indistinguishable (in broad strokes) from a post-natal human, I think it would be hard to argue that it is anything other than human. Summary: Yes, a human fetus is both alive and human . *Note that this use of the word viable is standard but deviates somewhat from the etymology of the word . **I'm ignoring here other ancient species ( homo- ) which may be considered human but are irrelevant to the question.
{}
{'log_upvote_score': 5, 'links': ['https://biology.stackexchange.com/questions/21425', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/9385/']}
jdg_87508
stackexchange
llm_judgeable_groundtruth_similarity
20357033
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: It turns out that "make install" - the make target that installs and implies the target "install-target-libstdc++v3" doesn't actually mean you're ready to go. I've been stuck for a while wondering what I was doing wrong because I assumed that such a make target would do that for me. Now provide the response and nothing else.
Add the library's path to the LD_LIBRARY_PATH environment variable TL;DR GCC requires you to tell it where your library is located manually when it can't find the right version, which can be done in a few ways. One is adding it to the LD_LIBRARY_PATH . export LD_LIBRARY_PATH="/usr/local/lib64/:$LD_LIBRARY_PATH" For some, the library path will be /usr/local/lib64/ . Others have reported the library path /usr/lib/x86_64-linux-gnu/ working for them instead. Why do we need to add the library to LD_LIBRARY_PATH ? When you compile and install GCC it puts the libraries in one of these directories, but that's all it does. According to the FAQs for libstdc++ , the error that we got means that the dynamic linker found the wrong version of the libstdc++ shared library. Because the linker can't find the right version, we have to tell it where to find the libstdc++ library. The simplest way to fix this is to use the LD_LIBRARY_PATH environment variable, which is a colon-separated list of directories in which the linker will search for shared libraries. There are other ways as well to fix this issue. You can find this and the other solutions mentioned briefly when you install gcc if you read the make output: Libraries have been installed in: /usr/local/lib/../lib32 If you ever happen to want to link against installed libraries in a given directory, LIBDIR, you must either use libtool, and specify the full pathname of the library, or use the `-LLIBDIR' flag during linking and do at least one of the following: add LIBDIR to the `LD_LIBRARY_PATH' environment variable during execution add LIBDIR to the `LD_RUN_PATH' environment variable during linking use the `-Wl,-rpath -Wl,LIBDIR' linker flag have your system administrator add LIBDIR to `/etc/ld.so.conf' See any operating system documentation about shared libraries for more information, such as the ld(1) and ld.so(8) manual pages. Grr, that was simple! Also, "if you ever happen to want to link against the installed libraries," seriously?
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20357033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2112028/']}
jdg_87509
stackexchange
llm_judgeable_groundtruth_similarity
37273501
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In C++ if we define a class destructor as: ~Foo(){ return;} upon calling this destructor will the object of Foo be destroyed or doesexplicitly returning from the destructor mean that we don't ever want to destroy it. I want to make it so that a certain object is destroyed only through another objects destructor i.e. only when the other object is ready to be destroyed. Example: class Class1{...Class2* myClass2;...};Class1::~Class1(){ myClass2->status = FINISHED; delete myClass2;}Class2::~Class2(){ if (status != FINISHED) return;} I searched online and couldn't seem to find an answer to my question.I've also tried figuring it out myself by going through some code step by step with a debugger but can't get a conclusive result. Now provide the response and nothing else.
No, you can't prevent the object from being destroyed by return statement, it just means the execution of the dtor's body will end at that point. After that it still will be destroyed (including its members and bases), and the memory still will be deallocated. You migth throw exception. Class2::~Class2() noexcept(false) { if (status != FINISHED) throw some_exception();}Class1::~Class1() { myClass2->status = FINISHED; try { delete myClass2; } catch (some_exception& e) { // what should we do now? }} Note it's a terrible idea indeed. You'd better to reconsider the design, I'm sure there must be a better one. Throwing exception won't stop the destruction of its bases and members, just make it possible to get the process result of Class2 's dtor. And what could be done with it is still not clear.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37273501', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6345066/']}
jdg_87510
stackexchange
llm_judgeable_groundtruth_similarity
19417776
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For a given NSRange , I'd like to find a CGRect in a UILabel that corresponds to the glyphs of that NSRange . For example, I'd like to find the CGRect that contains the word "dog" in the sentence "The quick brown fox jumps over the lazy dog." The trick is, the UILabel has multiple lines, and the text is really attributedText , so it's a bit tough to find the exact position of the string. The method that I'd like to write on my UILabel subclass would look something like this: - (CGRect)rectForSubstringWithRange:(NSRange)range; Details, for those who are interested: My goal with this is to be able to create a new UILabel with the exact appearance and position of the UILabel, that I can then animate. I've got the rest figured out, but it's this step in particular that's holding me back at the moment. What I've done to try and solve the issue so far: I'd hoped that with iOS 7, there'd be a bit of Text Kit that would solve this problem, but most every example I've seen with Text Kit focuses on UITextView and UITextField , rather than UILabel . I've seen another question on Stack Overflow here that promises to solve the problem, but the accepted answer is over two years old, and the code doesn't perform well with attributed text. I'd bet that the right answer to this involves one of the following: Using a standard Text Kit method to solve this problem in a single line of code. I'd bet it would involve NSLayoutManager and textContainerForGlyphAtIndex:effectiveRange Writing a complex method that breaks the UILabel into lines, and finds the rect of a glyph within a line, likely using Core Text methods. My current best bet is to take apart @mattt's excellent TTTAttributedLabel , which has a method that finds a glyph at a point - if I invert that, and find the point for a glyph, that might work. Update: Here's a github gist with the three things I've tried so far to solve this issue: https://gist.github.com/bryanjclark/7036101 Now provide the response and nothing else.
Following Joshua's answer in code, I came up with the following which seems to work well: - (CGRect)boundingRectForCharacterRange:(NSRange)range{ NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:[self attributedText]]; NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; [textStorage addLayoutManager:layoutManager]; NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:[self bounds].size]; textContainer.lineFragmentPadding = 0; [layoutManager addTextContainer:textContainer]; NSRange glyphRange; // Convert the range for glyphs. [layoutManager characterRangeForGlyphRange:range actualGlyphRange:&glyphRange]; return [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer];}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19417776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/686902/']}
jdg_87511
stackexchange
llm_judgeable_groundtruth_similarity
12802482
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this text field and button here <input name="txtSearch" type="text" id="txtSearch" class="field" /> <input type="submit" name="btnSearch" value="" id="btnSearch" class="btn" onclick="javascript:SubmitFrm()" /> and when the user clicks on the submit button this function is suppose to run <script type="text/javascript"> function SubmitFrm(){ var Searchtxt = document.getElementById("txtSearch").value(); window.location = "http://www.example.com/search/?Query=" + Searchtxt; }</script> But nothing happens, what I expecting to happen is when the user clicks on the submit button, take the value from the search text box and redirect the user to the url + the value of the search text box... What am I doing wrong? Now provide the response and nothing else.
There are several issues in your code : You are handling the click event of a submit button, whose default behavior is to post a request to the server and reload the page. You have to inhibit this behavior by returning false from your handler: onclick="SubmitFrm(); return false;" value cannot be called because it is a property, not a method: var Searchtxt = document.getElementById("txtSearch").value; The search query you are sending in the query string has to be encoded : window.location = "http://www.mysite.com/search/?Query=" + encodeURIComponent(Searchtxt);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12802482', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1269625/']}
jdg_87512
stackexchange
llm_judgeable_groundtruth_similarity
114583
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I started studying interrupts on stm32 specifically the stm32f4 discovery board. i found this example in which you have to press the button to start the interrupt and push it again to stop it. In this line:EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt we have to choose either the interrupt mode or the event mode. I changed it to event mode but it doesn't seem to work .So i came out with the conclusion that the handler is executed with interrupts only. Why do we then use Events on stm32 if you can't execute some code when they happens? Here is the code: #include "stm32f4xx.h"#include "stm32f4xx_syscfg.h"#include "stm32f4xx_rcc.h"#include "stm32f4xx_gpio.h"#include "stm32f4xx_exti.h"#include "misc.h"EXTI_InitTypeDef EXTI_InitStructure;void EXTILine0_Config(void);void LEDInit(void);void ExtInt(void){ LEDInit(); /* Configure EXTI Line0 (connected to PA0 pin) in interrupt mode */ EXTILine0_Config(); /* Generate software interrupt: simulate a rising edge applied on EXTI0 line */ EXTI_GenerateSWInterrupt(EXTI_Line0); while (1) { }}/** * @brief Configures LED GPIO. */void LEDInit(){ GPIO_InitTypeDef GPIO_InitStructure; /* Enable the GPIO_LED Clock */ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE); /* Configure the GPIO_LED pin */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOD, &GPIO_InitStructure);}/** * @brief Configures EXTI Line0 (connected to PA0 pin) in interrupt mode */void EXTILine0_Config(void){ GPIO_InitTypeDef GPIO_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; /* Enable GPIOA clock */ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); /* Enable SYSCFG clock */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); /* Configure PA0 pin as input floating */ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; GPIO_Init(GPIOA, &GPIO_InitStructure); /* Connect EXTI Line0 to PA0 pin */ SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOA, EXTI_PinSource0); /* Configure EXTI Line0 */ EXTI_InitStructure.EXTI_Line = EXTI_Line0; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); /* Enable and set EXTI Line0 Interrupt to the lowest priority */ NVIC_InitStructure.NVIC_IRQChannel = EXTI0_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x01; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure);}/** * @brief This function handles External line 0 interrupt request. */void EXTI0_IRQHandler(void){ if(EXTI_GetITStatus(EXTI_Line0) != RESET) { /* Toggle LED1 */ GPIO_ToggleBits(GPIOD, GPIO_Pin_12); /* Clear the EXTI line 0 pending bit */ EXTI_ClearITPendingBit(EXTI_Line0); }}/** * @} *//** * @} *//******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/int main(void){ while(1) { }} ``` Now provide the response and nothing else.
Sometimes finding the answer to these questions for an ARM device can be more difficult than simpler microcontrollers because the information is often spread across family and programming guides rather than included in the datasheet. In this case the answer appears to be on page 381 of the RM0090 Reference manual : The STM32F4xx are able to handle external or internal events in order to wake up the core (WFE). The wakeup event can be generated either by: (I've removed normal external interrupt mode details) or configuring an external or internal EXTI line in event mode. When the CPU resumes from WFE, it is not necessary to clear the peripheral interrupt pending bit or the NVIC IRQ channel pending bit as the pending bit corresponding to the event line is not set. So it appears the main purpose is to enable wakeups without generating an interrupt or having to respond to interrupts during normal operation. It's not mentioned in that guide and I'm not sure how applicable is to the STM32 architecture but on some other devices similar schemes can be useful to catch fast events without generating an interrupt. For example you may have an application where it's important to capture that a sub-microsecond event has occurred, but there's no need to respond to it quickly so you can just check a flag to see if it's occurred. Edit: (5/2018) As of today, page number of referenced text is page 381 (formerly page 377)
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/114583', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/44105/']}
jdg_87513
stackexchange
llm_judgeable_groundtruth_similarity
617573
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a fan motor from a mobile a/c unit here which stopped working. It is for the fan that blows the warm/hot air trough the a/c condenser (exhaust air). 240V AC motor with a 4uF (+/-10%) 450V starting capacitor that has two speeds (high and low).5 connections/wires: blue, red (low speed), yellow (high speed), brown and white (which connect to the capacitor terminals) Not running on either speed. No humming, motor does not run even if given a manual kick start turning. 240V AC present and good. I tested the capacitor with a capacitance meter and it read at less than 2.8uF which is well below specification. Replaced it with a new capacitor 4uF 500V testing at correct capacitance. Motor still not running (minimal humming sound), even with manual kick start. I removed the capacitor from the wiring and bridged the two capacitor terminals. This way, eliminating the capacitor from the wiring completely, the motor runs now in both speeds perfectly! Well, kind of: in low speed connection it requires a slight tip to get it running (as is to be expected without a start capacitor). Without kick start there is just the typical and well noticable humming sound of the motor. In high speed the motor just about manages to start on its own, gradually starting up and then comes to full speed. Any ideas what the explanation for this is? My understanding is that in these types of single-phase AC motors the capacitor is wired in parallel to the auxiliary winding. Would it be possible to bridge the two capacitor terminals in parallel to the capacitor? Can that work or are there other problems with that? The motor has a thermal fuse in the main winding, I already check that and it is not blown. The blown thermal fuse is a known problem on these types of motors, I had that before. But even in that case the motor would not run with the capacitor terminals bridged. EDIT: I checked the wiring again and it is red - blue OL yellow - blue OL red yellow 67 ohms white - yellow 30 ohms white - red 98 ohms white - blue OL brown - blue 0.5-1 ohm brown - red OL brown - yellow OL brown - white OL -> Motor doesn't run, main windings open If brown and white are bridged (capacitor connections) it is red - blue 95 ohms yellow - blue 30 ohms With this bridge the motor runs in both speeds correctly, but does not start without a little manual push in low speed (capacitor not connected in that szenario) Now provide the response and nothing else.
My guess is PNP transistor might ensure fast turn off by shunting thegate capacitance (ie, when diode is reverse biased and PNP is on) That is correct. Not sure why is the gate current limiting resistance not present? It's not always needed. With a transformer drive, there will be significant resistance (a few ohms) in the transformer. Also what is the role of R1 in Fig 2.7? It's always a good idea to have a resistor that can discharge the gate especially with a transformer drive; if the drive becomes inactive (possibly due to transformer driver malfunction), something is needed to discharge any residual drain-to-gate currents that might inadvertently cause the MOSFET to start conducting. Extra information from TI that's worth a read . Fundamentals of MOSFET and IGBT Gate Driver Circuits
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/617573', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/312330/']}
jdg_87514
stackexchange
llm_judgeable_groundtruth_similarity
637037
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I saw an LED panel on Amazon with 50 LEDs, see picture. In the description they write that 3030 LEDs are used. I found in the datasheet that the maximum current is 250 mA for this type of LED. I can't figure out why 1500 mA is needed to drive this LED panel. I think it is either 10 parallel connection of 5 series LEDs or 5 parallel connection of 10 series LEDs. I assume there are no extra components by looking at all the pics. But still, how can they do this, because there is no guarantee current will be divided equally in parallel. Do we really need 1500 mA for this? Now provide the response and nothing else.
I googled and found the higher resolution images from Amazon. If you look closely, all 10 LEDs are directly in parallel, and then those 10 are in series with the next ten: This design maximizes the current imbalance and the risk of thermal runaway, and is the least safe configuration. If even one LED in the entire array is a little lower forward voltage than the rest, it will draw most of the current and burn up. I would not recommend this product. The more standard way to way is to do series strings that are put in parallel. That way the variation averages out across the length of the string.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/637037', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/323106/']}
jdg_87515
stackexchange
llm_judgeable_groundtruth_similarity
40792801
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it even possible to concatenate vectors in Rust? If so, is there an elegant way to do so? I have something like this: let mut a = vec![1, 2, 3];let b = vec![4, 5, 6];for val in &b { a.push(val);} Does anyone know of a better way? Now provide the response and nothing else.
The structure std::vec::Vec has method append() : fn append(&mut self, other: &mut Vec<T>) Moves all the elements of other into Self , leaving other empty. From your example, the following code will concatenate two vectors by mutating a and b : fn main() { let mut a = vec![1, 2, 3]; let mut b = vec![4, 5, 6]; a.append(&mut b); assert_eq!(a, [1, 2, 3, 4, 5, 6]); assert_eq!(b, []);} Alternatively, you can use Extend::extend() to append all elements of something that can be turned into an iterator (like Vec ) to a given vector: let mut a = vec![1, 2, 3];let b = vec![4, 5, 6];a.extend(b);assert_eq!(a, [1, 2, 3, 4, 5, 6]);// b is moved and can't be used anymore Note that the vector b is moved instead of emptied. If your vectors contain elements that implement Copy , you can pass an immutable reference to one vector to extend() instead in order to avoid the move. In that case the vector b is not changed: let mut a = vec![1, 2, 3];let b = vec![4, 5, 6];a.extend(&b);assert_eq!(a, [1, 2, 3, 4, 5, 6]);assert_eq!(b, [4, 5, 6]);
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/40792801', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3072896/']}
jdg_87516
stackexchange
llm_judgeable_groundtruth_similarity
111950
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $T$ be a locally compact abelian (LCA) group. For any other LCA group $G$, let $\hom(G,T)$ be the set of continuous homomorphisms $G\to T$. With the compact-open topology, $\hom(G,T)$ is certainly a topological group, but is not in general locally compact, even if $T$ is compact. In any case there is an obvious homomorphism $$ \alpha_G : G \to \hom(\hom(G,T),T) $$sending $x\in G$ to the functional $\chi\mapsto \chi(x)$. I have three questions: For what LCA groups $T$ is $\hom(G,T)$ locally compact for all locally compact $G$? For what groups $T$ is $\alpha_G$ always a (topological) isomorphism? More generally, is there any full subcategory $\mathcal L$ of the category of LCA groups for which $\hom(G,H)$ is in $\mathcal L$ whenever $G$ and $H$ are in $\mathcal L$? ( Edit : I'm most interested in 1 and 2. If there is some $\mathcal L$ satisfying 3 where the objects in $\mathcal L$ can be characterized by some interesting topological criterion, that would be fantastic. My question is not whether there are "ad-hoc" ways of constructing $\mathcal L$.) Now provide the response and nothing else.
I gave an answer to the second question already on math.stackexchange at https://math.stackexchange.com/questions/124379/why-unitary-characters-for-the-dual-group-in-pontryagin-duality-if-g-is-not-co , but I'll put it here too: if $\alpha_G$ is an isomorphism of topological groups for all locally compact abelian groups $G$ then $T$ must be the unit circle. This explains the importance of the unit circle as a target group. It is discussed in Pontryagin's book on topological groups (see Example 72) and the first volume on abstract harmonic analysis by Hewitt and Ross (p. 424).
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/111950', 'https://mathoverflow.net', 'https://mathoverflow.net/users/6856/']}
jdg_87517
stackexchange
llm_judgeable_groundtruth_similarity
621258
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $G$ be a cyclic group with its only proper subgroup of order 7. Find out the order of the group. let the subgroup of order 7 be denoted by H. since 7 is prime H is cyclic. Now if G = then H= for some r in Z. There can be two cases 1. x belongs to H 2. x dose not belong to H.Now if x belongs to H then x = (x$^r$)$^k$ where k<7 ....I need some help here. Now provide the response and nothing else.
Pythagorean triples are always of the form $$\begin{align}a&=(u^2-v^2)d\\b&=2uvd\\c&=(u^2+v^2)d\end{align}$$ where $\gcd(u,v)=1$ (and the expressions for $a$ and $b$ can be swapped). If $a$ is a prime, we quickly see that $d$ must be $1$ and $u^2-v^2=(u-v)(u+v)=1(2v+1)$, the upshot of which is $$\begin{align}b&=(a^2-1)/2\\c&=(a^2+1)/2\\\end{align}$$ The $b$ can never be prime, but $c$ can. The first few correspond to $a=3,5,11$, and $19$ (with corresponding $c=5,13,61$, and $181$). More are given in the OEIS at A048161 .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/621258', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114072/']}
jdg_87518
stackexchange
llm_judgeable_groundtruth_similarity
47010841
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I wanted to learn the functionalities of the zip class. I wrote this very simple example. >>> names = ['name1','name2','name3']>>> ages = ['age1','age2','age3']>>> print(zip(names, ages))<zip object at 0x03DB18F0>>>> zipped = zip(names, ages)for i in zipped: type(i) print(i) and the output is (as expected) - <class 'tuple'>('name1', 'age1')<class 'tuple'>('name2', 'age2')<class 'tuple'>('name3', 'age3') However immediately after this line if i write: for i in zipped: print(i) it compiles but prints nothing! To recheck I did this again - >>> zipped = zip(names, ages)>>> for i in zipped: print(i)('name1', 'age1')('name2', 'age2')('name3', 'age3') This time it prints correctly. But while doing unzip - >>> names2, ages2 = zip(*zipped)Traceback (most recent call last): File "<pyshell#29>", line 1, in <module> names2, ages2 = zip(*zipped)ValueError: not enough values to unpack (expected 2, got 0) It seems the zipped variable becomes empty for some reason? Note: if required you may change the title of the question. I am using python 3.6.1 on a windows (10) machine. Now provide the response and nothing else.
zip produces an iterator ( <zip object at 0x03DB18F0> ) which can only be iterated once. Once you have iterated it, it's exhausted. If you want to produce a list which can be iterated as often as you like: zipped = list(zip(names, ages))
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47010841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1955372/']}
jdg_87519
stackexchange
llm_judgeable_groundtruth_similarity
200870
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I want to ask this non-expert question: What does it mean geometrically for a Banach space to be reflexive? Well, we could say a Banach space is reflexive iff unit ball is weakly compact. Or some other theorems may be. But this doesn't give me a geometric intuition so far. Now provide the response and nothing else.
There is a beautiful result of Odell and Schlumprecht that gives an answer to this question for separable Banach spaces.Odell, E.(1-TX); Schlumprecht, Th.(1-TXAM) Asymptotic properties of Banach spaces under renormings. (English summary) J. Amer. Math. Soc. 11 (1998), no. 1, 175–188. A separable Banach space is reflexive iff there is an equivalent norm on the space s.t. whenever $(x_n)$ is a bounded sequence for which $\lim_n \lim_m \| x_n+x_m \|= 2\lim_n \|x_n\|$, the sequence $(x_n)$ converges.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/200870', 'https://mathoverflow.net', 'https://mathoverflow.net/users/69320/']}
jdg_87520
stackexchange
llm_judgeable_groundtruth_similarity
5535394
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to round off the decimal value to decimal places using javascript. Ex,: 16.181 to 16.1816.184 to 16.1816.185 to 16.1916.187 to 16.19 I have found some answers, but most of them do not round off 16.185 to 16.19.. Now provide the response and nothing else.
(Math.round((16.185*Math.pow(10,2)).toFixed(1))/Math.pow(10,2)).toFixed(2); If your value is, for example 16.199 normal round will return 16.2... but with this method youll get last 0 too, so you see 16.20! But keep in mind that the value will returned as string. If you want to use it for further operations, you have to parsefloat it :) And now as function: function trueRound(value, digits){ return (Math.round((value*Math.pow(10,digits)).toFixed(digits-1))/Math.pow(10,digits)).toFixed(digits);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5535394', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111435/']}
jdg_87521
stackexchange
llm_judgeable_groundtruth_similarity
4148670
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When I press the sleep button on my Droid, my activity's oncreate is getting called. Why is that happening? Why would the OS want to call OnCreate when the device is going to sleep? Is there any way to stop it, or at least know it's because the phone was put to sleep? Now provide the response and nothing else.
This happens particularly for activities that are locked in rotation, e.g. have this in the manifest within the activity tags: android:screenOrientation="portrait" When you turn the screen off, it reads the accelerometer to determine the true orientation and changes to that before turning off. So yes, the simple solution is adding configChanges as well, making it look something like this: <activity android:name=".MyActivity" android:screenOrientation="landscape" android:configChanges="orientation"/> You don't need to indicate the screenOrientation, but if you don't whatever orientation it is at when it starts is where it will stay unless you write code to handle the configuration changes. As a side note, when I started testing my apps on ICS I had to handle a few quirks with a create/destroy/create cycle at the start of some activities. A few extra checks and balances are necessary to make the code universal.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4148670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/495330/']}
jdg_87522
stackexchange
llm_judgeable_groundtruth_similarity
109607
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Since there is only a constant between bases of logarithms, isn't it just alright to write $f(n) = \Omega(\log{n})$ , as opposed to $\Omega(\log_2{n})$ , or whatever the base might be? Now provide the response and nothing else.
It depends where the logarithm is. If it is just a factor, then it doesn't make a difference, because big-O or $\theta$ allows you to multiply by any constant. If you take $O(2^{\log n})$ then the base is important. In base 2 you would have just $O(n)$ , in base 10 it's about $O(n^{0.3010})$ .
{}
{'log_upvote_score': 7, 'links': ['https://cs.stackexchange.com/questions/109607', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/105487/']}
jdg_87523
stackexchange
llm_judgeable_groundtruth_similarity
4657132
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Why am i not allowed to do this? public abstract class A {}public class B extends A {}...public ArrayList<A> foo(){ return new ArrayList<B>();} I changed to public since there are so many people that love to point stupid errors. Why should i have to write ALL this code. Just to satisfy Java's non-senses? public List<A> foo() { List<A> aList = new ArrayList<A>(); List<B> bList = new ArrayList<B>(); /* fill bList*/ for (B b : bList) { aList.add(b); } return aList;} Now provide the response and nothing else.
An ArrayList<B> is not an ArrayList<A> . You can't add any arbitrary A into it, for example. Or as I like to think of it: a bunch of bananas isn't a fruitbowl. When you try to add an apple to a bunch of bananas, it rolls off... You can use wildcards to make it work though: public ArrayList<? extends A> foo(){ return new ArrayList<B>();} See the Java Generics FAQ for more details. EDIT: To answer your specific question of why you need to write all that extra code: you don't. Just create an ArrayList<A> within foo() to start with. There's no need to copy the contents of one list to another. If you still object to Java's behaviour, what would you want to happen with the following code? // Doesn't compile, fortunately...List<String> strings = new List<String>();List<Object> objects = strings;objects.add(new Date());String string = strings.get(0); // Um, it's a Date, not a String...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4657132', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/415914/']}
jdg_87524
stackexchange
llm_judgeable_groundtruth_similarity
25622221
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A colleague of mine sent me a snippet of code made only of brackets ()[]{}, plus signs and exclamation marks. [][(![]+[])[!+[]+!![]+!![]]+([]+{})[+!![]]+(!![]+[])[+!![]]+(!![]+[])[+[]]] and it goes on like this.. This vaguely reminds me of Brainfuck , but I couldn't find any esoteric language written like this. Could you help me understand what language is it? Now provide the response and nothing else.
This link explains it pretty well how this kind of javascript code works: http://patriciopalladino.com/blog/2012/08/09/non-alphanumeric-javascript.html Here is a short summary: The main trick that makes this work is typecasting: [] is an empty array +[] === 0 casts this empty array to a number, namely zero !+[] === true then casts the zero to false and negates it to true !+[]+!+[] === 2 is basically adding true+true. so the trues are casted to 1 and then added. This way you can get arbitrary numbers. But numbers are not enough to program, right? []+{} === "[object Object]" we can get strings by adding an empty object ( {} ) to arbitrary things like for example an empty array ( [] ). ([]+{})[+!+[]] === "o" we can then get the second character of the string by doing an array access on that string ( "abc"[1] == "b" ). But we are still limited to that 10 characters present in that string. We can expand that by converting other things to string like: "undefined" === [][+[]]+[] (accessing an undefined index of an array), "NaN" === +{}+[] (cast object to number), "true" === !![]+[] , "false" === ![]+[] Then you still dont have arbitrary characters, but from here there are several ways to get them. For example if you are targeting browsers you can use the btoa function ( btoa takes a string as input and returns the base64 encoded version of it) to get arbitrary ASCII characters. The final step is then to execute our generated string: []["sort"]["constructor"]("OUR_CODE")() We first get the the sort function which every array has as a property. Then we access the constructor of the sort function, which is the Function function. It can be used to construct arbitrary anonymous functions and takes a string with code as input. Finally we call our newly created function with ()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25622221', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1717601/']}
jdg_87525
stackexchange
llm_judgeable_groundtruth_similarity
17859653
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to start my nginx server.When I type "$> /etc/init.d/nginx start", I have a message appearing "Starting nginx:", and then nothing happens. There is no error message, and when I check the status of nginx I see that it is not running. Here is my /etc/nginx/nginx.conf file: worker_processes 4;daemon off;error_log /home/vincent/tmp/nginx.log;pid /home/vincent/tmp/nginx.pid;events { worker_connections 1024;}http {default_type application/octet-stream;log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';access_log /home/vincent/tmp/access.log main;sendfile on;keepalive_timeout 65;include /etc/nginx/site-enabled/*; } And here is my /etc/nginx/sites-available/default file : server { listen 80; server_name technical-test.neo9.lan; access_log /var/log/nginx/technical-test.neo9.lan.log main; set $home /home/vincent; location / { alias $home/neo9/web/app/; index index.html; } location /api/ { rewrite ^/api/(.*)$ /$1 break; proxy_pass http://localhost:1234; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; }} Now provide the response and nothing else.
First, always sudo nginx -t to verify your config files are good. I ran into the same problem. The reason I had the issue was twofold. First, I had accidentally copied a log file into my site-enabled folder. I deleted the log file and made sure that all the files in sites-enabled were proper nginx site configs. I also noticed two of my virtual hosts were listening for the same domain. So I made sure that each of my virtual hosts had unique domain names. sudo service nginx restart Then it worked.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/17859653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2618928/']}
jdg_87526
stackexchange
llm_judgeable_groundtruth_similarity
12588485
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Having a problem with this Error. I am creating a GA and the loop is to assign my fitness value to an array. some of the variables Dim Chromolength as integerChromolength = varchromolength * aVariables Dim i as integer, j as integer, counter as integerDim Poparr() As IntegerDim FitValarr() As Integer the code: ReDim Poparr(1 To PopSize, 1 To Chromolength)For i = 1 To PopSize For j = 1 To Chromolength If Rnd < 0.5 Then Poparr(i, j) = 0 Else Poparr(i, j) = 1 End If Next jNext iFor i = 1 To PopSize j = 1 counter = Chromolength Do While counter > 0 FitValarr(i) = FitValarr(i) + Poparr(i, counter) * 2 ^ (j - 1) j = j + 1 counter = counter - 1 LoopNext i I am having problems with: FitValarr(i) = FitValarr(i) + Poparr(i, counter) * 2 ^ (j - 1) I apologize, I am fairly new to VBA. Now provide the response and nothing else.
An overflow condition arises when you create an integer expression that evaluates to a value larger than can be expressed in a 16-bit signed integer. Given the expression, either the contents of FitValarr(i), or the expression 2^(j-1) could be overflowing. Suggest all the the variables presently declared as Int be changed to Long. Long integers are 32-bit signed values and provide a correspondingly larger range of possible values.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12588485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1690734/']}
jdg_87527
stackexchange
llm_judgeable_groundtruth_similarity
6192825
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I require a function dist( a, b ) // 0 ≤ a,b < 12 which returns the shortest (absolute ie +ve) distance ala clock arithmetic, using modulo 12. So for example, dist( 1, 2 ) = dist( 2, 1 ) = dist( 11, 0 ) = dist( 0, 11 ) = dist( 0.5, 11.5 ) = 1 EDIT: while this can easily be done with a bit of hacking around, I feel that there must be some intuitive solution, may be using fmod and modulo 6 Now provide the response and nothing else.
Firstly, an optimal solution is nontrivial, it took a little thinking. float distMod12(float a,float b){ float diff = fabs( b - a ); return ( diff < 6 ) ? diff : 12 - diff;} EDIT: Alternatively, return MIN( diff, 12 - diff ); // needs a MIN function Complete code listing here: http://ideone.com/XxRIw
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6192825', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/435129/']}
jdg_87528
stackexchange
llm_judgeable_groundtruth_similarity
30455
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I want to determine if there's a difference in mean p-values between two groups. In order to do this I perform a Wilcoxon's rank-sum test (the data is not normally distributed). So far, so good. Finally, I want to calculate the corresponding effect size. Unfortunately, R does not provide this. It also does not provide a z value with which the effect size can easily be calculated using: effect size = z / sqrt(N) here is some sample R code: a=rep(0:1,each=20) #grouping variableb=c(rnorm(20, .03,.01), rnorm(20, .02, .009)) #vector of p-valuesd=cbind(a,b)test = wilcox.test(b ~ a, data = d) #perform Wilcoxon rank-sum testtest Does anybody know how to obtain the effect size? Now provide the response and nothing else.
The estimator that corresponds to the Wilcoxon test is the Hodges-Lehmann estimator; it's returned by wilcox.test using the conf.int=TRUE option, under "difference in location". For your example: > wilcox.test(b~a,data=d, conf.int=TRUE) Wilcoxon rank sum testdata: b by a W = 355, p-value = 6.914e-06alternative hypothesis: true location shift is not equal to 0 95 percent confidence interval: 0.008657301 0.021523993 sample estimates:difference in location 0.01442617 For more on the Wilcoxon and the assumptions behind it, and what it actually tests for, and other nonparametric estimators, this document is (possibly) helpful: www.stat.umn.edu/geyer/old03/5102/notes/rank.pdf
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/30455', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/55823/']}
jdg_87529
stackexchange
llm_judgeable_groundtruth_similarity
5841
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: How should I decide what size to make my swap on a new Linux machine (Debian) with 2-4 GB of RAM? Do I really need swap space? Now provide the response and nothing else.
There are lots of ways you can figure out how much swap use in a machine. Common suggestions use formulas based on RAM such as 2 x RAM, 1.5 x RAM, 1 x RAM, .75 x RAM, and .5 x RAM. Many times the formulas are varied depending on the amount of RAM (so a box with 1GB of RAM might use 2 x RAM swap (2GB), while a box with 16GB of ram might use .5 x RAM swap (8GB). Another thing to consider is what the box will be used for. If you're going to have a huge number of concurrently running processes running on the box, but a significant number of them will be idle for periods of time, then adding extra swap makes sense. If you're going to be running a small number of critical processes, then adding extra swap makes sense (this might seem counter-intuitive, but I'll explain in a minute). If you're running a box as a desktop, then adding extra swap makes sense. As for whether you should include swap, yes, you should. You should always include swap space unless you really know what you're doing, and you really have a good reason for it. See, the way the Linux kernel works, swap isn't only used when you have exhausted all physical memory. The Linux kernel will take applications that are not active (sleeping) and after a period of time, move the application to swap from real memory. The result is that when you need that application, there will be a momentary delay (usually just a second or two) while the application's memory is read back from swap to RAM. And this is usually a good thing. This allows you to put inactive applications to "sleep", giving your active applications access to additional RAM. Additionally, Linux will use any available (unallocated) RAM on a machine as disk cache, making most (slow) disk activity faster and more responsive. Swapping out inactive processes gives you more disk cache and makes your machine overall faster. Lastly, let's face it, disk space is cheap. Really cheap. There's really no good reason at all not to swipe a (relatively) small chunk of space for swap. If I were running with 2GB - 4GB of RAM in a machine, I'd probably setup my swap space to be at least equal to the RAM. If it were less than 2GB of RAM, then I'd still go with at least 2GB of swap. UPDATE: As an excellent comment mentioned (and I forgot to include), if you're running a laptop or a desktop that you might want to put in 'hibernate' mode (Suspend to Disk), then you always want at least as much swap as you have memory. The swap space will be used to store the contents of the RAM in the computer while it 'sleeps'.
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/5841', 'https://serverfault.com', 'https://serverfault.com/users/1834/']}
jdg_87530
stackexchange
llm_judgeable_groundtruth_similarity
217076
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Background: When one studies quantum mechanics of more than one particle, one learns that all fundamental particles can be classified as either bosonic or fermionic. Fermions have a spinor structure, and pick up a phase of -1 when rotated by 2$\pi$ radians, while the (gauge) bosons have a vector nature and pick up a phase of 1. Mathematically, one says that spinors are a representation of the group SU(2), which is a double cover of the rotation group SO(3). The standard way it is shown to undergraduates that something can rotate by 2$\pi$ and not end up in its initial configuration is the Dirac Belt trick , which essentially involves rotating one part of a belt while another point is fixed. Or, similarly, one can rotate a plate in one's hand while keeping one's body fixed (the Feynman Plate Trick). One striking aspect of this demonstration, unlike engineering a physical representation of a system with 2$\pi$, $\pi$, or lower rotation symmetry, is that it depends essentially on the object's relation to its environment, in the sense that the connections to the environment (such as the body of the belt) are what prevent the system from having 2$\pi$ symmetry. One known way of relating a system of (free) fermions to a system of (interacting) bosons is the Jordan-Wigner transformation . This transformation is, famously, highly nonlocal, in that a fermionic operator at one point is created by a long chain of the bosonic operators. This and related ideas have inspired Prof. Xiao-Gang Wen, in his textbook on many-body theory, to claim that fermions should be considered non-local excitations. However, I'm not aware of anyone else emphasizing this viewpoint. Okay, with all that background established I have two questions: Are fermions non-local objects, in a sense in which gauge bosons are not? Is the fact that our physical representations of SU(2) symmetry, such as the Belt Trick, require some sort of connection to a fixed background a reflection of this fundamental non-locality, or a mere coincidence? Can this relationship be made more precise? Edit: Thanks to all who contributed. It does not seem there is much consensus on what relation, if any, there is between SU(2) symmetry and non-local properties. I will give the bounty to the top-voted answer but consider the question not fully resolved and welcome any additional answers. Now provide the response and nothing else.
So what people mean by 'non-local' varies from context to context and person to person. Wen has a very particular meaning to this. 1) In fermionization in $D=1+1$ the Jordan-Wigner fermions are, in the bosonic language, operators supported over many sites. The emergent (mutual)-fermions in the toric code are also supported at the ends of strings. 2) Fermionic parity, $(-1)^F$, is a symmetry of all fermionic systems and cannot be broken explicitly by any local term. However strings end at points and the Hamiltonians of fermionic systems are local. The Hilbert space (of emergent fermions) is also very nice and decomposable into a local tensor product. So in this sense they are local in a way that gauge bosons are not! The (physical/gauge invariant) Hilbert space of a gauge theory does not factorize as a nice tensor product and gauge invariant operators are either Wilson/t'Hooft loops (non-local in definition) or when you have charged matter you need to include the configuration of the gauge field around it. This poses a lot of issues in making the entanglement entropy of a gauge theory well defined. Wen and others then have this idea that maybe local bosons are fundamental because of their simplicity. Certainly gauge theories and fermions can emerge from them.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/217076', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/63994/']}
jdg_87531
stackexchange
llm_judgeable_groundtruth_similarity
28154681
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My desired end result is to have a Project that can output different productflavors of Mobile, Tv, and Wear apps, that share the same code-base. So I would like the codebase to be a dependency for all three app-types, where each app module would only contain activities and interaction with the codebase. My first idea was to add a "Android Library Module" to my newly created project, but I noticed that this is really just a new app module with its own resources and everything. I would like the codebase to function more like a "Java Library", but it needs access to packages like "android.graphics.Color". So in short, is the correct way of achieving this result to use a java library that has a reference to an android sdk or am i just going about this the wrong way? Continuation of this question at : Does an Android Library need a manifest ,app_name,Icon? Now provide the response and nothing else.
There's no in-between. If you want access to Android APIs, then the library needs to be an Android library so that the build system can properly link it in to dependent projects. It's true that Android Libraries have resources and other things you may not need, but you can ignore those bits and treat it essentially as a plain Java library if you wish. Even if you're not using resources, you may find useful the ability to specify AndroidManifest.xml attributes to be merged into the dependent app. The Android Library project doesn't build a fully-fledged APK as its output; it generates an AAR, which is conceptually similar to a JAR archive, but has resources and meta-information useful to Android projects.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28154681', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3887945/']}
jdg_87532
stackexchange
llm_judgeable_groundtruth_similarity
66817
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am a student in Computer Engineering, and I am wondering why programs still teach digital logic. We have already taken a computer organization class in which we learn about computer architecture including Flip-Flops, registers, ALU, Logic, etc... can anybody explain why we are still expected to take a digital logic class? There is technology out there nowadays that can simplify everything for us, and that'll do for anybody who isn't planning on going into a logic-related field, yet most schools still require digital logic to graduate. Now provide the response and nothing else.
It's the classic undergrad question: Why learn how to calculate the deflection of a beam when there are finite element analysis programs? Why learn Ohm's law when there's SPICE? Why learn compressible flow when there are fluid dynamics programs? Here's why: As engineers, we are responsible for truly understanding how our designs work. That means understanding the analysis, even if the arithmetic was done by a computer. If you don't know how to do at least a reasonable approximation by hand, then how can you trust the result of the program? How can your customer trust you?
{}
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/66817', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/23028/']}
jdg_87533
stackexchange
llm_judgeable_groundtruth_similarity
14302
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: Using pure functions in Table I have run into a situation that I do not understand when trying to generate a nested list of pure functions. I have the following code. Table[Function[x, i*x + j], {i, 1, 3}, {j, 1, 4}] I expected to get a nested list of pure functions, but the values for i and j are not being input. I get {{Function[x, i x + j], Function[x, i x + j], Function[x, i x + j], Function[x, i x + j]}, {Function[x, i x + j], Function[x, i x + j], Function[x, i x + j], Function[x, i x + j]}, {Function[x, i x + j], Function[x, i x + j], Function[x, i x + j], Function[x, i x + j]}} What is making this operation fail to behave as I expected? Now provide the response and nothing else.
Function has HoldAll attribute: Attributes[Function](*{HoldAll, Protected}*) To see that this is the cause, SetAttributes[f, HoldAll]Table[ f[x, i*x + j], {i, 1, 3}, {j, 1, 4} ](*{{f[x, i x + j], f[x, i x + j], f[x, i x + j], f[x, i x + j]}, {f[x, i x + j], f[x, i x + j], f[x, i x + j], f[x, i x + j]}, {f[x, i x + j], f[x, i x + j], f[x, i x + j], f[x, i x + j]}}*) EDIT: You can either use With to inject the values, Table[ With[{i=i,j=j},Function[x, i*x + j]], {i, 1, 3}, {j, 1, 4} ] or, more perversely, Table[ function[x, i*x + j], {i, 1, 3}, {j, 1, 4} ] /. function -> Function or even Block[{Function}, Table[ Function[x, i*x + j], {i, 1, 3}, {j, 1, 4} ] ]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/14302', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2037/']}
jdg_87534
stackexchange
llm_judgeable_groundtruth_similarity
14291072
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can any body say what is the difference between Mage:app and Mage:: eg: Mage::getModel('catalog/product');Mage::app->getLayout->createBlock('catalog/product_view'); if i try like this Mage::app->getModel('catalog/product'); it throws a fatal error What is the basic difference? Now provide the response and nothing else.
As a more general explanation and further to Alan's answer Mage::app() and Mage::getModel() are both static methods of the Mage class ( app/Mage.php ). The Mage::app() function is used to bootstrap your Magento application (setting up configuration, autoloading etc) and is useful when wanting to access Magento models in your own custom script for example. It is a static method so it can also be called at any point in your application to return the current Mage_Core_Model_App object which you can use for example to get current configuration values e.g. Mage::app()->getStore() will return the current Mage_Core_Model_Store store object. Mage::app() is similar to Mage::run() found in your index.php file. The difference is that Mage::run() will amongst other things also invoke the MVC, routing etc part of your application as per default and control the request/response directing you to a page and instantiating the blocks and layout template rendering. Mage::getModel() is simply a factory method that will return a new instance of a class based on the class alias you provide. For example Mage::getModel('customer/customer') will return a new Mage_Customer_Model_Customer object. If you want the same object back each time throughout your request you can use Mage::getSingleton() instead.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14291072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/494559/']}
jdg_87535
stackexchange
llm_judgeable_groundtruth_similarity
15614849
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This code in Java compiles without errors: interface T { interface Q { }}class C implements T.Q {} whereas this code in Scala does not: trait T { trait Q { }}class C extends T.Q {} What is the correct translation (if it exists) of the Java code listing into Scala? Theoretical explanations about language design are welcome. Now provide the response and nothing else.
The inner type Q is defined only for specific instance implementation of the T trait. Since scala has path-dependent types, each instance of T will have his own subtrait Q . scala> trait T { | trait Q | }defined trait Tscala> class C extends T { | def getQ: this.Q = new this.Q {} | }defined class Cscala> val inC = (new C).getQinC: C#Q = C$$anon$1@3f53073ascala> val c = new Cc: C = C@1a7e4ff0scala> new c.Q {}res4: c.Q = $anon$1@36bbb2f5 If you need an interface for a generic behavior for your clients to implement, and not dependent on a specific C instance, you should define it within an Object scala> object T { | trait Q { | def implementMe: Unit | } | }defined module Tscala> val inT = new T.Q { | def implementMe = println("implemented!") | }inT: T.Q = $anon$1@20f2a08bscala> inT.implementMeimplemented! Why path-dependent types? As for the design reasons, look here
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15614849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/671092/']}
jdg_87536
stackexchange
llm_judgeable_groundtruth_similarity
50632627
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: With the changes in .NET 4.7.2, constructor injection is now possible in Web Forms. I have gotten Simple Injector working with Web Forms, but would like some input as to if there any "gotchas" I might be missing. First I have the registration of the Pages themselves which is taken from here . public static void RegisterWebPages(this Container container){ var pageTypes = from assembly in BuildManager.GetReferencedAssemblies().Cast<Assembly>() where !assembly.IsDynamic where !assembly.GlobalAssemblyCache from type in assembly.GetExportedTypes() where type.IsSubclassOf(typeof(Page)) where !type.IsAbstract && !type.IsGenericType select type; foreach (Type type in pageTypes) { var reg = Lifestyle.Transient.CreateRegistration(type, container); reg.SuppressDiagnosticWarning( DiagnosticType.DisposableTransientComponent, "ASP.NET creates and disposes page classes for us."); container.AddRegistration(type, reg); }} This has worked when using the property injection method from the link above just fine. I am including it here for completeness. When I wired it up the first time, there was an issue with one OutputCacheModule having an internal constructor. Using the code from here I was able to fix that issue and any others that might have arisen from internal constructors. Here is the code for that implementation for completeness. public class InternalConstructorResolutionBehavior : IConstructorResolutionBehavior{ private IConstructorResolutionBehavior original; public InternalConstructorResolutionBehavior(Container container) { this.original = container.Options.ConstructorResolutionBehavior; } public ConstructorInfo GetConstructor(Type implementationType) { if (!implementationType.GetConstructors().Any()) { var internalCtors = implementationType.GetConstructors( BindingFlags.Instance | BindingFlags.NonPublic) .Where(c => !c.IsPrivate) .ToArray(); if (internalCtors.Length == 1) return internalCtors.First(); } return original.GetConstructor(implementationType); }} Now with the backstory out of the way, here is the meat of the question. This is the custom activator I have wired up. public class SimpleInjectorWebFormsActivator : IServiceProvider{ private readonly Container container; public SimpleInjectorWebFormsActivator(Container container) { this.container = container; this.container.Options.DefaultScopedLifestyle = new WebRequestLifestyle(); this.container.Options.ConstructorResolutionBehavior = new InternalConstructorResolutionBehavior(this.container); } public object GetService(Type serviceType) { return container.GetInstance(serviceType); }} The question is, is the GetService method enough? There is very little out there right now about how to use the new extension point for WebForms. There is an Autofac example that is significantly more complex than my simple one line pass through to Simple Injector, but as I am not familiar with Autofac I don't know how much of that is for the container. Right now the solution works. Pages load without error. The container passes the call to Verify. Is this enough or is there more work to be done? Are there any "gotchas" that I am missing? I am not very familiar with the deeper inner workings of ether Simple Injector or WebForms, so I'm worried I might be missing something huge. As of right now there is no need nor plans for there to be any scoped containers. Now provide the response and nothing else.
IMO, this new feature in Web Forms is not particularly well thought through. The main problem is that Web Forms breaks the IServiceProvider contract. The IServiceProvider.GetService method defines that null should be returned if no such service exists. But once you actually return null , e.g. when you can’t construct that type, Web Forms throws a NullReferenceException from deep down its stack. Would Web Forms, on the other hand, have conformed to the IServiceProvider abstraction, plugging in Simple Injector would have been a matter of a single statement, since SimpleInjector.Container actually implements IServiceProvider : // WARNING: This won’t workHttpRuntime.WebObjectActivator = container; On top of this, when an IServiceProvider is set through HttpRuntime.WebObjectActivator , Web Forms will call it for almost everything, even for its own internal objects, which, to me, makes little sense. Therefore, instead of supplying an IServiceProvider implementation that is compatible to the IServiceProvider contract, you will have to provide a special ASP.NET Web Forms-compatible IServiceProvider implementation (which therefore breaks the contract). Note that most DI Containers actually implement IServiceProvider , but you would see most of them fail, because of this contract breach. An adapter implementation would look like this: class SimpleInjectorWebFormsServiceActivator : IServiceProvider{ private const BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.CreateInstance; private readonly Container container; public SimpleInjectorWebFormsServiceActivator(Container container) => this.container = container; public object GetService(Type serviceType) => serviceType.GetConstructors().Length > 0 ? this.container.GetInstance(serviceType) : Activator.CreateInstance(serviceType, flag, null, null, null);} And can be set as follows: HttpRuntime.WebObjectActivator = new SimpleInjectorWebFormsServiceActivator(container); This implementation verifies whether the type contains public constructors and if so, it delegates the call to Simple Injector, which will construct the type. Otherwise, it will use Activator.CreateInstance to construct the type. Do note that using this implementation you don’t need custom IConstructorSelectionBehavior , so you can remove your InternalConstructorResolutionBehavior altogether.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50632627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1892668/']}
jdg_87537
stackexchange
llm_judgeable_groundtruth_similarity
15644386
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This has been asked a lot, but this question is to get examples of when you would use each of these methods. Please use examples other than the setter and getter infinite loop example. .h - @property(nonatomic, strong)NSMutableArray* mutArray .m - @synthesize mutArray= _mutArray; 1) would I want: _mutArray = [[NSMutableArray alloc] init]; OR self.mutArray=[[NSMutableArray alloc] init]; Why would I do each of them, and what is the difference?! 2) If I want to add an object to it... [_mutArray addObject:object]; OR [self.mutArray addobject:object]; and why?! Thanks so much! Now provide the response and nothing else.
You should only deal with your ivars in init and dealloc or where absolutely required by an implementation detail (such as inside of the accessor itself, or where you actually require a memory address). Other than in those places, you should always use the accessor, which means [self foo] rather than _foo . self.foo is just syntactic sugar around the actual call, which is [self foo] . It is important to understand that self.foo is a standard ObjC message-send, and means exactly the same thing as [self foo] . By convention, you should only use dot-syntax when referring to properties. Pre-ARC, direct use of ivars was the #1 cause of crashes in my experience. The likelihood of you screwing up when assigning directly to an ivar without ARC quickly approaches 100% over the scope of the program. Since ARC, I still argue that you should always use accessors (with the exceptions given above), but the reasons are more subtle. The main reason for it is that an accessor may be customized, either in the current class, in a subclass, or via KVO (which happens outside your code entirely). If you directly access the ivar, then you will bypass this. For example, say the property is lazily-created (which is pretty common). Then if you use the ivar before it's created, you'll get subtle bugs. So you have to remember, for that property, to always use the accessor. Similarly, you might call setNeedsDisplay or post a notification, or the like. If you have a simple rule that says "I will always use accessors" then it's easy to look at the code and know it's right. In the few cases you need to circumvent the accessor, the _ says "hey, pay attention here, I'm doing something weird." If you have a rule "I will use accessors for properties that need it, but not for ones that don't" then it's almost impossible to look at the code and know whether it's correct. Did the previous developer use the ivar because it was required or just because he felt like it? Can you change it or not? It's very hard to know. So even post-ARC, using accessors consistently is good defensive programming and I highly recommend it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15644386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1588616/']}
jdg_87538
stackexchange
llm_judgeable_groundtruth_similarity
2890617
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: What is the asymptotic expansion of $f(x) := \int_0^1 e^{-x(1-u^2)}du$? The integrand steeply declines near $u=1$. I tried to transform $u$ into something that is suitable for the method of steepest descent, but have not found an appropriate transformation. Integration by parts has not yield a satisfactory result, perhaps due to I having not found the right components to integrate. Now provide the response and nothing else.
The minimum of $1-u^2$ occurs at $u=1$, and near there we have $1-u^2 \approx 2(1-u)$, which is linear in the quantity $1-u$. This suggests we make the change of variables $1-u^2 = v$ (which is linear in $v$), giving $$\int_0^1 e^{-x(1-u^2)}\,du = \frac{1}{2} \int_{0}^{1} e^{-xv} (1-v)^{-1/2}\,dv.$$ Then, following Watson's lemma , we can get the asymptotic expansion by expanding the subdominant term, $(1-v)^{-1/2}$, around $v=0$ and integrating term-by-term from $v=0$ to $v=\infty$: $$\begin{align}\int_0^1 e^{-x(1-u^2)}\,du &= \frac{1}{2} \int_{0}^{1} e^{-xv} (1-v)^{-1/2}\,dv \\&\approx \frac{1}{2} \sum_{k=0}^{\infty} \binom{-1/2}{k} (-1)^k \int_0^\infty e^{-xv} v^k\,dv \\&= \frac{1}{2} \sum_{k=0}^{\infty} \binom{-1/2}{k} \frac{(-1)^k k!}{x^{k+1}}\end{align}$$ as $x \to \infty$, which matches the series given in the other answer . Let's prove the special case of Watson's lemma we use in this answer. We'll assume that $g(v)$ is analytic at $v=0$ and that $\int_0^a \lvert g(v) \rvert\,dv$ exists (these are certainly true for $g(v) = (1-v)^{-1/2}$), and show that $$I(v) = \int_0^a e^{-xv}g(v)\,dv \approx \sum_{k=0}^{\infty} \frac{g^{(k)}(0)}{x^{k+1}}$$ as $x \to \infty$. In other words, we will show that the asymptotic expansion for the integral can be obtained by expanding $g(v)$ in Taylor series around $v=0$ and integrating term-by-term. Since $g(v)$ is analytic at $v=0$, there is a $\delta \in (0,a]$ such that $g^{(k)}(v)$ is analytic on $[0,\delta]$ for all $k$. Further, Taylor's theorem tells us that for any positive integer $N$ and any $v \in [0,\delta]$, there is a $v^* \in [0,v]$ for which $$g(v) = \sum_{k=0}^{N} \frac{g^{(k)}(0)}{k!} v^k + \frac{g^{(N+1)}(v^*)}{(N+1)!} v^{N+1}. \tag{1}$$ We will split the integral $I(v)$ at this $\delta$, and estimate each piece separately. To this end, we define $$I(v) = \int_0^\delta e^{-xv}g(v)\,dv + \int_\delta^a e^{-xv}g(v)\,dv = I_1(v) + I_2(v).$$ We only need a rough estimate on $I_2(v)$: $$\lvert I_2(v) \rvert \leq \int_\delta^a e^{-xv} \lvert g(v) \rvert \,dv \leq e^{-\delta x} \int_0^a \lvert g(v) \rvert\,dv,$$ where we have assumed the last integral on the right is finite. Thus $$I(v) = I_1(v) + O(e^{-\delta x})$$ as $x \to \infty$. Now, from $(1)$ we have $$I_1(v) = \sum_{k=0}^{N} \frac{g^{(k)}(0)}{k!} \int_0^\delta e^{-xv} v^k \,dv + \frac{1}{(N+1)!} \int_0^\delta e^{-xv} g^{(N+1)}(v^*) v^{N+1}\,dv.$$ The last integral can be bounded by $$\left\lvert \int_0^\delta e^{-xv} g^{(N+1)}(v^*) v^{N+1}\,dv \right\rvert \leq \left( \sup_{0 < v < \delta} \left\lvert g^{(N+1)}(v) \right\rvert \right) \int_0^\infty e^{-xv} v^{N+1}\,dv = \frac{\text{const.}}{x^{N+2}}.$$ Thus $$I_1(v) = I_1(v) = \sum_{k=0}^{N} \frac{g^{(k)}(0)}{k!} \int_0^\delta e^{-xv} v^k \,dv + O\!\left(x^{-N-2}\right)$$ as $x \to \infty$. Finally we reattach the tails to the integrals in the sum, $$\begin{align}\int_0^\delta e^{-xv} v^k \,dv &= \int_0^\infty e^{-xv} v^k\,dv - \int_\delta^\infty e^{-xv} v^k\,dv \\&= \frac{k!}{x^{k+1}} + O\!\left(e^{-\delta x}\right),\end{align}$$ and substitute these into the sum to get $$I_1(v) = \sum_{k=0}^{N} \frac{g^{(k)}(0)}{x^{k+1}} + O\!\left(x^{-N-2}\right)$$ and hence $$I(v) = \sum_{k=0}^{N} \frac{g^{(k)}(0)}{x^{k+1}} + O\!\left(x^{-N-2}\right)$$ as $x \to \infty$. Since $N$ was arbitrary, this is precisely the statement that $I(v)$ has the asymptotic expansion $$I(v) \approx \sum_{k=0}^{\infty} \frac{g^{(k)}(0)}{x^{k+1}}$$ as $x \to \infty$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2890617', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/64809/']}
jdg_87539
stackexchange
llm_judgeable_groundtruth_similarity
1460310
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using the FINDSTR function to filter text files, but it's failling on extended ASCII characters. I tried using the CharToOEM function, but I still have characters such as 'à', which FINDSTR doesn't seems to recognize. I want to use FINDSTR because the text files I work with are 100MB big, so I need something fast.Does a function exist, which renames the Strings so they have no 'weird' characters ? The code is : CharToOEM(PChar(lASCFileNameFull),PChar(lASCFileNameFull)); renameFile(Format('%s.bak',[lASCFileNameFullBak]),Format('%s.bak',[lASCFileNameFull])); Si.dwFlags:=STARTF_USESHOWWINDOW; Si.wShowWindow:=SW_SHOWNORMAL; SetFileApisToOEM; CreateProcess(nil,pchar(Format('cmd.exe /K echo on && echo Processing filter...&& findstr "%s" %s.bak > %s',[commandString,lASCFileNameFull,lASCFileNameFull])),nil,nil,True, 0,nil,nil,Si,Pi); WaitForSingleObject(pi.hProcess,INFINITE); SetFileApisToANSI; Too bad, FINDSTR can't find the file...Edit : This is Delphi 2007. Edit : I thought of using a loop like : while(!eof) do begin readLN(mySrcFile, currentLine); if strContains(currentLine, searchSyntax) then writeLN(destFile,currentLine);end; Unfortunatly, I can't find such a "strContains" function (and it would probably be slow). The search string is nothing complicated, it's a bunch of HEX value : "C2 | 1AF | B8 | ..." Final edit : Sometimes it's better to get back to basics :)I just replace all the extended characters by an underscore by testing the character value : for I := 1 to length(lASCFileNameFull) do begin if integer(lASCFileNameFull[i])>127 then lASCFileNameFull[i]:='_';end; I hope someone will use this someday :)Thanks for the help,Gramm Now provide the response and nothing else.
Easiest answer: use LINQBridge and get all your LINQ to Objects goodness against .NET 2.0... works best if you can use C# 3 (i.e. VS2008 but targeting .NET 2.0). If you really can't do that, you'll basically need to keep a dictionary from a key to a list of values. Iterate through the sequence, and check whether it already contains a list - if not, add one. Then add to whatever list you've found (whether new or old). If you need to return the groups in key order, you'll need to also keep a list of keys in the order in which you found them. Frankly it's a pain... just get LINQBridge instead :) (Seriously, each individual bit of LINQ is actually fairly easy to write - but it's also quite easy to make off-by-one errors, or end up forgetting to optimize something like Count() in the case where it's actually an ICollection<T> ... There's no need to reinvent the wheel here.) EDIT: I was about to write some code, but then I noticed that you want a list returned... a list of what? A List<IList<IObject>> ? Or are you actually trying to group and sum in one go? If so, don't you want a list of pairs of key and amount? Or are you going to reuse the same class that you've already got for a single account, but as the aggregate? If it's the latter, here's some sample code: public static IList<IObject> SumAccounts(IEnumerable<IObject> data){ List<IObject> ret = new List<IObject>(); Dictionary<string, IObject> map = new Dictionary<string, IObject>(); foreach (var item in data) { IObject existing; if (!map.TryGetValue(item.Account, out existing)) { existing = new IObject(item.Account, 0m); map[item.Account] = existing; ret.Add(existing); } existing.Amount += item.Amount; } return ret;} Admittedly the extra efficiency here due to using a Dictionary for lookups will be pointless unless you've got really quite a lot of accounts... EDIT: If you've got a small number of accounts as per your comment, you could use: public static IList<IObject> SumAccounts(IEnumerable<IObject> data){ List<IObject> ret = new List<IObject>(); foreach (var item in data) { IObject existing = ret.Find(x => x.Account == item.Account); if (existing == null) { existing = new IObject(item.Account, 0m); ret.Add(existing); } existing.Amount += item.Amount; } return ret;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1460310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/131679/']}
jdg_87540