qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
sequence
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
45,585,642
When I try to export report in PDF/Excel/Word or print report, I got a error. Error description : ``` Server Error in '/' Application. Operation could destabilize the runtime. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Security.VerificationException: Operation could destabilize the runtime. ``` Source Error: ``` An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. ``` Stack Trace: ``` [VerificationException: Operation could destabilize the runtime.] [TypeInitializationException: The type initializer for 'System.Diagnostics.Activity' threw an exception.] [TargetInvocationException: Exception has been thrown by the target of an invocation.] System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +153 System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +336 System.Collections.Generic.IList`1.get_Item(Int32 index) +0 Microsoft.ReportingServices.ReportIntermediateFormat.TextBox.SetExprHost(ReportExprHost reportExprHost, ObjectModelImpl reportObjectModel) +101 Microsoft.ReportingServices.OnDemandProcessing.OnDemandProcessingContext.RuntimeInitializeTextboxObjs(ReportItem reportItem, Boolean setExprHost) +74 Microsoft.ReportingServices.OnDemandReportRendering.OnDemandPageEvaluation.InitializeEnvironment() +778 Microsoft.ReportingServices.OnDemandReportRendering.OnDemandPageEvaluation..ctor(Report report) +84 Microsoft.ReportingServices.OnDemandReportRendering.Report..ctor(Report reportDef, ReportInstance reportInstance, RenderingContext renderingContext, String reportName, String description) +100 Microsoft.ReportingServices.ReportProcessing.Execution.RenderReportOdp.PrepareROM(RenderingContext& odpRenderingContext) +158 Microsoft.ReportingServices.ReportProcessing.Execution.RenderReport.Execute(IRenderingExtension newRenderer) +306 [LocalProcessingException: An error occurred during local report processing.] Microsoft.Reporting.WebForms.LocalReport.InternalRender(String format, Boolean allowInternalRenderers, String deviceInfo, PageCountMode pageCountMode, CreateAndRegisterStream createStreamCallback, Warning[]& warnings) +166 Microsoft.Reporting.WebForms.LocalModeSession.RenderReport(String format, Boolean allowInternalRenderers, String deviceInfo, NameValueCollection additionalParams, Boolean cacheSecondaryStreamsForHtml, String& mimeType, String& fileNameExtension) +193 Microsoft.Reporting.WebForms.ExportOperation.PerformOperation(NameValueCollection urlQuery, HttpResponse response) +514 Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context) +250 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +188 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69 Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1087.0 ``` Any ideas. Thanks.
2017/08/09
[ "https://Stackoverflow.com/questions/45585642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8438590/" ]
I had the same issue and was able to resolve it by commenting out the Microsoft.ApplicationInsights.Web.AspNetDiagnosticTelemetryModule in the ApplicationInsights.config.
I had this issue too. Started to see this issue after I had upgraded NuGet packages in my application to the latest version. The application would worke fine on my development machine, but once I deployed the it to a production server I started to see this error when trying to access a ReportViewer page. I ended up removing all ApplicationInsights NuGet packages in my application. This got rid of the reference to the System.Diagnostics.DiagnosticsSource dll and then my application started working normaly.
8,790,784
For a project, we need a way to run user scripts that can come with attached JAR files with additional classes. What are my options when I want to write a couple of tests to make sure normal script don't leave anything dangling behind? I specifically need to know: Are all classes from the attached JARs "unloaded"? Note: I'm not looking for the 100% super-watertight solution that works across all versions of Java from 1.0 to 7. Right now, I just need to be better than "I have no idea".
2012/01/09
[ "https://Stackoverflow.com/questions/8790784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34088/" ]
The likely best option is to ensure your loaded jars are loaded by a specific class loader, and then to discard that class loader (after discarding all the objects). As far as unit testing the unloading, if you go with this option, you need to extend your testing framework and customized class loaders to have a "create class loader on demand" flag. Then you load the class once with the flag on, discard the class loader, and attempt to load the class again with the flag off. If the class is truly not reachable, the second attempt should throw a class not found exception. You then wrap your unit tests to pass if they fall into the exception, and fail if they succeed in hitting the line after the second load attempt. If you are disposed to use more than pure-Java tools, an OSGi container might be a consideration. Most of the established OSGi container implementations explicitly test class unloading.
I wouldn't try to unit test this. Instead, I'd run the JVM with -XX:-TraceClassUnloading and look to see if the classes in question show up in the trace output.
9,346,188
I'm trying to make a page where a user may enter a url into an input box, click submit, and the script will return the WebCite page. (WebCite is a url caching service. For example, if I "archive" www.google.com, the archive page is www.webcitation.org/65YgIgei6.) So WebCite has a query syntax that when given a url to cache, an email, and the parameter `&returnxml=true`, it will return an xml file. (For example, <http://www.webcitation.org/archive?url=http://www.google.com&email=testtt@test.com&returnxml=true> leads to an xml file where the text between the `<webcite_url>` tags is the archive page.) So I would like some Javscript (or jquery) that will search the xml file for "`<webcite_url>`" and "`</webcite_url>`" and return the url within those tags. <http://jsfiddle.net/gxHWk/> is the basic idea. btw, I read stackoverflow.com/questions/6648454/search-and-output-data-from-an-xml-file-using-javascript, but I can't figure out how to adapt the code there to my circumstances. (\*removed "http://" from some links because of spam filter) Thanks!
2012/02/19
[ "https://Stackoverflow.com/questions/9346188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190269/" ]
I strongly disagree with the answer by @Dzek Trek. When creating html emails i never use divs, and the only css i use is inline css. I say this with 6 months experience building emails. An example of my overall email layout would be: ``` <table cellpadding="0" cellspacing="0" width="100%"> <tr> <td>&nbsp;</td> <td width="600"> YOUR CONTENT. Start with a table </td> <td>&nbsp;</td> </table> ``` This will center the email inside the email client and will also correct any outer spacing bugs.
Well, yes for graphical layout you could use html5 and css3. Here is an example of it ``` <html> <head> <title>{blog_title}</title> </head> <body> <h3>{blog_heading}</h3> {blog_entries} <h5>{title}</h5> <p>{body}</p> {/blog_entries} </body> </html> ``` And if you want to make it more user friendly and eye pleasent, you could make css file and declare the output of every html element as you like it. Parsing values is achieved by the following example ``` $this->load->library('parser'); $data = array( 'blog_title' => 'My Blog Title', 'blog_heading' => 'My Blog Heading', 'blog_entries' => array( array('title' => 'Title 1', 'body' => 'Body 1'), array('title' => 'Title 2', 'body' => 'Body 2'), array('title' => 'Title 3', 'body' => 'Body 3'), array('title' => 'Title 4', 'body' => 'Body 4'), array('title' => 'Title 5', 'body' => 'Body 5') ) ); $this->parser->parse('blog_template', $data); ``` You could declare inline elements, but for better handling and less code, declare it externally, in some css file and call it in the html file.
36,294,955
I've just tried to use a simple `date` pipe in my **angular2** app: ``` Registered: {{user.registered | date:'shortDate'}} ``` The error I get is: ``` Invalid argument '2016-03-28T07:25:40.824Z' for pipe 'DatePipe' in [{{user && user.registered | date:'shortDate' }} in UserDialog@16:57] ``` I do have a User model (minimal here) shared between this component and some others: ``` export class User { public registered: Date; } ``` I get the user data as JSON from backend, and it's a ISO 8601: **`2016-03-28T07:26:01.202Z`**. When I use my own custom pipe, it works (example bellow). ``` import {Pipe, PipeTransform} from 'angular2/core'; /** * The default ISO Date is not parseable by ts compiler or some such. */ @Pipe({ name: 'betterDate' }) export class BetterDatePipe implements PipeTransform { transform(date: number): string { let d = new Date(date); return d.toLocaleDateString(); } } ``` The name, ***Better****DatePipe* is obviously a pun at me writing better angular2 code then the inventors ;)
2016/03/29
[ "https://Stackoverflow.com/questions/36294955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162070/" ]
I see merits in both, but the OP's code somewhat limiting: it always returns the same date format all the time, you're ultimately going to write another Pipe to change that format anyway. The second method sounds a whole lot more manageable: however, a few things, the pipes isn't something you include in the @Component, you'd have to refer that in the app.module.ts as both an import statement: `import { StringToDatePipe } from './???/string-to-date.pipe'` as well as needing to include it in the @NGModule({... further down the page under declarations. From there, you can use the Custom Pipe, and then moving onto using [Angular's Date Pipe](https://angular.io/docs/ts/latest/api/common/index/DatePipe-pipe.html "Angular's Date Pipe")
The argument is obviously a `string`, not a `Date`. You need to convert it to `Date` before passing it to the pipe. JSON doesn't support type `Date`. ``` user.registered = new Date(json.registered); ``` or similar depending on how you get the user object. See also [Converting string to date in js](https://stackoverflow.com/questions/5619202/converting-string-to-date-in-js)
130,939
If one or more of my players decide to go on a shopping spree, I've previously had problems describing the shop's inventory, without going into much detail or making it seem like the shop has only 2 items. Of course, I can describe the atmosphere and the general nature of the inventory (e.g. "herbs" or "jewelry"), and that's just fine if the players walk into the shop looking for something specific, such as an herb that stops bleeding or a silver necklace with a sapphire embedded into it. However, I'm unsure how to handle players that recently noticed "Hey, I've got 500 gold floating around that I want to spend on useless stuff". Or, in other words, players that want to look around for random shops with a random inventory to see if they find something of interest. In the real world, this works, because you can literally walk into a random shop and look around to see if there's anything interesting. In D&D, the DM has to come up with something, and it's boring and frustrating for the players if it's always the same things. **So, what can I do to make random shopping interesting for the players, without for example preparing huge inventory lists in advance?**
2018/09/01
[ "https://rpg.stackexchange.com/questions/130939", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/38495/" ]
What is this browsing you speak of? ----------------------------------- Note in the real medieval period you could not browse a shop. You were not even allowed *in* the shop most of the time: too much risk of theft. There was a window with a counter and you told the shop owner what you wanted and they brought it to you. That did not change until very recently. That is why smaller shops had half doors ([Dutch doors](https://en.wikipedia.org/wiki/Dutch_door)): you would open the top but leave the bottom shut, thus doing business but not letting people inside. Larger shops had a purpose built window with a shutter. Many people lived in their shops as well, so there is even less reason they wanted to let you in the shop. You characters will not be allowed in a shop without a good reasons, such as a cobbler's or tailor's that needs to take measurements. This depends on what level of realism you want, but it can also help player to get into the mindset of a setting where the craftspeople are the people selling their goods. [![A medieval shopfront. There are two wide open windows with counters between two closed doors. Objects litter the counters, and a stool sits outside.](https://i.stack.imgur.com/HTY6p.jpg)](https://i.stack.imgur.com/HTY6p.jpg) A shop only selling one thing is fine. -------------------------------------- Shops also tended to be very specialized, and many things were made to order. A shop may only sell paper, and nothing else. It may have many kinds of paper, but it is completely believable for paper to be the only thing they sell. A dialog would go along the following lines: "What does this shops sell?" "Candles." The shopkeeper points to a carved candle over the door. "Just candles?" "I have big candles, small candles, tall candles, even scented candles that smell like flowers. It's a candleshop. I'm a chandler, if you want boots go see a cobbler." Smaller towns might not even have many types of merchants, relying instead on traveling merchants for many goods. Hand them a list of shops ------------------------- All you really need is a list of shops and maybe a brief description of what they sell (not everyone will know what a cobbler is). This list would be roughly the same for any city that size, although you can create some unique shopkeepers to add flavor or cross out a random shop ("Eaten by wolves, very sad"). You could literally just hand this list to a player — that will let them scan it for ideas instead of you basically reading the same list. Then they can decide which shop they actually want to go to. If you want to narrate this, most shops had a carved sign to identify what they sell, and the list could represent the characters scanning all the signs as they walk along, which they can do while walking and talking or even while just doing other things around town. You can give almost every single item on the equipment list its own shop in a large city. The rich actually hired stewards to handle all the day-to-day shopping for them. For this reason (among others), the stewards' job was to know where every merchant was and buy things when needed. If you want a master list for the players, there is an old book, Gary Gygax's *World Builder*, which is nothing but list and lists of mundane objects. [Lord Eadric's master equipment](http://members.tripod.com/Lord_Eadric/netequip.html) list is good as well, even if it is for an older edition. At best there might be a seasonal or permanent marketplace with stalls; each seller would not have much variety though, but at least they would be mostly in the same place. That's where you pull out the "lots of foodstuffs, some animals skins, a few animals, but one stall catches your eye..." general narration. [Chaotic shiny](http://chaoticshiny.com/bazaargen.php) actually has a nice generator for bazaars/markets you can use to bulk out your list quickly. I myself have a random mundane useful item list I made just for random stuff players might find in defeated NPC's pockets — things like a collapsable leather bucket, a jar of grease, or a stuffed mouse. Any time the players think of something we add it to the list; it helps make the fallen feel real but could just as easily be used to flavor up a market or bazaar. The one exception to the one shop per item was pawn shops, which had such diverse merchandise they had to let people see it, but even then it was separated by a counter. You could easily create a spreadsheet or chart for pawnshops. The various magical shop inventories you find might be a good example of what a pawn shop might look like, where most of the merchandise is unique. Donjon's [shop generator](https://donjon.bin.sh/d20/magic/shop.html) is good for this one. This is balancing narration and information — there is such a thing as too much narration. Do I take several minutes to try to describe the location of every character every time anyone moves, or do I use a map grid? Do I describe the puzzle in minute detail or do I hand the players a sketch of it? If the player wants a list of everything, then give them a list. A simple physical list is far faster for browsing than taking several hours to narrate every shop in a city, and better reflects how browsing happens.
If you already know that your players like to go shopping, prepare for that in advance. Shops with limited sortiment ---------------------------- First of, don't include supermarkets. These didn't exist until quite recently. It would be better to design your shopping areas like a traditional village market place. You have between one and three market stands, each selling only a very limited amount of things. Such market stands would not carry anything extraordinary but rather items that everyone would need. If you want special items, you need a special craftsman for that. So for example, a regular market stand would not sell armor, weapons, clothing or shoes. For these items the players have to go to a blacksmith, tailor or cobbler. This means, if the players encounter a shop, you don't need to give them a huge selection of items, because the shop only has a very limited range of goods. Craftsmen --------- Items like clothing, armor, weapons, shoes or similar would not be made in advance. Stocking multiple sizes and styles of items (as is done in a clothing or shoe store nowadays) is also a relatively new invention. If you buy items from a craftsman, they are usually only made after they are ordered (and possibly even paid), since they need to be fitted to the buyer. Again, here you don't have to prepare that much, since the players have to order what they want. So the players choose what they'd like to have and you, as a GM have to determine whether the craftsman can make that, how much it would cost and how long it would take. Special merchants ----------------- As a rather rare occasion the players could meet a (traveling) merchant who would have special items. This works well for trinkets, potions and other little things. The trader either has items that players can buy right now, or maybe he knows where to get stuff the players request. Here, you also don't have to prepare that much. The merchant would not have that many items on himself. He would also probably not let the players just browse his stock, but would rather tell the players what the highlights of his items are. --- I ran into that problem on one occasion where the players came across a town with a market place, that I put there mainly as decoration, but the players stopped and wanted to go shopping. I didn't have any stock prepared for the market stands, so I said it was a cheese fair and all the merchants would sell was different kinds of cheese. They actually explored every last one of the stands and during the time they spent looking through all the cheese I actually figured out something cool that one of the last stand owners randomly had, that he would sell to the players. This scene is actually one of the running gags that they still bring up years later.
2,080,167
What is the closed form for $$\sum\_{n=0}^{\infty}{(-1)^n\left({{\pi\over 2}}\right)^{2n}\over (2n+k)!}=F(k)?$$ My try: I have found a few values of $F(k)$, but was unable to find a closed form for it. $F(0)=0$ $F(1)={2\over \pi}$ $F(2)=\left({2\over \pi}\right)^2$ $F(3)=\left({2\over \pi}\right)^2-\left({2\over \pi}\right)^3$ $F(4)={1\over 2}\left({2\over \pi}\right)^2-\left({2\over \pi}\right)^4$ $F(5)={1\over 6}\left({2\over \pi}\right)^2-\left({2\over \pi}\right)^4+\left({2\over \pi}\right)^5$
2017/01/02
[ "https://math.stackexchange.com/questions/2080167", "https://math.stackexchange.com", "https://math.stackexchange.com/users/343408/" ]
Note that $$\sum\_{n=0}^\infty \frac{(-1)^nx^{2n}}{(2n)! } = \cos(x)$$ You can reach the result by integrating $k$-times. $$\sum\_{n=0}^\infty \frac{(-1)^nx^{2n}}{(2n+k)! } = \frac{1}{x^{k}}\int^{x}\_0 \mathrm{d}t\_{k-1}\int^{t\_{k-1}}\_0 \mathrm{d}t\_{k-2} \cdots\int^{t\_1}\_0\mathrm{d}t\_0\cos(t\_0) $$ For example when $k=1$ $$\sum\_{n=0}^\infty \frac{(-1)^n(\pi/2)^{2n}}{(2n+1)! } = \frac{2}{\pi}\int^{\pi/2}\_0 \mathrm{d}t\_0 \cos(t\_0)\,= \frac{2}{\pi}$$ For $k=2$ \begin{align} \sum\_{n=0}^\infty \frac{(-1)^n(\pi/2)^{2n}}{(2n+2)! } &= \left( \frac{2}{\pi}\right)^2\int^{\pi/2}\_0 \mathrm{d}t\_{1}\int^{t\_1}\_0\mathrm{d}t\_0\cos(t\_0) \\ &= \left( \frac{2}{\pi}\right)^2\int^{\pi/2}\_0 \mathrm{d}t\_{1}\sin(t\_1)\\ & = \left( \frac{2}{\pi}\right)^2 \end{align} For $$f\_k(x) = \sum\_{n=0}^\infty \frac{(-1)^n x^{2n+k}}{(2n+k)!}$$ We can define recursively $$f\_0(x) = \cos(x)$$ $$f\_k(x) =\int^x\_0 f\_{k-1}(t)\,dt$$ By solving the recursive formula $$\sum\_{n=0}^\infty \frac{(-1)^n x^{2n+k}}{(2n+k)!} = \begin{cases} \sum\_{n=0}^{\lceil k/2 \rceil-2}\frac{x^{2n+1}(-1)^{\lceil k/2 \rceil+n}}{(2n+1)!}-(-1)^{\lceil k/2 \rceil}\sin(x) & \text{If $k$ is odd} \\ \sum\_{n=0}^{k/2-1}\frac{x^{2n}(-1)^{n+k/2}}{(2n)!}-(-1)^{k/2}\cos(x) & \text{If $k$ is even}\end{cases}$$ Finally we have the closed form > > $$F(k) = \begin{cases}\left( \frac{2}{\pi}\right)^k \sum\_{n=0}^{\lceil > k/2 \rceil-2}\frac{(\pi/2)^{2n+1}(-1)^{\lceil k/2 > \rceil+n}}{(2n+1)!}-\left( \frac{2}{\pi}\right)^k(-1)^{\lceil k/2 > \rceil} & \text{If $k$ is odd} \\ \left( > \frac{2}{\pi}\right)^k\sum\_{n=0}^{k/2-1}\frac{(\pi/2)^{2n}(-1)^{n+k/2}}{(2n)!}& > \text{If $k$ is even}\end{cases}$$ > > > To check the correctness of the formula For $k=5$ we have $$F(5)=\left(\frac{2}{\pi}\right)^5 \sum\_{n=0}^{1}\frac{(\pi/2)^{2n+1}(-1)^{3+n}}{(2n+1)!}-\left( \frac{2}{\pi}\right)^5(-1)^{3} = {1\over 6}\left({2\over \pi}\right)^2-\left({2\over \pi}\right)^4+\left({2\over \pi}\right)^5$$
The sum can also be expressed in terms of the *Regularized Incomplete Gamma* function ($Q(a,z)$). In fact, premised that for a general function of a integer $f(k)$ we have $$ \begin{gathered} \frac{{\left( {i^{\,k} + \left( { - i} \right)^{\,k} } \right)}} {2}f(k) = \left( {\frac{{e^{\,i\,k\frac{\pi } {2}} + e^{\, - \,i\,k\frac{\pi } {2}} }} {2}} \right)f(k) = \cos \left( {k\frac{\pi } {2}} \right)f(k) = \hfill \\ = \left[ {k = 2j} \right]\left( { - 1} \right)^{\,j} f(2j)\quad \left| {\;k,j\; \in \;\;\mathbb{Z}\,} \right. \hfill \\ \end{gathered} $$ and that the *Lower Incomplete Gamma* function can be expressed as: $$ \begin{gathered} \gamma (s,z) = \int\_{\,0\,}^{\,z\,} {t^{\,s - 1} \;e^{\, - \,t} dt} = \hfill \\ = z^{\,s} \;e^{\,\, - z} \;\Gamma (s)\;\sum\limits\_{0\, \leqslant \,k} {\frac{{z^{\,k} }} {{\Gamma (s + k + 1)}}} = \frac{{z^{\,s} \;e^{\,\, - z} }} {s}\sum\limits\_{0\, \leqslant \,k} {\frac{{z^{\,k} }} {{\left( {s + 1} \right)^{\,\overline {\,k\,} } \,}}} = \hfill \\ = z^{\,s} \;e^{\,\, - z} \sum\limits\_{0\, \leqslant \,k} {\frac{{z^{\,k} }} {{s^{\,\overline {\,k + 1\,} } \,}}} = z^{\,s} \sum\limits\_{0\, \leqslant \,j} {\frac{{\left( { - 1} \right)^{\,j} }} {{\,\left( {s + j} \right)}}\frac{{z^{\,j} }} {{j!}}} \hfill \\ \end{gathered} $$ we can then write $$ \begin{gathered} F(x,m) = \sum\limits\_{0\, \leqslant \,k} {\left( { - 1} \right)^{\,k} \frac{{x^{\,2k} }} {{\left( {2k + m} \right)!}}} = \hfill \\ = \frac{1} {2}\left( {\sum\limits\_{0\, \leqslant \,k} {\frac{{\left( {i\,x} \right)^{\,k} }} {{\left( {k + m} \right)!}}} + \sum\limits\_{0\, \leqslant \,k} {\frac{{\left( { - \,i\,x} \right)^{\,k} }} {{\left( {k + m} \right)!}}} } \right) = \hfill \\ = \frac{1} {{2\,\Gamma (m)}}\left( {\frac{{e^{\,\,i\,x} \,\gamma (m,i\,x)}} {{\left( {i\,x} \right)^{\,m} }} + \frac{{e^{\, - \,i\,x} \,\gamma (m, - i\,x)}} {{\left( { - i\,x} \right)^{\,m} }}} \right) = \hfill \\ = \frac{1} {{\left| x \right|^{\,\,m} }}\,\operatorname{Re} \left( {e^{\,\,i\,x} e^{\,\, - \,i\,m\,\left( {sign(x)\pi /2} \right)} \,\frac{{\gamma (m,i\,x)}} {{\Gamma (m)}}} \right) = \hfill \\ = \frac{1} {{\left| x \right|^{\,\,m} }}\,\operatorname{Re} \left( {e^{\,\,i\,x} e^{\,\, - \,i\,m\,\left( {sign(x)\pi /2} \right)} \,\left( {1 - Q(m,i\,x)} \right)} \right) \hfill \\ \end{gathered} $$ So, for $x=\pi /2$ we get $$ \begin{gathered} F(\pi /2,m) = \sum\limits\_{0\, \leqslant \,k} {\left( { - 1} \right)^{\,k} \frac{{\left( {\pi /2} \right)^{\,2k} }} {{\left( {2k + m} \right)!}}} = \hfill \\ = \left( {\frac{2} {\pi }} \right)^{\,\,m} \,\operatorname{Re} \left( {e^{\,\, - \,i\,\left( {m - 1} \right)\,\left( {\pi /2} \right)} \,\frac{{\gamma (m,i\,\pi /2)}} {{\Gamma (m)}}} \right) = \hfill \\ = \left( {\frac{2} {\pi }} \right)^{\,\,m} \,\operatorname{Re} \left( {e^{\,\, - \,i\,\left( {m - 1} \right)\,\left( {\pi /2} \right)} \,\left( {1 - Q(m,i\,\pi /2)} \right)} \right) \hfill \\ \end{gathered} $$ **example with $m=5$** $$ \begin{gathered} F(\pi /2,5) = \sum\limits\_{0\, \leqslant \,k} {\left( { - 1} \right)^{\,k} \frac{{\left( {\pi /2} \right)^{\,2k} }} {{\left( {2k + 5} \right)!}}} = \hfill \\ = \left( {\frac{2} {\pi }} \right)^{\,\,5} \,\operatorname{Re} \left( {e^{\,\, - \,i\,4\,\left( {\pi /2} \right)} \,\left( {1 - Q(5,i\,\pi /2)} \right)} \right) = \hfill \\ = \left( {\frac{2} {\pi }} \right)^{\,\,5} \,\operatorname{Re} \,\left( {1 - \frac{1} {{24}}\left( {12\,\pi - \frac{1} {2}\pi ^{\,3} + i\left( {3\pi ^{\,2} - \frac{1} {{16}}\pi ^{\,4} - 24} \right)} \right)} \right) = \hfill \\ = \left( {\frac{2} {\pi }} \right)^{\,\,5} \left( {1 - \,\frac{\pi } {2} + \frac{1} {{48}}\pi ^{\,3} } \right) = \left( {\frac{2} {\pi }} \right)^{\,\,5} - \,\left( {\frac{2} {\pi }} \right)^{\,\,4} + \frac{1} {6}\left( {\frac{2} {\pi }} \right)^{\,2} \hfill \\ \end{gathered} $$ which matches with the value given by *Zaid Alyafeai*, as well as with the fomula indicated by *Igor Rivin* $$ \begin{gathered} F(\pi /2,5) = \sum\limits\_{0\, \leqslant \,k} {\left( { - 1} \right)^{\,k} \frac{{\left( {\pi /2} \right)^{\,2k} }} {{\left( {2k + 5} \right)!}}} = \left( {\frac{2} {\pi }} \right)^{\,\,5} - \,\left( {\frac{2} {\pi }} \right)^{\,\,4} + \frac{1} {6}\left( {\frac{2} {\pi }} \right)^{\,2} = \hfill \\ = 0.007860176 \cdots = \hfill \\ = \frac{1} {{5!}}{}\_1F\_2 \left( {1\;;\;\frac{5} {2} + \frac{1} {2},\;\frac{5} {2} + 1\;;\; - \frac{1} {4}\left( {\frac{\pi } {2}} \right)^{\,2} } \right) \hfill \\ \end{gathered} $$ and concerning the latter, a computer calculation over multiple values of $m$ and $x$ shows a full match.
103,123
The problem is that the links (as well as the PDF bookmarks) of abstract, explanation, CV and appendix do not lead to the right pages. abstract leads to the `titlepage` and appendix to introduction etc. Also the sections belong to the introduction in the bookmarks :( Maybe it is due to the page numbering I did (and I need). I've tried so many things, I'm about to leave it like that :( Please correct my codes if you find the mistake. I'm a beginner and have a lot of difficulties to adjust the options, packages etc... ``` \makeatletter \renewcommand*{\@pnumwidth}{3em} \makeatother \documentclass[a4paper,12pt,ngerman]{article} \usepackage[ colorlinks, linkcolor=black, filecolor=black, citecolor=black ]{hyperref} \usepackage{amssymb} \usepackage{amsmath} \usepackage{eurosym} \usepackage{latexsym} \usepackage{graphicx} \usepackage[abbr,agsmcite,agsm,round]{harvard} \usepackage{longtable} \usepackage{portland} \usepackage{lscape} \usepackage[onehalfspacing]{setspace} \usepackage{footmisc} \usepackage{hyphenat} \usepackage{rotating} \usepackage[USenglish]{babel} \usepackage{array} \usepackage{tabularx} \usepackage[latin1]{inputenc} \usepackage[para]{threeparttable} \usepackage{caption} \usepackage[capposition=top]{floatrow} %\usepackage[subfigure] \usepackage{currvita} \usepackage{enumitem} %\usepackage[latin9]{inputenc} %\usepackage[T1]{fontenc} \setcounter{MaxMatrixCols}{12} \setlength{\skip\footins}{10mm} \setlength{\evensidemargin}{0cm} \setlength{\textwidth}{15cm} \setlength{\textheight}{23cm} \setlength{\topmargin}{-1cm} \pagenumbering{arabic} \renewcommand\harvardand{and} \renewcommand{\labelenumi}{\Alph{enumi})} \renewcommand{\labelenumii}{\arabic{enumii}.} \renewcommand{\cite}{\citeasnoun} \renewcommand{\harvardand}{and} \begin{document} \begin{titlepage} \begin{center} Title \end{center} \end{titlepage} \newpage \pagenumbering{Roman}% \renewcommand{\abstractname}{Acknowledgements} \begin{abstract} \noindent bla bla \end{abstract} \newpage \phantom{T}\vspace{5,3cm} \renewcommand{\abstractname}{Abstract} \begin{abstract} TEXT \end{abstract} \addcontentsline{toc}{section}{Abstract} \newpage \tableofcontents \newpage \listoffigures \addcontentsline{toc}{section}{List of Figures} \newpage \listoftables \addcontentsline{toc}{section}{List of Tables} \newpage \section*{Symbols} \addcontentsline{toc}{section}{Symbols}% \newpage \section*{List of abbreviations} \begin{tabular}{L{5.5cm} L{9cm}} \end{tabular}% \addcontentsline{toc}{section}{List of abbreviations}% \newpage \pagenumbering{arabic} \setcounter{page}{1}% \section{Introduction} text text text \newpage \section{System and whatever} \subsection{System} \setcounter{table}{0} \setcounter{figure}{0} \setcounter{section}{0} \newcommand{\initAnhang}{ \renewcommand{\thepage}{\Alph{section}\ \arabic{page}} \newpage } \renewcommand\appendix{\par \renewcommand\thesection{\Alph{section}} \renewcommand\thesubsection{\Alph{section}\arabic{subsection}} \renewcommand\thefigure{\Alph{section}\arabic{figure}} \renewcommand\thetable{\Alph{section}\arabic{table}}} \newcommand{\anhang}[1]{ \setcounter{page}{1} \input{#1} \newpage } \appendix\initAnhang \section{Appendix} %\addcontentsline{toc}{section}{Appendix}% \subsection{Descriptive Statistics} \newpage \nocite{*} \bibliographystyle{dcu} \bibliography{bib} \addcontentsline{toc}{section}{References} \newpage \section*{Explanation} \addcontentsline{toc}{section}{Explanation} \newpage \begin{cv}{CV} \addcontentsline{toc}{section}{CV}% \end{cv} \end{document} ```
2013/03/18
[ "https://tex.stackexchange.com/questions/103123", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/27398/" ]
Load `hyperref` as last package and then ``` ... \phantomsection \phantom{T}\vspace{5.3cm} \renewcommand{\abstractname}{Abstract} \begin{abstract} TEXT \end{abstract} \addcontentsline{toc}{section}{Abstract} \newpage ... ```
Finally, I solved the problem. In my case of only one Appendix, this is sufficient: ``` \setcounter{table}{0} \setcounter{page}{1} \newcommand{\initAnhang}{ \renewcommand{\thepage}{A\arabic{page}} \newpage } \renewcommand\appendix{\par \renewcommand\thesection{A} \renewcommand\thesubsection{A\arabic{subsection}} \renewcommand\thetable{A\arabic{table}}} \appendix\initAnhang \section{Appendix} \subsection{Descriptive Statistics} ``` Instead of resetting the counter of the sections (that was the problem!), I just typed manually "A" to start the counting of the appendix, the pages and tables from "A" on. The red borders of the links only disappear when putting `hyperref` before ``` \usepackage[abbr,agsmcite,agsm,round]{harvard} ```
14,605,075
I need to copy each row as many times as how many hours there are between `StartTime` and `EndTime`. Example data: **[SQLFIDDLEExample](http://sqlfiddle.com/#!3/587a4/1)** ``` TimeKey HourKey SensorKey IdleTimeMinute StartTime EndTime 20121017 8 45 110 2012.10.17 08:31 2012.10.17 10:21 20121017 10 45 25 2012.10.17 10:26 2012.10.17 10:51 20121017 12 45 5 2012.10.17 12:21 2012.10.17 12:26 20121017 12 45 60 2012.10.17 12:41 2012.10.17 13:41 20121017 13 45 55 2012.10.17 13:51 2012.10.17 14:46 20121017 15 45 5 2012.10.17 15:11 2012.10.17 15:16 20121017 15 45 35 2012.10.17 15:46 2012.10.17 16:21 20121017 18 45 5 2012.10.17 18:51 2012.10.17 18:56 ``` **Explanation** For example, the first row spans the hours 8, 9, and 10. In each of the three output rows, `IdleTimeMinute` needs to be the minutes duration within that hour. Expected Result: ``` TimeKey HourKey SensorKey IdleTimeMinute StartTime EndTime 20121017 8 45 29 2012.10.17 08:31 2012.10.17 10:21 20121017 9 45 60 2012.10.17 08:31 2012.10.17 10:21 20121017 10 45 21 2012.10.17 08:31 2012.10.17 10:21 20121017 10 45 25 2012.10.17 10:26 2012.10.17 10:51 20121017 12 45 5 2012.10.17 12:21 2012.10.17 12:26 20121017 12 45 19 2012.10.17 12:41 2012.10.17 13:41 20121017 13 45 41 2012.10.17 12:41 2012.10.17 13:41 20121017 13 45 9 2012.10.17 13:51 2012.10.17 14:46 20121017 14 45 46 2012.10.17 13:51 2012.10.17 14:46 20121017 15 45 5 2012.10.17 15:11 2012.10.17 15:16 20121017 15 45 14 2012.10.17 15:46 2012.10.17 16:21 20121017 16 45 21 2012.10.17 15:46 2012.10.17 16:21 20121017 18 45 5 2012.10.17 18:51 2012.10.17 18:56 ``` **Smaller Example** Smaller example from first two lines: ``` TimeKey HourKey SensorKey IdleTimeMinute StartTime EndTime 20121017 8 45 110 2012.10.17 08:31 2012.10.17 10:21 20121017 10 45 25 2012.10.17 10:26 2012.10.17 10:51 ``` For first line we have time `8:31 - 10:21` so In 8 Hour 29 Minutes, In 9 Hour 60 Minutes, In 10 Hour 21 Minute. Expected small result: ``` TimeKey HourKey SensorKey IdleTimeMinute StartTime EndTime 20121017 8 45 29 2012.10.17 08:31 2012.10.17 10:21 20121017 9 45 60 2012.10.17 08:31 2012.10.17 10:21 20121017 10 45 21 2012.10.17 08:31 2012.10.17 10:21 20121017 10 45 25 2012.10.17 10:26 2012.10.17 10:51 ```
2013/01/30
[ "https://Stackoverflow.com/questions/14605075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1076151/" ]
You should try using the [TabControl.SelectedTab Property](http://msdn.microsoft.com/en-us/library/system.windows.forms.tabcontrol.selectedtab.aspx): > > Gets or sets the currently selected tab page. > > > The topic above also has the following remark: > > The tab page must be in the TabPages collection to make it the current > tab page. > > > In your case, this should work: ``` //somewhere in your code, you have to add first the TabPage to the TabControl tabControl1.TabPages.Add(tabPage2); tabControl1.SelectedTab = tabPage2; ``` **[UPDATE]** If that doesn't work either, it's likely you haven't associated the `button1_Click` method as the `button1`'s `Click` event handler. And it's even more likely that you just created the `button1` control in another control container of your form or the form itself and then **cutted and pasted** it to the `tabPage1` control. That will remove the event handler. Just reassign the `button1_Click` method as `button1`'s `Click` event handler and make sure you use the `SelectedTab` property (or `SelectedIndex` as shown in some other answers and comments of this question). Here's a reference to a similar problem: [cut and paste controls lost event handlers](http://social.msdn.microsoft.com/Forums/pl/csharpide/thread/8a5d8c22-1eae-49a9-b972-79b2e851f46c).
try this code: ``` tabControl1.SelectedPage = tabpage1; ```
43,303,003
I'm working on a program that works with a linked list of generic objects, inside the class that defines a single list there is a method that returns the value of that link: ``` public class Link<E> { private E _value; public E getValue() { return _value; } ``` Then I want to use this return value of type < E > in the linked link class to return the value of a link at a certain position in the list ``` public class LinkedList <E> implements List <E> { public E get(int index){ Link current = goTo(index); //go to is a helper method that returns a pointer to a Link at position index E value = current.getValue(); //this is the source of the problem return value; } } ``` The problem has something to with the generic type < E >, I don't fully understand how it works. **Update** I get the message: `Type mismatch: cannot convert from Object to E` on the line indicated in the source.
2017/04/09
[ "https://Stackoverflow.com/questions/43303003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7159699/" ]
It seems you should do like this: ``` Link<E> current = goTo(index); ``` as `Link current` (without `<E>`) pointed to list of Object class.
I think your problem is this line: Link current = goTo(index); You have to correct it to specify the type of Object you want to use: `Link <TypeOfObject> current = goTo(index);` replace "TypeOfObject with the return type value of goTo method. I am assuming it is an Integer, so if that is the case just replace `Link <TypeOfObject> current = goTo(index);` with `Link <Integer> current = goTo(index);`
51,780,304
After installing tensorflow for python 3.7, I tried to import it but it gave me a syntax error. the command used for installation : sudo -H pip3 install --upgrade <https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.10.0-py3-none-any.whl> I don't think tensorflow has supported python3.7 yet. Is there a way to fix it? [enter image description here](https://i.stack.imgur.com/6f5Pe.png)
2018/08/10
[ "https://Stackoverflow.com/questions/51780304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7584145/" ]
just use like this. ``` for i in range(256): for j in range(256): ip = "192.168.%d.%d" % (i, j) print ip ``` output: ``` 192.168.0.0 192.168.0.1 192.168.0.2 192.168.0.3 192.168.0.4 . . 192.168.255.254 192.168.255.255 ```
If you want your range of IP addresses to be dynamic, you can do the following: ``` ip1='192.168.0.0' ip2='192.168.255.255' first, second, thirdStart, lastStart = list(map(int,ip1.split("."))) thirdEnd, lastEnd = list(map(int,ip2.split(".")))[2:] for i in range(thirdStart,thirdEnd+1,1): for j in range(lastStart,lastEnd+1,1): print(".".join(list(map(str,[first,second,i,j])))) ``` Output: ``` 192.168.0.0 192.168.0.1 192.168.0.2 192.168.0.3 192.168.0.4 192.168.0.5 192.168.0.6 . . . 192.168.255.252 192.168.255.253 192.168.255.254 192.168.255.255 ```
204,465
I'm planning to develop an app for the iPhone and that app would have to access a couple of SOAP services. While doing some basic checking in the iPhone SDK I was not able to find any support for accessing SOAP services, a bit of Googling lead to the conclusion that there is no support for SOAP in the iPhone SDK. So if I do want to build that app I'll need to come up with a approach to access SOAP services from the iPhone. What would be the best approach? Any best practices? Did someone already write a library using the functionality that is present in the iPhone SDK to access SOAP services? (Since the service I need to access is exposed by another party and they only expose it as SOAP, it's unfortunately not an option to switch to another type of interface (e.g. REST based API). Gero
2008/10/15
[ "https://Stackoverflow.com/questions/204465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25277/" ]
I've historically rolled my own access at a low level (XML generation and parsing) to deal with the occasional need to do SOAP style requests from Objective-C. That said, there's a library available called SOAPClient ([soapclient](http://ditchnet.org/soapclient/)) that is open source (BSD licensed) and available on Google Code ([mac-soapclient](http://code.google.com/p/mac-soapclient/)) that might be of interest. I won't attest to it's abilities or effectiveness, as I've never used it or had to work with it's API's, but it is available and might provide a quick solution for you depending on your needs. Apple had, at one time, a very broken utility called WS-MakeStubs. I don't think it's available on the iPhone, but you might also be interested in an open-source library intended to replace that - code generate out Objective-C for interacting with a SOAP client. Again, I haven't used it - but I've marked it down in my notes: [wsdl2objc](http://code.google.com/p/wsdl2objc/)
Have a look at [gsoap](http://sourceforge.net/projects/gsoap2) that includes two iOS examples in the download package under ios\_plugin. The tool converts WSDL to code for SOAP and XML REST.
14,095,552
I am looking at and trying to understand the [DnDns](http://dndns.codeplex.com/) project, it's a very impressive project altogether, but I have come across a method, and I don't understand the reason behind it. ``` public static string GetServByPort(short port, ProtocolType proto) { StringBuilder ans = new StringBuilder(); switch (proto) { case ProtocolType.Tcp: { TcpServices tcps; tcps = (TcpServices)port; ans.Append(tcps); ans.Append("("); ans.Append(port); ans.Append(")"); break; } case ProtocolType.Udp: { UdpServices udps; udps = (UdpServices)port; ans.Append(udps); ans.Append("("); ans.Append(port); ans.Append(")"); break; } default: { ans.Append("("); ans.Append(port); ans.Append(")"); break; } } return ans.ToString(); } ``` TcpServices and UdpServices are enums. Here is TcpServices: ``` public enum TcpServices : short { /// <summary> /// Domain Name Server Port /// </summary> Domain = 53 } ``` Here is UdpServices: ``` public enum UdpServices : short { /// <summary> /// Domain Name Server Protocol Port /// </summary> Domain = 53 } ``` Let's say the port number is 1. The output if the protocol type is TCP or UDP is going to be: > > 1(1) > > > If the protocol type is anything else, the output is this: > > (1) > > > Therefore, I want to rewrite this method like so for my project (still giving full credit to the original developers etc): ``` private static string GetServerByPort(short port, ProtocolType protocolType) { if (protocolType == ProtocolType.Tcp || protocolType == ProtocolType.Udp) { return string.Format("{0}({0})", port); } return string.Format("({0})", port); } ``` I wrote the below short console application to test: ``` using System; using System.Net.Sockets; namespace ConsoleApplication4 { class Program { static void Main(string[] args) { Console.WriteLine(GetServByPort(1, ProtocolType.Tcp)); Console.WriteLine(GetServByPort(2, ProtocolType.Udp)); Console.WriteLine(GetServByPort(3, ProtocolType.SpxII)); Console.ReadLine(); } public static string GetServByPort(short port, ProtocolType proto) { switch (proto) { case ProtocolType.Tcp: return string.Format("{0} ({1})", (TcpServices)port, port); case ProtocolType.Udp: return string.Format("{0} ({1})", (UdpServices)port, port); default: return string.Format("({0})", port); } } } public enum UdpServices : short { Domain = 53 } public enum TcpServices : short { Domain = 53 } } ``` And this was my output: ![Screenshot](https://i.stack.imgur.com/SmyqV.jpg) However I can't help but think that the developers went to all of that complexity for a reason I am not seeing. My question is am I right to refactor this method in the way I am planning to or is there a good reason for the way the original developers have done this that I am not seeing, and that will cause me problems down the line if I do things the simpler way?
2012/12/30
[ "https://Stackoverflow.com/questions/14095552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/969613/" ]
Calling `ToString()` on an enum will use the enum value *name* if there is one. (It will give the numeric version when there's no corresponding named value.) So for example, in your `TcpServices` case, if the value is 53, the result would be `Domain (53)` in the original code - but `53 (53)` in your suggested replacement code. There's no point in using a `StringBuilder` here though. I'd rewrite the original method as: ``` public static string GetServByPort(short port, ProtocolType proto) { switch (proto) { case ProtocolType.Tcp: return string.Format("{0} ({1})", (TcpServices) port, port); case ProtocolType.Udp: return string.Format("{0} ({1})", (UdpServices) port, port); default: return string.Format("({0})", port); } } ```
For well-known services, your output will look like this: ``` Domain (53) HTTP (80) HTTPS (445) FTP (21) ``` etc. While the unknown ones will be like you've shown: ``` 1 (1) 2 (2) ``` etc.
168,956
I am really struggling with this one - hopefully someone here can help... I am installing a brand new, fresh version of Wordpress v4.0 (A task I've performed easily 100+ times before without incident) I have setup a brand new sub-domain and database for it then run the install script... But, everytime I try, I get caught in an infinite loop... I tried deleting the sub-domain and database and recreating a new, completely different sub-domain and database name but the same thing occurs... I also delete the wp-config.php and start over again but always, when I get to point 4, it gets caught in an infinite loop... The install process: 1. got oo URL 2. Select Country 3. Click "Let's Go" 4. Enter the db\_name, db\_user, password, host and table prefix and click submit 5. Click "run the install" But every time, I get the same result: > > This web page has a redirect loop > > > The web page at > <http://www.domainname.com/wp-admin/install.php> has > resulted in too many redirects. Clearing your cookies for this site or > allowing third-party cookies may fix the problem. If not, it is > possibly a server configuration issue and not a problem with your > computer. Learn more about this problem. Error code: > ERR\_TOO\_MANY\_REDIRECTS > > > I tried clearing the cookies but I know that's unrelated because I also went to rexswain.com and viewed the http header and it also gets caught in the same redirect loop... I don't even know where to start looking! There is no .htaccess file - 100% confirmed! And when I check the database - no tables have even been created! I am perplexed - any advice on how to do some debugging would be awesome!
2014/11/20
[ "https://wordpress.stackexchange.com/questions/168956", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10368/" ]
`wp_rel_nofollow()` add nofollow attribute to all links so we can not use it or may be I am not sure how. You can use this function to add `rel="nofollow"` to all external links. This function will check all links in content against your blog/website URL (as internal domain) and add nofollow attribute if both does not match. ``` function add_nofollow_external_links( $content ) { return preg_replace_callback( '/<a>]+/', 'auto_nofollow_callback', $content ); } function auto_nofollow_callback( $matches ) { $link = $matches[0]; $site_link = get_bloginfo('url'); if (strpos($link, 'rel') === false) { $link = preg_replace("%(href=S(?!$site_link))%i", 'rel="nofollow" $1', $link); } elseif (preg_match("%href=S(?!$site_link)%i", $link)) { $link = preg_replace('/rel=S(?!nofollow)S*/i', 'rel="nofollow"', $link); } return $link; } add_filter( 'the_content', 'add_nofollow_external_links' ); ``` not tested.
Based on @Robert hue's answer and the wordpress functions [wp\_rel\_nofollow()](http://wpseek.com/function/wp_rel_nofollow/) and [wp\_rel\_nofollow\_callback](http://wpseek.com/function/wp_rel_nofollow_callback/) I came up with this very similar solution that works for me because for some reason Robert's wasnt adding the nofollow attribute to the link. ``` function add_rel_nofollow( $text ) { // This is a pre save filter, so text is already escaped. $text = stripslashes($text); $text = preg_replace_callback('|<a (.+?)>|i', 'add_rel_nofollow_callback', $text); //$text = wp_slash($text); //I had to remove this because it was adding undesired backslashes to the output return $text; } function add_rel_nofollow_callback( $matches ) { $text = $matches[1]; $site_link = get_bloginfo('url'); if (strpos($text, 'rel') === false) { $text = preg_replace("%(href=S(?!$site_link))%i", 'rel="nofollow" $1', $text); } elseif (preg_match("%href=S(?!$site_link)%i", $link)) { $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text); } return "<a $text rel=\"nofollow\">"; } add_filter( 'the_content', 'add_rel_nofollow' ); ``` This adds a `rel="nofollow"` attribute to all previously published and future posts. Regarding performance, I asked @Roberthue the same question and this is what he said: > > I don't know why it should. It's mostly the same as using > wp\_rel\_nofollow() except it has a additional check for external > domain. That's it but if you add tons of domains to check and exclude > then it probably will. – Robert hue > > >
3,496
Let me preface by saying that this may not be the right SE. I considered asking on the Physics SE, but I thought I might try here first. If it is wrong, I am not against it being migrated. From basic principles of Physics, power is computed as Work/time. So consider a rider and bike system climbing a hill. The work done is the difference in potential from bottom to top, and obviously the time will be climb-time. Now, my question is: > > Given the same rider, same bike weight, and same climb-time, does your gearing affect power? Also assume that the climb is efficient, no slipping tires, normal pedaling, etc. > > > From a physical perspective, I expect the answer is no. Same difference in potentials, same time, same power. However, from the rider perspective, I know that it sure feels like a lot more power is being used to climb with a harder ratio. I expect that the answer is that the disparity comes from idealizing the system. If we consider the bike a closed system, we expect that all the energy put into the bike carries it up the hill, but this is not the case. Moreover I think the inefficiency of the human body will be relevant. However, I still cannot resolve the question.
2011/04/21
[ "https://bicycles.stackexchange.com/questions/3496", "https://bicycles.stackexchange.com", "https://bicycles.stackexchange.com/users/779/" ]
I suspect you mean efficiency rather than power. In my opinion the main trade-off is between increased biomechanical losses at higher rpm (basically muscle friction) and decreased blood flow with higher forces at lower rpm. The balance depends both on the rider and the duration. In the [IHPVA Journal of Human Power, Issue 45](http://www.ihpva.org/HParchive/PDF/45-v13n2-1998.pdf)(pdf, [index here](http://www.ihpva.org/hparchive.htm)) is a paper called Maximum Human Power where they talk about Tyler Hamilton winning the Mt Washinton climb in 51 minutes: > > "he rode much of the climb, however, in the 23-tooth cog, and made several surges in the 21." If he had 700- mm wheels, as seems likely, his average cadence would have been 63 RPM. > > > The whole article is worth reading, and it might pay to browse the index for similar papers. The flip side is that top sprinters often go well over 150rpm in the final sprint. At that point they're trading biomechanical efficiency for peak power. I used to peak at over 900W for 10 seconds (>8W/kg) at around 130rpm, but my hour performance of around 350W used a cadence of about 80-90rpm. The real answer is specific to you. It will depend on your body shape, muscle type, fitness and more transient factors. It's also a question best answered by experiment, and should be part of your tr4aining schedule if you're competing. If not, I suggest finding a climb you ride regularly and keep a [training diary](http://www.google.com/search?q=cycling%20training%20diary). There has also been much discussion over the hydration for long climbs. Is it better to hydrate and start heavier, or run slightly dehydrated so you weigh less? IIRC the conclusion was that hydration was better, but I can't find the reference.
No, gear and gain ratios do not affect power. While you are correct in assuming that it would feel different to the rider, if the other three variables are equal, then the power rate will be the same. In this case, in an "easier" gear ratio, the cadence would require a significant increase to maintain the same climb time (speed) and if the rider is identical, then the work rate is identical. The increase in speed of pedaling makes up the difference in wattage expenditure compared to the "harder" gear at a lower cadence.
36,406
I have two variables $X$ and $Y$ given as tuples of $(x, y)$, and I want to see if there is a relationship between the two variables. I can do so by finding the correlation coefficient. However, I found that by selecting an arbitrary subset of the data (e.g. $(x, y) | x > k$ ), I can get a higher correlation coefficient and a stronger result. Is doing so mathematically sound? I have no a priori reason to believe that certain data points are "more important" than others, to put it simply.
2018/08/03
[ "https://datascience.stackexchange.com/questions/36406", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/57120/" ]
You do not want to remove all correlated variables. It is only when the correlation is so strong that they do not convey extra information. This is both a function of the strength of correlation, how much data you have and whether any small difference between correlated variables tell you something about the outcome, after all. The first two you can tell before you do any model, the final one not. So, it may be very reasonable to remove variables based on the combination of the first two considerations (i.e. even if the extra variables may in principle contain some useful information, you would not be able to tell given the strength of correlation and how much data you have) before you do any modelling/feature engineering. The final point can really only be assessed after doing some modelling.
It doesn't matter. But for efficiency before feature engineering.
65,187,539
I managed to convert the Koncorde indicator from version 2 to version 3 and then to 4, but I cannot see the graph of 2 variables ("azul" and "verde") I have spent several hours and I decided to ask you because maybe for you this is easy to solve This is the error I get: line 14: Shadowing built-in variable 'nvi' line 30: Shadowing built-in variable 'pvi' line 35: Shadowing built-in variable 'nvi' line 6: Shadowing built-in variable 'pvi' This is the code: ``` //@version=4 study(title="Koncorde V4") calc_pvi() => sval = volume pvi = 0.0 pvi := 1.1 ? 1.1 : volume > volume[1] ? nz(pvi[1]) + (close - close[1]) / close[1] * (na(pvi[1]) ? pvi[1] : sval) : nz(pvi[1]) pvi calc_nvi() => sval = volume nvi = 0.01 nvi := 1 ? 1 : volume < volume[1] ? nz(nvi[1]) + (close - close[1]) / close[1] * (na(nvi[1]) ? nvi[1] : sval) : nz(nvi[1]) nvi calc_mfi(length) => src = hlc3 upper = sum(volume * (change(src) <= 0 ? 0 : src), length) lower = sum(volume * (change(src) >= 0 ? 0 : src), length) rsi(upper, lower) tprice = ohlc4 lengthEMA = input(255, minval=1) m = input(15) pvi = calc_pvi() pvim = ema(pvi, m) pvimax = highest(pvim, 90) pvimin = lowest(pvim, 90) oscp = (pvi - pvim) * 100 / (pvimax - pvimin) nvi = calc_nvi() nvim = ema(nvi, m) nvimax = highest(nvim, 90) nvimin = lowest(nvim, 90) azul = (nvi - nvim) * 100 / (nvimax - nvimin) xmf = calc_mfi(14) mult = input(2.0) basis = sma(tprice, 25) dev = mult * stdev(tprice, 25) upper = basis + dev lower = basis - dev OB1 = (upper + lower) / 2.0 OB2 = upper - lower BollOsc = (tprice - OB1) / OB2 * 100 xrsi = rsi(tprice, 14) calc_stoch(src, length, smoothFastD) => ll = lowest(low, length) hh = highest(high, length) k = 100 * (src - ll) / (hh - ll) sma(k, smoothFastD) stoc = calc_stoch(tprice, 21, 3) marron = (xrsi + xmf + BollOsc + stoc / 3) / 2 verde = marron + oscp media = ema(marron, m) bandacero = 0 vl = plot(verde, color=#66FF66, style=plot.style_area, title="verde") // COLOURED(102,255,102) as “verde” , GREEN ml = plot(marron, color=#FFCC99, style=plot.style_area, title="marron", transp=0) // COLOURED(255,204,153) as"marron" , BEIGE al = plot(azul, color=#00FFFF, style=plot.style_area, title="azul") // COLOURED(0,255,255) as “azul” , plot(marron, color=#330000, style=plot.style_line, linewidth=2, title="lmarron") // COLOURED(51,0,0) as “lmarron” , plot(verde, color=#006600, style=plot.style_line, linewidth=2, title="lineav") // COLOURED(0,102,0) as “lineav” , plot(azul, color=#000066, style=plot.style_line, title="lazul") // COLOURED(0,0,102) as “lazul” , plot(media, color=color.red, title="media", style=plot.style_line, linewidth=2) // COLOURED(255,0,0) as “media” , plot(bandacero, color=color.black, title="cero") // COLOURED(0,0,0) as "cero" ``` I would appreciate for any help. Regards, Luciano
2020/12/07
[ "https://Stackoverflow.com/questions/65187539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14781660/" ]
As @mat already mentioned in the comments, you need a `protocol` to mock `UserDefaults` dependency. Something like this will do: ``` protocol UserDefaultsStorage { func value(forKey key: String) -> Any? func setValue(_ value: Any?, forKey key: String) } extension UserDefaults: UserDefaultsStorage {} ``` Then you can change your `DefaultsStorage` propertyWrapper to use a `UserDefaultsStorage` reference instead of `UserDefaults`: ``` @propertyWrapper struct DefaultsStorage<Value> { private let key: String private let storage: UserDefaultsStorage var wrappedValue: Value? { get { return storage.value(forKey: key) as? Value } nonmutating set { storage.setValue(newValue, forKey: key) } } init(key: String, storage: UserDefaultsStorage = UserDefaults.standard) { self.key = key self.storage = storage } } ``` After that a mock `UserDefaultsStorage` might look like this: ``` class UserDefaultsStorageMock: UserDefaultsStorage { var values: [String: Any] init(values: [String: Any] = [:]) { self.values = values } func value(forKey key: String) -> Any? { return values[key] } func setValue(_ value: Any?, forKey key: String) { values[key] = value } } ``` And to test `DefaultsStorage`, pass an instance of `UserDefaultsStorageMock` as its storage parameter: ``` import XCTest class DefaultsStorageTests: XCTestCase { class TestUserDefaultsStorage { @DefaultsStorage( key: "userName", storage: UserDefaultsStorageMock(values: ["userName": "TestUsername"]) ) var userName: String? } func test_userName() { let testUserDefaultsStorage = TestUserDefaultsStorage() XCTAssertEqual(testUserDefaultsStorage.userName, "TestUsername") } } ```
This might not be the best solution, however, I haven't figured out a way to inject `UserDefaults` that use property wrappers into a `ViewModel`. If there is such an option, then [gcharita](https://stackoverflow.com/users/6791677/gcharita)'s proposal to use another protocol would be a good one to implement. I used the same `UserDefaults` in the test class as in the `ViewModel`. I save the original values before each test and restore them after each test. ``` class ViewModelTests: XCTestCase { private lazy var userDefaults = newUserDefaults() private var preTestsInitialValues: PreTestsInitialValues! override func setUpWithError() throws { savePreTestUserDefaults() } override func tearDownWithError() throws { restoreUserDefaults() } private func newUserDefaults() -> UserDefaults.Type { return UserDefaults.self } private func savePreTestUserDefaults() { preTestsInitialValues = PreTestsInitialValues(userName: userDefaults.userName) } private func restoreUserDefaults() { userDefaults.userName = preTestsInitialValues.userName } func testUsername() throws { //"inject" User Defaults with the desired values let username = "No one" userDefaults.userName = username let viewModel = ViewModel() let usernameFromViewModel = viewModel.getUserName() XCTAssertEqual(username, usernameFromViewModel) } } struct PreTestsInitialValues { let userName: String? } ```
18,419,558
I have a search icon that when hovered over reveals an input text search box. I'm using jQuery to add a class to the input to reveal the text box when the search icon is hovered over. That is working fine. The next function is that if the user decides not to click in the search box and elsewhere on the page, the search box goes away. That's working fine too. The only remaining issue is that if the user clicks in the search box, it also goes away which I don't want. My HTML: ``` <input type="text" class="form-text text-hidden" title="Enter the terms you wish to search for." value="" size="15" id="edit-search-block-form-1" name="search_block_form" maxlength="128"> <input type="image" src="http://d3j5vwomefv46c.cloudfront.net/photos/large/802431483.png?1377197793" class="form-submit search-hover" alt="Search" id="edit-submit"> ``` My jQuery: ``` $(".search-hover").hover(function () { $('.text-hidden').addClass('hover'); }); // Now remove the class in case of a false start or the user decides to do something else. $("body:not(.text-hidden)").click(function(){ //alert('The body click is working!!!'); $('.form-text.text-hidden').removeClass('hover'); }); ``` Note that I'm attempting to use the `:not` selector to indicate to only remove the `hover` class if clicked anywhere but the search box but it's not working. [I've got a fiddle here](http://jsfiddle.net/highrockmedia/xCsCM/)
2013/08/24
[ "https://Stackoverflow.com/questions/18419558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/819276/" ]
You get 3,3,3 because you have defined the variable indexNumber as static. So when instantiating three student objects the indexNumber gets value 3. To increment define the indexNumber as instance variable and pass the value for it as parameter.
Static members are shared with all objects. You not indexed, you counted with your test.
71,955,141
this is my first question here. So please be merciful with me :-). I am grateful for any suggestions for improvement. Here is my question: I have a grouped and sorted tibble and I want to go through row by row and make comparisons with both the previous row and the next row. For this I have to treat the first and the last row differently. Each row has an interval defined by "start" and "end" and I want to find out if these intervals overlap. The "if" function does not do what what I want it to do. I have tried a lot of things but I can't get a result. Maybe there is a much simpler solution. Thanks in advance for helping! ``` library(tidyverse) library(lubridate) ID <- c(1, 1, 1, 1, 2, 2, 2, 2) start <- ymd_hms(c("2022-04-15 10:10:00", "2022-04-15 10:15:00", "2022-04-15 10:35:00", "2022-04-15 10:50:00", "2022-04-15 11:20:00", "2022-04-15 11:35:00", "2022-04-15 11:45:00", "2022-04-15 11:50:00")) end <- ymd_hms(c("2022-04-15 10:20:00", "2022-04-15 10:30:00", "2022-04-15 10:40:00", "2022-04-15 10:55:00", "2022-04-15 11:30:00", "2022-04-15 11:40:00", "2022-04-15 11:55:00", "2022-04-15 11:55:00")) data <- tibble(ID, start, end) data %>% group_by(ID) %>% arrange(start, .by_group = TRUE) %>% mutate(overlap = { if (row_number()==1) {lead(start) < end } else if (row_number()==n()) {start < lag(end) } else {(lead(start) < end) | (start < lag(end))} }) # A tibble: 8 x 4 # Groups: ID [2] ID start end overlap <dbl> <dttm> <dttm> <lgl> 1 1 2022-04-15 10:10:00 2022-04-15 10:20:00 TRUE 2 1 2022-04-15 10:15:00 2022-04-15 10:30:00 FALSE 3 1 2022-04-15 10:35:00 2022-04-15 10:40:00 FALSE 4 1 2022-04-15 10:50:00 2022-04-15 10:55:00 NA 5 2 2022-04-15 11:20:00 2022-04-15 11:30:00 FALSE 6 2 2022-04-15 11:35:00 2022-04-15 11:40:00 FALSE 7 2 2022-04-15 11:45:00 2022-04-15 11:55:00 TRUE 8 2 2022-04-15 11:50:00 2022-04-15 11:55:00 NA ``` My expected output would be: ``` # A tibble: 8 x 4 # Groups: ID [2] ID start end overlap <dbl> <dttm> <dttm> <lgl> 1 1 2022-04-15 10:10:00 2022-04-15 10:20:00 TRUE 2 1 2022-04-15 10:15:00 2022-04-15 10:30:00 TRUE 3 1 2022-04-15 10:35:00 2022-04-15 10:40:00 FALSE 4 1 2022-04-15 10:50:00 2022-04-15 10:55:00 FALSE 5 2 2022-04-15 11:20:00 2022-04-15 11:30:00 FALSE 6 2 2022-04-15 11:35:00 2022-04-15 11:40:00 FALSE 7 2 2022-04-15 11:45:00 2022-04-15 11:55:00 TRUE 8 2 2022-04-15 11:50:00 2022-04-15 11:55:00 TRUE ```
2022/04/21
[ "https://Stackoverflow.com/questions/71955141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18893708/" ]
Your existing query will raise the same error. You can't concatenate first, and then apply `TO_CHAR`; `TO_CHAR` expects a number, not a string. First convert the number to string, and then concatenate `'dst.'` to the result of `TO_CHAR`. After you fix this first mistake (even for your existing query), multiplying by 0.01 in the argument to `TO_CHAR` should not cause any kind of new problem.
You can use ```sql SELECT 'dst.'||.01 * TO_NUMBER( per_growth, 'FM9G999G999G999G999G990D99999999999', 'NLS_NUMERIC_CHARACTERS = '',.'' ') FROM dst__d_data; ``` prefix some string stuff after finishing the numerical conversion with **`'',.''`** pattern(as the data seems to have comma as decimal seperator) and multiplication operation `[Demo](https://dbfiddle.uk/?rdbms=oracle_21&fiddle=af078f8382f07629124521bc181dc187)`
68,249,781
Looking for some help with my sanity please. I have created an Azure Search Services instance (Cognitive Search) but when I attempt to create an Datasource for an Azure SQL Indexer I receive errors in the portal. [![Error](https://i.stack.imgur.com/t66i8.png)](https://i.stack.imgur.com/t66i8.png) I have also tried to create the data source using the Azure SDK and whilst it "succeeds" it appears to be unusable for creating an Indexer (receive a 500 error). I did this last week in another subscription and had no issues. I'm guessing this could be an intermittent Azure issue or I may have missed something simple. Any help to resolve this is greatly appreciated! FYI. I've raised an Azure Feedback item here but I'm hoping someone has a workaround in the meantime: <https://feedback.azure.com/forums/263029-azure-search/suggestions/43745931-bug-the-portal-currently-shows-an-error-when-tryi>
2021/07/05
[ "https://Stackoverflow.com/questions/68249781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/219177/" ]
What you're doing is unsupported, so it's not really surprising if it doesn't work on all systems. The correct documented approach is to use KVO on the audio session `outputVolume` property: <https://developer.apple.com/documentation/avfaudio/avaudiosession/1616533-outputvolume>
I was also struggling to solve the task of handling volume buttons press event, aiming to * get the event * recognise if it is volume up or down * be able to react even at system max/min level * handle the event (in my case, executing the js callback in WKWebView) * have it working on both iOS 15 / iOS below 15. Final solution which works for me (as per sep-2022) is below: In my view controller ``` var lastVolumeNotificationSequenceNumber: Int? //see below explanations - avoiding duplicate events var currentVolume: Float? //needed to remember your current volume, to properly react on up/down events ``` In my loadView func: ``` if #available(iOS 15, *) { NotificationCenter.default.addObserver(self, selector: #selector(volumeChanged(_:)), name: NSNotification.Name(rawValue: "SystemVolumeDidChange"), object: nil) } else { NotificationCenter.default.addObserver(self, selector: #selector(volumeChanged(_:)), name: NSNotification.Name(rawValue: "AVSystemController_SystemVolumeDidChangeNotification"), object: nil) } ``` #available tag allows you to choose the notification set up according to iOS version. ...And my view controller has this: ``` @objc func volumeChanged(_ notification: NSNotification) { DispatchQueue.main.async { [self] in if #available(iOS 15, *) { volumeControlIOS15(notification) } else { volumeControlIOS14(notification) } } } ``` This one is to handle the event itself and to distinguish the code for 14/15 versions (slightly different) Please note: DispatchQueue.main.async used here, as soon as completion handler is (as stated above) NOT on the main thread, and in my case it HAS to be. I had some crashes and thread warnings before I figured it out. ``` func manageVolume(volume: Float, minVolume: Float) { switch volume { case minVolume: do { currentVolume = minVolume + 0.0625 } case 1: do { currentVolume = 0.9375 } default: break } if let cV = currentVolume { if volume > cV { //do your stuff here } if volume < cV { //do your stuff here } currentVolume = volume } else { currentVolume = volume } } ``` This function is to handle the volume button press event, and also helps you to a) understand if the event is "up" or "down", and b) manage the case of reaching max/min value, should you need to proceed with event handling even when you're touching the max/min (this is done by simply reducing/increasing current volume variable - remember, you can't change the system volume itself, however, the variable is all yours ;) ) ``` func volumeControlIOS15(_ notification: NSNotification) { let minVolume: Float = 0.0625 if let volume = notification.userInfo!["Volume"] as? Float { //avoiding duplicate events if same ID notification was generated if let seqN = self.lastVolumeNotificationSequenceNumber { if seqN == notification.userInfo!["SequenceNumber"] as! Int { NSLog("Duplicate nofification received") } else { self.lastVolumeNotificationSequenceNumber = (notification.userInfo!["SequenceNumber"] as! Int) manageVolume(volume: volume, minVolume: minVolume) } } else { self.lastVolumeNotificationSequenceNumber = (notification.userInfo!["SequenceNumber"] as! Int) manageVolume(volume: volume, minVolume: minVolume) } } } ``` It is the main iOS 15 implementation func. As you can see, minVolume is not a number, it's a let constant - and it's different from iOS 14 (I found on iOS 14 it is 0, while iOS 15 is not going below 0.0625 on my physical device - please don't ask me why, it's a mystery ;)) It is also handling the last notification unique ID and omitting duplicated notification events, which are (somehow) quite common with iOS15. ``` func volumeControlIOS14(_ notification: NSNotification) { //old implementation for iOS < 15 let minVolume: Float = 0 if let volume = notification.userInfo!["AVSystemController_AudioVolumeNotificationParameter"] as? Float { manageVolume(volume: volume, minVolume: minVolume) } } ``` Same here for iOS 14, with 3 main differences: a) notification UserInfo key, as stated above, is different b) no duplicate notifications control - as soon as there are no duplicates I ever observed on iOS 14, and c) minVolume is 0, which is correct for iOS 14 Hope it is helpful :)
12,167,592
If I have a URl like `"/api/User/Details/2c021192-25cb-43e1-9bba-3bd5604a0a3d"` what would be the best way to get the ID `"2c02ds92-25cb-43e1-9bba-3bd5604a0a3d"` out of the URL client side? I need to be able to build a `$.getJSON` request with the ID and I'm looking for the cleanest way to do it using JavaScript, jQuery, etc. Thanks ``` $.getJSON('/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d')... ```
2012/08/28
[ "https://Stackoverflow.com/questions/12167592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/139599/" ]
Use [regular expressions](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions) and extract the appropriate part (which seems to be UUID) from the URL. The alternative is to just split the string by `/` and get last element. **EDIT**: The example on how to retrieve UUID from the URI: ``` var url = '/api/User/2c021192-25cb-43e1-9bba-3bd5604a0a3d'; var pattern = /[\da-f]{8}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{4}\-[\da-f]{12}/; var match = url.match(pattern)[0]; ``` `url.match(pattern)` returns array of matches, so assuming there is at least one, and only one match, you should pick it (using `[0]`, as in the example). Proof: <http://jsfiddle.net/p6zud/2/> **EDIT 2**: Shortened the pattern used for matching (see revision history for comparison).
using `split`, convert the url to an array of parameters. Then last array item in your case would be your ID. there are very sophisticated URL parsers out there for javascript, perhaps you should look around on google for one that suits your needs.
45,662,253
I'm running a Keras model, with a submission deadline of 36 hours, if I train my model on the cpu it will take approx 50 hours, is there a way to run Keras on gpu? I'm using Tensorflow backend and running it on my Jupyter notebook, without anaconda installed.
2017/08/13
[ "https://Stackoverflow.com/questions/45662253", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8176285/" ]
Of course. if you are running on Tensorflow or CNTk backends, your code will run on your GPU devices defaultly.But if Theano backends, you can use following > > Theano flags: > > > > > > > "THEANO\_FLAGS=device=gpu,floatX=float32 python my\_keras\_script.py" > > > > > > > > >
See if your script is running GPU in Task manager. If not, suspect your CUDA version is right one for the tensorflow version you are using, as the other answers suggested already. Additionally, a proper CUDA DNN library for the CUDA version is required to run GPU with tensorflow. Download/extract it from [here](https://developer.nvidia.com/rdp/cudnn-archive) and put the DLL (e.g., cudnn64\_7.dll) into CUDA bin folder (e.g., C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin).
656,651
I've never used it in the professional software even though in our shop, and others I have worked for, we design large scale systems. The only time I messed with virtual inheritance was during my interview in a company. Nonetheless, I played with it during afterhours. Do you guys use it? Do you understand how it works in depth (how most popular compiler vendors implement it)? I would really like to know how it is used in professional software, if at all. Tricks and tips would be appreciated, too. To me, virtual inheritance was just a solution to an infamous diamond problem. Hence, it never found its way in our software, as we don't have in our architecture MI resulting in the diamond. Thanks.
2009/03/18
[ "https://Stackoverflow.com/questions/656651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
> > I've never used it in the professional software even though in our shop, > > > Do you use `iostream`? We do. Look up the design of iostreams and you'll know you've been using virtual inheritance.
Virtual inheritance can also be used to make a class a final class, i.e. to make it so that no other classes can derive from it. I grabbed that trick once from Stroustroup (<http://www.research.att.com/~bs/bs_faq2.html#no-derivation> see below for updated hyperlinks and sources): > > The other variant of this problem, how to prevent derivation for logical reasons, has a solution in C++11. For example: > > > > ``` > [...] > > ``` > > For older compilers, you can use a somewhat clumsy technique: > class Usable; > > > > ``` > class Usable_lock { > friend class Usable; > private: > Usable_lock() {} > Usable_lock(const Usable_lock&) {} > }; > > class Usable : public virtual Usable_lock { > // ... > public: > Usable(); > Usable(char*); > // ... > }; > > Usable a; > class DD : public Usable { }; > > DD dd; // error: DD::DD() cannot access > // Usable_lock::Usable_lock(): private member > > ``` > > --- Update 2018 ----------- C++ has received a `final` keyword [in the meanwhile](http://www.stroustrup.com/bs_faq2.html#final): > > Why doesn't C++ have a final keyword? > ------------------------------------- > > > [It has, but it is not as useful as you might think.](http://www.stroustrup.com/bs_faq2.html#no-derivation) > > > which leads to: > > Can I stop people deriving from my class? > ----------------------------------------- > > > Yes, but why do you want to? There are two common answers: > > > * for efficiency: to avoid my function calls being virtual > * for safety: to ensure that my class is not used as a base class (for example, > to be sure that I can copy objects without fear of slicing) > > > In my experience, the efficiency reason is usually misplaced fear. In C++, virtual function calls are so fast that their real-world use for a class designed with virtual functions does not to produce measurable run-time overheads compared to alternative solutions using ordinary function calls. Note that the virtual function call mechanism is typically used only when calling through a pointer or a reference. When calling a function directly for a named object, the virtual function class overhead is easily optimized away. > > > If there is a genuine need for "capping" a class hierarchy to avoid virtual function calls, one might ask why those functions are virtual in the first place. I have seen examples where performance-critical functions had been made virtual for no good reason, just because "that's the way we usually do it". > > > The other variant of this problem, how to prevent derivation for logical reasons, has a solution in C++11. For example: > > > > ``` > struct Base { > virtual void f(); > }; > > struct Derived final : Base { // now Derived is final; you cannot derive from it > void f() override; > }; > > struct DD: Derived {// error: Derived is final > > // ... > }; > > ``` > > ... which then leads to the initial passage of this answer.
182,756
Shell Type: ``` >echo $SHELL /bin/ksh ``` Cronjob : `15 * * * * /bin/ksh /wls_domains/resMGT/logs/bea/wlr3queuetransaction.sh > /wls_domains/resMGT/logs/bea/data/script.log` The script is as below: ``` ##log files and lookup file "wlr3queue.txt" are in the same path of the script ##/wls_domains/resMGT/logs/bea/wlr3queuetransaction.sh Script : #!/bin/ksh dt=`date +%Y-%m-%d` xy=`date|awk '{print $4}'|awk -F":" '{print $1}'` yz=`expr $xy - 1` if [ $yz -le 9 ] then yz=0$yz fi if [ $xy -gt 0 ] then for i in `cat wlr3queue.txt` do sum=0 count=`gzgrep -i "$dt" admin_resMGT_access.log* | grep "$yz:[0-5][0-9]" | grep "$i" | wc -l` if [ $count -gt 0 ] then name=`echo $i | cut -d'/' -f3` gzgrep -i "$dt" admin_resMGT_access.log* | grep "$yz:[0-5][0-9]" | grep "$i" | awk '{print $8}' > consumed_time.txt for j in `cat consumed_time.txt` do j_ms=`echo "$j * 1000" | bc` echo $j_ms >> consumed_ms_time.txt done for k in `cat consumed_ms_time.txt` do sum=`echo "$sum + $k" | bc` done avg=`echo "scale=2; ($sum/$count) "| bc` min=`cat consumed_ms_time.txt | sort -n | head -1` max=`cat consumed_ms_time.txt | sort -n | tail -1` else avg=0 min=0 max=0 fi ( echo $yz","$count","$avg","$min","$max )>>/wls_domains/resMGT/logs/bea/data/$name$dt.csv rm -f consumed_ms_time.txt done else echo "script won't execute at this hour" > temp.txt fi ``` I have executed the following commands and the script ran successfully. ``` ./wlr3queuetransaction.sh sh -x wlr3queuetransaction.sh /bin/ksh /wls_domains/resMGT/logs/bea/wlr3queuetransaction.sh /bin/ksh/ wlr3queuetransaction.sh. ``` How to debug? What to do?
2015/02/03
[ "https://unix.stackexchange.com/questions/182756", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/101753/" ]
Items in crontab execute with a limited environment. At the top of your script you can specify your PATH, for example, ``` PATH=$PATH:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin ``` or alternatively you can call each executable with its absolute path.
First of all, for debugging purposes, redirect the stderr to some file as well. This way you'll know what goes wrong. `15 * * * * /bin/ksh /wls_domains/resMGT/logs/bea/wlr3queuetransaction.sh 2>LOG_FILE > /wls_domains/resMGT/logs/bea/data/script.log` Next if it isn't a file location issue, take a look at this question, as it is very similar: [how to set crontab PATH variable](https://unix.stackexchange.com/questions/148133/how-to-set-crontab-path-variable).
10,286
Can we become God? Most people believe that the Gods that we are worshipping are fixed and no human can reach the state of God. Is this true? If a person is born and lives as the purest one and when he attains the state as God, can he be included in the Gods of today? Can a person become God if he learns all the things that a God knows?
2016/01/30
[ "https://hinduism.stackexchange.com/questions/10286", "https://hinduism.stackexchange.com", "https://hinduism.stackexchange.com/users/3996/" ]
If you can perform sarvamedha or purushmedha you can become Brahman or something close to it. [What are the similarities and differences between Purushamedha Yagna and Sarvamedha Yagna?](https://hinduism.stackexchange.com/questions/21968/what-are-the-similarities-and-differences-between-purushamedha-yagna-and-sarvame) Narayana was only a rishi (i.e., a human) in Rig Veda and became the supreme being after performimg purushamedha. > > Purusha Nârâyana desired, 'Would that I overpassed all beings! would that I alone were everything here (this universe)!' He beheld this five-days’ sacrificial performance, the Purushamedha, and took it , and performed offering therewith; and having performed offering therewith, he overpassed all beings, and became everything here. And, verily, he who, knowing this, performs the Purushamedha, or who even knows this, overpasses all beings, and becomes everything here. > > > We don't know if Purushamedha/Sarvamedha can be performed any more.
Lord May be realized on different levels. As Bhagavatam States [here](https://www.vedabase.com/en/sb/1/2/11) > > Learned transcendentalists who know the Absolute Truth call this > nondual substance Brahman, Paramātmā or Bhagavān. > > > Just like Sun and Sunshine. There are three features viz, Sunshine(Brahman), Sun Globe(Paramatma), Sun Deity Vivasvan(Bhagvana or personal feature). There are different philosophies that subscribe to Vedanta school, Viz Advaita, VishishtAdvaita, Dvaita and so on as described in this [answer](https://hinduism.stackexchange.com/questions/4064/dvaita-vs-advaita-vs-vishistadvaita-vs-shuddhadvaita-vs-any-other) Now different philosophies have different opinions as to three levels of God realization. I.e Advaita says that Brahman realization is highest where as there are other schools(Vaishnava) who believe that associating with God in His personal form is superior i.e. Realization of Bhagavan feature is highest. As per Advaita **YOU ARE GOD**. So no question of becoming God, of course you have forgotten or due to Avidya you perceive the individuality. Now as I have mentioned the sun example, You may merge into sunshine but you can never become one with the King of Sun planet. That is in Advaita terms you can never become a Saguna Brahman(refer this answer [here](https://hinduism.stackexchange.com/questions/14114/how-does-adishankaracharya-advaita-explain-concept-of-avatar)). Also in Vedanta sutra and Gita it is mentioned that we are part and parcel of One Supreme God. **We are not one with Him**. But we are one in quality with Him. Just like Sunshine is one in quality with Sun but Sunshine is not Sun.
38,415,421
`S_IWGRP` and `S_IWOTH` flags does not make any effect when specified in `open(2)`. File opened and created as ``` open(file,O_CREAT|O_WRONLY,S_IWGRP|S_IWOTH); ``` that resulting in ``` ---------- 1 root root 0 Jul 16 21:25 file ``` any other flags works properly. Where should I start the troubleshooting?
2016/07/16
[ "https://Stackoverflow.com/questions/38415421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6260800/" ]
Use the following format ``` (container) row col-md-4 col-xs-6 col-md-4 col-xs-6 ...(6x) ``` The columns will wrap below each other, so on medium views, you'll get 3 columns in a row, and on mobile views, 2 columns in a row. If the trailing columns bother you, just add the classes `col-xs-offset-3` and `col-md-offset-2` (for example). The offsets will changed based on view. You can image this offset as an "invisible" column placed before the first in that new row.
Try this : ``` <div class="row"> <div class="col-xs-6 col-md-4"> <img class="images img-responsive" src="" alt="text"></img> </div> <div class="col-xs-6 col-md-4"><img class="images img-responsive" src="" alt="text"></img> </div> <div class="col-xs-6 col-md-4"><img class="images img-responsive" src=""></img> </div> <div class="col-xs-6 col-md-4"> <img class="images img-responsive" src="" alt="text"></img> </div> <div class="col-xs-6 col-md-4"><img class="images img-responsive" src="" alt="text"></img> </div> <div class="col-xs-6 col-md-4"><img class="images img-responsive" src=""></img> </div> <div class="col-xs-6 col-md-4"> <img class="images img-responsive" src="" alt="text"></img> </div> <div class="col-xs-6 col-md-4"><img class="images img-responsive" src="" alt="text"></img> </div> <div class="col-xs-6 col-md-4"><img class="images img-responsive" src=""></img> </div> </div> ```
45,627,021
The task is this: print out the first letter of the third word of SongLine. The tutor/demonstrator says I should use a loop. ``` import java.lang.*; public class SongApp{ public static void main(String[] args){ Song song1 = new Song("While my guitar weeps"); Song song2 = new Song("Let it be"); //Song song3 = new Song("Penny Lane"); String str1 = song1.toString(); String str2 = song2.toString(); System.out.println(song1.toString()); //System.out.println("Length is: " + str1.length()); System.out.println(song2.toString()); //System.out.println("Length is: " + str2.length()); //System.out.println(str1.charAt(str1.length()-1)); //System.out.println(str2.charAt(str2.length()-1)); int s1 = str1.indexOf(' '); System.out.println(str1.substring(0, str1.indexOf(' ', s1 +1))); //System.out.println(str1.substring(str1.indexOf(' ', s1 + 2))); int s2 = str2.indexOf(' '); System.out.println(str2.substring(0, str2.indexOf(' ', s2 +1))); //System.out.println(str2.substring(str2.indexOf(' ', s2 + 1))); } } public class Song{ private String songLine; public Song (String sLine){ songLine = sLine; } public String toString(){ return songLine; } public void process(){} } ``` I'm stuck and don't know how to proceed. I also need to print the first two words which I've done, but need to print the rest of the string on another line, so far I have it mostly working apart for the extra space at the beginning. Thanks, JXDee
2017/08/11
[ "https://Stackoverflow.com/questions/45627021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8448703/" ]
``` public static void main(String[] args){ Song song1 = new Song("While my guitar weeps"); Song song2 = new Song("Let it be"); String str1 = song1.toString(); String str2 = song2.toString(); int x=0; int currentSpace=0; String wordResult=""; while (x<song1.length()){ if (song1.charAt(x)=' ') { currentSpace++; } if (currentSpace = 2) { wordResult =wordResult + song1.charAt(x); } x++; } System.out.println("The first character is: " + wordResult.charAt(0)); System.out.println("The result is :" + wordResult); } } ``` Ive edited the code so that it will fit to your need which is using the while loop. As you can see, the loop will check all the characters. The loop will also look for the spaces.. when the loop scan that the space reaches 2 the it will start to record the 3rd word in the sentence. character by character. as you can see there is a condition that if the currentSpace variable is still 2 then it will keep recording the characters until it reaches the next space or the end of sentence.. then lastly on printing to get the first character of 3rd word we will just use the charAt to finished it.. i hope this helps
A working solution: :-) ``` String x = "While my guitar weeps"; x= x.trim(); for(int i=1; i<=2; i++) x = x.substring(x.indexOf(" ")+1) ; char reqChar = x.charAt(0); ```
340,429
Actually I'm trying to dive into Fourier series and have some trouble understanding the idea behind the Fourier coefficients. Let's have a Fourier series $$f(x) = a\_0 + \sum\_{n=1}^{\infty}[a\_n\cos(\omega\_nx) + b\_n\sin(\omega\_nx)]$$ where $x \in \langle-\frac{T}{2}, \frac{T}{2}\rangle$, $n \in \mathbb{N}$, $\omega\_n = \frac{2\pi}{T}n$ is angular frequency, $T$ is the period of function $f$. If I understand it correctly I would say that $a\_n$/$b\_n$ is the amplitude of cosine/sine functions with frequency $n$ Hz (harmonic, since $n \in \mathbb{N}$). And by combining these (potentially infinite) number of functions I get function $f$ ([visualization](http://www.spektrumanalizoru.com/images/time_vs_freq1.gif), [animation](http://upload.wikimedia.org/wikipedia/commons/7/72/Fourier_transform_time_and_frequency_domains_%28small%29.gif)). Now comes the interesting part - amplitudes/coefficients $a\_0$, $a\_n$, $b\_n$. I understand the calculations... multiplying the equation by $\cos(\omega\_kx)$/$\sin(\omega\_kx)$, $k \in \mathbb{N}$ and integrating over $\langle-\frac{T}{2}, \frac{T}{2}\rangle$ results in: $$a\_0=\frac{1}{T}\int\limits\_{-T/2}^{T/2}f(x)\mathrm{d}x,$$ $$a\_k=\frac{2}{T}\int\limits\_{-T/2}^{T/2}f(x)\cos(\omega\_kx)\mathrm{d}x,$$ $$b\_k=\frac{2}{T}\int\limits\_{-T/2}^{T/2}f(x)\sin(\omega\_kx)\mathrm{d}x.$$ Since $\int\_{-T/2}^{T/2}f(x)\mathrm{d}x$ is area beneath function $f$ on interval $\langle-\frac{T}{2}, \frac{T}{2}\rangle$, $a\_0$ can be geometrically interpreted as the average value of function $f$ on interval $\langle-\frac{T}{2}, \frac{T}{2}\rangle$ or as the new center of oscillation instead of zero. What I do not understand is that how $a\_k$/$b\_k$ can be geometrically interpreted. In particular, I can imagine how $f(x)\cos(\omega\_kx)$ look like but I can't wrap my head around the fact that the area beneath $f(x)\cos(\omega\_kx)$ on interval $\langle-\frac{T}{2}, \frac{T}{2}\rangle$ divided by $\frac{2}{T}$ is the correct amplitude for function $cos(\omega\_kx)$ to be the proper function to be added to others to build up function $f$ (the same for sine function too). Why is there a $2$? And how is it possible that $\int\_{-T/2}^{T/2}f(x)\cos(\omega\_kx)\mathrm{d}x$ is the right number to determine the correct amplitude for the Fourier series? What is the connection between the area beneath the function and the amplitude? I can't see it geometrically so I think that I miss some very important idea. Or some property of sine/cosine maybe... Can someone explain the idea behind Fourier coefficients or paste a link where this is explained, please? I've read/watched couple of materials covering this topic but didn't find the answers :( Usually calculations of Fourier coefficient where presented but never the explanation of what does it actually in "human language" means. I consider it to be very important in understanding the essence of Fourier series. Thanks in advance for any advice.
2013/03/25
[ "https://math.stackexchange.com/questions/340429", "https://math.stackexchange.com", "https://math.stackexchange.com/users/68323/" ]
On mathoverflow.net Carlo Beenakker recommended <http://techhouse.brown.edu/~dmorris/projects/tutorials/fourier_tutorial.pdf>. He hit the nail (right) on the head.
The undestanding of intuition behind coefficients of the Fourier transform may be simplified as follows. The imaginary exponential runs from minus infinity to positive infinity. As a result, all imaginary parts (the sine functions) form the negative and positive sides cancel out. What is left is the cosine part. The coefficients are then calculated as an integral of the product of $ f(x)$ and $\cos (\omega x)$. To satisfy the conditions for a Fourier transform, f(x) has to be sum of cosine functions. As the cosine funcions are orthonormal, each integral extracts the correct cosine function from $f(x)$. Thus, $f(x)$ is transformed to a sum of cosine functions.
54,752,748
I'm a batch scripting novice. I can spin up basic menus for my own needs but I need a little nudge in the right direction regarding menus and variables. So I wish to create a menu which defines a variable upon selection of one, from multiple items to define the path of an item where file operations begin. So here's an example I'm looking to figure out how tot integrate: ``` CHOICE /N /C:1234 /M "Option: " IF ERRORLEVEL ==4 SET foo IF ERRORLEVEL ==3 SET bar IF ERRORLEVEL ==2 SET quak IF ERRORLEVEL ==1 SET baz [something something define %bark% from above] rem overwrite file.png with new option copy %src%\%bark%\file.png %des%\%quak%\file.png ``` Now I know I am missing stuff here. *I'm an idiot* if I hadn't made that clear enough. How do I make a batch menu which sets a variable for doing the same thing, multiple times without bloating my code using unique operations for each?
2019/02/18
[ "https://Stackoverflow.com/questions/54752748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11080440/" ]
You have a many to many relationship between bus lines (loops) and bus stops : using a junction table is the standard way to go. In the junction table, says loops\_stops, you want to store a fk to the bus lines, another fk to the bus stops, and the sequence of the stop of the line. You can have a unique key on the two constraint columns (include the sequence of it is possible that the same stop is served twice by the same line). Nb : un MySQL, you usually want to use autoincremented integer primary keys. In the stops table, you store information that is common to stops, like the name, location, equipments and so on. Using a junction table is the proper way to represent your data. It will also prevent you from duplicating information in the lines tables. We can see that this is starting to happen with your sample data : what if you need to add an information that is common to all lines ? in your sample data (eg location) ? You would need to duplicate it on each row, which is not efficient and a maintenance nightmare when you need to update that value.
You can do it without junction table as below: ``` Declare @Loop Table (Loop_Id int, Name varchar(50)) Insert into @Loop Values (1,'Red'), (2,'Green'), (3,'Blue') Declare @Stop_Table Table (Stops varchar(500), Loops varchar(50), DisplayOrder int, Id int) Insert into @Stop_Table (Stops,Loops,DisplayOrder,Id) Values ('West Stop' ,'Red' ,'1','12'), ('North Stop' ,'Red' ,'2','43'), ('Building Stop' ,'Red' ,'3','15'), ('Park Stop' ,'Red' ,'4','14'), ('Park Stop' ,'Green' ,'1','42'), ('West Stop' ,'Green' ,'3','11'), ('Building Stop' ,'Green' ,'2','8'), ('Building Stop' ,'Blue' ,'1','2'), ('Park Stop' ,'Blue' ,'3','4'), ('West Stop' ,'Blue' ,'2','6') --To get all loops sort select S.*,L.* from @Stop_Table S Join @Loop L On L.Name = S.Loops Order by L.Loop_Id,S.DisplayOrder asc --To get stops for a specific loop.For Ex:Red select S.*,L.* from @Stop_Table S Join @Loop L On L.Name = S.Loops where L.Name = 'Red' Order by L.Loop_Id,S.DisplayOrder asc ```
7,374,779
This is the scenario: I have a WCF service running, who communicates with this method, in C#: ``` public bool ValidateUser(UserPass up) { initializeAttributes(); IMembershipService Member = new AccountMembershipService(); bool login = Member.ValidateUser(up.User, up.Pass); return login; } ``` The parameter are encapsulated in this class: ``` [DataContract] public class UserPass { string user = ""; string pass = ""; string email = ""; [DataMember] public string User { get { return user; } set { user = value; } } [DataMember] public string Pass { get { return pass; } set { pass = value; } } [DataMember] public string Email { get { return email; } set { email = value; } } } ``` Now, I want to connect to the server via an Android application, now, my question is, how can I replicate the UserPass class in Java, so the ValidateUser method can receive its parameter in a way it can understands it. for reference, this is the code where I'm obtaining the User and Password: ``` private void validateUser(String user, String pass) { String SOAP_ACTION = "http://tempuri.org/IUserService/ValidateUser/"; String METHOD_NAME = "ValidateUser"; String NAMESPACE = "http://tempuri.org/"; String URL = "http://10.0.2.2/UserService.svc"; AlertDialog popup; SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); request.addProperty(user, pass); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; HttpTransportSE httpTransport = new HttpTransportSE(URL); try { httpTransport.call(SOAP_ACTION, envelope); //here's the exception!! Object response = envelope.getResponse(); popup = createAlertDialog("Respuesta",response.toString(),"OK"); popup.show(); } catch (Exception exception) { String exceptionStr=exception.toString(); popup = createAlertDialog("Exception!!",exceptionStr,"OK"); popup.show(); } } ``` The exception it throws is xmlpullparserexception, which, according to my understanding, is because of a missmatch between the parameters of the request and the actual method. Many thanks for reading my question, and many more for those who can answer it :) EDIT: I finnaly got how to compare the XMLs... now, this is what my SOAP is providing: ``` <v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/"> <v:Header /> <v:Body> <ValidateUser xmlns="http://tempuri.org/" id="o0" c:root="1"> <User i:type="d:string">someuser</User> <Pass i:type="d:string">somepass</Pass> <Email i:type="d:string"></Email> </ValidateUser> </v:Body> ``` and this is what it SHOULD have made (retrieved from WCF Test Client application from Visual Studio 2010): ``` <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header> <Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/IUserService/ValidateUser</Action> </s:Header> <s:Body> <ValidateUser xmlns="http://tempuri.org/"> <up xmlns:d4p1="http://schemas.datacontract.org/2004/07/LiveAndesWCF" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <d4p1:Email i:nil="true" /> <d4p1:Pass>somepass</d4p1:Pass> <d4p1:User>someuser</d4p1:User> </up> </ValidateUser> </s:Body> </s:Envelope> ``` Now, I'm lost on how to code my soap code to have it generate a xml file like the latter one. Many thanks again.
2011/09/10
[ "https://Stackoverflow.com/questions/7374779", "https://Stackoverflow.com", "https://Stackoverflow.com/users/915768/" ]
have you tried to look at the xml created by the soap call? you can compare it to the xml created by a .net proxy. maybe this helps to find a solution. here is how you can enable the logging of the soap calls: <http://msdn.microsoft.com/en-us/library/ms730064.aspx>
This line looks suspect to me: ``` request.addProperty(user, pass); ``` As far as I can tell, `SoapObject` comes from the KSOAP2 library, and according to the docs, addProperty takes the name of the property and the value. To set user and pass, I would expect something more like this: ``` request.addProperty("user", user); request.addProperty("pass", pass); ``` Currently, it looks like you're adding a single property named using the value of the `user` parameter. If the endpoint is expecting at least 2 arguments, then this could be the source of your mismatch. Also, is the value "Email", from the `UserPass` wrapper class, optional? As I don't see it being set anywhere, and the wrapper class suggests it's required by the SOAP request
947,819
I have a HP ENVY 17-3200 (switchable graphics: Intel HD 4000 + AMD Radeon HD 7800M) with a triple monitor setup: * Laptop's builtin LVDS 1080p display * DisplayPort WQXGA display * DisplayPort 1080p display This configuration worked under Windows 7, 8, and 8.1. After upgrading to Windows 10, only 2 displays work. I have the latest drivers. * Intel driver 10.18.10.4252 * AMD driver 15.7.1 (15.200.1062.1002) I suspect this may have something to do with the fact the 4000's drivers only support WDDM 1.3 and the AMD drivers support WDDM 2.0. How do I get all 3 monitors working again?
2015/07/30
[ "https://superuser.com/questions/947819", "https://superuser.com", "https://superuser.com/users/34958/" ]
Try this... Right click anywhere on your screen and select "Graphic Properties". When the Intel HD Graphics Control Panel comes up click the "Display" tab. Right under Intel HD Graphics Control Panel is a "Display" with a dropdown arrow. Don't confuse it with the "Select Display". Click the dropdown and select "Multiple Displays". Then select your primary #1 and #2 monitor. Click apply and that should work.
Please download the latest Intel display drivers. <https://downloadcenter.intel.com/product/81499/Intel-HD-Graphics-4000-for-3rd-Generation-Intel-Core-Processors> The newest driver just came out 2 days ago (19-9-2015). For other models: <https://downloadcenter.intel.com/> I have a dual-monitor setup with my laptop (Intel i7-4700HQ with Intel HD Graphics 4600, NVIDIA GeForce GT 745M) and upgraded from Windows 8.1 to 10. My laptop screen flickered all the time, even with the cable unplugged. In the end, the problem lies in the Intel display driver. Updating to the new Intel display driver for Windows 10 solved the problem. Reinstalling the latest NVIDIA driver doesn't help, since the desktop or in general Windows is rendered with the Intel HD Graphics.
4,895,041
I have used following 2 patterns to create a view. ``` @property (retain, nonatomic) SomeView* someView; ... // First pattern self.someView = [[SomeView alloc] initWithFrame frame]; // Second pattern SomeView* aSomeView = [[SomeView alloc] initWithFrame]; self.someView = aSomeView; [aSomeView release]; ``` Now, looking back at this code, the first pattern's method should be changed to ``` self.someView = [[[SomeView alloc] initWithFrame frame] autorelease]; ``` shouldn't it? I feel dumb :(
2011/02/04
[ "https://Stackoverflow.com/questions/4895041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/433570/" ]
Look at it like this: ``` [[SomeView alloc] initWithFrame: frame]; ``` The above line creates an object and gives it a retain count of 1. ``` self.someView = [[SomeView alloc] initWithFrame: frame]; ``` This line leaves it with a retain count of two, because the someView property is declared with retain: ``` @property (**retain**, nonatomic) SomeView* someView; ``` So, doing it this way leaves your someView property pointing to an object with retain count of 2. You can do it this way if you add an autorelease call to it: ``` self.someView = [[[SomeView alloc] initWithFrame: frame] autorelease]; ``` Your second pattern is better, if you ask me. You create an object with a retain count of one. You assign it to a retaining property (now it has a retain count of 2) and then you release the original variable, leaving the object again with a retain count of 1. It's three lines where you might want only one, but it makes sense in the right context. Additionally, it's usually best to avoid using autorelease outside of an alloc or copy method since its usually an indication you don't fully understand memory management in Obj-C. And as a commenter said in the comments to the question, don't feel dumb. None of this is intuitive at first. Nobody picks up a guitar and plays like Hendrix their first time.
Yes, you are right. `autorelease` means "release a bit later".
49,801,611
I have drawn an outline of a mobile phone. I need to fit some short video clips into the screen of the phone. How would you go about it? The drawn screen and video ratio are the same. It needs to be responsive of course, so my video has to scale with the frame (the graphics). Because of the graphics it is not as simple as placing the video element in a container. I was trying to achieve it first with the phone as a background image. Now I'm thinking of two absolutely positioned elements (phone and video) overlapping each other. Maybe a div containing the video and an absolutely positioned pseudo element ::after holding the graphics? I often make simple things complex, so please kindly advise if there is a better way to achieve it.
2018/04/12
[ "https://Stackoverflow.com/questions/49801611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4163155/" ]
I found a better solution using the options ``` function formatState(state) { const option = $(state.element); const color = option.data("color"); if (!color) { return state.text; } return $(`<span style="color: ${color}">${state.text}</span>`); }; jQuery(node).select2({ templateResult: formatState, templateSelection: formatState, }); ``` The color comes from the html data attribute in my case ``` <option style="color: #F00" data-color="#F00" value="1">Red Option</option> ```
You can use the CSS attribute selector like so on select2-results\_\_option elements: ```js $(".select2").select2(); ``` ```css .select2-selection__rendered[title="Apple"] { color: red !important; } .select2-results__option[id*="Apple"] { color: red; } select { width: 200px; } ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script> <select class="select2" name="fruit"> <option class="red-option">Apple</option> <option class="green-option">Kiwi</option> <option class="blue-option">Grape</option> </select> ```
269,882
If I do this: ``` // In header class Foo { void foo(bar*); }; // In cpp void Foo::foo(bar* const pBar) { //Stuff } ``` The compiler does not complain that the signatures for Foo::foo do not match. However if I had: ``` void foo(const bar*); //In header void Foo::foo(bar*) {} //In cpp ``` The code will fail to compile. What is going on? I'm using gcc 4.1.x
2008/11/06
[ "https://Stackoverflow.com/questions/269882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35227/" ]
In the first, you've promised the compiler, but not other users of the class that you will not edit the variable. In your second example, you've promised other users of the class that you will not edit their variable, but failed to uphold that promise. I should also note that there is a distinct difference between ``` bar* const variable ``` and ``` const bar* variable ``` and ``` const bar* const variable ``` In the first form, the pointer will never change, but you can edit the object that is pointed to. In the second form, you can edit the pointer(point it to another object), but never the variable that it points to. In the final form, you will neither edit the pointer, nor the object it points to. [Reference](http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.5) To add a bit more of a clarification to the question stated, you can always promise MORE const than less. Given a class: ``` class Foo { void func1 (int x); void func2 (int *x); } ``` You can compile the following implementation: ``` Foo::func1(const int x) {} Foo::func2(const int *x) {} ``` or: ``` Foo::func1(const int x) {} Foo::func2(const int* const x) {} ``` without any problems. You've told your users that you may possibly edit their variables. In your implementation, you've told the compiler that this particular implementation will not edit those variables, even though the told the users you might. You haven't broken a promise to the user, and so the code compiles.
It probably doesn't care much about `void Foo::foo(bar* const pBar)` because how you treat the pointer itself (const or not) doesn't matter one bit outside of the routine. The C rules say that no change to pBar will travel outside of foo either way. However, if it is `(const bar* pBar)`, that makes a difference, because it means the compiler is not to allow callers to pass in pointers to non-const objects.
13,738,955
Can anybody explain why in python builtin buinction `all` return `True` in this case `all([])`? ``` In [33]: all([]) Out[33]: True In [34]: all([0]) Out[34]: False In [35]: __builtins__.all([]) Out[35]: True ```
2012/12/06
[ "https://Stackoverflow.com/questions/13738955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/655500/" ]
I'm not convinced that any of the other answers have really address the question of *why* this should be the case. The definition for Python's `all()` comes from boolean logic. If for example we say that "all swans are white" then a single black swan disproves the statement. However, if we say that "all unicorns are pink" logicians would take that as a true statement simply because there are no non-pink unicorns. Or in other words "all " is [vacuously true](http://en.wikipedia.org/wiki/Vacuous_truth). Practically it gives us a useful invariant. If `all(A)` and `all(B)` are both true then the combination of `all(A + B)` is also true. If `all({})` was false we should have a less useful situation because combining two expressions one of which is false suddenly gives an unexpected true result. So Python takes `all([]) == True` from boolean logic, and for consistency with other languages with a similar construct. Taking that back into Python, in many cases the vacuous truth makes algorithms simpler. For example, if we have a tree and want to validate all of the nodes we might say a node is valid if it meets some conditions and all of its children are valid. With the alternative definition of `all()` this becomes more complex as we have to say it is valid if it meets the conditions and either has no children or all its children are valid. ``` class Node: def isValid(self): return some_condition(self) and all(child.isValid for child in self.children) ```
Another explanation for this is that `all` and `any` are generalisations of the binary operators `and` and `or` for arbitrarily long numbers of parameters. Thus, `all` and `any` can be defined as: ``` def all(xs): return reduce(lambda x,y: x and y, xs, True) def any(xs): return reduce(lambda x,y: x or y, xs, False) ``` The `True` and `False` parameters show that `all([]) == True` and `any([]) == False`.
10,751,458
So, every time I am developing something big, with multiple modules coming together to build a final functionality, I've been wondering the same question: Where to initialize the random seed if more than 1 module needs to use the random function? If I have a certain class that needs random (e.g. class that initializes itself by sorting an input array with self-implemented quicksort, so I would need a random for the pivot choice), I usually have a private `static bool isRandOn;` variable, so before I start the random pivot choice, I check that variable and do `srand(time(NULL));` if the random is not on yet. If I have a ton of utility functions in a namespace, I do a very similar thing: I put such a variable in an anonymous namespace inside my utils library, and do the more-or-less same thing as with a class. *The problem I have* is when combining those modules. All by it self, I know each module will not set the seed more than once. But, I want to be able to use a various amount of my modules together, I want other people to be able to use one or more of my modules independent of the others... So, **what is the best way** to handle multiple random-seed-needing modules? Set the seed in each module? Do not set the seed at all but instead document the usage of random and make the user initialize the seed if he wants to use the module? Something third?
2012/05/25
[ "https://Stackoverflow.com/questions/10751458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/884412/" ]
I would suggest using Boost.Random rather than relying on some global state shared at the program level. Boost.Random has two concepts: * Engine: which generates random numbers * Distributions: which adapt the result from the engines to provide results fitted to a certain distribution (normal, poisson, gaussian, ...) Each module may then have its own Engine, or indeed several of them: there is no specific reason for a given Engine to be shared between several different functions within the same module. As a final word: whatever you do make sure you have a way to set the seed(s) deterministically for bug repro purposes. Bug repro may benefit from having multiple engines (isolation of the parts helps).
@penelope gave a correct answer. There is some complex algorithm for generating pseudo-random number sequence behind `rand()`. This is like some function `rand_func(prev_rand)`, which generates next pseudo-random number from previous. For the first time you call `srand(time(NULL))`, which sets `prev_rand` to in these terms supposing `time(NULL)` to be quite undetermined. So you can safely call `srand()` (which sets ) multiple times. The special issue is if you neet *predictable* pseudo-random sequences: for example, `srand(0)` etc. But it seems to be not your case.
51,573
Similar to this question: [Visually stunning math concepts which are easy to explain](https://math.stackexchange.com/questions/733754/visually-stunning-math-concepts-which-are-easy-to-explain), what are some great visualizations of basic DSP concepts such as FFTs, filters, etc?
2018/08/28
[ "https://dsp.stackexchange.com/questions/51573", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/37197/" ]
Personally, I very much like the interactive visualisations of filters that connect various bits together. There is a great website called [MicroModeller DSP](http://www.micromodeler.com/dsp/) (I am not affiliated with it). You can choose the filter type, its parameters and interactively see how impulse response, zeros & poles, or even the Z-transform function change. Honestly, I think this tool is better in terms of exploration than the MATLAB's `fdesign`. [![enter image description here](https://i.stack.imgur.com/CJX5R.png)](https://i.stack.imgur.com/CJX5R.png)
A colleague and friend, Vincent Mazet, has [DSP and digital communication animations](https://vincmazet.github.io/spetsi/) (in French), among which the [cisoid or complex exponential](https://vincmazet.github.io/spetsi/expo.html): [![cisoid, or complex exponential](https://i.stack.imgur.com/WxYFo.png)](https://i.stack.imgur.com/WxYFo.png)
33,680,380
Consider this code: ``` os.mkdir('foo') open('foo/bar.txt') ``` I tried this: ``` try: os.makedir('foo') except OSError, e: if e.errno != errno.EEXIST: raise open('foo/bar.txt') ``` and this: ``` try: open('foo/bar.txt') except IOError: os.makedir('foo') open('foo/bar.txt') ``` But in both cases, we still end up with a race condition. Been thinking about this for a little while and I can't figure out a way to get rid of it. Anyone has a solution?
2015/11/12
[ "https://Stackoverflow.com/questions/33680380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407054/" ]
`Arrays.sort(Object[])` expects that all elements in the array are `!= null` since it demands that > > all elements in the array must be *mutually* comparable (that is, e1.compareTo(e2) ... > > > What you see is the result of `null.compareTo(something)`. Your `InventoryItem[] array` has presumable 100 slots, but not all of them are filled. To fix that, you could * copy the non-null data into a correctly sized array * sort just the filled subset via [`Arrays.sort(Object[] array, int fromIndex, int toIndex)`](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#sort-java.lang.Object:A-int-int-) (with `0, lastIndexUsed` as params). * Provide a `Comparator` that can handle `null`. With one the algorithm is no longer `null.compareTo(something)` but `comparator.compare(null, something)` which does not result in a NPE. See [How to sort an array of objects containing null elements?](https://stackoverflow.com/questions/27556104/how-to-sort-an-array-of-objects-containing-null-elements) * use a `List`
The InventoryItem array is initialized as 100, and if you don't read in 100 rows, then you'll have null pointers for the non-existent indexes. You'll need to use a List, rather than a java array. ``` List<InventoryItem> inventoryItems = new List<InventoryItem>(); ``` then when you add them do something like this, ``` inventoryItems.add(new InventoryItem(name, value, quantity)); ```
109,647
I work in a Startup where I was hired at the first employee, after the founder. Naturally, after the company started growing, I rose the ranks quite fast. I am still quite young and the founder of the company was an experienced Regional Director of a very big and famous multinational company. He decided to implement a 6-day work week. On any single day, we start work at 9 am and doesn't end till 8pm on average. Sometimes, it goes far beyond that. We don't get remunerated for overtime as, in his own words, it is a startup. This 6-day workweek and along with the long working hours is proving more detrimental to the company. Unfortunately, he values long working hours more, employees who validates his idea and generally loyalists that will keep their heads down and do as they say. On Saturday, there was a situation where I decided to leave at 7 and he "made a joke" about how we should swap jobs and I should take his. He even involved my other colleagues in the discussion whereby they were discussing how "lucky" I am to be working in this specific area and how stressful their job is. I smiled then, but it really got me thinking. Colleagues are complaining internally to each other, but no one has the guts to say anything to him. Do I need to say anything? How do I approach this subject? **EDIT** To clarify some few things: * The company is based in Dubai, United Arab Emirates * The working hours specified in my contract is 09:00 - 18:00, Monday to Friday * The maximum working hours in a week in UAE is 48 hours. Overtime should be paid. However, in my signed contract, it says overtime won't be paid. I am aware that the country's law takes precedence. * Yes I do own stocks in the company. It has the potential to grow into a successful company, but I don't think the long hours is helping with that. It is doing more harm than good. * 6 days a week was instituted after 15 months of me joining the company.
2018/03/25
[ "https://workplace.stackexchange.com/questions/109647", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/85326/" ]
It sounds like saying anything will be a career limiting move at this place, but that may not be a bad thing. Many companies may ask for occasional overtime to get past short-term deadlines, but it's clear that here a 60+ hour week is considered normal and expected of you. It is bad enough that you're not being paid for that level of effort (and "it's a startup" is no excuse, he is blatantly exploiting your goodwill), but more importantly it is simply not sustainable. You will damage your health and relationships at this rate. Start planning your exit now; this is a toxic environment and you shouldn't be putting up with it.
I've seen this brought up briefly: **What are YOUR motivations for working 20-30 hours a week extra?** A startup, to me, means they are aiming for one of two things: **Massive growth** or **getting bought out** by a bigger fish. **What are you getting out of the extra hours?** You question doesn't mention any details and your comments mention you are paid under market rate. Things to get from a job: * Experience - I've taken jobs for under market to get experience. My first programming job was $21/k when $40-50k was the normal starting pay expected - but I got started somewhere. * Skills - are you learning new technology? I've done things for free/cheap to learn a new stack... I'll put in a few extra hours to come up to speed on something new. * Title - I've seen a couple people work under-rate and over-time for a title - Senior Developer. Chief Architect. etc. * Money - self explanatory. * Stock - Are you getting any stock? Company ownership? Many people work at startups for the chance to be part owner of the next Facebook, Instagram, Uber, Lyft, etc... Are you getting ANY of that? Is the experience and skills worth, what I assume, is a lack of money and stock options? On top of that: **What was your initial agreement on hours?** Your boss "instituted" a 6x11 work week... was that immediately? weeks in? Months in? If you agreed to get paid $x for 40 hours - basically $y/hour... you are now getting paid $x for 80 hours... basiclaly $1/2y/hour. If you were paid $30/hour before - you now make $15/hour. (Whatever the actual numbers are - even less because, honestly, you are getting screwed out of overtime). **What are the laws in your country?** There are overtime laws in the US. There are some exclusions for those laws for certain jobs and certain pay rates... Is what your boss doing illegal? if so, you (and your co-workers) could be owed back-pay. I Am Not A Lawyer, so you need to ask one in your locale.
48,611,720
So I'm trying to make a simple web application that takes data from a form and adds them to a table using VueJS. Here is the code: ``` <!DOCTYPE html> <html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <title>Vue test</title> <script src="https://cdn.jsdelivr.net/npm/vue@2.5.13/dist/vue.js"></script> <script src="app.js"></script> </head> <body> <div id="vue-app"> <form> <input type="text" v-model="name"/>{{name}}<br/> <input type="text" v-model="last"/>{{last}}<br/> <input type="text" v-model="index"/>{{index}}<br/> <select v-model="grade"> <option>5</option> <option>6</option> <option>7</option> <option>8</option> <option>9</option> <option>10</option> </select> {{grade}} <button type="submit" v-on:click="add()">Add To Table</button> </form> <table border="1"> <thead><td>Name</td><td>Last Name</td><td>Index</td><td>Grade</td></thead> <tbody> <tr v-for="x in arr"> <td>{{x.first}}</td> <td>{{x.lastn}}</td> <td>{{x.index}}</td> <td>{{x.grade}}</td> </tr> </tbody> </table> </div> <script src="app.js"></script> </body> </html> ``` And here is the script: ``` new Vue ({ el: '#vue-app', data: { name: '', last: '', index: 0, grade: 0, arr: [] }, methods: { add: function () { this.arr.push({first: this.name, lastn: this.last, index: this.index, grade: this.grade}); console.log(1); } } }); ``` However whenever I click the submit button instead of adding the data to the table the page refreshes and nothing is added to the table. Any ideas on what might be causing the problem?
2018/02/04
[ "https://Stackoverflow.com/questions/48611720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8800595/" ]
This is because by default `<button type="submit"/>` in a `<form>` tag will try to submit form and reload the page Check detail at [How do I make an HTML button not reload the page](https://stackoverflow.com/questions/1878264/how-do-i-make-an-html-button-not-reload-the-page) If you prevent the default action on the form, it works. `<form @submit.prevent="add()">`
I've had the same problem when working with forms in Vue and Nuxt. Make sure that there's no errors in the terminal window where you're running your Nuxt app. Then, empty your cache in your browser and everything should work fine.
346,361
I have Ubuntu 13.04 with Gnome 3.8. I installed `compiz`, `CCSM`. I tried to activate Wobbly Windows, but it doesn't work. It was working properly on Ubuntu 10.10 with Gnome. Why it isn't working now?
2013/09/16
[ "https://askubuntu.com/questions/346361", "https://askubuntu.com", "https://askubuntu.com/users/193476/" ]
The wobbly windows is a feature not of Gnome, but of the window manager e.g. Compiz. The Window manager in [Gnome Shell](http://en.wikipedia.org/wiki/GNOME_Shell) is Mutter. and this does does not support Wobbly Windows (yet). There is a [Gnome Shell extension](https://extensions.gnome.org/extension/669/wobbly-windows/) in beta that allows you to get a wobbly window effect. This appears to be buggy currently and is only a beta.
*Gnome shell* does not support wobbly windows. *Wobbly windows* use the default Ubuntu desktop (Unity). *Gnome shell* doesn't use the *compiz window manager*, so you can't configure it using `ccsm`.
10,102,155
I have a COM object (C#, visual studio) with a function that takes a two dimensional array as an in parameter. When I want to access this function via Agilent VEE is is not visible in the Function & Objects browser, and not accessible. If I change the array to be single dimension, is becomes visible right away. I have heard that VEE is not good for dealing with two dimensional arrays, but there should be a workaround. Anyone that knows anything about making com objects with two dimensional arrays visible from vee? Best regards, AK
2012/04/11
[ "https://Stackoverflow.com/questions/10102155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/455479/" ]
COM Automation supports SafeArray as the wrapper type for arrays. The CLR interop layer for COM automatically generates them from a C# array type. But they are equivalent to multi-dimensional arrays, not jagged arrays. There is no equivalent automation type for arrays-of-arrays, they'll be exposed as a single dimensional array of variants where each variant is an array. Enough to trip up a COM client, perhaps, the syntax gets hairy.
Ok, found it, of course two minutes after posting a question. I declared my arrays as jagged arrays, `int [][] array = new [][];`and changed it to`int[,] array = new int [,];` Now it works!
50,643,873
can you show me how to work with Dialogflow with node.js. Where can I find information? For example, here I have found one example in Python, but how to make the same in node.js? Python code: ``` from telegram.ext import Updater, CommandHandler, MessageHandler, Filters import apiai, json updater = Updater(token='ВАШ API ТОКЕН') # Токен API к Telegram dispatcher = updater.dispatcher def startCommand(bot, update): bot.send_message(chat_id=update.message.chat_id, text='Привет, давай пообщаемся?') def textMessage(bot, update): request = apiai.ApiAI('ВАШ API ТОКЕН').text_request() # Токен API к Dialogflow request.lang = 'ru' # На каком языке будет послан запрос request.session_id = 'BatlabAIBot' request.query = update.message.text responseJson = json.loads(request.getresponse().read().decode('utf-8')) response = responseJson['result']['fulfillment']['speech'] if response: bot.send_message(chat_id=update.message.chat_id, text=response) else: bot.send_message(chat_id=update.message.chat_id, text='Я Вас не совсем понял!') start_command_handler = CommandHandler('start', startCommand) text_message_handler = MessageHandler(Filters.text, textMessage) dispatcher.add_handler(start_command_handler) dispatcher.add_handler(text_message_handler) updater.start_polling(clean=True) updater.idle() ```
2018/06/01
[ "https://Stackoverflow.com/questions/50643873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9275608/" ]
As you use it here, `withLatestFrom` will always be executed. You don't need logic to check for items, tweak your structure a bit: ``` @Effect() updateAfterChanges$ = this.actions$.pipe( ofType(ActionTypes.ChangesInItems), switchMap(action => { return this.store.pipe( select(fromReducers.getItemsList), map(items => { return [new UpdateItems()] }), ); }), ) ```
This is an expected behaviour, it's how **withLatestFrom** works, so it will start listening to the given observable **immediately**, but it will only emit the value when source get emitted! This [example](https://stackblitz.com/edit/withlatestfrom-test?file=index.ts) will explain what’s happening: So the console.log inside `test()` will shown immediately but the returned value from `test()` will only shown when the click event triggered
23,311,236
I'm a SQL newbie. I have a postgres table that has datetime, and values. with subminute entries. I want to create a new table that takes the average of each minute and saves that instead of having subminute entries. so something like this: ``` 1-12-07 12:29:56:00 2 1-12-07 12:29:56:16 3 1-12-07 12:29:56:34 3 1-12-07 12:29:56:58 4 1-12-07 12:30:00:00 7 ``` to ``` 1-12-07 12:29:00 3 1-12-07 12:30:00 # ``` Is there a way to do it in postgres? The only solution I can think of is using a python script to do the trick. But that will take forever as I have a significant amount of data.
2014/04/26
[ "https://Stackoverflow.com/questions/23311236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1871528/" ]
Why not using array\_keys()? ``` $new_array = array_keys($array); ```
use `array_keys` function: ``` $keys = array_keys($arr); ``` It returns an array of all the keys in array.
28,824,037
If you are using TestNG you would find that to use a method as a data provider you have to create a method that returns a two dimensional Object array. So if I have a List of (say) Students , is there any utility method to convert it into a two dimensional array. I am **NOT** looking to convert it manually using a loop like this ``` List<Student> studentList = getStudentList(); Object [][] objArray = new Object[studentList.size][]; for(int i=0;i< studentList.size();i++){ objArray[i] = new Object[1]; objArray[i][0] = studentList.get(i); } return objArray; ``` Instead I am looking at a utility function if any is available in any of the libraries. Or a better way of writing a data provider method for TestNG
2015/03/03
[ "https://Stackoverflow.com/questions/28824037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/775603/" ]
So be it ... let stackoverflow call me a tumbleweed ... but here is the answer. ``` List<Student> studentList = getStudentList(); Object [][] objArray = new Object[studentList.size][]; for(int i=0;i< studentList.size();i++){ objArray[i] = new Object[1]; objArray[i][0] = studentList.get(i); } return objArray ```
IT worked for me in single dimension array also, I converted list to single dimension array in testng data provider, Might be useful to someone ``` @DataProvider(name = "Passing List Of Maps") public Object[] createDataforTest3(){ TestDataReader testDataReader = new TestDataReader(); List<String> caselDs = new ArrayList<String>(); caselDs = testDataReader.getValueForThekeyFromTestDataDirectory("testdate,"XYZ"); Object[] data = new String[caseIDs.size()]; for (int i=0;i<caseIDs.size()-1;i++) { data[i]= caselDs.get(i); return data;} @Test(dataProvider = "Passing List Of Maps",description= "abc") public void test(String value) { System.out.println("Value in first Map:" + value); } ```
23,338,511
I'm hoping someone can help with an issue I'm having with RestSharp. It's all working; I'm getting my reply using the following code: ``` var client = new RestClient("http://mybaseuri.com"); var request = new RestRequest("service/{id}", Method.GET); request.AddUrlSegment("id", id); // execute the request IRestResponse response = client.Execute(request); ``` I'd like to get a value from the response headers along the lines of: ``` string userId = response.Headers["userId"] ``` I can't find any examples online, can anyone help get a value from the `response.Headers` object which is of type `IList<parameter>`? I'm not looking to iterate the entire collection, just extract a single value by name.
2014/04/28
[ "https://Stackoverflow.com/questions/23338511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3580862/" ]
Using LINQ: ``` string userId = response.Headers .Where(x => x.Name == "userId") .Select(x => x.Value) .FirstOrDefault(); ``` This requires no knowledge of the index of the element, and deals with the scenario where the header does not exist.
If you know the index of "userId" then you can do the following: ``` string userId = response.Headers.ElementAt(indexOfUserId).Value.ToString(); ```
22,895,299
I want to replace a comma followed by a < br > so I used regex et replace method to do that: ``` var str = "<a class=added> ,,, ,, blbl;test, </a><br>, <a class=added>" str = str.replace(/br>(,\s)/g, " "); alert(str); ``` In the result I noticed that 'br>' was also removed and it is not the exected result. Is there anything wrong with my regex? ``` "<a class=added> ,,, ,, blbl;test, </a>< <a class=added>" ```
2014/04/06
[ "https://Stackoverflow.com/questions/22895299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2578661/" ]
This question is similar to: [How to select option in drop down protractorjs e2e tests](https://stackoverflow.com/questions/19599450/how-to-select-option-in-drop-down-protractorjs-e2e-tests/20308276#20308276) So long as you're on a recent version of protractor, you can just do: ``` element(by.cssContainingText('option', 'BeaverBox Testing')).click(); ``` If you want to click by number, you can do: ``` var selectDropdownbyNum = function ( element, optionNum ) { if (optionNum){ var options = element.findElements(by.tagName('option')) .then(function(options){ options[optionNum].click(); }); } }; ```
As you want to select option by value, you can use: ``` var select = element.one(by.model('selectData')); select.$('[label="Option 1"]').click(); ```
21,597,880
I am having the hardest trouble trying to run SWI-prolog on my Mac. When I type: ``` /opt/bin/local/swipl ``` I get an error saying: ``` /opt/local/bin/swipl: No such file or directory ``` When I just type "swipl" I get: ``` swipl: command not found ``` I've tried this on both terminal and XQuartz. I've even gone into ``` /Applications/SWI-Prolog.app/Contents/MacOS ``` to see if that would do anything, however the prolog "Welcome" text never appears. Quite possibly the closest I ever got it to work was when I typed "pl" when inside the MacOS folder. However I was left with my terminal doing nothing and had to use Crtl-D. Is there something I'm doing wrong? Did I install something incorrectly? I'm running on a Mac OS X 10.9.1 Mavericks. I placed the SWI-Prolog application into my application folder and I also downloaded XQuartz per recommendation by the website.
2014/02/06
[ "https://Stackoverflow.com/questions/21597880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3278629/" ]
There are three sensible ways of installing SWI-Prolog on MacOS X, in increasing order of complexity: 1. Download the SWI-Prolog application. In this case, you just download a disk image, open it, and drag the application to your disk (e.g. to your `Applications` folder. You use the application as any other application by double-clicking on its icon. If you want to also use the binary inside the application bundle, add the `Contents/MacOS` directory inside it to your system path (for example, assuming that you copied the SWI-Prolog application to your applications folder, do `export PATH=/Applications/SWI-Prolog.app/Contents/MacOS:$PATH` in your shell configuration file). 2. Using MacPorts. Assuming it's installed and up-to-date, simply type either `sudo port install swi-prolog` for the stable version or `sudo port install swi-prolog-devel` for the development version. Replace `sudo port install` by `sudo port -u upgrade` when upgrading the installed version. It you're already using MacPorts, then `/opt/local/bin` should already be in your system path. Type `echo $PATH` in a `Terminal` window to check. 3. Compiling from sources. In this case, download the source archive, uncompress it, and follow the instructions in the `README.MacOSX` file.
Homebrew has moved swi-prolog to the top a few days ago and because of this, the other answers are not valid anymore. The reason for that: the swi-prolog formula was located in the x11 bottle but the x11 dependency is only optional. As of today, to install swi-prolog with homebrew, simply do: ``` brew install swi-prolog ``` If you've installed it from the x11 bottle before, consider to uninstall an reinstall from the new location. Otherwise you might run into errors when updating/upgrading.
3,579,531
how do I write an expression which checks for lowcaps, dots, and without any white space in the string? the code below so far was trying to check for lowcaps and dots (it does not work anyway!) but I don't know how to add in the expression for white spaces. ``` # check for matches of lowcaps or lowcaps with a dot if (!preg_match('/([a-z0-9]|[a-z0-9\.])/', $cst_value)) { $error = true; echo ' please use lowcaps only with dot(s) and without any spacing.'; } ```
2010/08/26
[ "https://Stackoverflow.com/questions/3579531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/413225/" ]
`[a-z0-9.]` matches a lower-case letter or a digit or a dot. `[^a-z0-9.]` matches all characters that are not a lower-case letter or a digit or a dot. So if `/[^a-z0-9.]/` matches anywhere the string contains something other than lc-letter,digit or dot. If it does not match your condition is fulfilled. ``` if ( !preg_match('/[^a-z0-9.]/', $cst_value) ) { // only lower-case letters, digits or dots } ``` or without digits ``` if ( !preg_match('/[^a-z.]/', $cst_value) ) { // only lower-case letters or dots } ``` --- update: example: ``` foreach( array('abcdef', 'abc de', 'abc.de', 'aBcde') as $cst_value) { echo $cst_value, ': '; if ( !preg_match('/[^a-z.]/', $cst_value) ) { echo " ok.\n"; } else { echo "failure\n"; } } ``` prints ``` abcdef: ok. abc de: failure abc.de: ok. aBcde: failure ```
``` /^[a-z0-9.]+$)/ ``` Should do it. Just think about that *only small letters, dots and digits are allowed*. The expression will not match if any white-space is included. Btw. you don't have to escape meta-characters in a capture group. `^` and `$` indicates that the whole string should only contain those characters in the capture group (they mark the start and the end of the string) and the `+` says that at least one of these characters must occur. Depending on your needs you can change it to e.g. `{3,}` which means that the string must be at least 3 characters long. Example: ``` $values=array("fooBar", "123.45", "foo bar", "foo.bar"); foreach($values as $value) { if (!preg_match('/^[a-z0-9.]+$/', $value)) { echo "Not valid: $value\n"; } } ``` prints: ``` Not valid: fooBar Not valid: foo bar ```
43,773,952
How can I list all uppercase/lowercase permutations for any letter specified in a character array? So, say I have an array of characters like so: ['h','e','l','l','o'] and I wanted print out possible combinations for say the letter 'l' so it would print out [hello,heLlo,heLLo,helLo]. This is what I have so far(the only problem is that I can print the permutations however I'm not able to print them inside the actual word. so my code prints [ll,lL,Ll,LL] instead of the example above. my code: ``` import java.util.ArrayList; import java.util.HashSet; public class Main { public static void main(String[] args) { //Sample Word String word = "Tomorrow-Today"; //Sample Letters for permutation String rule_char_set = "tw"; ArrayList<Character> test1 = lettersFound(word, rule_char_set); printPermutations(test1); } public static void printPermutations(ArrayList<Character> arrayList) { char[] chars = new char[arrayList.size()]; int charIterator = 0; for(int i=0; i<arrayList.size(); i++){ chars[i] = arrayList.get(i); } for (int i = 0, n = (int) Math.pow(2, chars.length); i < n; i++) { char[] permutation = new char[chars.length]; for (int j =0; j < chars.length; j++) { permutation[j] = (isBitSet(i, j)) ? Character.toUpperCase(chars[j]) : chars[j]; } System.out.println(permutation); } } public static boolean isBitSet(int n, int offset) { return (n >> offset & 1) != 0; } public static ArrayList<Character> lettersFound(String word, String rule_char_set) { //Convert the two parameter strings to two character arrays char[] wordArray = word.toLowerCase().toCharArray(); char[] rule_char_setArray = rule_char_set.toLowerCase().toCharArray(); //ArrayList to hold found characters; ArrayList<Character> found = new ArrayList<Character>(); //Increments the found ArrayList that stores the existent values. int foundCounter = 0; for (int i = 0; i < rule_char_setArray.length; i++) { for (int k = 0; k < wordArray.length; k++) { if (rule_char_setArray[i] == wordArray[k]) { found.add(foundCounter, rule_char_setArray[i]); foundCounter++; } } } //Convert to a HashSet to get rid of duplicates HashSet<Character> uniqueSet = new HashSet<>(found); //Convert back to an ArrayList(to be returned) after filtration of duplicates. ArrayList<Character> filtered = new ArrayList<>(uniqueSet); return filtered; } } ```
2017/05/04
[ "https://Stackoverflow.com/questions/43773952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5016598/" ]
Sanket Makani answer is perfect. I may offer a more objective approach of this problem. As an input you have a string to modify, and characters, which should be replaced with the modified case ( upper or lower ). As an output you will have all permutated strings. I would create a structure which contains index, and possible values to change with: ``` class Change { int index; char values[]; } ``` We will need to make all possible combinations, so lets include field which will tell which character is currently used in to our structure, and add some methods: ``` class Change { int index; char values[]; int cur; void reset() {cur=0;} boolen isMax(){return cur==values.length-1;} void next(){cur++;} char getValue(){ return values[cur]; } } ``` We will have a list or array of these classes then, which we will put in to a separate class ``` class Combination { Change changes[]; void reset() { for (Change c: changes) c.reset();} boolean next() { for ( int i=0; i<changes.length; i++) if ( changes[i].isMax()) changes[i].reset(); // next change will be taken in cycle, with "next()" else {changes[i].next(); return true;} return false; // all changes are max } } ``` So when you initialize your "Combination" class by your input data, you may use it in cycle then. ``` Combination c = new Combination(); .... // initialization here c.reset(); do { ... // update and print your string } while ( c.next() ); ``` The initialization of "Combination" and using of values for updating the input string I leave after you :)
For the permutation case, I think recursion is the best fit in terms of readability, taking into account that maybe is not best in terms of performance. My approach would be this: ``` public static void main(String[] args) { generateCombinations("hello", "l", ""); } public static void generateCombinations(String text, String changingLetters, String current) { if (0 == text.length()) { System.out.println(current); return; } String currentLetter = text.substring(0, 1); if (changingLetters.contains(currentLetter)) { generateCombinations(text.substring(1), changingLetters, current + currentLetter.toUpperCase()); } generateCombinations(text.substring(1), changingLetters, current + currentLetter); } ``` The output for the main execution will be: ``` heLLo heLlo helLo hello ```
59,334,343
I'm trying to fill missing value with R. If all other value is 0, then I want to fill missing with 0. An example is shown below. In this data, All value in `c` column except `NA` is 0. So, I want to fill `Na` with 0. ``` set.seed(1000) a<-rnorm(10) b<-rnorm(10) c<-rep(0,10) c[c(2,4,8)]<-NA test<-cbind(a,b,c) a b c [1,] 0.1901328 0.6141360 0 [2,] -0.9884426 0.6508993 NA [3,] -0.9783197 2.1059862 0 [4,] -1.8584651 0.4354903 NA [5,] 0.6623067 1.6382126 0 [6,] -1.2542872 0.1370791 0 [7,] -1.9971880 1.9302738 0 [8,] 1.9417941 0.0449239 NA [9,] 1.7046508 1.0726263 0 [10,] -0.7289351 -2.8374912 0 ``` I can't find a good example of code. Would you give me a good advice?
2019/12/14
[ "https://Stackoverflow.com/questions/59334343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11275093/" ]
Quick value, if all your columns are numeric: ``` colSums(!is.na(test)) == colSums(test==0,na.rm=TRUE) a b c FALSE FALSE TRUE ``` We change the TRUE columns ``` wh = which(colSums(!is.na(test)) == colSums(test==0,na.rm=TRUE)) for(i in wh){test[is.na(test[,i]),i] = 0} a b c [1,] -0.44577826 -0.98242783 0 [2,] -1.20585657 -0.55448870 0 [3,] 0.04112631 0.12138119 0 [4,] 0.63938841 -0.12087232 0 [5,] -0.78655436 -1.33604105 0 [6,] -0.38548930 0.17005748 0 [7,] -0.47586788 0.15507872 0 [8,] 0.71975069 0.02493187 0 [9,] -0.01850562 -2.04658541 0 [10,] -1.37311776 0.21315411 0 ```
First convert `test` into data frame to access `$` operator ``` set.seed(1000) a<-rnorm(10) b<-rnorm(10) c<-rep(0,10) c[c(2,4,8)]<-NA test<-cbind(a,b,c) test <- data.frame(test) ``` Convert variable `c` into a factor and create a level "0", if `test$c` is "NA" ``` test$c <- as.factor(test$c) test$c[is.na(test$c)] <- "0" ``` Check test data set for 'NA' are replaced by '0' ``` test a b c -0.44577826 -0.98242783 0 -1.20585657 -0.55448870 0 0.04112631 0.12138119 0 0.63938841 -0.12087232 0 -0.78655436 -1.33604105 0 -0.38548930 0.17005748 0 -0.47586788 0.15507872 0 0.71975069 0.02493187 0 -0.01850562 -2.04658541 0 -1.37311776 0.21315411 0 ```
222,284
To start off, I'm not a physicist but a programmer, and only had a few years of physics education in high school so I'm sorry if I'm asking a stupid question. I just finished watching the movie [Gravity](http://www.imdb.com/title/tt1454468/) (2013) and I found online already a whole list of things wrong with the movie, but there are two things that I think is wrong that I couldn't find: * The premise of the movie is that a satellite is hit by a missle which causes debris setting off a chain reaction leading to the catastrophic destruction of space stations and space shuttles. Is it true that debris can stay in orbit at the same height as space stations, while having a very large relative speed to the space stations? It was my understanding that if the velocity of objects change, then also its orbit altitude (given a circular orbit), right? * In the end, the main character gets to the Chinese space station, which is already deorbiting although it seems structurally intact. Is it possible for the intact station to deorbit, simply by getting a little bit hit (it couldn't have been much since it was still mostly intact)?
2015/12/04
[ "https://physics.stackexchange.com/questions/222284", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/100459/" ]
> > Is it true that debris can stay in orbit at the same height as space stations, while having a very large relative speed to the space stations? > > > Most [LEO](https://en.wikipedia.org/wiki/Low_Earth_orbit) objects orbit in the same direction, namely the direction the Earth rotates. This is done to take advantage of the initial speed supplied by the [Earth's rotation](https://en.wikipedia.org/wiki/Earth%27s_rotation). So the main velocity difference would likely be due to different [inclinations](https://en.wikipedia.org/wiki/Orbital_inclination) (i.e., not in the same plane) or [elliptical](https://en.wikipedia.org/wiki/Elliptic_orbit) vs. [circular](https://en.wikipedia.org/wiki/Circular_orbit) orbits. Let's make it simple and assume that two objects, **E** and **I**, both have circular orbits at the same altitude, thus they have the same orbital speed. However, let us assume object **I** has an inclined orbit at some angle $\alpha$ to the equatorial plane and that they orbit in the same azimuthal direction. Now the when we move into the frame of, say, the equatorial orbiting object the inclined object will appear to be coming from ahead of you. If the inclined orbit is from south-to-north(north-to-south), then object **I** would appear to be coming at you from the south(north) and from ahead of you. This is just from the vector subtraction, where: $$ \mathbf{V}\_{I} - \mathbf{V}\_{E} = -\mathbf{V}\_{rel} \tag{1} $$ or $$ \mathbf{V}\_{E} = \mathbf{V}\_{I} + \mathbf{V}\_{rel} \tag{2} $$ where $\lvert \mathbf{V}\_{E} \rvert = \lvert \mathbf{V}\_{I} \rvert$ we have defined: $$ \begin{align} \mathbf{V}\_{E} & \sim V\_{E} \ \hat{\mathbf{x}} \tag{3a} \\ \mathbf{V}\_{I} & \sim V\_{I} \left( \cos{\alpha} \ \hat{\mathbf{x}} + \sin{\alpha} \ \hat{\mathbf{y}} \right) \tag{3b} \end{align} $$ **Note:** I really should be doing this in [spherical trigonometry](http://mathworld.wolfram.com/SphericalTrigonometry.html), but let's only concern ourselves with the immediate region of interaction so we can take the limit as the radius of curvature goes to infinity. As you can see, $\mathbf{V}\_{rel}$ is given by: $$ \mathbf{V}\_{rel} = V\_{E} \left[ \left( 1 - \cos{\alpha} \right) \hat{\mathbf{x}} - \sin{\alpha} \hat{\mathbf{y}} \right] \tag{4} $$ which shows that $\lim\_{\alpha \rightarrow 0} \mathbf{V}\_{rel} = 0$, as expected. The maximum of $\lvert \mathbf{V}\_{rel} \rvert$ occurs in the limit as $\alpha \rightarrow \pi/2$, which is $\sim \sqrt{2} \ V\_{E}$. The typical orbital speed of a LEO object is ~7-8 km/s (or ~25,200-28,800 kph = ~15,700-17,900 mph), so the maximum impact speed is going to be ~10-11 km/s (or ~35,600-40,700 kph = ~22,100-25,300 mph). So the short answer to your question is yes. If the objects were orbiting in opposite directions, then the maximum of $\lvert \mathbf{V}\_{rel} \rvert$ would increase, of course. Regardless, unless $\alpha \ll 1$, $\lvert \mathbf{V}\_{rel} \rvert$ is going to be large for all intents and purposes. > > Is it possible for the intact station to deorbit, simply by getting a little bit hit (it couldn't have been much since it was still mostly intact)? > > > I am going to guess no because of my response to the previous part. A space station has a great deal of linear and angular momentum. To exert enough force and torque to change those would require high impact speeds. Since most of the space station's outer hull is very thin, the end result would not be the entire object being "shoved" to a different altitude. Rather, the impacting object would probably just tear through the station and/or [ablate](https://en.wikipedia.org/wiki/Ablation) on impact. **More Important Note** ======================= In the movie, the characters are able to see the objects moving towards them. If we assume that the objects are moving at, say, $\alpha \sim \pi/6$ to the space station's plane, then $\lvert \mathbf{V}\_{rel} \rvert \sim \sqrt{2 - \sqrt{3}} V\_{E}$. If we assume the same values as above for LEO orbits, then $\lvert \mathbf{V}\_{rel} \rvert$ ~3.6-4.1 km/s (or ~13,000-14,900 kph = ~8,100-9,200 mph). These values correspond to [Mach](https://en.wikipedia.org/wiki/Mach_number) ~ 10-12 at sea level. For comparison, the [muzzle velocity](https://en.wikipedia.org/wiki/Muzzle_velocity) of a bullet from a high powered [rifle](https://en.wikipedia.org/wiki/Rifle) varies from Mach ~ 1.8-3.6, depending on the caliber and model. I am inclined to think that were this situation to really occur, a human would not be able to see the incident objects unless they were very large because of the lighting conditions and the speed at which the objects were moving. A more accurate portrayal would have shown parts of the space station just disappearing and/or exploding. There would not have been the nice, slow moving objects flying by that destroyed everything. **Update** ========== When we look at the full range of muzzle velocities from a [list of cartridges](https://en.wikipedia.org/wiki/Table_of_handgun_and_rifle_cartridges), we find handguns/pistols range from ~304–515 m/s and rifles range from ~600–1392 m/s. I plotted the relative speed between two orbiting objects as a function of inclination (i.e., Equation 4 above) shown in the following image. [![relative speeds](https://i.stack.imgur.com/7UdhK.jpg)](https://i.stack.imgur.com/7UdhK.jpg) As shown, after even only ~3-4 degrees the speed differences exceed most handgun round muzzle speeds and after ~11 degrees nearly all civilian rifle rounds.
* The satellite did not start in the ISS orbit, and not all orbits are circles. The ISS orbit is free of large satellites. So the fictional one from the movie was in a different orbit. Therefore it's not too difficult to believe that debris from it would have a high relative velocity. The debris might have been in a very elliptical orbit with a large range of altitudes. It's not even necessary for them to have different altitudes. As long as they intersect at an angle, the relative speeds will be very high. (Much higher than would be useful for a movie). That doesn't mean that the action depicted in the movie was accurate, just that any intersection would likely be at very high closing speeds. * By large objects, no. If the other space station had been hit by debris, it would have been damaged. High-speed impacts can't change the momentum of the entire station much. The material gives way before forces build up much, and the interaction time is low. Deorbit happens over a much longer period of time due primarily to atmospheric drag.
8,360
I want to make a column in a relation unmodifyable for consistency reasons. The backstory is that I have a n:n relationship where the "connecting" relation has additional values. I don't want that anyone is able to change the IDs of the relationship partners. What I have come up with so far: Creating a trigger that checks if the NEW value is the same as the OLD value. But I don't know how to deny the UPDATE action if the condition proves as TRUE. Here is my trigger so far: ``` CREATE TRIGGER deny_nton_change BEFORE UPDATE ON Schueler_in_Klasse FOR EACH ROW BEGIN IF NEW.Schueler_ID != OLD.Schueler_ID OR NEW.Klasse_ID != OLD.Klasse_ID THEN END IF; END; ```
2011/11/24
[ "https://dba.stackexchange.com/questions/8360", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/4689/" ]
[I actually learned a back-alley approach to aborting triggers](https://dba.stackexchange.com/q/2368/877). It is very crude, but works because SIGNAL processing is not implemented in MySQL's Stored Procedure Language. It can be emulated at best. Chapter 11, Pages 254-256 of the book **[MySQL Stored Procedure Programming](http://rads.stackoverflow.com/amzn/click/0596100892)** under the subheading **'Validating Data with Triggers'** suggests making a SELECT of a character string into a dummy integer (in terms of syntax, it is correct, but dies on execution [NO PUN INTENDED]): ``` CREATE TRIGGER deny_nton_change BEFORE UPDATE ON Schueler_in_Klasse FOR EACH ROW BEGIN DECLARE dummy INT; IF NEW.Schueler_ID != OLD.Schueler_ID OR NEW.Klasse_ID != OLD.Klasse_ID THEN SELECT 'Cannot Carry Out This Trigger Any Further' INTO dummy FROM table_you_know_does_not_exist WHERE 1=1 LIMIT 1; END IF; END; ```
It is actually possible to do this neatly without using triggers if you are using InnoDB. Create another table with just one column. That column should have a foreign key (hence the innodb requirement in this solution) that points to the immutable column of the original table in question. Put a restriction like "ON UPDATE RESTRICT". In summary: ``` CREATE TABLE original ( .... immutable_column ... INDEX index1(immutable_column) .... ) ENGINE=INNODB; CREATE TABLE restricter ( ..... col1, INDEX index2(col1), FOREIGN KEY (col1) REFERENCES original (immutable_colum) ON UPDATE RESTRICT ON DELETE CASCADE ) ENGINE=INNODB; ```
66,863,200
I am using Vite (<https://vitejs.dev/>) for a static multipage site. This is the default project folder structure after the build command. ``` my-app/ ├─ node_modules/ ├─ dist/ │ ├─ assets/ │ ├─ index.html ├─ index.html ├─ main.js ├─ style.scss ├─ package.json ``` But I want to make this a multipage site and change the input and output directory for a better organizable way like this ``` my-app/ ├─ node_modules/ ├─ package.json ├─ src/ │ ├─ about.html │ ├─ index.html │ ├─ main.js │ ├─ style.scss ├─ dist/ │ ├─ assets/ │ ├─ about.html │ ├─ index.html ``` Basically, it should take the `src` as an input folder and output `dist` as a child of the `my-app`. When I try to do this it shows errors, then I change the scripts of the `package.json` into this ``` "scripts": { "dev": "vite src", "build": "vite build src", "serve": "vite preview" }, ``` This way the `dev`command works fine. But the 'build' command makes the dist folder inside the `src` folder and does not generate other HTML files except `index.html`. Now how can I fix this? Any suggestion?
2021/03/30
[ "https://Stackoverflow.com/questions/66863200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5705914/" ]
Create a `vite.config.js` file and define your project root and output directory as such: ```js module.exports = { root: 'src', build: { outDir: '../dist' } } ``` For more info, checkout [config](https://vitejs.dev/config/#build-outdir).
When you want to use defineConfig in your vite.config.ts you can use it like this: ```js import { defineConfig } from 'vite' import reactRefresh from '@vitejs/plugin-react-refresh' import eslintPlugin from 'vite-plugin-eslint' // https://vitejs.dev/config/ export default defineConfig({ plugins: [reactRefresh(), eslintPlugin({ cache: false })], root: 'src', build: { outDir: '../dist' } }) ```
13,830,647
I have a form ``` <form name="loginForm" method="POST"> Username: <input type="text" name="username" value="" /> <br /> Password: <input type="password" name="password" value="" /> <input type="submit" name="submitButton" /> </form> ``` How do I take the information above after hitting the submit button, and do something with said data? Such as, ``` <script> function checkLogin(){ //some code here } </scipt> ``` I really want to know how to use the SUBMIT button, and not just onClick.
2012/12/12
[ "https://Stackoverflow.com/questions/13830647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896252/" ]
Use the onSubmit event: HTML: ``` <form name="loginForm" method="POST" onsubmit="checkLogin()"> Username: <input type="text" name="username" value="" /> <br /> Password: <input type="password" name="password" value="" /> <input type="submit" name="submitButton" /> </form> ``` Script: ``` function checkLogin(){ // If you return "false" it will stop the form from being submitted } ```
You will use $.post in the following way { ``` $.post(URL_TO_YOUR_SCRIPT, { username: $("#username").val(), password: $("#password).val() }, function(data) { alert(data); }); ``` to achieve this, you will have to give ID's to your input boxes like ``` <input type="text" name="username" id="username" /> <input type="password" name="password" id="password" /> ``` Cheers!
52,187,980
Having a lot of trouble solving this (I looked through other posts with the same problem but unfortunately I didn't have much luck in applying proposed solutions to my situation). I have a single (very large) table with transactional information. One of the columns is Transaction Execution Time (field type Time). Execution Time is usually <1 sec but it can go up to a couple of minutes. Daily, Weekly, Monthly and Yearly transaction reports need to be available and they need to contain average transaction time. Due to large number of entries I am facing overflow when doing average/sum. Here is a (simplified) sample I am using to test: ``` SELECT DATEPART (YEAR, TimeStamp) as 'Year', COUNT(*) as 'Transaction count', AVG((DATEDIFF(MILLISECOND, '0:00:00',ExecutionTime))) as 'Average execution time', SUM((DATEDIFF(MILLISECOND, '0:00:00',ExecutionTime))) as 'Total execution time' FROM RecordedTransactions GROUP BY DATEPART (YEAR, TimeStamp) ``` What would be the best approach to solve the overflow?
2018/09/05
[ "https://Stackoverflow.com/questions/52187980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3760419/" ]
The complete solution to this problem consists of three steps: **STEP 1**: In the `onCreate()` of your `BaseActivity` (or all your `Activity`s), set the `Locale` as follows: ``` @Override protected void onCreate(Bundle savedInstanceState) { // set the Locale the very first thing Utils.setLocale(Utils.getSavedLocale()); requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); ...... ...... } ``` where `getSavedLocale()` is the `Locale` corresponding to the current region (this will be specific for your project ... ). And the method `Utils.setLocale(...)` is defined as follows: ``` public static void setLocale(Locale locale){ Context context = MyApplication.getInstance(); Resources resources = context.getResources(); Configuration configuration = resources.getConfiguration(); Locale.setDefault(locale); configuration.setLocale(locale); configuration.setLayoutDirection(locale); // updateConfiguration(...) is deprecated in N if (Build.VERSION.SDK_INT >= 25) { context = context.getApplicationContext().createConfigurationContext(configuration); context = context.createConfigurationContext(configuration); } context.getResources().updateConfiguration(configuration, resources.getDisplayMetrics()); } ``` This sets the correct `Locale` in every `Activity`. This is enough for apps supporting API level 25. For API level 26 & above, STEP 2 and STEP 3 are also required. **STEP 2**: Override the following method in your `BaseActivity`: ``` @Override protected void attachBaseContext(Context newBase) { newBase = Utils.getLanguageAwareContext(newBase); super.attachBaseContext(newBase); } ``` where the function `getLanguageAwareContext(...)` is defined as follows: ``` public static Context getLanguageAwareContext(Context context){ Configuration configuration = context.getResources().getConfiguration(); Locale locale = getIntendedLocale(); configuration.setLocale(locale); configuration.setLayoutDirection(locale); return context.createConfigurationContext(configuration); } ``` This, along with STEP 1, sets the correct `Locale` in every `Activity` of your app for API level 26 and above. One more step, however, is required for setting the language direction correctly ... **STEP 3**: In the `onCreate()` of your `BaseActivity`, add the following code: ``` @Override protected void onCreate(Bundle savedInstanceState) { .... .... // yup, it's a legit bug ... :) if (Build.VERSION.SDK_INT >= 26) { getWindow().getDecorView().setLayoutDirection(Utils.isRTL() ? View.LAYOUT_DIRECTION_RTL : View.LAYOUT_DIRECTION_LTR); } .... .... } ``` where the `isRTL()` function is defined as follows: ``` public static boolean isRTL(){ return TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == View.LAYOUT_DIRECTION_RTL; } ``` The above steps should take care of all issues (at least regarding setting the `Locale` and text direction) on all extant versions of Android.
``` public void setLocale(final Context ctx, final String lang) { AppSettings.getInstance(ctx).save(PrefKeys.language, lang); final Locale loc = new Locale(lang); Locale.setDefault(loc); final Configuration cfg = new Configuration(); cfg.locale = loc; ctx.getResources().updateConfiguration(cfg, null); } ``` Change to English: `setLocale(getActivity(), "en";` Change to Arabic : `setLocale(getActivity(), "ar");` After this you need to restart the application to get the Language change effects.
15,289,059
Hello I am trying to install Java on my mac with osx 10.8.2. If I am typing `java -version` in the terminal, I get the following error: `No Java runtime present, requesting install. 2013-03-08 08:36:03.477 java[1192:707] JLRequestRuntimeInstall: Error calling: CFMessagePortCreateRemote` Yesterday I completely uninstalled java 6 from my pc with `sudo rm -fr /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin` After downloading Java 7u17 from the oracle site and installing it, the installer said that Java was completely installed. I typed again `java -version` and it gave me the same error (No Java Runtime present). Do you know any solution for this problem?
2013/03/08
[ "https://Stackoverflow.com/questions/15289059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1979703/" ]
I finally fixed it by uninstalling everything with java and installing the java packet with the sdk.
Install the JDK from [Java JDK](http://www.oracle.com/technetwork/java/javase/downloads/index.html) - Follow the instructions from: [here](http://docs.oracle.com/javase/8/docs/technotes/guides/install/mac_jdk.html) Once installed run `java -version` again.
7,011,494
I have declared an int e.g. int i; I have a method that is looped: ``` public static void NumberUp(int i) { i++; System.Console.WriteLine(i); ... } ``` although each time the number is returned, it is always 1. Not 1,2,3 and so on.. I would have imagined that "i" increases by one which each run of the method?
2011/08/10
[ "https://Stackoverflow.com/questions/7011494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/887901/" ]
You can pass the variable [by reference](http://msdn.microsoft.com/en-us/library/14akc2c7.aspx). ``` public static void NumberUp(ref int i) { i++; System.Console.WriteLine(i); ... } ``` This, however is bad design, as you now have a method with a side effect on the passed in parameter (which the method name doesn't indicate) - something that can catch other programmers by surprise. It would be a better design to return the incremented value: ``` public static int NumberUp(ref int i) { return i + 1; } ```
It would be better to define `NumberUp` like this ``` public static int NumberUp(int number) { System.Console.WriteLine(++number); return number; } ``` Then assign the return value in your loop.
20,345,201
I want get the id of the element that is clicked and within a specified class, and want to print the ID. Here is my JS , I am really new JS , Please help ``` $('.wrapinner').click(function(e) { $('.wrapinner').css("margin-top","0"); $('.wrapinner').css("opacity","0.4"); $(this).css("margin-top","25px"); $(this).css("opacity","1"); var r= document.getElementById(this).attributes.toString(); document.write(r); }); ```
2013/12/03
[ "https://Stackoverflow.com/questions/20345201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2429059/" ]
You can call the native javascript object directly; `this.id`. ``` $('.wrapinner').click(function(e) { $('.wrapinner').css("margin-top","0").css("opacity","0.4"); // chained these two $(this).css("margin-top","25px").css("opacity","1"); // chained these two var r = this.id; // this should already reference the correct element. document.write(r); }); ```
**Try this example:** ``` <table> <tbody> <tr id="CustomerScreen" class="rows"></tr> <tr id="TraderScreen" class="rows"></tr> <tr id="DistributorScreen" class="rows"></tr> </tbody> </table> <script> $('.rows').each(function () { var ar = this.id; console.log(ar); }); </script> ```
5,819,297
Do you know any C# based "puzzles and answers" like book? Article? Resource? Why I am asking this is to enlarge my vision with some interesting quiz-like scenarios; to force myself think in a different way and which I can maybe have an advantage on unexpected interview questions. Thanks!
2011/04/28
[ "https://Stackoverflow.com/questions/5819297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/136141/" ]
Although it's not specific to C#, [Project Euler](http://projecteuler.net/) is a lot of fun.
A StackExchange site: [Programming Puzzles & Code Golf](https://codegolf.stackexchange.com/)
29,278,480
I have an array of objects, an example of a few of them being ``` [ { "lang_code": "eng", "site_language": "1", "name": "English" }, { "lang_code": "afr", "site_language": "1", "name": "Afrikaans" }, { "lang_code": "ale", "site_language": "0", "name": "Aleut" }, ] ``` I want to be able to search the whole array for a specific `lang_code`, let's say I use `eng`. I want to search the whole array for `eng`. If it's there, I want it to return `English`, if not, I want it to return `invalid`. Any ideas on this?
2015/03/26
[ "https://Stackoverflow.com/questions/29278480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4622086/" ]
How about a `for` loop. Something like: ``` function find_lang(input_arr, lang_code) { for(var i = 0; i < input_arr.length; i++) { var o = input_arr[i]; if( o.lang_code === lang_code ) { return o.name; } } return "invalid"; } ```
You could do it this way: ``` // configure your parameters function checkArr(){ for (var i = 0; i < x.length; i++){ if (x[i].lang_code == "eng") return "English"; } return "invalid"; } var x = [ { "lang_code": "eng", "site_language": "1", "name": "English" }, { "lang_code": "afr", "site_language": "1", "name": "Afrikaans" }, { "lang_code": "ale", "site_language": "0", "name": "Aleut" } ]; ```
14,840,984
I'm running two libraries that are dependency aware. What I mean is the order of their execution does not matter. They will detect each other and run in any order. ``` script1.js script2.js ``` Would I benefit by running these scripts in parallel ([parallel processing](http://en.wikipedia.org/wiki/Parallel_processing)) using web workers? ([MDN Doc](https://developer.mozilla.org/en-US/docs/DOM/Worker)) I mean would they run faster than if I just ran them serially? Both scripts are already available on the client ( I don't have to download them ).
2013/02/12
[ "https://Stackoverflow.com/questions/14840984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
No, javascript is executed on a single thread in the web browser. So you cannot run them in parallell unless they are not user interactive (does not interact with the DOM). However, you can LOAD the script asynchronously to speedup initialization. Simply use the `async=true` attribute on `<script>`. Like this: ``` <script async="async">....</script> ```
My bet, **YES**. Its like asking `1 man takes 6 days to do a task. How much time will 2 men take?` :-) Most **ideal** use-case for WebWorkers
60,500,654
I tried to fill the whole screen with black using `flex: 1`. but the result is like this [![resuls in iphone simulator](https://i.stack.imgur.com/7GpYd.png)](https://i.stack.imgur.com/7GpYd.png) [![result in my android devices](https://i.stack.imgur.com/dO7DN.jpg)](https://i.stack.imgur.com/dO7DN.jpg) ``` <View style={{ flex: 1, backgroundColor: 'black', }} /> ``` i've also tried using: ``` height: '100%', width: '100%', ``` and ``` const HEIGHT = Dimensions.get('window').height; const WIDTH = Dimensions.get('window').width; ``` but the result is still the same. is there a way to completely fill the whole screen?
2020/03/03
[ "https://Stackoverflow.com/questions/60500654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10207535/" ]
First import: ``` import { StatusBar } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; ``` Change your layout to: ``` <StatusBar backgroundColor="black" barStyle="white-content"/> <SafeAreaView style={{ flex: 1, backgroundColor: 'black', }} > <View>...</View> </SafeAreaView> ```
You can user Dimensions.get('window') to get the full height and width of the screen. declare a const ``` const HEIGHT = Dimensions.get('window').height; const WIDTH = Dimensions.get('window').width; ``` then use this inside style ``` style = {{ height = HEIGHT, width = WIDTH, backgroundColor = 'black', }} ```
19,145,999
I'm using YQL to fetch a bunch of pages, some of which could be offline (obviously I don't know which ones). I'm using this query: ``` SELECT * FROM html WHERE url IN ("http://www.whooma.net", "http://www.dfdsfsdgsfagdffgd.com", "http://www.cnn.com") ``` Where the first and the last one are actual sites, while the second one obviously doesn't exist. Two results are actually returned but the url from where they were loaded doesn't appear anywhere. So what would be the way to find out which html page belongs to which url, if not every page in the query is loaded?
2013/10/02
[ "https://Stackoverflow.com/questions/19145999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774236/" ]
Unfortunately, I do not know a way where you can get a key=>value pair in the response where key being the url and value being the html response. But, you can try the following query and see if it meets your use case: ``` select * from yql.query.multi where queries="select * from html where url='http://www.whooma.net';select * from feed where url='http://www.dfdsfsdgsfagdffgd.com';select * from html where url='http://www.cnn.com'" ``` Try it [here](http://tinyurl.com/kydw8nn). What you can do is before firing the query, maintain the order in an array of the `url` in the `queries` like so `['http://www.whooma.net','http://www.dfdsfsdgsfagdffgd.com','http://www.cnn.com']`. We can call this array `A` When you iterate over the response from the YQL query, the url which does not exists will return a null. A sample response from the above query: ``` <results> <results> // Response from select * from html where url='http://www.whooma.net'. This should be some html </results> <results> // Response from select * from feed where url='http://www.dfdsfsdgsfagdffgd.com'. This should be null. </results> <results> // select * from html where url='http://www.cnn.com'. This should also be some html </results> </results> ``` So in conclusion, you can iterate over array `A` and response from YQL. The first element of array `A` should correspond to the first `results`(inner results) element of that YQL response. i.e You are creating a hashmap from two arrays. I know the answer is long but I think it was needed. Let me know if there is any confusion.
You can figure out which urls aren't loading by using the YQL diagnostics flag. The diagnostics flag will cause the response to include a `diagnostics` property with a `url` array that indicates whether the corresponding servers were found. Presumably, once you eliminate the urls that didn't load, the result pages will match up with the remaining urls.
20,544,017
**Hi All** I'm running: EXT.KEY: news on TYPO3 v. 6.1 with FLUID/EXTBASE. I have 2 issue's/question. 1 - News Tag's disappear, when using "tag list" in plugin. ========================================================== I have added a "tag list" as element on my TYPO3 page, and its working fine, my problem is when i add another news plugin on another page, it's showing all the tag's from the two news plugin setup and I dont what to do that, so if i go to "Startingpoint" in Settings/plugin for the "Tag List" news-element and set it to the folder I save my newslist1 in, then all the tag's are disappeared, how can I set the "Tag list" so it's only show the tag's thats in the news from the folder "Newslist1"? I have done this "startingpoint" with the list show and its working fine, if at news page 1 it show the news from folder "newslist1" and if on news page 2 it shows only the news/items from folder "portfolio". 2 - more images for a news. =========================== Is it possible to add some image for the news text, so i have 2-3 images in the site, like when u add a normal text/image element?
2013/12/12
[ "https://Stackoverflow.com/questions/20544017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/514993/" ]
Split your functions so that they do *one thing*. ``` def switch_x_with_y(line): return line.replace("x", "y") def replace_z_with_a(line): return line.replace("z", "a") f_output = open("output.txt", "w") for line in open("input.txt", "r"): line = replace_x_with_y(line) line = replace_z_with_a(line) f_output.write(line) ``` Most importantly, split off the file handling stuff from the actual processing stuff.
Your question is poorly written. Any way if you want to keep data and do some processing you can use [pandas](http://pandas.pydata.org/pandas-docs/dev/dsintro.html) `DataFrame`s. ``` import pandas as pd import numpy as np from pandas import read_csv df = pd.read_csv('input.txt') df.columns = ['col'] #I suppose you don't need to split data df['col'] = misc['col'].str.replace('x', 'y') ```
298,130
I have a win 2003 DC that has failed and i'm trying to clean up the metadata using ntdsutil as per instructions from <http://www.petri.co.il/delete_failed_dcs_from_ad.htm> and <http://support.microsoft.com/kb/216498> At the "remove selected server" step i get the following error > > DsRemoveDsServerW error 0x5(Access is denied.) > > > Any advice on how to proceed. This is a Win2008 r2 box and of course i'm logged on with full access Rights. All PC clients can log on successfully and dcdiag shows no errors except for failed replications to this non-existing DC.
2011/08/05
[ "https://serverfault.com/questions/298130", "https://serverfault.com", "https://serverfault.com/users/49410/" ]
You posted that you have full access Rights, but are you a member of the Enterprise Admin group? During a demotion, I ran into a few issues because at the time, I was only a Domain Admin. Once added to the Enterprise Admin group, I was able to complete the demotion.
Under AD Sites and Services, go to the NTDS folder of the server. Look at the properties. Under the Object tab, make sure "Protect object from accidental deletion" is unchecked.
2,702
En algunas ediciones del [translation-golf](https://spanish.stackexchange.com/questions/tagged/translation-golf "show questions tagged 'translation-golf'"), el texto original tiene referencias a números, expresadas en algunos casos con cifras y en otros con letras. Por poner un ejemplo, en [la edición XIV](https://spanish.stackexchange.com/q/21724/12637) el texto a traducir contenía un número en cifras: > > *E nella camera 200 note* > > > y en las traducciones nadie lo expresó de ninguna otra forma. A fin de cuentas, "200" ya tiene muy pocos caracteres y no necesita ser reducido más. Pero en otras ediciones, los textos sí contienen referencias a cantidades expresadas con letras: > > *...six-limbed, with six tiny eyes set all around its body...* > > > [En aquella ocasión](https://spanish.stackexchange.com/q/20863/12637) pareció que todos respetaron aquello y en las traducciones propuestas pone "seis". Sin embargo, en otras ediciones han salido [textos como este](https://spanish.stackexchange.com/q/22308/12637): > > *...and a hundred baby spiders came out...* > > > y las traducciones mencionaban "cien" hasta que alguien propuso "100" y se abrió el debate sobre si se debía permitir eso o no. Así pues, debatamos correctamente para ver si modificamos [las reglas de los *translation-golf*](https://spanish.meta.stackexchange.com/a/2592/12637) o no: **¿Se debe permitir usar números en las respuestas a los translation-golf si el original no los tiene?**
2017/09/19
[ "https://spanish.meta.stackexchange.com/questions/2702", "https://spanish.meta.stackexchange.com", "https://spanish.meta.stackexchange.com/users/12637/" ]
No == Se debe respetar el original si este ha decidido no usar números. Además, si todo el mundo usa números se pierde la competitividad al dejarse de buscar sinónimos o expresiones equivalentes escritas con letras (ejemplo: "doscientas treinta y siete" por "más de doscientas"). Si todos escribieran "237" no tendría gracia. [Añadir más razones si se considera oportuno.]
Si, pero deben ser normalizados =============================== Hay casos en que los números parecen mejores y otros en que no lo parecen. Por ejemplo `T-101` vs `T-ciento uno` y `morirán mil` vs `moriran 1000`. La pregunta de cómo se escriben números no debería influir en los puntos. Una manera de garantizarlo sería cambiar números en letras antes de contarlas. Hay casos en que los números parecen mejores y otros en que no lo parecen. Por ejemplo `T-101` vs `T-ciento uno` y `Somos cinco.` vs `Somos 5.`. Por ejemplo antes de contar las letras `Había 2000 maneras de hacerlo.` se cambiaría en `Había dos mil maneras de hacerlo.`
43,122,911
I'm using a scroll view which is having only one child linearlayout. Linearlayout contains listview and some other items also, but only listview is scrolling. what should i do ? Here is my layout ``` <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:fresco="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/beco_white" android:orientation="vertical"> <include layout="@layout/toolbar" /> <ScrollView android:layout_width="match_parent" android:layout_height="fill_parent" android:fillViewport="true"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ViewSwitcher android:id="@+id/view_switcher" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="125dp" android:background="@android:color/white" android:orientation="horizontal"> <Button android:id="@+id/button_sign_in" android:layout_width="150dp" android:layout_height="40dp" android:layout_gravity="center" android:layout_marginLeft="@dimen/dp20" android:background="@drawable/dark_blue_round_corner" android:fontFamily="sans-serif-normal" android:text="Login to beCo" android:textAllCaps="false" android:textColor="@android:color/white" android:textSize="14sp" /> <Button android:id="@+id/button_sign_up" android:layout_width="150dp" android:layout_height="40dp" android:layout_gravity="center" android:layout_marginLeft="20dp" android:layout_marginRight="@dimen/dp20" android:background="@drawable/customborder" android:fontFamily="sans-serif-normal" android:text="Create New Account" android:textAllCaps="false" android:textColor="@color/colorAccent" android:textSize="14sp" /> </LinearLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="125dp" android:background="@android:color/white"> <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/image_profile" android:layout_width="@dimen/dp88" android:layout_height="@dimen/dp88" android:layout_gravity="left" android:layout_marginBottom="@dimen/dp10" android:layout_marginLeft="@dimen/dp10" android:layout_marginTop="@dimen/dp10" fresco:actualImageScaleType="centerCrop" fresco:placeholderImage="@drawable/no_profile_pic" fresco:roundAsCircle="true" fresco:roundingBorderColor="@color/white" fresco:roundingBorderWidth="@dimen/dp2" /> <TextView android:id="@+id/user_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginLeft="@dimen/dp10" android:layout_toRightOf="@+id/image_profile" android:fontFamily="sans-serif-normal" android:text="John Doe" android:textColor="@android:color/black" android:textSize="25sp" /> <TextView android:id="@+id/email" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/user_name" android:layout_marginLeft="@dimen/dp10" android:layout_toEndOf="@+id/image_profile" android:layout_toRightOf="@+id/image_profile" android:fontFamily="sans-serif-normal" android:text="johndoe@mail.com" android:textColor="@android:color/black" android:textSize="14sp" /> <Button android:id="@+id/button_edit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_alignTop="@+id/image_profile" android:background="@drawable/customborder" android:text="Edit Profile" android:textAllCaps="false" android:textColor="@color/colorAccent" /> </RelativeLayout> </ViewSwitcher> <View android:layout_width="wrap_content" android:layout_height="1dp" android:background="@color/grey_200" /> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> </ScrollView> </LinearLayout> ``` Any one please help me?
2017/03/30
[ "https://Stackoverflow.com/questions/43122911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7505436/" ]
Never put A `ListView` inside a `ScrollView`. It is a bad practice and it defeats the purpose of having a `ListView`. Who wants two scrollable areas on a screen anyway? Instead add a header or footer view on your listView depending on what you need.
Try this layout: changes: 1. Make your inner linearlayout wrap into `Scrollview` 2. Apply `android:layout_height="wrap_content"` for `scrollview` 3. End the `scrollview` before `Listview` as both can not be applied together ``` <?xml version="1.0" encoding="utf-8"?> ``` ``` <include layout="@layout/toolbar" /> <ScrollView android:layout_width="match_parent" android:layout_height="wrap_content" android:fillViewport="false"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ViewSwitcher android:id="@+id/view_switcher" android:layout_width="match_parent" android:layout_height="wrap_content"> <LinearLayout android:layout_width="match_parent" android:layout_height="125dp" android:background="@android:color/white" android:orientation="horizontal"> <Button android:id="@+id/button_sign_in" android:layout_width="150dp" android:layout_height="40dp" android:layout_gravity="center" android:layout_marginLeft="@dimen/dp20" android:background="@drawable/dark_blue_round_corner" android:fontFamily="sans-serif-normal" android:text="Login to beCo" android:textAllCaps="false" android:textColor="@android:color/white" android:textSize="14sp" /> <Button android:id="@+id/button_sign_up" android:layout_width="150dp" android:layout_height="40dp" android:layout_gravity="center" android:layout_marginLeft="20dp" android:layout_marginRight="@dimen/dp20" android:background="@drawable/customborder" android:fontFamily="sans-serif-normal" android:text="Create New Account" android:textAllCaps="false" android:textColor="@color/colorAccent" android:textSize="14sp" /> </LinearLayout> <RelativeLayout android:layout_width="match_parent" android:layout_height="125dp" android:background="@android:color/white"> <com.facebook.drawee.view.SimpleDraweeView android:id="@+id/image_profile" android:layout_width="@dimen/dp88" android:layout_height="@dimen/dp88" android:layout_gravity="left" android:layout_marginBottom="@dimen/dp10" android:layout_marginLeft="@dimen/dp10" android:layout_marginTop="@dimen/dp10" fresco:actualImageScaleType="centerCrop" fresco:placeholderImage="@drawable/no_profile_pic" fresco:roundAsCircle="true" fresco:roundingBorderColor="@color/white" fresco:roundingBorderWidth="@dimen/dp2" /> <TextView android:id="@+id/user_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginLeft="@dimen/dp10" android:layout_toRightOf="@+id/image_profile" android:fontFamily="sans-serif-normal" android:text="John Doe" android:textColor="@android:color/black" android:textSize="25sp" /> <TextView android:id="@+id/email" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/user_name" android:layout_marginLeft="@dimen/dp10" android:layout_toEndOf="@+id/image_profile" android:layout_toRightOf="@+id/image_profile" android:fontFamily="sans-serif-normal" android:text="johndoe@mail.com" android:textColor="@android:color/black" android:textSize="14sp" /> <Button android:id="@+id/button_edit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" android:layout_alignTop="@+id/image_profile" android:background="@drawable/customborder" android:text="Edit Profile" android:textAllCaps="false" android:textColor="@color/colorAccent" /> </RelativeLayout> </ViewSwitcher> </LinearLayout> </ScrollView> <View android:layout_width="wrap_content" android:layout_height="1dp" android:background="@color/grey_200" /> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent" /> ```
2,176,544
Hey, I'm just wondering how I could remove all the text if it encounters a certain string inside a string : EX: 24 Season 1 Episode 3 I would like, that if it find the text Season that it removes it and everything after so it would just leave you with : 24 Thanks Ah sorry I forgot to say I need this in PHP.
2010/02/01
[ "https://Stackoverflow.com/questions/2176544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/263192/" ]
``` $string="24 Season 1 Episode 3"; $s = explode("Season",$string,2); echo $s[0]; ```
1.If u need all the strings which occurs after certain word this will work $str="24 Season 1 Episode 3"; echo strstr($str, 'Season'); 2.If u need all the strings which occurs before certain word this will work ``` $str="24 Season 1 Episode 3"; $arr = explode("Season", $str, 2); $first = $arr[0]; echo $first; ```
8,769,656
I want to redirect the user to login page on landing, While user is not logged in. for example :- ``` example.com ->(not logged in)-> redirect to login page. example.com ->(logged in)-> redirect to Home page. ``` How can i do this ? I was found some function like this ``` public function preDispatch() { parent::preDispatch(); if (!Mage::getSingleton('customer/session')->authenticate($this)) { $this->setFlag('', 'no-dispatch', true); } } ``` How can i use or where should i use this. Hope some will have experience on this. Thanks in advance
2012/01/07
[ "https://Stackoverflow.com/questions/8769656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/430112/" ]
``` $customerId = (int) $this->getRequest()->getParam('id'); $customer = Mage::getModel('customer/customer') ->load($customerId); $userSession = Mage::getSingleton('customer/session'); $userSession->setCustomer($customer); Mage::dispatchEvent('customer_login', array('customer'=>$customer)); $this->getResponse()->setRedirect(Mage::getUrl('customer/account')); ``` Hope this help
``` $redirect_url = Mage::getUrl('customer/account/login/'); $current_url = Mage::helper('core/url')->getCurrentUrl(); if((!$this->helper('customer')->isLoggedIn()) && ($current_url != $redirect_url)){ Mage::app()->getFrontController()->getResponse()->setRedirect($redirect_url); } ```
57,961,666
I am writing code that will count the number of times each word in an array appears as well as the total of number of all the words appearing. I have managed to create an array which allows the user to add in a number of words they wish to check. However, I am struggling to find a way to count the number of times each word is within the sentence individually (I can only get it working for the first element of the array). I have tried a for loop that when completed it will move to the next element in the array but it does not start for loop again for the next element but ends the code block. ``` int occurences = 0; string[] words = new string[_wordCount]; for (int i = 0; i < words.Length; i++) { Console.WriteLine("Type in the censored words you wish to be counted: "); words[i] = Console.ReadLine(); if (_sentence.Contains(words[i])) { occurences++; } if (i > words.Length) { i++; } } Console.WriteLine("Number of censored word occurences: " + occurences); return occurences; ```
2019/09/16
[ "https://Stackoverflow.com/questions/57961666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Initialize Postgres container with Data --------------------------------------- Create a `docker-compose.yml` ``` version: '2' services: postgress-postgresql: image: postgres:11.3 volumes: # - ~/volumes/jhipster/postgress/postgresql/:/var/lib/postgresql/data/ - ./init.sql:/docker-entrypoint-initdb.d/init.sql environment: - POSTGRES_USER=postgress - POSTGRES_PASSWORD= ports: - 5432:5432 ``` Create a `init.sql` with the script ``` CREATE USER platops WITH PASSWORD 'platops'; CREATE DATABASE platopsdb; GRANT ALL PRIVILEGES ON DATABASE platopsdb TO platops; ``` RUN with `docker-compose up -d`
The underlaying problem in our case was that the sql script was stored on a ntfs partition mounted with ntfs-3g which by default has got permissions' functionality disabled (<https://superuser.com/questions/451475/chmod-doesnt-work>). Running it on a normal ext4 partition solved the problem.
9,521,568
Should i include classes that are part of the Java API, such as `HttpURLConnection` or `JSONObject` in my class diagram, or should i include only the classes that was developed for the project? My Program connecting to a server, retrieving data, constructing a `JSONObject` then uses this data to construct some objects. I feel these classes are part of the flow, but I'm just using them - often, but just using - not inheriting or implementing an interface. So, on one hand i feel they are important, on the other they are not part of my project as a contract or a super-class. Thank You.
2012/03/01
[ "https://Stackoverflow.com/questions/9521568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/352660/" ]
This of course goes with personal taste. But I personally tend not to include them. Or only refer to them by name but without the properties/methods listed to bring in the point that we don't control this class.
What do you want to achieve / communicate with your UML diagram? Does including these classes help achieving that? Look, there it is. Your answer.
65,586,826
I have a 3d array in Java which is like this: (size 3x2x4) ``` {{{1,2,3,0},{1,2,0,3}},{{1, 1, 1, 0}, {1 , 1, 0, 1} } , {{ 2,2,2,0},{2,2,0,2}}}; ``` I want to return the sum of every third and forth columns values, and to return as array the value of third and fourth columns. This means: (array value of third and fourth columns ; sum ), i.e right side is the sum of the array of third and fourth columns values. ``` {1,2,3,0} ---> [3 0] ; 3 {1,2,0,3} ---> [0 3] ; 3 {1,1,1,0} ---> [1 0] ; 1 {1,1,0,1} ---> [0 1] ; 1 {2,2,2,0} ---> [2 0] ; 2 {2,2,0,2} ---> [0 2] ; 2 ``` I'm trying to implement this function in Java, I've implemented this: ```java public static void sumElements(void) { int[3][2][4] arr1 = {{{1,2,3,0},{1,2,0,3}},{{1, 1, 1, 0}, {1 , 1, 0, 1} } , {{ 2,2,2,0},{2,2,0,2}}}; for (int i = 0 ;i < arr1.length ; l++) { system.println.out( IntStream.of(arr1[i, 3 , i]).sum()); system.println.out( IntStream.of(arr1[i, 3 , i]).sum()); // here I print the sum of third and fourth columns elements. } } ``` Any help out how do I implement correctly that function? I came from world of C++ and I just started coding in Java for some months.
2021/01/05
[ "https://Stackoverflow.com/questions/65586826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14947625/" ]
Solution -------- **For the sum Method** The code should be straightforward. So I go down all the three dimensions with the for loops and as you said the size is fixed. > > size 3x2x4) > > > In the last Dimension I just build the sum of the third and fourth element at index 2 and 3 and and then put it into a result array which I return afterwards. ``` public static int[] sumElements() { int[] sumArray = new int[6]; int counter = 0; int[][][] arr1 = { { { 1, 2, 3, 0 }, { 1, 2, 0, 3 } }, { { 1, 1, 1, 0 }, { 1, 1, 0, 1 } }, { { 2, 2, 2, 0 }, { 2, 2, 0, 2 } } }; for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1[i].length; j++) { int sum = 0; for (int l = 0; l < arr1[i][j].length; l++) { if (l == 2 || l == 3) { sum += arr1[i][j][l]; } } sumArray[counter] = sum; counter++; } } return sumArray; } ``` The output is `[3, 3, 1, 1, 2, 2]` **For the method which returns the two summands** I create a temp array there I place the two values and then I push the array into a result array. ``` public static int[][] sumands() { int secondCounter = 0; int[][] summandsArray = new int[6][2]; int[][][] arr1 = { { { 1, 2, 3, 0 }, { 1, 2, 0, 3 } }, { { 1, 1, 1, 0 }, { 1, 1, 0, 1 } }, { { 2, 2, 2, 0 }, { 2, 2, 0, 2 } } }; for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1[i].length; j++) { int firstCounter = 0; int[] tempArray = new int[2]; for (int l = 0; l < arr1[i][j].length; l++) { if (l == 2 || l == 3) { tempArray[firstCounter] = arr1[i][j][l]; firstCounter = firstCounter + 1; } } summandsArray[secondCounter] = tempArray; secondCounter++; } } return summandsArray; } } ``` The output is `[[3, 0], [0, 3], [1, 0], [0, 1], [2, 0], [0, 2]]` Now putting all together for a snippet which prints out the results. ``` package hall; import java.util.Arrays; import java.util.Scanner; import java.util.stream.IntStream; public class Whatever { public static void main(String[] args) { int[] sums = Whatever.sumElements(); int[][] summands = Whatever.sumands(); System.out.println(Arrays.toString(sums)); System.out.println(Arrays.deepToString(summands)); } public static int[] sumElements() { int[] sumArray = new int[6]; int counter = 0; int[][][] arr1 = { { { 1, 2, 3, 0 }, { 1, 2, 0, 3 } }, { { 1, 1, 1, 0 }, { 1, 1, 0, 1 } }, { { 2, 2, 2, 0 }, { 2, 2, 0, 2 } } }; for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1[i].length; j++) { int sum = 0; for (int l = 0; l < arr1[i][j].length; l++) { if (l == 2 || l == 3) { sum += arr1[i][j][l]; } } sumArray[counter] = sum; counter++; } } return sumArray; } public static int[][] sumands() { int secondCounter = 0; int[][] summandsArray = new int[6][2]; int[][][] arr1 = { { { 1, 2, 3, 0 }, { 1, 2, 0, 3 } }, { { 1, 1, 1, 0 }, { 1, 1, 0, 1 } }, { { 2, 2, 2, 0 }, { 2, 2, 0, 2 } } }; for (int i = 0; i < arr1.length; i++) { for (int j = 0; j < arr1[i].length; j++) { int firstCounter = 0; int[] tempArray = new int[2]; for (int l = 0; l < arr1[i][j].length; l++) { if (l == 2 || l == 3) { tempArray[firstCounter] = arr1[i][j][l]; firstCounter = firstCounter + 1; } } summandsArray[secondCounter] = tempArray; secondCounter++; } } return summandsArray; } } ```
The sum of the third dimension of the 3d array by the third and fourth columns: ```java int[][][] arr3d = { {{1, 2, 3, 0}, {1, 2, 0, 3}}, {{1, 1, 1, 0}, {1, 1, 0, 1}}, {{2, 2, 2, 0}, {2, 2, 0, 2}}}; int[][] arr = Arrays.stream(arr3d) .map(arr2d -> Arrays.stream(arr2d) // sum of third and fourth columns .mapToInt(arr1d -> arr1d[2] + arr1d[3]) .toArray()) .toArray(int[][]::new); System.out.println(Arrays.deepToString(arr)); // [[3, 3], [1, 1], [2, 2]] ``` Flatten 2d array to 1d array: ```java int[] flatArr = Arrays.stream(arr) .flatMapToInt(Arrays::stream) .toArray(); System.out.println(Arrays.toString(flatArr)); // [3, 3, 1, 1, 2, 2] ```
24,323
I'm currently trying to subscribe to my Google Contact's Birthday calendar from Hotmail, so far without success. I've used the ical link from the calendar settings in Google to create the subscription and it appears to create successfully. Going back into the calendar settings in Hotmail the same error is repeated five times:- > > Errors: This calendar wasn't updated because of a problem with the > publisher's file. We'll try updating it again later. > > > A search on that phrase hasn't turned up anything useful to date.
2012/02/29
[ "https://webapps.stackexchange.com/questions/24323", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/17746/" ]
Currently this isn't possible due to the fact that the iCal address for your Contact Birthdays Calendar isn't a personalized URL. This is the url that you get for Google Contact Birthdays: `https://www.google.com/calendar/ical/%23contacts%40group.v.calendar.google.com/public/basic.ics` This will only work from within a Google calendar page.
Mismatch of syntax between calendars.... One syntax check which can lead to this in Outlook, is a line in the ics data DTSTART;VALUE=DATE:20141014T193000Z which should set the date but not the time. The time should be left at default 00:00 DTSTART:20141014T193000Z will set the start time to 19:30. If the top format is used in Outlook it will fail with the given error message. Took me three hours to find that. I would not be surprised if other minor 'errors' creep into public calendars. Google handles the problem by ignoring the extra time data. To check/solve you could download the ics file and check it with a text editor. There are almost certainly more than just this one problem I have had. But as the error message says, it won't update if the source is faulty.
33,643,377
I created my own function to reverse the words in a phrase such as: ``` reverse("Hello my name is Bob") Bob is name my Hello ``` This is the code that I have ``` def first_word(string): first_space_pos = string.find(" ") word = string[0:first_space_pos] return word def last_words(string): first_space_pos = string.find(" ") words = string[first_space_pos+1:] return words def reverse(string): words = string.count(" ") +1 count = 1 string_reversed = "" while count <= words: string_reversed = first_word(string) + str(" ") + string_reversed string = last_words(string) count += 1 return string_reversed ``` Whenever I enter a string, the last letter of the first word of the phrase always gets cut off ``` reverse("Hello my name is Bob") Bob is name my Hell ``` The "o" is missing in Hello. Where did I go wrong?
2015/11/11
[ "https://Stackoverflow.com/questions/33643377", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5254097/" ]
Although you can use [::-1] to get a reversed list, you can also use `reversed`, cause it's more readable and explicit. ``` >>> words = "Hello my name is Bob" >>> ' '.join(reversed(words.split(' '))) 'Bob is name my Hello' ```
you need to modify your loop slightly ``` def reverse(string): words = string.count(" ") +1 count = 1 string_reversed = "" while count < words: string_reversed = first_word(string) + str(" ") + string_reversed string = last_words(string) count += 1 print(string + " " + string_reversed) return string + " " + string_reversed ```
26,443,642
I am trying to get which of the \* is clicked in text of label as in picture. ![Pic](https://i.stack.imgur.com/vft1F.png) NOTE : Number of \* is not known at first.User inputs it.So the position of mouse click is not useful.
2014/10/18
[ "https://Stackoverflow.com/questions/26443642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2511763/" ]
Answer is : X of first \*'s location is known, equals = 10 .The asterisks are spaced equally,distance between two \* is ~15 pixel . When user clicks on one of asterisks , index of asterisks can be calculated as the code below ``` private void label4_MouseDoubleClick(object sender, MouseEventArgs e) { double t = (e.X - 10) / 15.0; int indexOfClickedAsterisk=(int)Math.Round(t) + 1; } ```
It depends. If you are willing to display the text in a TextBox instead of Label (which is what it looks like you're using now), then you can use the [GetCharIndexFromPosition](http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.getcharindexfromposition(v=vs.110).aspx) method. Just make sure you specify the Point in client coordinates (comes for free if you are handling mouse clicks in the Label control itself). Note that you can set the TextBox as ReadOnly, assuming you don't want the user actually modifying the text. They will still be able to select the text though. If you need an actual Label control (e.g. you don't even want selectable text and the grayed-out appearance of a disabled TextBox isn't appropriate), then you'll have to write your own (or find one online that someone else wrote already), as the built-in one doesn't have that functionality. It would not be too difficult. You can use the TextRenderer methods to determine where each character is laid out when drawn and then use that information to correlate character positions with mouse clicks.
65,310
I am using Apache Axis to connect my Java app to a web server. I used wsdl2java to create the stubs for me, but when I try to use the stubs, I get the following exception: > > org.apache.axis.ConfigurationException: No service named `<web service name>` is available > > > any idea?
2008/09/15
[ "https://Stackoverflow.com/questions/65310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2328/" ]
According to the [documentation](http://wiki.apache.org/ws/FrontPage/Axis/DealingWithCommonExceptions) linked to by @arnonym, this exception is somewhat misleading. In the first attempt to find the service a ConfigurationException is thrown and caught. It is logged at DEBUG level by the ConfigurationException class. Then another attempt is made using a different method to find the service that may then succeed. The workaround for this is to just change the log level on the ConfigurationException class to INFO in your log4j.properties: ``` log4j.logger.org.apache.axis.ConfigurationException = INFO ```
I don't know what version of Axis you're using but I'm using Axis2 for both server and client and the Java2WSDL create a default endpoint for the service on localhost. If you create the client stub with WSDL2Java, the default constructor of the stub will then point to localhost. If the service is on other endpoint you must use the constructor with the endpoint as parameter... Maybe the problem is not that at all but as said on other answers, without the WSDL you're using as WSDL2Java input it's hard to say.
4,215,127
I would like to map a file into memory using mmap function and would like to know if the amount of virtual memory on the current platform is sufficient to map a huge file. For a 32 system I cannot map file larger than 4 Gb. Would `std::numeric_limits<size_t>::max()` give me the amount of addressable memory or is there any other type that I should test (off\_t or something else)? As Lie Ryan has pointed out in his comment the "virtual memory" here is misused. The question, however holds: there is a type associated with a pointer and it has the maximum value that defines the upper limit of what you can possibly adress on your system. What is this type? Is it size\_t or perhaps ptrdiff\_t?
2010/11/18
[ "https://Stackoverflow.com/questions/4215127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18775/" ]
Hi you can use GlobalMemoryStatusEx and VirtualQueryEx if you coding in win32
You can try `sizeof(int*)`. This will give you the length (in bytes) of a pointer on the target platform. Thus, you can find out how big the addressable space is.
50,480,098
Our company is developing a very complex single page app(something like excel) with vue.js. There are 10000+ components(each cell is a component) and each component would have about 100 reactive props(data items). We also use vuex. It works but we are worried about its performance(Indeed it performs a little slowly). We heard that too many reactive data will bring poor performance. I often hear people said that if it is rewritten by jQuery it will be faster. My question is: can vue handle so many reactive data? If not, what is the limit? Or if my app performs poorly, is it really caused by vue itself?
2018/05/23
[ "https://Stackoverflow.com/questions/50480098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1446907/" ]
> > if it is rewritten by jQuery it will be faster > > > Even if that was true, it would make your app harder to maintain. But this statement is a **False Dichotomy**, as if the choice between the frameworks/libraries were the deciding factor in determining the application's performance. It's *not*. However if you want to get the best performance, benchmarks have shown time and time again, that a tuned *vanilla* js application outperforms ***any*** framework. The key to having anything perform well is to design (and implement) properly. While Vue has many performance improvements built in, there are additional things you can do to improve performance, such as use of functional (stateless) components. You could also consider react, it doesn't come with the out-of-the-box performance tuning that Vue has, but it makes controlling these things easier. The end result (going back to my original point) will still largely depend on your implementation.
The following [link](https://codepen.io/pdg/pen/MoVWKw) proves Vue/Vuex is not the problem, perhaps your design is flawed? > > This simple test measures the creation of elements in an array > and the output to the DOM through a sync and an async loop, on a VUEjs > reactive attribute. From the UX point of view, the async method offers > a better experience as it allows for notifications. > > > > > ``` Credits to Pablo Garaguso ```
174,795
I have been job hunting for a few months, as of writing. I have gone through a number of interviews, in some of which the interviewer/hiring manager has asked "could you tell us about yourself?"/"what have you been doing over the past XXX period" (or phrased similarly.) As someone who is graduating from university, has presented all my experience, education, skills and experience on my CV, and may have sent a cover letter, and filled out a few screening questions/forms before the interview, I've found these questions to be mildly insulting (although I will never show it in the interview, only when I reflect afterwards)- as it comes across to me that the interviewer has not gone to the effort of glancing at my CV and seeing that I have ABC education and XYZ experience. When I am asked these questions, I often retell most of what is already on my CV (with one or two extra details that don't add much). Most of the time, the recruitment process progresses. Am I missing something for these questions, and should I pursue jobs where these sort of questions are asked?
2021/07/20
[ "https://workplace.stackexchange.com/questions/174795", "https://workplace.stackexchange.com", "https://workplace.stackexchange.com/users/-1/" ]
This is the most common opener question in any job interview for any applicant. They ask for exactly that: Tell us about yourself. They have read your resume, sometimes througoutly, sometimes just skimmed through. Doesn't matter. Now they want to hear it from your perspective. Not just the hard facts, but how you see yourself. What you have done until now, what are you proud about, where is your focus. NEVER react annoyed, this would irritate every interviewer. See it as a friendly invitation to talk about yourself. What makes you special, what are you passionate about (Bonus points: Why are you passionate about wanting to work for that company). Talk about more than just the hard facts. Show them the human behind the CV.
First, this seems to be a common complaint among new computer-workers on SE Workplace: > > I've found these questions to be mildly insulting... it comes across > to me that the interviewer has not gone to the effort of glancing at > my CV... > > > Well, they probably haven't, so you need to get over this. Maybe there's a stack of a hundred resumes and they don't have the capacity to read and memorize all of them. Or they have a huge backlog of critical tasks today and got handed your resume 5 minutes ago. Or they think, "well I'm talking to him anyway, I'll just get it straight from the person". *Most* human beings *don't* work like the "don't repeat yourself rule" from *Pragmatic Programmer*, and you'll be frustrated forever if you expect that. More essentially, any time you're given a chance to talk in any venue, you should have a preplanned script of a few key talking points that you're trying to convey in the interaction. In the case of a job interview, you are trying to sell yourself to the company. So when given the floor you should pitch the top couple of items that would make you valuable to this specific company. Sell how your experience interfaces specifically with the work they do. Even if the question wasn't ostensibly about that, bend it a bit to your sales pitch. Of course, the company also needs to sell itself to you, and there should be an opportunity for you to ask and get answers in the reverse direction, but that's a separate question.
207,394
Referring to question like [Differences between HashMap and Hashtable?](https://stackoverflow.com/questions/40471/differences-between-hashmap-and-hashtable) I wonder how could it be accepted as it satisfy none of criteria mentioned in SO. I should be able to flag it off-topic as it falls under *Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself*. And also *Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist* I don't doubt about the quality and importance of the questions but to me the rule supposed to be same for all. And the very first line in the [Help Center](https://stackoverflow.com/help/dont-ask) clearly says > > **First, make sure that your question is on-topic for this site**.You should only ask practical, answerable questions based on actual problems that you face. Chatty, open-ended questions diminish the usefulness of our site and push other questions off the front page. > > > **How to Ask** > > Is your question about programming? > > > We prefer questions that can be answered, not just discussed. > > > **Provide details. Share your research.** > > > I don't understand how these are justified in these cases? Some more similar entried I could find (And this list could go on) [What is a serialVersionUID and why should I use it?](https://stackoverflow.com/questions/285793/what-is-a-serialversionuid-and-why-should-i-use-it) [How can a string be initialized using " "?](https://stackoverflow.com/questions/17489250/how-can-a-string-be-initialized-using/17489410#17489410)
2013/11/14
[ "https://meta.stackexchange.com/questions/207394", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/232504/" ]
> > Questions **concerning problems with code you've written** must describe the specific problem — and include valid code to reproduce it — in the question itself > > > The question is not concerning a problem with code the author wrote, so that doesn't apply. > > Questions **asking for code** must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist > > > The question isn't asking for code. As for: > > Provide details. Share your research. > > > Yes, this question is lacking in research. It would have been better if the author spent more time researching the differences, and demonstrated what research they had done and what they had failed to find. When you come across questions that failed to provide enough research their is a particular tool available to you. That tool's tooltip is: > > This question does not show any research effort; it is unclear or not useful > > > That tool is a downvote. That is the appropriate response to a question you feel is not sufficiently well researched. In this particular case, one could also make an argument for the question being "too broad", especially with respect to the second question, as it could mean a lot of things and trying to explain them all would be just too much. As for the first question, it doesn't appear to be overly broad given the answers to the question. --- Regardless, when you come across a question that you feel should be closed, just vote/flag it for closure. There's no real need to start a meta question about it unless you're 1) unsure of whether or not it should be closed 2) there is a clear controversy over the question and it is constantly being reopened/closed or there is an involved discussion over it's closure in the comments. As for why there are questions that exist that should be closed (or even are closed) but have a lot of upvotes, there are a number of reasons. Some of those questions were once on topic, but are no longer, there are questions that people like asking/answering even though they aren't on topic, etc. As a rule, you can ignore a questions popularity when determining if it should be opened/closed. (However it's popularity is *highly* relevant when determining if it should be deleted.)
There's a tension here between being a repository of answers to questions and expecting people to do research. The first 1/2 of that question about hash tables is a factual question that many new Java programmers need to answer. It's also one with many perfectly good answers findable on Google. Now, of course, the stackoverflow post is one of them. Further, this question dates from a time when many more questions were considered on-topic. The question is at least in complete English sentences, does not ask 'send me the codez', and does not come decorated with irrelevancies. The admissibility of a question depends on the community's judgement of laziness. If five people run Google queries and see good answers, it gets closed. If they don't see clear, on point, answers, it stays open. If someone asked a question at the same level today, well, I'd guess it would get closed, or at least end up in the giant close vote review pigpile.
404,457
I need to change the layout of the keyboard while working in the console on Linux. I need to set up English layout as the default for the console. How can I do it?
2012/03/24
[ "https://superuser.com/questions/404457", "https://superuser.com", "https://superuser.com/users/63329/" ]
To change the system-wide keyboard layout, run ``` sudo dpkg-reconfigure keyboard-configuration ``` or edit the `XKBLAYOUT` line in `/etc/default/keyboard`.
`loadkeys us`, it loads US keys but for a single session.
115,685
How can we refer to the polite phrase used at the beginning of a letter (email in my specific context)? For example, we may start our letter: > > Dear Bob, I hope that you're well and had a nice weekend. > > > If we want to make reference to the line > > I hope that you're well and had a nice weekend > > > in such a way that we could say: > > I often wonder how to begin a letter of bad news, but my > [interjection] stands genuine non the less > > > The term "interjection" doesn't seem like a good fit here. Is there a word that describes the polite phrases we often use to begin our letters?
2013/06/03
[ "https://english.stackexchange.com/questions/115685", "https://english.stackexchange.com", "https://english.stackexchange.com/users/3045/" ]
Either '[greeting](http://www.thefreedictionary.com/greeting)' or '[salutation](http://www.thefreedictionary.com/salutation)' would fit. From the online dictionary, meaning 3 is appropriate: > > sal·u·ta·tion (sly-tshn) n. > > > 1. a. A polite expression of greeting or goodwill. b. salutations Greetings indicating respect and affection; regards. > 2. A gesture of greeting, such as a bow or kiss. > 3. A word or phrase of greeting used to begin a letter or message. > > >
I don't know of a word that describes this kind of remark (sentence) when it is made in a written context such as a letter. On the other hand, the term *phatic* is used to describe similar sorts of remarks when they are spoken. "How are you?" is frequently used as a phatic utterance; consider, for example, the telephone sales-person who greets you when you answer the phone with "Hello Ms Smith, How are you today?" The correct (social) response is "Fine, thank you", not a truthful answer that describes your state of well-being. The reason is that the question is *phatic*; that is (to quote the OED), "it serves to establish or maintain social relationships rather than to impart information, communicate ideas".
572,552
How are they different in pronunciation? In other words, how can one recognise the difference purely by sound?
2021/08/10
[ "https://english.stackexchange.com/questions/572552", "https://english.stackexchange.com", "https://english.stackexchange.com/users/426380/" ]
Here are some opinions voiced on [WordReference](https://forum.wordreference.com/threads/pronunciation-th-%CE%B8-%C3%B0-after-t-or-d-sound.2254580/) by native speakers about this difficulty of English pronunciation; it appears to be a matter of how careful the speakers like to be, and, apparently there is no solution that will permit a clear distinction if you speak fast; however, a leisurely flow of speech allows the pronunciation of the two sounds without too much difficulty. > > **question** Lukas Brazil > > What if /θ/or /ð/ sounds come after a /t/ or a /d/ sound? I mean, it is difficult to speak quickly, so I thought the "th" could be also removed. I think so because I have seen cases like that. Just one example: how would be "you crossed the line" pronounced? > > > > > **answer 1** Julian Stuart, Senior Member Sonoma County CA English (UK then US) > > For example: "what does this mean?" It is pronounced like: "what does 'is mean?" without the /ð/. > > I would acknowledge that some say it that way, but it is not a rule, by any means. There are likely many different variations on how the voiced th /ð/ sounds after a t or d. I personally do not omit the voiced sound (also that's an example). When speaking faster, my voicing is briefer, and possibly less loud, but doesn't disappear. > > > > > **answer 2** Crockett, Senior Member Tucson Arizona US English > > I completely agree with JulianStuart. The voiced th /ð/ sound, in my opinion, should never be removed. However, there may be some people that do this anyways. In the sentence, "you crossed the line"- I would still be careful to enunciate each word. Even if I were speaking quickly, I would pronounce the 'th' sound (as in 'the'). > > > *Useful links and advice, from more native speakers, issued from the same source* [Difficulty pronouncing TH after T or D](https://forum.wordreference.com/threads/difficulty-pronouncing-th-after-t-or-d.2413453/) > > PaulQ, Senior Member, UK, English - England > > My advice? **Keep trying to pronounce the preceding T or D and the following TH distinctly**. > > > [Pronunciation: Nice shirt though (t > th)](https://forum.wordreference.com/threads/pronunciation-nice-shirt-though-t-th.196597/) [Pronunciation: t followed by th (t > ð)](https://forum.wordreference.com/threads/pronunciation-t-followed-by-th-t-%C3%B0.2306208/)
Cook the: /kʊk ðə/ or /kʊk ðiː/ Cooked the: /kʊkt ðə/ or /kʊkt ðiː/
23,736,216
I need to send a data from a Symfony form with an Ajax call with an extra Data containing options for the controller. I'm working on a custom framework including the Symfony form component. So I try in my JS to send values like this : ``` $.ajax ( { type: "POST", url: '/myUrl', data: { 'formData' : $(this).serialize(), 'extraData' : {'test1' : 'test1', 'test2' : 'test2'} }, success: function(result) { // do something } } ); ``` How can I get my form data in my controller to let the component correctly understand it ? This code won't work : ``` $formData = $this->getRequest()->request('formData'); $form->bind($formData); ``` Thank you. I hope my question is clear enough Edit: I finally integrated the data into hidden fields in my form. The form doesn't declare any data\_class, as the ORM we use is a really custom one. Thanks for the answers
2014/05/19
[ "https://Stackoverflow.com/questions/23736216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3652328/" ]
You need to set the id as String or UUID (or anything you need). Below, an example of my class User with another possibility: ``` import java.util.UUID class User { String id = UUID.randomUUID().toString() static mapping = { id generator:'assigned' } } ```
Here's what I did in my Grails 3 domain class... ``` class MyClass { static constraints = { } UUID id static mapping = { id generator: "UuidGenerator", length: 36, type: "uuid-char" } } ``` Then here's what I have inside UuidGenerator.groovy ``` import org.hibernate.id.IdentifierGenerator; import org.hibernate.engine.spi.SessionImplementor import java.security.SecureRandom; /** * */ class UuidGenerator implements IdentifierGenerator { Serializable generate(SessionImplementor session, Object object) { UUID.randomUUID() } } ``` For grails 2.x.x my UuidGenerator.groovy looks like this... ``` import org.grails.datastore.mapping.core.SessionImplementor import org.hibernate.id.IdentifierGenerator; import org.hibernate.engine.SessionImplementor; /** * */ class UuidGenerator implements IdentifierGenerator { Serializable generate(SessionImplementor session, Object object) { return UUID.randomUUID().toString() } } ``` And my domain class looks like this... ``` class MyClass { static constraints = { } String id static mapping = { id generator: "com.novadge.UuidGenerator", length:36 } } ```
11,417,551
I am trying to unbind a link from all functions. When I do: ``` $('a').unbind(); ``` It works perfectly. But obviously this is not what I want - I only want one specific link to not be manipulated by any functions. So I tried selecting the specific link: ``` $('.page1->index').unbind(); ``` But this did not work, the function was still manipulating the link. I also tried ``` $('a.page1->index').unbind(); ``` But that did not work either. I feel like my second approach should work. Is there something I'm missing? HTML: ``` <a id ="page1->index" href="#play1" data-role="button" data-icon="back" data-iconpos="notext" data-transition="fade" data-direction="reverse"></a> ```
2012/07/10
[ "https://Stackoverflow.com/questions/11417551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1464197/" ]
If the name of your class is `page1->index`, then you need to escape '`>`' symbol, because it has a [special meaning](http://www.w3.org/TR/css3-selectors/#child-combinators) in `CSS` selectors: ``` $('.page1-\\>index').unbind(); ```
Use the ID of the link. ID will be unique so you will get only one element in your jQuery selector ``` $('#yourLinkId').unbind(); ``` Assuming your HTML is like this (with the ID) ``` <a href="somepage.aspx" id="yourLinkId">Wonderful Link</a> <a href="somepage3.aspx" id="yourMagicLink">Magic Link</a> ```
10,079,304
I've recently begun to realize that the use of the "extern" keyword is highly encouraged. Thus I began to wonder if there is anything wrong with the current (extern-less) way I use header files: main.c: ``` #include "main.h" #include "function.h" int main(void){ globalvariable = 0; testfunction(); return 0; } ``` main.h: ``` #ifndef MAIN_H_ #define MAIN_H_ int globalvariable; #endif /* MAIN_H_ */ ``` function.c: ``` #include "main.h" #include "function.h" void testfunction(){ globalvariable++; return; } ``` function.h: ``` #ifndef FUNCTION_H_ #define FUNCTION_H_ void testfunction(void); #endif /* FUNCTION_H_ */ ``` Thus every new source file that needs access to *globalvariable* simply needs to include main.h. One obvious drawback to this method is arrays: you can't use {element0, element1, ...} formatting to assign values to an array once it has been declared. By the way, when I give *globalvariable* an initial value of zero, am I defining it at that point? Or is memory allocated earlier? Also, is there an official term for the method I'm using?
2012/04/09
[ "https://Stackoverflow.com/questions/10079304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/860618/" ]
``` extern int globalvariable; ``` is a *declaration* ``` int globalvariable; ``` is both a declaration and a *tentative definition*. In C, it's illegal for the same variable to have multiple definitions, and that will happen if you use the latter in a header file that's included in more than one translation unit. Unix systems however historically allow this usage, so most compilers will accept the code despite it being invalid C.
ANSI C standard says > > If the declaration of an identifier for an object has file scope and > no storage-class specifier, its linkage is external. > > >
42,548,602
I want to use Python's multiprocessing unit to make effective use of multiple cpu's to speed up my processing. All seems to work, however I want to run `Pool.map(f, [item, item])` from within a class, in a sub module somewhere deep in my program. The reason is that the program has to prepare the data first and wait for certain events to happen before there is anything to be processed. The [multiprocessing docs](https://docs.python.org/2/library/multiprocessing.html) says you can only run from within a `if __name__ == '__main__':` statement. I don't understand the significance of that and tried it anyway, like so: ``` from multiprocessing import Pool class Foo(object): n = 1000000 def __init__(self, x): self.x = x + 1 pass def run(self): for i in range(1,self.n): self.x *= 1.0*i/self.x return self class Bar(object): def __init__(self): pass def go_all(self): work = [Foo(i) for i in range(960)] def do(obj): return obj.run() p = Pool(16) finished_work = p.map(do, work) return bar = Bar() bar.go_all() ``` It indeed doesn't work! I get the following error: > > PicklingError: Can't pickle : attribute lookup > **builtin**.function failed > > > I don't quite understand why as everything seems to be perfectly pickeable. I have the following questions: 1. Can this be made to work without putting the p.map line in my main program? 2. If not, can "main" programs be called as sub-routines/modules, such to make it still work? 3. Is there some handy trick to loop back from a submodule to the main program and run it from there? I'm on Linux and Python 2.7
2017/03/02
[ "https://Stackoverflow.com/questions/42548602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/546465/" ]
> > you are submitting form with array of text fields and select box, try > below > > > ``` public function store(Request $request) { $count = Client::count(); foreach( $request->client_id as $key=>$val){ $payment = Payment::create(['amount' => $request->amount[$key], 'client_id' => $val, ]); } return redirect()->action('PaymentController@index'); } ```
Ty to create the record like this: ``` $payment = Payment::create($request->input); ``` And change you redirect action to this: ``` View::make('path/to/view/') ``` or just use just `back();` just to test if it works
2,610,416
I am writing code that catches this `OutOfMemoryException` and throws a new, more intuitive exception: ``` /// ... /// <exception cref="FormatException">The file does not have a valid image format.</exception> public static Image OpenImage( string filename ) { try { return Image.FromFile( filename ); } catch( OutOfMemoryException ex ) { throw new FormatException( "The file does not have a valid image format.", ex ); } } ``` Is this code acceptable to its user, or is `OutOfMemoryException` intentionally being thrown for a particular reason?
2010/04/09
[ "https://Stackoverflow.com/questions/2610416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233098/" ]
No, it is history. GDI+ was written quite a while before .NET ever came around. The SDK wrapper for it was written in C++. Exceptions are iffy in C++, not everybody buys into them. Google doesn't for example. So to keep it compatible it reports problems with error codes. That just never scales well, library programmers make it a goal to intentionally limit the number of possible error codes, it lessen the burden on the client programmer having to report them. GDI+ has this problem in spades, it defines only 20 error codes. That is *not* much for such a large chunk of code with so many external dependencies. Which in itself is a problem, there are a gazillion ways to mess up an image file. No way that a library's error reporting can be fine-grained enough to cover them all. The fact that these error codes were picked long before .NET defined standard Exception derived types certainly didn't help. The Status::OutOfMemory error code got overloaded to mean different things. Sometimes it really does mean out of memory, it can't allocate enough space to store the bitmap bits. Sadly, an image file format problem is reported by the same error code. The friction here is that it cannot possibly decide if the width \* height \* pixels it read from the image file is a problem because there isn't enough storage available for the bitmap. Or if the data in the image file is junk. It assumes that image file is not junk, fair call, that's another program's problem. So OOM is what it reports. For completeness, these are the error codes: ``` enum Status { Ok = 0, GenericError = 1, InvalidParameter = 2, OutOfMemory = 3, ObjectBusy = 4, InsufficientBuffer = 5, NotImplemented = 6, Win32Error = 7, WrongState = 8, Aborted = 9, FileNotFound = 10, ValueOverflow = 11, AccessDenied = 12, UnknownImageFormat = 13, FontFamilyNotFound = 14, FontStyleNotFound = 15, NotTrueTypeFont = 16, UnsupportedGdiplusVersion = 17, GdiplusNotInitialized = 18, PropertyNotFound = 19, PropertyNotSupported = 20, #if (GDIPVER >= 0x0110) ProfileNotFound = 21, #endif //(GDIPVER >= 0x0110) }; ```
It's a misleading exception. Microsoft [says](http://support.microsoft.com/kb/810109): > > **You receive a "System.OutOfMemoryException" error message when you try to use the Bitmap.FromFile method in the .NET Framework 1.0** > > > This problem may occur when you use the **Bitmap.FromFile** method and one of the following conditions is true: > > > * The image file is corrupted. > * The image file is incomplete. > > > **Note** You may experience this problem if your application is trying to use the **Bitmap.FromFile** method on a file stream that is not finished writing to a file. > \* The image file does not have a valid image format or GDI+ does not support the pixel format of the file. > \* The program does not have permissions to access the image file. > \* The **BackgroundImage** property is set directly from the **Bitmap.FromFile** method. > > > (Bitmap descends from Image) Of course, it's also possible to get this exception when you try to load an image which is too big. So you need to consider that.
46,531
in putting together a new installation, one of the requirements is that we use fiber to the desktop. we are going to use multimode, but im not sure which connector. is there a material (ie cost) difference between SC and LC? what about durability? It would seem to me that the fragile part (the fiber) doesnt benefit much from either connector, so is either OK? any other advice or things that seem obvious in hindsight would also be appreciated. edited: also, if anyone has some insight as to which 1000baseSX nics one should avoid (if any) that would be most appreciated.
2009/07/27
[ "https://serverfault.com/questions/46531", "https://serverfault.com", "https://serverfault.com/users/11087/" ]
The main benefit of LC over SC is the form factor. An LC connector is similar in size to an RJ45 jack whereas an SC connector is about twice the size. I have not found any differences in the durability of the connectors.
It is worthwhile to note that with LC connectors, it is difficult to change the fiber pairs from crossover to straight through. SC is easier, and ST is obviously trivial.
60,082,599
For some reason, I have a code that is completely identical and it works fine when I test it on codepen, but it will not resize at all when I bring it to github for publishing. The codepen is: <https://codepen.io/daniel-albano/pen/ExaedBr?editors=1100> This is one extract of my CSS not properly resizing: ``` .mission2 p { font-size: 1.5vw; font-family: 'roboto'; padding: 4% 0% 0% 0%; clear: right; line-height: 1.4; } ``` The actual website is located at: MFASP.com I honestly have no idea what to look at for the cause of this, as both codes are exactly the same.
2020/02/05
[ "https://Stackoverflow.com/questions/60082599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12847580/" ]
``` #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" ... the code using the deprecated API ... #pragma clang diagnostic pop ```
@available in Objective-C is used when you want to check, if current iOS (/MacOS) version supports this API. It is called when you implement API which is supported starting by some iOS version, but not supported by older iOS. As far as I know, you can't silent warning about deprecated API - you can only replace it with new.
51,044
There are two similar questions here: [what are some dictionaries about vocabulary of classical chinese?](https://chinese.stackexchange.com/questions/9888/what-are-some-dictionaries-about-vocabulary-of-classical-chinese) [Resources: Modern Chinese -> Classical Chinese (Dictionary/References/etc.)](https://chinese.stackexchange.com/questions/12685/resources-modern-chinese-classical-chinese-dictionary-references-etc) But my question is different: I am looking for an online Classical Chinese dictionary.
2022/04/23
[ "https://chinese.stackexchange.com/questions/51044", "https://chinese.stackexchange.com", "https://chinese.stackexchange.com/users/27314/" ]
Not much, I suppose. If you have access to Brill, then the [Chinese-English Dictionary Online](https://chinesereferenceshelf.brillonline.com/chinese-english) contains the entries, among others, from Paul W. Kroll's [A Student's Dictionary of Classical and Medieval Chinese](https://brill.com/view/title/20918). But randomly having access to Brill is one of the most rare things in the world though ($160 and that expires after five years of usage???) Alternatively, if you have Pleco, you may purchase the same Kroll as a $40 add-on and browse it with ease in a native iOS or Android app. They also have the 漢語大詞典 for $50, which covers all the periods of the language including Classical, and the Gu Hanyu Da Cidian for $20, specifically aimed at Classical language. If you are looking for a free source, consider [the dictionary of ctext.org](https://ctext.org/dictionary.pl?if=en). If not much, it will at least provide the whole text of Kangxi dictionary definition in a digitized format, so if you already read Classical Chinese on a basic level, it will allow to get the general gist of things. Personally, out of the non-Chinese language dictionaries of Classical Chinese, I am very partial to the dictionary attached to Kai Vogelsang's [Introduction to Classical Chinese](https://global.oup.com/academic/product/introduction-to-classical-chinese-9780198834977?cc=ru&lang=en&), so if there is any chance to (somehow, such as through institutional access) get hold of it, it would be probably a better option than all of the entries above. I mean, it contains the data that one generally expects from a language dictionary (such as Old Chinese pronuunciation, parts of speech, how the word combines with other words), which Classical Chinese dictionaries ordinarily neglect. Kroll is a helpful addition to that, but only an addition; its definitions are brief, and its stronger sides are just more characters and medieval usages. Out of the Chinese-language dictionaries of Classical Chinese, then probably the 古漢語字典 by Wang Li would be the best option.
I suggest dict.cn.com. It is an online, English-Chinese and Chinese-English, two-way dictionary. [![enter image description here](https://i.stack.imgur.com/r5b9F.png)](https://i.stack.imgur.com/r5b9F.png)
597,362
I'm using Microsoft Office 2013 Word. Pages that have page numbers displayed as Roman numerals are displayed in the Table of Contents with Arabic numeral page numbers. Here is a screenshot of the Table of Contents: ![enter image description here](https://i.stack.imgur.com/pRv7X.png) Here is a screenshot showing that the "ABBREVIATIONS" are on page "IV": ![enter image description here](https://i.stack.imgur.com/vz6Xg.png) How do I change this to use Roman Numerals?
2013/05/19
[ "https://superuser.com/questions/597362", "https://superuser.com", "https://superuser.com/users/88617/" ]
Word should automatically pick the correct numbering type from the section the heading comes from, just make sure that the numbering format is set per section, so that you insert a section break and then change the numbering type by going to the header/footer -> Page Number -> Format Page Number. If you changed the numbering of the individual field (through Right Click -> Edit Field) then this will not be reflected in the TOC.
I had the issue and could fix it by double clicking the footer, Right-Click on the number field and go to "Format Page Numbers" and set it to roman numbers there. The numbers were Roman before, dont get me wrong, but by changing this the TOC also recognized that.
13,507,821
i want to set banner(image) at top of list view dynamically.i am calling list view data from webservices .i did this coding in my lazy adapter class but no banner being visible.i wana set banner like this.![](https://i.stack.imgur.com/tvLrK.png) ``` RelativeLayout layout1 = new RelativeLayout(mContext); ImageView image = new ImageView(mContext); LayoutParams params2 = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT); image.setLayoutParams(params2); image.setScaleType(ImageView.ScaleType.CENTER); image.setMaxHeight(50); image.setMaxWidth(50); image.getPaddingTop(); image.setImageResource(R.drawable.topheader); layout1.getPaddingTop(); layout1.addView(image);*/ ``` i have banner image in my drawable. --- this is my full code of lazy adpter class ``` package com.example.jsonparsing; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.RelativeLayout.LayoutParams; public class LazyAdapter extends BaseAdapter { int counter = 0; Context mContext; Activity a; public LazyAdapter(Context context) { this.mContext = context; this.a = a; } public int getCount() { System.out.println("Called..."+ Constants.vctrCategoryId.size()); return Constants.vctrCategoryId.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { System.out.println("Exception before.."); String strUrl = Constants.vctrImagePath.elementAt(counter).toString();// getting url of the images System.out.println("Urls...." + strUrl); URL url =null; try { url = new URL(strUrl); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } Bitmap bitmap = Constants.DownloadImage(strUrl); Bitmap resized = Bitmap.createScaledBitmap(bitmap, 100, 100, true); //text.setImageBitmap(bitmap); /* this coding i did for setting banner /*RelativeLayout layout1 = new RelativeLayout(mContext); ImageView image = new ImageView(mContext); LayoutParams params2 = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT); image.setLayoutParams(params2); image.setScaleType(ImageView.ScaleType.CENTER); image.setMaxHeight(50); image.setMaxWidth(50); image.getPaddingTop(); image.setImageResource(R.drawable.topheader); layout1.getPaddingTop(); layout1.addView(image);*/ RelativeLayout layout = new RelativeLayout(mContext); //RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT); //layout.setLayoutParams(params); TextView text1 = new TextView(mContext); text1.setText(Constants.vctrCategory.elementAt(counter).toString()); LayoutParams params1 = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); text1.setLayoutParams(params1); text1.setTextSize(20); text1.setGravity(Gravity.RIGHT); layout.addView(text1); ImageView img = new ImageView(mContext); img.setImageBitmap(resized); layout.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL); layout.addView(img); counter++; return layout; } private void setContentView(ImageView image) { // TODO Auto-generated method stub } } ```
2012/11/22
[ "https://Stackoverflow.com/questions/13507821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1317798/" ]
Your solution from the layout point of view: ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:src="@drawable/ic_launcher" /> <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/imageView1" > </ListView> </RelativeLayout> ``` Guess it helps!
Use this: ``` View headerView1 = ((LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_add, null, false);///this is your imageview list_view.addHeaderView(headerView1); ```
36,725,828
--Short Version-- How do you get ng-pattern to use regex from angular constants? --Long Version-- I'm working on a huge Angular 1 project and we have multiple forms. A lot of these forms have the same fields like Zip and Phone Number. I wanted to look for a consistent way to use ng-pattern but have the regex in one location for consistency. I want to use angular constants for this but I can't get ng-pattern to take the value and I can't figure out why. --What I've done-- I did find this answer [Angularjs dynamic ng-pattern validation](https://stackoverflow.com/questions/18900308/angularjs-dynamic-ng-pattern-validation) for placing regex dynamically into ng-pattern and I tried that but that method didn't seem to work for angular constants. I've tried storing the regex as strings and converting it in the HTML. I've tried using a function that returns the regex value. --jsfiddle of the issue-- <https://jsfiddle.net/Michael_Warner/692deLsb/8/> The issue goes down to this line of code. ``` ng-pattern="patterns.zip" ``` If I embed the regex into ng-pattern directly then it will work as you can see in the fiddle ``` ng-pattern="/^\d{5}(?:-\d{4})?$/" ```
2016/04/19
[ "https://Stackoverflow.com/questions/36725828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4139335/" ]
You can do it in two ways: 1: As string *literal*, when you must double slashes: ``` .constant("formPattern", { zip: new RegExp("^\\d{5}(?:-\\d{4})?$") }) ``` 2: As regular expression: ``` .constant("formPattern", { zip: /^\d{5}(?:-\d{4})?$/ }) ``` Both worked in your fiddle.
Just add the constants to a `$scope` variable ``` $scope.myPattern = /^\d{5}(?:-\d{4})?$/; ``` and then in html ``` ng-pattern=myPattern ```
44,214,802
I am using Volley to acquire data from server.Some times when the network connection is slow I get the response twice or thrice or more than that.I followed the answer from a similar problem in [Android volley sending data twice](https://stackoverflow.com/questions/27873001/android-volley-sending-data-twice) .But still I am stuck with the same problem.Below is my code.Please help me Code: ``` public void volley_get_list() { RequestQueue requestQueue = Volley.newRequestQueue(getActivity()); StringRequest stringRequest = new StringRequest(Request.Method.POST, srch_lst_url, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.e("Response", response); if(!broadcast_unregister) { getActivity().unregisterReceiver(broadcastReceiver); Log.e("BroadcastReceiver", "Unregistered"); broadcast_unregister=true; } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }) { @Override protected Map<String, String> getParams() { HashMap<String,String> hashMap = new HashMap<>(); hashMap.put("search", typed_text); hashMap.put("latt", lat); hashMap.put("long", longt); return hashMap; } }; RetryPolicy retryPolicy=new DefaultRetryPolicy(0,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); stringRequest.setRetryPolicy(retryPolicy); stringRequest.setShouldCache(false); requestQueue.add(stringRequest); requestQueue.start(); } ```
2017/05/27
[ "https://Stackoverflow.com/questions/44214802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5320053/" ]
What you are trying to do here, is remove a word from a string. When you try to `sentence.pop()`, you are trying to remove an element from an Immutable Sequence Type. Which means that you are trying to remove an element from a string, which does not make too much sense. What you should instead do, is break the string into words by `words.split(' ')` and then removing whichever element you want to remove from it. So a solution to replace line 17 is: `word = words.split(' ').pop(len(words.split(' '))-1)` That will remove the last word from the sentence and assign it to `word`. Note: This is obviously not the most efficient solution. I broke it down to make it readable. Hope this helps
See `pop()` is not a string function so going forward you can create a function, pass n as the index of the character you need to pop out of the string as str. write below code into the popout: ``` def popout(str,n): front = str[:n] # up to but not including n back = str[n+1:] # n+1 through end of string return front + back ``` > > This might answer your question as per my understanding. if not, please > correct me in the comment section. > > >
33,864,160
I am getting null pointer exception randomly, usually it works and sometime it crashes, I had searched a lot but didn't get any help as it there is no proper line from where I get any help, I am also using handler with it. My logcat error is as follows and code is added below it, ``` java.lang.NullPointerException: Attempt to invoke virtual method 'int android.text.Layout.getLineCount()' on a null object reference at android.widget.TextView.onMeasure(TextView.java:6703) at android.view.View.measure(View.java:17547) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436) at android.widget.LinearLayout.measureVertical(LinearLayout.java:722) at android.widget.LinearLayout.onMeasure(LinearLayout.java:613) at android.view.View.measure(View.java:17547) at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:727) at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:463) at android.view.View.measure(View.java:17547) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535) at android.widget.FrameLayout.onMeasure(FrameLayout.java:436) at android.support.v7.internal.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135) at android.view.View.measure(View.java:17547) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535) at android.widget.FrameLayout.onMeasure(FrameLayout.java:436) at android.view.View.measure(View.java:17547) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535) at android.widget.FrameLayout.onMeasure(FrameLayout.java:436) at android.view.View.measure(View.java:17547) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436) at android.widget.LinearLayout.measureVertical(LinearLayout.java:722) at android.widget.LinearLayout.onMeasure(LinearLayout.java:613) at android.view.View.measure(View.java:17547) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535) at android.widget.FrameLayout.onMeasure(FrameLayout.java:436) at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2615) at android.view.View.measure(View.java:17547) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767) at android.view.Choreographer.doCallbacks(Choreographer.java:580) at android.view.Choreographer.doFrame(Choreographer.java:550) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:135) at android.app.ActivityThread.main(ActivityThread.java:5254) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) ``` This is my code as follows, here it usually crash on click of register or forget button on first install and after that it usually works fine but sometime it gives me error, ```java public class Login extends AppCompatActivity implements View.OnClickListener,ProcessedResult { private Handler uiThreadHandler; private Context context; private EditText ed_password,ed_Username; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); StorageManager storageManager=new StorageManager(this,"abc"); String accessTokenCheck=storageManager.getValue(Constants.SharedPreferences.LACCESSTOKEN, null); if(accessTokenCheck!=null) GeneralFunctions.moveToNextActivity(MainActivity.class,this); uiThreadHandler = new UIThreadHandler(); new Thread(new Runnable() { @Override public void run() { init(); } }).start(); } //Initialization part private final void init() { context=this; FontsManager.initFormAssets(this, "fonts/Lato-Regular.ttf"); FontsManager.changeFonts(this); TextView myTextView = GeneralFunctions.findViewByIdAndCast(this, R.id.login_tv_noAccount); myTextView.setMovementMethod(new LinkTouchMovementMethod()); myTextView.setHighlightColor(getResources().getColor(android.R.color.transparent)); SpannableString mySpannable = new SpannableString(myTextView.getText().toString()); TouchableSpan touchableSpan = new TouchableSpan(Color.parseColor("#606060"),getResources().getColor(R.color.colorBlue),Color.TRANSPARENT) { @Override public void onClick(View textView) { GeneralFunctions.simpleMoveToNextActivity(Register.class, context); } }; mySpannable.setSpan(touchableSpan, GeneralFunctions.getText(myTextView).indexOf("Register"), GeneralFunctions.getText(myTextView).length(), 0); myTextView.setText(mySpannable, TextView.BufferType.SPANNABLE); TextView tv_forgetPassword = GeneralFunctions.findViewByIdAndCast(this,R.id.login_tv_foregetPassword); GeneralFunctions.setTextColorSelector(Color.parseColor("#606060"),getResources().getColor(R.color.colorBlue),tv_forgetPassword); tv_forgetPassword.setOnClickListener(this); ed_password = (EditText) findViewById(R.id.login_ed_password); ed_Username = (EditText) findViewById(R.id.login_ed_usrName); ed_password.setTransformationMethod(new AsteriskPasswordTransformationMethod()); Button bt_Login= GeneralFunctions.findViewByIdAndCast(this,R.id.login_bt_signin); setSelector(R.drawable.big_green_btn_normal, bt_Login); Button bt_linkedInd= GeneralFunctions.findViewByIdAndCast(this,R.id.login_bt_linkedin); setSelector(R.drawable.big_blue_btn_normal, bt_linkedInd); } private final void setSelector(final int resourceId,final Button button) { button.setOnClickListener(this); try { String name = getNameofResyrce(activity,resourceId); String newString=name.replace("normal","pressed"); StateListDrawable states = new StateListDrawable(); states.addState(new int[] {android.R.attr.state_pressed}, getDrawablebyName(activity,newString)); states.addState(new int[] {android.R.attr.state_focused},getDrawablebyName(activity, newString)); states.addState(new int[]{}, getDrawablebyName(activity, name)); if(view instanceof Button) ((Button)view).setBackground(states); else if(view instanceof ImageView) ((ImageView)view).setImageDrawable(states); } catch (Exception e) { } } public static synchronized Drawable getDrawablebyName(Context context,String name) { Resources resources = context.getResources(); final int resourceId = resources.getIdentifier(name, "drawable", context.getPackageName()); return resources.getDrawable(resourceId); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.login_bt_linkedin: { DWebView transparentDialog = DWebView.newInstance(); showProgressDialog(transparentDialog, Constants.DialogConstants.WEB); } break; case R.id.login_bt_signin: uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.VALIDATION); break; case R.id.login_tv_foregetPassword: GeneralFunctions.simpleMoveToNextActivity_Without_history(ForgetPassword.class, context); break; } } //Listener part @Override public <IResponse, IMethod> void processedResult(IResponse iResponse, IMethod iMethod) { switch (iMethod.toString()) { case "back": finish(); break; case "showProgress": uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.SHOWDIALOG); break; case "hideProgress": uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.HIDEDIALOG); break; } } //Handler part private class UIThreadHandler extends Handler { @Override public void handleMessage(Message msg) { switch (msg.what) { case Constants.ActivityBasicsCode.SETERROR: { CustomException exception=(CustomException)msg.obj; TextView editText=exception.getTextView(); editText.setError(exception.getMessage()); editText.setFocusable(true); editText.requestFocus(); } break; case Constants.ActivityBasicsCode.HIDEDIALOG: hideProgressDialog(Constants.DialogConstants.Transparent); break; case Constants.ActivityBasicsCode.SHOWDIALOG: { DTDialog dtDialog=DTDialog.newInstance(); showProgressDialog(dtDialog,Constants.DialogConstants.Transparent); } break; case Constants.ActivityBasicsCode.VALIDATION: { //Here validation is done in separate thread new Thread(new Runnable() { @Override public void run() { try { if (Validation.validate(Login.this)) GeneralFunctions.moveToNextActivity(MainActivity.class, context); } catch (CustomException e) { //Catch exception for validation is thrown here Message message = uiThreadHandler.obtainMessage(Constants.ActivityBasicsCode.SETERROR); message.obj=e; uiThreadHandler.sendMessage(message); }finally { uiThreadHandler.sendEmptyMessage(Constants.ActivityBasicsCode.HIDEDIALOG); } } }).start(); break; } } super.handleMessage(msg); } } public final<T extends DialogFragment> void showProgressDialog(T currentDialog,String tagName) { FragmentManager fragmentManager =getSupportFragmentManager(); currentDialog.show(fragmentManager, tagName); } public final void hideProgressDialog(String tagName) { FragmentManager fragmentManager =getSupportFragmentManager(); DialogFragment transparentDialog = (DialogFragment)fragmentManager.findFragmentByTag(tagName); if (transparentDialog == null) { return; } transparentDialog.dismiss(); } } ``` XML file ``` <?xml version="1.0" encoding="utf-8"?> ``` ``` <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_gravity="center" android:gravity="center"> <ImageView style="@style/imageview" android:layout_marginTop="@dimen/_7sdp" android:src="@mipmap/ic_launcher"/> <EditText android:tag="@string/login_emailId_phone" android:layout_marginTop="@dimen/_12sdp" style="@style/edittext" android:drawableLeft="@drawable/user_icon" android:id="@+id/login_ed_emailPhone" android:inputType="text"/> <EditText android:tag="@string/login_password" android:layout_marginTop="@dimen/_12sdp" android:drawableLeft="@drawable/password_icon" android:id="@+id/login_ed_password" android:inputType="textPassword" android:hint="@string/login_password" style="@style/edittext"/> <TextView android:layout_marginTop="@dimen/_11sdp" android:id="@+id/login_tv_foregetPassword" android:text="@string/login_forgetPassword" style="@style/textView" android:textColor="#606060" android:textStyle="normal"/> <Button android:layout_marginTop="@dimen/_30sdp" android:id="@+id/login_bt_signin" style="@style/button" android:text="@string/login_singin" android:background="@drawable/big_green_btn_normal" /> <cl.tempclick.ui.custom_view.LineThroughTextView android:layout_marginTop="@dimen/_12sdp" app:android_textColor="#606060" android:gravity="center" android:layout_width="match_parent" android:layout_height="wrap_content" app:lineHeight="@dimen/_2sdp" app:lineColor="@color/colorGray" app:android_textSize="@dimen/_15sdp" app:android_text="@string/login_or" app:textPadding="@dimen/_10sdp"/> <Button android:layout_marginTop="@dimen/_12sdp" android:id="@+id/login_bt_linkedin" style="@style/button" android:text="@string/login_linkedin" android:background="@drawable/big_blue_btn_normal" /> <TextView android:layout_marginTop="@dimen/_12sdp" android:id="@+id/login_tv_noAccount" android:text="@string/login_noAccount" style="@style/textView" android:textStyle="normal" android:textColor="#606060" android:layout_marginBottom="@dimen/_7sdp"/> </LinearLayout> <ViewStub android:id="@+id/login_vs_empty" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:layout="@layout/empty_view" /> ```
2015/11/23
[ "https://Stackoverflow.com/questions/33864160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3528461/" ]
you must call textview `getLayout()` after the textview measure ,so it's better to call `getLayout()` in ``` textview.post(new Runnable() { @Override public void run() { textview.getLayout().... } }); ```
I think the error came from this line ``` mySpannable.setSpan(touchableSpan, GeneralFunctions.getText(myTextView).indexOf("Register"), GeneralFunctions.getText(myTextView).length(), 0); ``` try to logout you get the index value & textview text from gettext(textview) & indexOf() method.
13,576,031
Suppose we have the following: ``` class StringClass { public: ... void someProcessing( ); ... StringClass& operator=(const StringClass& rtSide); ... private: char *a;//Dynamic array for characters in the string int capacity;//size of dynamic array a int length;//Number of characters in a }; StringClass& StringClass::operator=(const StringClass& rtSide) { capacity = rtSide.capacity; length = rtSide.length; delete [] a; a = new char[capacity]; for (int i = 0; i < length; i++) a[i] = rtSide.a[i]; return *this; } ``` My question is: why does this implementation of overloading the assignment operator cause problems when we try to assign an object to itself like: ``` StringClass s; s = s; ``` The textbook I'm reading (Absolute C++) says that after `delete [] a;` "The pointer s.a is then undefined. The assignment operator has corrupted the object s and this run of the program is probably ruined." Why has the operator corrupted s? If we're reinitalizing s.a right after we delete it, why does this cause such a problem in the program that we have to redefine the function as: ``` StringClass& StringClass::operator=(const StringClass& rtSide) { if (this == &rtSide) //if the right side is the same as the left side { return *this; } else { capacity = rtSide.capacity; length = rtSide.length; delete [] a; a = new char[capacity]; for (int i = 0; i < length; i++) a[i] = rtSide.a[i]; return *this; } } ```
2012/11/27
[ "https://Stackoverflow.com/questions/13576031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1218732/" ]
Consider what the value of `rtSide.a` is when you're inside the broken `operator=`. It's the same as `this->a`, the values you just clobbered. Accessing non-owned memory is undefined behavior, thus accessing this->a is undefined behavior (since you just freed it). ``` delete [] a; a = new char[capacity]; for (int i = 0; i < length; i++) a[i] = rtSide.a[i]; //Invalid when this->a == rtSide.a //because rtSide.a is no longer owned by your program. ``` If you did actually want to do this, you would have to make a copy of a before deleting it: ``` char* ca; if (this == &rtSide) { ca = copy of rtSide.a or this->a; } else { ca = rtSide.a; } //Do your assigning and whatnot if (this == &rtSide) { delete[] ca; } ``` Obviously it's much more efficient to just do nothing instead of making temporary copies of all of an instances own members. It's the same concept as doing `int x = 5; int y = x; x = y;`
It is because you've first deleted the pointer `delete [] a;` and then later on trying to copy from the deleted location: ``` for (int i = 0; i < length; i++) a[i] = rtSide.a[i]; //rtSide has already been deleted as 'this' and '&rtSide' are same. ``` Remember it is the same location you are trying to copy from, which you've already deleted. Hence, the error! The later code you posted fixes this problem by checking for self-assignment as a separate case.
68,430,492
I'm not too sure if I'm just completely forgetting basics here but can someone please tell me why after changing the flag only T1 stops? ``` #include <thread> #include <iostream> void job(const bool &flag) { using namespace std::chrono_literals; while (flag) { std::cout << "Working T2" << '\n'; std::this_thread::sleep_for(1s); } } int main(int argc, char const *argv[]) { bool flag = true; std::thread t1([&flag]() { using namespace std::chrono_literals; while (flag) { std::cout << "Working T1" << '\n'; std::this_thread::sleep_for(1s); } }); std::thread t2(job, flag); std::cin.get(); flag = false; t1.join(); t2.join(); return 0; } ``` my understanding is that both are accessing the same piece of memory as the flag is being passed as a reference, so the job function should not be creating it's own copy of the flag, and should just access the same flag passed to it, is this not how this works? Many Thanks
2021/07/18
[ "https://Stackoverflow.com/questions/68430492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7187050/" ]
As posters above have mentioned, you'd need to check whether the value is null. You simply can't loop through an object that doesn't exist! So your choice would be not to use null objects in your structure -I'm not quite sure why you need them in the first place, maybe you could have a structure you loop through and another, placeholder structure - OR to check for null.
Onclick function should be outside of both of for loops. p.s: Using the snippet makes things easier. ```js var myObject = [{ "field one": "something ", "Image Gallery": [{ "src": "anImage.jpg", "title": "more text" }, { "src": null, "title": "a title here" }, { "src": "otherImg.jpg", "title": null } ], "Management": null, "Scientific Name": "Urophycis tenuis", "Species Illustration Photo": { "src": null, }, "last_update": "05/19/2021 - 13:04" }, { "Habitat Impacts": "something ", "Image Gallery": null, "Management": 'some value', "Scientific Name": null, "Species Illustration Photo": { "src": 'img.jpg', }, "last_update": "05/19/2021 - 13:04" }, { "Habitat Impacts": "something ", "Image Gallery": // Note that the Image gallery structure is a string here { "src": "anImage.jpg", "alt": "some text", "title": "more text" }, "Management": 'some value', "Scientific Name": "Urophycis tenuis", "Species Illustration Photo": { "src": 'img.jpg', }, "last_update": "05/19/2021 - 13:04" } ] function createCards(myObject) { let cardContainer = document.getElementById('cardContainer'); aInfoButtonLeft.onclick = function() { for (let i = 0; i < myObject.length; i++) { if (myObject[i]["Image Gallery"]) { for (let x = 0; x < myObject[i]["Image Gallery"].length; x++) { console.log(myObject[i]['Image Gallery'][x]["src"]) } } } } } createCards(myObject) ``` ```html <input id="aInfoButtonLeft" type="button" value="Button"> ```
24,193,845
I have a Bootstrap webpage set up which displays a collapsible table. Each table row has a button which has a `glyphicon-chevron-down` icon. When a user clicks on this button, that icon needs to change to `glyphicon chevron-up`. I have tried doing this a few different ways to no avail. Current set up is: ``` <script > function toggleChevron(button) { if (button.find('span').hasClass('glyphicon-chevron-down')) { button.find('span').className = "glyphicon glyphicon-chevron-up"; } if (button.find('span').hasClass('glyphicon-chevron-up')) { button.find('span').className = "glyphicon glyphicon-chevron-down"; } } </script> <button type="button" onclick="toggleChevron(this)" class="btn btn-default"> <span class="glyphicon glyphicon-chevron-down"></span> </button> ``` [JSFiddle](http://jsfiddle.net/V9LSS/2/)
2014/06/12
[ "https://Stackoverflow.com/questions/24193845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2887128/" ]
This works: ``` toggleChevron = function(button) { $(button).find('span').toggleClass('glyphicon-chevron-down glyphicon-chevron-up'); } ``` The main issue is that you are passing `this`, which isn't a jQuery object, so you need to wrap `button` in the jQuery function `$(button)` <http://jsfiddle.net/V9LSS/4/>
``` function toggleChevron(button) { if ($(button).find('span').hasClass('glyphicon-chevron-down')) { $(button).find('span').removeClass("glyphicon-chevron-down").addClass("glyphicon-chevron-up"); }else{ $(button).find('span').removeClass("glyphicon-chevron-up").addClass("glyphicon-chevron-down"); } } ```
12,016,235
i have the following CSS style sheet in Site.css ``` .img { width: 1300px; height: auto; } ``` and the following codes in my default.aspx ``` <div class="img"> <img src="http://files.g4tv.com/images/blog/2008/06/18/633493967095957891.jpg" alt="DOMO" /> <div class="desc">Add a description of the image here</div> </div> ``` how come my picture is not reflecting the width and height stated in the CSS?
2012/08/18
[ "https://Stackoverflow.com/questions/12016235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1470932/" ]
You are applying class to your division. If you want to select image inside division then Change to: ``` .img img { width: 1300px; height: auto; } ``` [Example](http://jsfiddle.net/4dkUP/)
Apply class on your `img` instead on that `div` ``` <div > <img class="img" src="http://files.g4tv.com/images/blog/2008/06/18/633493967095957891.jpg" alt="DOMO" /> <div class="desc"> Add a description of the image here </div> </div> ``` OR You can create your css like this ``` img { width: 1300px; height: auto; } ``` But it has a drawback that this css will be applied on every `img` in your document. So first one is better.