text
stringlengths
70
452k
dataset
stringclasses
2 values
How to get keyof typeof x when x is [key in string]: any I have the object x with the type [key in string]: any. I want to get key of type of x but when I do keyof typeof x, it's string. How can I get the keys of x? My code. InbuiltRuleNames is string. export type InbuiltRuleNames = keyof typeof rules; // OBS: DONT CHANGE PREFIX!!! // OBS: ADD ISSUE TO ISSUEIDS.md export const rules: { readonly [name in string]: Rule } = { 'multiple-context-bindings': { code: prefix(1), message: 'Only one of [$0], can control descendant bindings. Separate into distinct elements.' }, 'no-viewmodel-reference': { code: prefix(2), message: 'Missing ViewModel reference in file $0' }, 'multiple-comment-bindings': { code: prefix(3), message: 'Can not have multiple bindings in the same comment.' }, 'javascript-syntax-error': { code: prefix(4), message: 'JavaScript syntax error.' } }; I don't think there's an easy way to infer an object's keys but restrict its values. See How to make Typescript infer the keys of an object but define type of its value? for a workaround. Do I understand you correctly, that you want to have the type InbuiltRuleNames = "multiple-context-bindings" | "no-viewmodel-reference" | "multiple-comment-bindings" | "javascript-syntax-error"? The easiest way to to that would be to avoid setting a type to the rules object. Even though it's nicer to have a type.
common-pile/stackexchange_filtered
Jade rendering engine for Laravel5? Is there actually a Jade template engine for Laravel5? Jade code would be much easier to develop with, and - it would produce a compact HTML code. You can use build tools to compile Jade to HTML. https://github.com/gruntjs/grunt-contrib-jade I am new to Laravel since today, figuring out the same question you have. I think there are two different approches: Compiling via build tools First you could use npm, gulp and elixir - witch both come with Laravel. Therefore you have to have npm and gulp installed (I assume you already have). Use the laravel-elixir-jade module via npm i --save-dev laravel-elixir-jade After adding a couple of lines in your gulpfile you can run the default task via gulp Here is an example of an elixir function inside the gulpfile.js var elixir = require('laravel-elixir'); require('laravel-elixir-jade'); elixir(function(mix) { mix.less('app.less') .jade({ baseDir: './resources', blade: true, dest: '/views/', pretty: true, search: '**/*.jade', src: '/jade/' }); }); Dont forget the require('laravel-elixir-jade'); at the beginning. Compiling at server-side You also have the possibility to let the PHP-Server render your jade files while rendering the page. I have created a package called mhochm/laravel-jadephp could be the right module for you. I promise: Create views as always but in Jade syntax Require this package with composer: composer require mhochm/laravel-jadephp Add the ServiceProvider to the providers array in config/app.php: 'mhochm\LaravelJadePHP\LaravelJadePHPServiceProvider', I hope this will help you :) Moses thank you very much, I've been using laravel-elixir-jade for a while, but it always compiles all .jade files into .blade.php, so I wrote my own jade2blade script, which works without gulp, it watches for file changes on the .jade files and only compiles the necessary files. https://github.com/eschmid72/jade2blade/
common-pile/stackexchange_filtered
Finding $h(n)$ such that $h(n)/f(n) \rightarrow \infty$ and $h(n)/g(n) \rightarrow 0$ Suppose we have a function $f(n) = n^a$ for some fixed $a>0$ and another function $g : \mathbb{N} \rightarrow \mathbb{R}$ with $g(n) \rightarrow \infty$ such that $g(n)/f(n) \rightarrow \infty$ as $n \rightarrow \infty$. I.e. $g$ grows at a faster rate than $f$. I want to prove that there always exist a function $h : \mathbb{N} \rightarrow \mathbb{R}$ such that $h(n)/f(n) \rightarrow \infty$ and $h(n)/g(n) \rightarrow 0$ as $n \rightarrow \infty$. So my two questions are: A) Is this statement correct? B) How can I prove it? There seems to be a typo in your question. The title says $h/f$ and $h/g$, whereas the statement of the problem says $h/f$ in both cases. Thanks, @AnuragA, I've fixed the typos! Is this your homework? @uniquesolution, it's not homework. This lemma came up in relation to threshold functions in probabilistic graph theory. The simplest description of such a function (I think) is $$ h(n) = \sqrt{f(n)g(n)} $$ assuming $g(n)$ is always non-negative. If $g(n)$ is negative for some $n$, you need to tweak the definition of $h$ for those $n$. Beautiful, thanks a lot!
common-pile/stackexchange_filtered
Why mean life of radioactive element is slightly greater than halflife..? I was reading radioactivity where I find that half life of a radioactive material is less than mean life due the presence of $\log2$ in the numerator: $$ t_{1/2} = \frac{0.693}{\lambda} $$ But how what does it mean that the mean life is greater than the half life and why it need to be so? How strong is your calculus? Are you familiar with $e$, the natural logarithm, and the magic ways they interact with the kinds of integrals that go into computing an average? Possible duplicates here and here. Does this answer your question? Link between average lifespan and half time in radioactivity Does this answer your question? What is the mean life of a radioactive substance? I do not think that the answer has already been given. They mainly consists of proving that the relationship between half-life and transformation constant without an explanation in words. If anything this answer has within it the explanation. I would like to be given the opportunity to write a short answer to this question. See also What is the probability distribution for the detection times of radioactive emissions from a radioactive sample? TLDR: Half of the atoms in a sample will decay in less time than the half-life. The other half will take longer. Half of the other half will take more than twice as long. A few of the other half will take a lot longer. Those outliersβ€”the ones that take a lot longer to decayβ€”raise the mean lifetime.
common-pile/stackexchange_filtered
Layers in Leaflet.Draw is different every time What I want: To click delete, choose drawn layers, and delete them from the UI and firestore when clicking save How I have it now: Every time i am creating a new leaflet.Draw layer (ex. a rectangle), I save it to firestore, delete all, and create every layer again. This is to solve an issue of duplicating layers. However, every time i load and create layers from firestore (or refresh the page), the layers gets new id's. I need the id's to be consistent, so that I can store the id in firebase, and use it later for deletion. The question: How can i do this? Or is there a better way? The code I am using for creating is here: this.subscriptions.add(this.fieldmapsMainViewService.mapAnnotations$.subscribe(mapAnnotations => { console.log('mapAnnotations', mapAnnotations) this.mapAnnotations = mapAnnotations || [] this.drawnItems.clearLayers() // tslint:disable-next-line:prefer-for-of for (let i = 0; i < this.mapAnnotations.length ; i += 1 ) { if (this.mapAnnotations[i].type === 'rectangle') { // console.log('printing rectangle') L.rectangle([ [ this.mapAnnotations[i].NW.u_, this.mapAnnotations[i].NW.h_, ], [ this.mapAnnotations[i].SE.u_, this.mapAnnotations[i].SE.h_, ], ]).addTo(this.drawnItems) } } })) The way I'm finding the id when deleting is this: map.on(L.Draw.Event.DELETED, e => { // this.dummyMethod(this.dummyValue) e.layers.eachLayer(layer => { console.log(layer._leaflet_id) }) }) you have to create a own id. The leaflet_id is every time different, there is no way that this is constant @FalkeDesign I am trying to do this right now, but i can't seem to find any documentation on how to set own id. Any suggestions?
common-pile/stackexchange_filtered
PostGres - How to return null date in query I have the following function definition: CREATE FUNCTION accounting.func_getData(inputBusinessId bigint, injectionId bigint, inputEndDate DATE) RETURNS TABLE ( categoryName TEXT, amount DECIMAL, startDate DATE, endDate DATE ) LANGUAGE plpgsql AS $$ BEGIN RETURN QUERY( SELECT 'foo', <some value> AS amount, CAST(NULL AS DATE), inputEndDate UNION ... ) Originally I had 4 input params, one being a date that is always null, so we removed it and added CAST(NULL AS DATE), which works but seems to be noticeably slower, I can't change the returned columns because we have a common object that requires all fields used in multiple places, is there a way to fix this? Returning NULL does not seem to work here. Casting costs about half a microsecond, that in itself can’t be the issue. However, you didn’t share the rest of the code
common-pile/stackexchange_filtered
Rust read last x lines from file Currently, I'm using this function in my code: fn lines_from_file(filename: impl AsRef<Path>) -> Vec<String> { let file = File::open(filename).expect("no such file"); let buf = BufReader::new(file); buf.lines().map(|l| l.expect("Could not parse line")).collect() } How can I safely read the last x lines only in the file? Memory map the file, scan backwards successively for newlines x + 1 times, pull out everything after that last newline and convert it to lines? Same basic solution in any language. To avoid storing files in memory (because the files were quite large) I chose to use rev_buffer_reader and to only take x elements from the iterator fn lines_from_file(file: &File, limit: usize) -> Vec<String> { let buf = RevBufReader::new(file); buf.lines().take(limit).map(|l| l.expect("Could not parse line")).collect() } The tail crate claims to provide an efficient means of reading the final n lines from a file by means of the BackwardsReader struct, and looks fairly easy to use. I can't swear to its efficiency (it looks like it performs progressively larger reads seeking further and further back in the file, which is slightly suboptimal relative to an optimized memory map-based solution), but it's an easy all-in-one package and the inefficiencies likely won't matter in 99% of all use cases. I don't use rust enough (yet) to know if there's a generator equivalent (I'm sure there is) but a memory map solution seems potentially memory intensive. Especially in the case of a buf reader that doesn't know the length of a file. @BrandonKauffman: Memory mapping is virtual memory address space intensive (I don't recommend it if you're on a 32 bit system), but it's the opposite of RAM intensive; data is paged in solely on demand, a page at a time (the OS might prefetch a few pages beyond those accessed based on access patterns, more if you use an API like madvise to ask for more), everything else is pages that will be populated on demand (consuming no RAM until used, easily dropped if under memory pressure since they can always be reread from disk). Note: The tail crate seems to work well, but in many places it panics instead of returning an error, so it might not be suitable for all applications.
common-pile/stackexchange_filtered
ConEmu + WSL: Open new console in current tab directory I'm using WSL and ConEmu build 180506. I'm trying to setup a task in ConEmu to use the current directory of the active tab when opening a new console but I cannot get it to work. What I did is to setup the task {Bash: bash} using the instructions on this page setting the task command as : set "PATH=%ConEmuBaseDirShort%\wsl;%PATH%" & %ConEmuBaseDirShort%\conemu-cyg-64.exe --wsl -C~ -cur_console:pm:/mnt Then following the instruction on this page, I added to my .bashrc if [[ -n "${ConEmuPID}" ]]; then PS1="$PS1\[\e]9;9;\"\w\"\007\e]9;12\007\]" fi and finally setup a shortcut using the macro : Shell("new_console", "{bash}", "", "%CD%") But it always open the new console in the default directory ('/home/[username]'). I don't understand what I'm not doing right. I also noticed that a lot of environment variables listed here are not set. Basically, only $ConEmuPID and $ConEmuBuild seem to be set. Any help would be appreciated. Don't use Old Builds I uninstalled ConEmu, downloaded the installer and reinstalled but the problem remains. All environment variables has no sense because WSL is Unix subsystem and you can't run Windows binaries there. Does ConEmu show proper CD in Tab title (look for tab templates) or Restart dialog (Win+~)? Try macro Shell("new_console:I", "{bash}", "", "%CD%") ConEmu show proper directory path in the tab title. I tried the macro you posted but I got the following error (sorry it's a screenshot, I could not copy the text from the terminal): https://prnt.sc/ji6jfu If it might give any relevant info, the "Current Directory" given on the error screen is not the one from where I opened the new tab. It matches the "startup directory for new processes" displayed when I press Win+~ though. Regarding the tab templates, I'm not sure I understand. In the "Tab Bar" I see that in console, I have "<%c> %s" which should display "<Console #> Title" but I am not sure where that "Title" is defined. In my case that would correspond to "username@host: current directory". If I switch the console field to "%d" it only display the proper current directory. Sorry for the triple comments but I could not edit the previous ones anymore. I tried to change the macro to Shell("new_console:I", "{Bash::bash}", "", "%CD%") as it is the complete name of the task and instead of the previous error message, I now get http://prntscr.com/ji6wv9 (the first line changed) GuiMacro Shell was intended to run certain commands, not tasks. You think you may try to run macro Task("{bash}","%CD%") Or set your {bash} task parameters to -dir %CD% and just set hotkey for your task. Of course both methods require working CD acquisition from shell. Seems like it's OK in your case - %d shows proper folder. Thanks for the clarification. I actually have -dir %CD% in the task parameter but that doesn't help neither. I tried Task("{bash}","%CD%") but it's not working neither. It always open the home directory for the new console. I'm really stumped as indeed %d shows the correct value! Is there a way to retrieve that value and store it in an environment variable before opening the new console and then just set in my .bashrc a cd command using that environment variable? I got it to work. The issue was that I had -C~ in the task command which was forcing it to go to the home folder, apparently ignoring the task parameter. I removed it and now it works. Sorry, and thank you! Actually I restarted ConEmu and it's not working again :-/ What's happening now: if I am anywhere within my home folder (/home/zupalex/[...]) it opens the new tab in the default startup folder. If I am anywhere else (e.g. /mnt/d/) it displays en error message "Can't create new console, command execution failed (code 267) the directory name is invalid. [...] Working folder:"\mnt\d"". Not sure what's happening. I think there is an issue in the way the paths are passed between ConEmu and WSL. WSL home path can't be mapped to Windows filesystem, so these "invalid" paths can't be processed by ConEmu. You removed -new_console:m:/mnt? I tried to remove it at some point but I put it back. Currently it "kind of" work. It just produces errors if I try to open a new console while being in /mnt root directory or /opt/[...] or any other kind of path which is not either /mnt/[...] (which open the console in the proper location) or /home/user/[...] which open the console in the last known /mnt/[...] path. Is there any workaround to get the WSL "internal" paths working? I tried to assign the %CD% value to an environment variable with option -eTESTVAR=%CD% but then it actually literally assign %CD% to $TESTVAR instead of the value of %CD% %CD% is virtual variable processes only in certain places if ConEmu code. But the -e switch is processed by wslbridge. You may try -eTESTVAR=%ConEmuWorkDir% instead. As I said, certain WSL folders have no representation in Windows filesystem, so ConEmu can't "restart" your shell there. Thank you, I understand. Just trying to figure out if I could "post process" an invalid path using a environment variable :-) I'll mark the question solved though as it is solved as best as it can. I found the answer: Shell("new_console:I", "bash.exe", "", "%CD%") The readme is actually pretty good: https://github.com/cmderdev/cmder/blob/master/README.md
common-pile/stackexchange_filtered
TDateTime To ShortDateString In Satellite Forms "VB-clone" I am trying to find a calculation that will convert the TDateTime value 40653.6830593 into a year, a month, a day, an hour, a minute and a second. I am sure this is possible, of course, but my brain doesn't have the power, it seems, to write a formula that will extract those values from that double. I am using a Satellite Forms, a vb-like language, but don't expect that I would need any specific .NET libraries to do this, right? It should just be a numeric calculation... right? Thanks for the help! Most sincerely. Joe For verification, is your intended output for that value equal to 4/20/11 4:23:36 PM? Does this "vb-like" language have a name? To extract Hours, remember 1.0 = 24 hours, thus hours:= floor(0.683059324) mod 24, minutes:= floor(0.68305932460) mod 60, seconds:= minutes:= floor(0.6830593246060) mod 60 Legacy VB or VBA (even Excel) would treat a Date as the number of days since 12/30/1899, and I believe the same is true for Delphi. As such, in legacy VB/VBA, you could write Dim myDate as Date myDate = myDate + 40653.68303593 To get April 20, 2011 4:23:36 PM. In VB.NET, it's different, as the DateTime struct defaults to January 1, 0001. Dim myDate As New DateTime(1899, 12, 30) myDate = myDate.AddDays(40653.68303593) Another user has already posted a Delphi answer. At any rate, the basic premise is that you're adding the number of days, with the decimal portion representing the time. So in this example, 40653 full days have passed since 12/30/1899, and 0.683... partial days. worth to mention what fraction is special Based on your 'Delphi' tag... In Delphi implementation uses DateUtils; .... var MyDate: TDateTime; ...other vars... begin MyDate:= double(40653.6830593); MyYear:= YearOf(MyDate); MyMonth:= MonthOf(MyDate); MyDay:= DayOf(MyDate); MyHour:= HourOf(MyDate); MyMinute:= ... ah well you get the idea. BTW: VB or Delphi, which is it? If you want to roll your own From the sysutils unit (released under a dual license GPL2/Borland No nonsense) Which you can find at: http://www.koders.com/delphi/fidF6715D3FD1D4A92BA7F29F96643D8E9D11C1089F.aspx?s=hook function DecodeDateFully(const DateTime: TDateTime; var Year, Month, Day, DOW: Word): Boolean; const D1 = 365; D4 = D1 * 4 + 1; D100 = D4 * 25 - 1; D400 = D100 * 4 + 1; var Y, M, D, I: Word; T: Integer; DayTable: PDayTable; begin T := DateTimeToTimeStamp(DateTime).Date; if T <= 0 then begin Year := 0; Month := 0; Day := 0; DOW := 0; Result := False; end else begin DOW := T mod 7 + 1; Dec(T); Y := 1; while T >= D400 do begin Dec(T, D400); Inc(Y, 400); end; DivMod(T, D100, I, D); if I = 4 then begin Dec(I); Inc(D, D100); end; Inc(Y, I * 100); DivMod(D, D4, I, D); Inc(Y, I * 4); DivMod(D, D1, I, D); if I = 4 then begin Dec(I); Inc(D, D1); end; Inc(Y, I); Result := IsLeapYear(Y); DayTable := @MonthDays[Result]; M := 1; while True do begin I := DayTable^[M]; if D < I then Break; Dec(D, I); Inc(M); end; Year := Y; Month := M; Day := D + 1; end; end; function IsLeapYear(Year: Word): Boolean; begin Result := (Year mod 4 = 0) and ((Year mod 100 <> 0) or (Year mod 400 = 0)); end; function TryEncodeDate(Year, Month, Day: Word; out Date: TDateTime): Boolean; var I: Integer; DayTable: PDayTable; begin Result := False; DayTable := @MonthDays[IsLeapYear(Year)]; if (Year >= 1) and (Year <= 9999) and (Month >= 1) and (Month <= 12) and (Day >= 1) and (Day <= DayTable^[Month]) then begin for I := 1 to Month - 1 do Inc(Day, DayTable^[I]); I := Year - 1; Date := I * 365 + I div 4 - I div 100 + I div 400 + Day - DateDelta; Result := True; end; end; -1. I don't see how this is helpful. The question clearly states that the language being used is a "VB-like" language, not Delphi. The Delphi tag is there because the question is about the Delphi data type. An answer using Delphi-specific library functions isn't much help for someone using a different language. Maybe you could describe how DecodeDate works, instead, since that's what those functions all use. (And the functions are YearOf, MonthOf, etc., not just Year, Month, ....) @Rob included the code for DecodeDate, EncodeDate and IsLeapYear as well as a link. To bad the OP hasn't listed this mysterious language he's using, 'cause the stuff he's trying to do is probably already done in a standard lib for that language/IDE already. It is helpful, translate the above code to whatever "vb like" language you have. Its extremely unhelpful not to specify the actual language, but that's the OP's problem. Wow! This place is super helpful.. thanks for the replies. I should have checked back sooner to add more information. The mystery "VB-like" language I am using is a scripting language bundled with a mobile application RAD tool called Satellite Forms. The syntax is very vb-like (Len, InStr, Mod, etc...). I am looking for a way to turn a double into its component year, month, day, hour, minute, and second. From there, I will be able to generate a shortdatestring. To extract Hours: remember 1.0 = 1 day = 24 hours, thus DayPart:= double(MyDateTime) - Floor(double(MyDateTime)); //there is a function for fraction, but I forgot the name, //never use that stuff. //if we want to round 0.9999999999 up from 23:59:59 to 24:00:00, do this: if (RoundTimeUpByHalfASecond = true) then DayPart:= DayPart + (1/(24*60*60*2)); hours:= floor(DayPart*24); minutes:= floor(DayPart*24*60) mod 60; seconds:= minutes:= floor(DayPart*24*60*60) mod 60; Hope that helps
common-pile/stackexchange_filtered
raphael.js passing parameter using the .data() method I'm trying to use the .data method on raphael.js. var r = Raphael('diagram', width, width); [...] var z = r.path().attr({ arc: [value, color, rad], 'stroke-width': width/24 }); z.data({"entry": entry}); z.mouseover(function(){ this.animate({ 'stroke-width': width/14, opacity: .75 }, 1000, 'elastic'); if(Raphael.type != 'VML') //solves IE problem this.toFront(); title.stop().animate({ opacity: 0 }, speed, '>', function(){ this.attr({ text: this.data('entry').name + '\n' + this.data('entry').value + '%' }).animate({ opacity: 1 }, speed, '<'); }); Unfortunately it doesn't work. Is this a bug in raphael.js, or is my code incorrect? Please help, thank you. How can I pass the parameter to the mouseover method? http://jsfiddle.net/stefanszakal/St9Ky/ You are using Raphael JS 1.5. .data() method on elements was not implemented. Use this one: //cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js the fiddle works great with it. Error message: Uncaught TypeError: Object [object Object] has no method 'data'. I've tried in all sorts of ways to get this work and no success. when I try to do z.data({"entry": entry}); I get exception. By the way, I'm running this in Chrome. You were not using the good library version - I edited my answer Thank you, this fixed the runtime error. But this took me back to square 1. If you look at the widget when you go with mouse over the arcs, all arcs have the same value (text in the black circle). How can I get the desired behavior? Thanks This is not the original question. If you have another question, create a new one and close this one as answerd (but "giveme teh codez" questions are usually not appreciate.). And I don't know what is the desired behavior. Ok, I see: in the mouseover function, add: var entry = this.data('entry'); at the beginning and then, in the same function, instead of z.data('entry'). use entry.
common-pile/stackexchange_filtered
Metric to track actual CPU usage I've been a bit confused by the metrics available for monitoring CPU usage and what I'm looking for is to track actual CPU usage (not just increases) over time. kube-state-metrics exposes a container_cpu_usage_seconds_total metric which is a cumulative value represented as core-seconds. So if the latest value is 0.7, it means I used 700 millicores of CPU usage for 1 second so far. Most implementations trying to track CPU usage then apply the rate function to this metric which gives you how much the usage increased per second. So if the initial value (for the specified interval) is 0.2, then the calculation is (0.7-0.2)/(seconds_passed) which tells me how much additional CPU I used on average per second. Is there a metric that just tells me what the absolute CPU usage at a moment in time is (similar to container_memory_working_set_bytes for memory)? I feel like I am misunderstanding because most seem to be happy using a rate on the cumulative value, but it's not particularly helpful for me. For instance, when I see a service getting throttled, it would be great to know how high above the limit the CPU usage was. I'm also trying to look for services that are overprovisioned and having a metric showing the absolute usage over time would help so much. Thanks!
common-pile/stackexchange_filtered
$ \frac{a^{2}}{a+2 b^{3}}+\frac{b^{2}}{b+2 c^{3}}+\frac{c^{2}}{c+2 a^{3}} \geq 1 $ Question Let.a, $b, c$ be positive real numbers with sum 3 . Prove that $$ \frac{a^{2}}{a+2 b^{3}}+\frac{b^{2}}{b+2 c^{3}}+\frac{c^{2}}{c+2 a^{3}} \geq 1 $$ my doubt - by using cauchy reverse technique i have estimate the given expression with difference of two another expression and i just want to prove that $b \sqrt[3]{a^{2}}+c \sqrt[3]{b^{2}}+a \sqrt[3]{c^{2}} \leq 3$ now they write According to AM-GM, we obtain $$ 3 \sum_{c y c} a \geq \sum_{c y c} a+2 \sum_{c y c} a b=\sum_{c y c}(a+a c+a c) \geq 3 \sum_{c y c} a \sqrt[3]{c^{2}} $$ but how they proved that $ 3 \sum_{c y c} a \geq \sum_{c y c} a+2 \sum_{c y c} a b$ this means that $a+b+c > ab+bc+ca$ how ??? i know this is little doubt but i want to clear it .... thankyou OP's questions seem to be from a book. He seems to be working on the AM-GM section currently (or at least, for the previous question). @User88463 FYI These 2 recent questions are "very basic AM-GM", so maybe you should revisit the start of the book instead of reading deeper. They should have been almost immediate (in the sense that you know how to expand and force out the AM-GM if very desperate). ohh,yeah i did not see it..thanks calvin Hint: AM-GM $3 \sum a = (\sum a )^2 = (a^2+b^2+c^2) + 2\sum ab = \left(\frac{1}{2} \sum ( a^2 + b^2 ) \right) + 2 \sum ab $ $ \geq \sum ab + 2 \sum ab = 3 \sum ab $ Another way. We need to prove that $$a^3c^2+b^3a^2+c^3b^2\leq3$$ for non-negatives $a$, $b$ and $c$ such that $a^2+b^2+c^2=3$. Indeed, let $\{a,b,c\}=\{x,y,z\}$, where $x\geq y\geq z$. Thus, by Rearrangement, AM-GM and AM-GM we obtain: $$a^3c^2+b^3a^2+c^3b^2=a\cdot a^2c^2+b\cdot b^2a^2+c\cdot c^2b^2\leq x\cdot x^2y^2+y\cdot x^2z^2+z\cdot y^2z^2=$$ $$=y(x^3y+x^2z^2+z^3y)=y\left(x^2\left(xy+\frac{z^2}{2}\right)+z^2\left(\frac{x^2}{2}+yz\right)\right)\leq$$ $$\leq y\left(x^2\left(\frac{x^2+y^2}{2}+\frac{z^2}{2}\right)+z^2\left(\frac{x^2}{2}+\frac{y^2+z^2}{2}\right)\right)=\frac{3}{2}y(3-y^2)\leq3.$$
common-pile/stackexchange_filtered
Potassium permanganate and hydrogen peroxide decomposition I saw a reaction by chemicalforce on YouTube where he decomposed $\ce{H2O2}$ into $\ce{H2O}$ and $\ce{O2}$ using potassium permanganate. The permanganate is a catalyst in the reaction. I am wondering if this decomposition occurs because the initial $\ce{H2O2}$ decomposition reacts with the $\ce{KMnO4}$ and reproduces $\ce{H2O2}$ which then again decomposes? How is the permanganate a catalyst? Permanganate is not exactly a catalyst here, it gets destroyed as well. https://chemistry.stackexchange.com/questions/43256/why-is-the-reaction-between-potassium-permanganate-and-hydrogen-peroxide-spontan Potassium permanganate is involved in two ways. It oxidizes hydrogen peroxide to oxygen: $$\ce{2 MnO4- + 3 H2O2 -> 2 MnO2 + 2 OH- + 3 O2 + 2 H2O}$$ The formed $\ce{MnO2}$ acts as the catalyst of reaction: $$\ce{2 H2O2 ->[MnO2] 2 H2O + O2}$$ Hello Poutnik! Is it a mistake to call the first reaction a disproportionation? The oxidation state of oxygen goes down (to $-2$ in $\ce{H2O}$) and goes up (to $0$ in $\ce{O2}$). Or calling it a redox reaction is more accurate in this case? You would not need permanganate for it.
common-pile/stackexchange_filtered
Download a file using file ID in google app script I have a drive link to the CSV file that should be downloaded to my local machine. But not sure about how to do that. I can get the file name from the file ID. I am not clear on how to download the file. function myFunction() { var fileID = '1e598PoBd76cALrawCR5mrKAaQdDiz2LR' var fileName = DriveApp.getFileById(fileID).getDownloadUrl() Logger.log(fileName); } Can anyone help me to download the file to the specified location on my local computer? TIA! It depends. Would a Web App work for your case? I need to set a trigger for a function that downloads the file based on the file IDs which will be populated in a column in google sheet What kind of trigger is it? Also, would it be always need to be downloaded to the same computer? Or to the computer of whoever is dispatching the trigger (eg. somebody who edited the sheet)? It should be downloaded in the same machine For the same machine I'd consider to install Google Drive. This way any file saved on cloud Drive (in a synced folder) will appear on the local machine. There are multiple ways of doing this. Do you need to avoid user interaction (make it fully-automated)? Can you have a local script? Can you run scripts and use Google libraries (for example using Python 3 with pip)?
common-pile/stackexchange_filtered
Spring JMS configuration of a queue Consumer I am trying to run a very basic application to learn Spring JMS + ActiveMQ. I see my Producer creating the message (sysout), but nothing shows up in my Consumer and no exception is thrown. I think I am missing something simple here; would really appreciate any help. [EDITED, THE FOLLOWING CODE WORKS] Producer: @Component public class JmsMessageProducer { @Autowired private JmsTemplate template; public void generateMessages() throws JMSException { template.send(new MessageCreator() { public Message createMessage(Session session) throws JMSException { System.out.println("sending.."); TextMessage message = session.createTextMessage("this is a Producer created message!"); return message; } }); } } Consumer: @Component public class JmsMessageConsumer implements MessageListener { @Override public void onMessage(Message message) { if (message instanceof TextMessage) { TextMessage tm = (TextMessage) message; try { System.out.println("CONSUMER - received ["+tm.getText()+"]"); } catch (Throwable th) { th.printStackTrace(); } } } } Producer Configuration: <context:component-scan base-package="mrpomario.springcore.jms"/> <!-- finds the JmsMessageProducer --> <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"> <property name="brokerURL" value="tcp://localhost:8082"/> </bean> <bean id="pomarioQueue" class="org.apache.activemq.command.ActiveMQQueue"> <constructor-arg value="mrpomario.springcore.jms.queue"/> </bean> <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"> <property name="connectionFactory" ref="connectionFactory"/> <property name="defaultDestination" ref="pomarioQueue"/> </bean> Consumer Configuration: <jms:listener-container> <jms:listener ref="jmsMessageConsumer" method="onMessage" destination="mrpomario.springcore.jms.queue"/> </jms:listener-container> <bean id="pomarioQueue" class="org.apache.activemq.command.ActiveMQQueue"> <constructor-arg value="mrpomario.springcore.jms.queue"/> </bean> <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"> <property name="brokerURL" value="tcp://localhost:8082"/> </bean> <amq:broker id="broker" useJmx="false" persistent="false"> <amq:transportConnectors> <amq:transportConnector uri="tcp://localhost:8082" /> </amq:transportConnectors> </amq:broker> Test Case: @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:mrpomario/springcore/jms/jms-config.xml") public class JmsTest { @Autowired JmsMessageProducer jmsMessageProducer; @Test public void test_Single_Queue_Producer_and_Consumer_Unidirectional() throws JMSException { try { jmsMessageProducer.generateMessages(); assertTrue(true); } catch (Throwable th) { System.out.println("\n\nJmsTest: remote invocation failed. Ensure the web server is running.\n\n"); } } } I run the producer inside a Java EE container (mvn jetty:run) where a Spring MVC application also runs. I think you are ending up sending to and consuming from two completely different brokers(and subsequently different queues): Have your broker defined in only one place, say your producer config: <amq:broker id="broker" useJmx="false" persistent="false"> <amq:transportConnectors> <amq:transportConnector uri="tcp://localhost:8082" /> <amq:transportConnector uri="vm://localhost" /> </amq:transportConnectors> </amq:broker> <amq:connectionFactory id="jmsFactory" brokerURL="vm://localhost" /> From your consumer config remove the broker configuration and have only the connectionFactory: Either (if you are in the same VM): <amq:connectionFactory id="jmsFactory" brokerURL="vm://localhost" /> Or(If remote): <amq:connectionFactory id="jmsFactory" brokerURL="tcp://localhost:8082" /> Hi Biju, thanks a lot for your feedback! I tried a new configuration layout that follows that of an official Spring tutorial, but still cannot make it work (the consumer is not invoked). Would you please review it and give me feedback? Looks good, can you confirm if you are running the producer and the consumer from in the same vm.. yup, both running in the same VM. The Producer is running using JUnit and the Consumer is running inside an embedded Jetty server (starts with mvn jetty:run). Could this configuration layout be causing me trouble? Yes, I think so Pomario, it is likely not the same VM hmmm... how would you go about it, I mean, having a Consumer in on VM and the Producer in another? If you want consumer in one and producer in another one, that is also straightforward with ActiveMQ, you will have to expose a ActiveMQ as a server - the first broker configuration in my answer does it..<amq:transportConnector uri="tcp://localhost:8082"/> and connect from the consumer also using the same url instead of vm://.. It works! :-) One last question before I close, @Biju: why do I need to define the Consumer URL twice, one in the connectionFactory bean then duplicate the same URL in the broker bean? See my code (I updated it with the working version)
common-pile/stackexchange_filtered
Does xcode support tab controls? I am developing a dashboard system which I need to split the app's screen into 4 blocks. Each block needs to have a page/tab control with different tabs such as day, month, week, etc Is this not supported in xcode? I can only see references to a tab control where the tabs are at the bottom of the app's screen By "in Xcode", do you mean the Cocoa Touch API? Yes I will be using monotouch so will have access to all the native controls Well I think I mean cocoa touch Api not too sure as am new to this Note that Xcode is just the IDE. @Paul Fine, I edited the tags. Can you please try one of the control here in http://www.cocoacontrols.com/tags/tab? Thanks looks like I could use the browser tab view. I can't test it yet but I think it will be fine but I need to see how I can get 4 of them on a screen on the iPad I strongly recommend sticking with the tabs at the bottom. If you want them at the top you will have to implement your own solution or find one by someone else. I will be having 4 charts visible at once , each chart needs to be in its own page control so that the user can be on, say, month for 2 charts and year for the other 2. The normal tab approach wouldn't allow me to show all 4 charts at the same time
common-pile/stackexchange_filtered
Where does discrete probabilities in Forward-Backward algorithm for Hidden Markov Models come from? I am trying to derive a Forward-Backward algorithm used in Hidden Markov Models to compute the likelihood $P(x | \theta)$ that sample $x = (x_1, ... x_n)$ comes from HMM defined by set of parameters $\theta$ which includes: $k \times k$ transition matrix $A$ such that $A_{i,j}$ gives probability of transition from hidden state $Z = i$ to hidden state $Z = j$. initial probabilities $\pi_1 = P(Z_1 = 1), ..., \pi_k = P(Z_1 = k)$ parameters of distributions of $X$ for each hidden state, e.g. if we assume Gaussian distribution then we have $(\mu_1, ... \mu_k), (\sigma_1, ..., \sigma_k)$ I wrote down that $$P(x|\theta) = P(x_1 | \theta) \cdot P(x_2 | x_1; \theta) \cdot ... \cdot P(x_n | x_1, ..., x_{n-1}; \theta)$$ which is also how all video explanations and articles I've ever seen start. Then I realized when distribution is discrete, it doesn't make sense. All sources say at the beginning something like "we assume that matrix $A$, vector $\pi$ and probabilities $P(X = x | Z = k)$ are known", somehow going from knowing parameters of in many cases continuous distribution to discrete probabilities. How is it done? For the discrete version, the distributions of $X$ (e.g. Gaussian distributions) are replaced with discrete probabilities. These discrete probabilities are the new parameters of the model. The formula you wrote still holds! If you have some model in mind, you will have to discretize your probability distributions. For example: if $x_1 = -1, x_2 = 1$, then if you have a Gaussian centered at 0 for $Z=1$ and a Gaussian centered at, say 1, with $\sigma=1$ for $Z=2$, then $P(X=x_1|Z=1)=1/2, P(X=x_2|Z=1)=1/2, P(X=x_1|Z=2)=1/(1+e^{-4}),P(X=x_2|Z=2)=e^{-4}/(1+e^{-4})$ @Daylight so by "probability od x1" they mean "value of probability density function at point x1", right? And another question is: what about parameter estimation, when we know only the data x1, ... xn and use Baum-Welch to fit the model, i.e. estimate its parameters. Do we estimate parameters of distribution then, or just probability densities again - it sounds bad because then we wouldnt be able to generate samples from fitted model. Yes. Although idk how they defined the PDF. I've only worked with discrete probabilities. With these, we just describe a PDF as some function $P$ such that $P(x_1)+P(x_2)+...+P(x_n) = 1$, where ${x_i}$ are the set of all observables. 2. You must give a guess for the probability densities initially for an HMM. You must define what the observables $x_1, ..., x_n$ are, though. Using these, and a sequence of observations $x(t=1), x(t=2), ...$, you can estimate the parameters $A$, $\Pi$, and $B$ (for the discrete case) or I guess $\mu$ and $\sigma$ (for the continuous case?)
common-pile/stackexchange_filtered
Generate keys on smartcard with given exponent I am generating keys on a smartcard with OpenSC. Is it possible to specify a certain exponent to use? Currently I am calling sc_pkcs15init_generate_key() to generate the key pair. But I did not find a way to set the exponent. I am aware, that it is possible to generate the key with a given exponent on the PC, but I do not want to do that for security reasons. Not all smart cards are happy with the exponents you'd like to use, even when importing existing keys. There is no uniform way of passing in the exponent for the newly generated key in OpenSC, AFAIK/AFAIS.
common-pile/stackexchange_filtered
Is it necessary to have static constructors when we follow the "RAII " way of doing things in C++? If I were to follow the RAII rule and would be developing a class in C++, would it be necessary to have static constructors? Will static constructors help me in any way or would be a wrong step to do? are there static constructors in C++? there is no such thing as static constructor in c++. what are you talking about? By static constructor, you mean having the real constructor private, and static functions creating objects? I take it you are talking about a static factory function that creates an instance of your class (As others pointed out). In which case, you don't need to use the RAII pattern. Remember you need your class to be stack allocated, so that the constructor is called (automatically) and initializes various data. also, the destructor is called (automatically) when the stack unwinds and performs other operations: such as freeing resources etc.. If your class initializes it's data statically then the RAII pattern will fail, since statically held data is not bound to an instance of a class. So when the stack unwinds there is no instance to destruct, no destructor gets called, and the RAII pattern is not implemented. That doesn't make any sense, you cannot have a static constructor. The entire purpose of the constructor is to initialize a specific instance of a class; if it were static, it wouldn't belong to any instance. RAII just says that you need to free a resource in the destructor, and that the acquisition of that resource happens with the initialization (construction) of the object who will run that destructor. (Which entails you need a working or forbidden copy-constructor, along with a working assignment operator.) You could have some static function CreateInstance() that would return you the instance of your class. With RAII your function will probably have to return you some smart pointer to the instance you created to avoid copying of the actual object. Then you store this pointer, copy it if you need it in other places. When all smart pointers are destructed the object will be destructed too. If that's what you want, then yes - you could have "static constructor". Of course it's not a must in RAII and normally would be just unneeded complication.
common-pile/stackexchange_filtered
IPC between multiple pods on same kubernetes node I know that containers in a Pod can share data with each other via shared memory.γ€€γ€€ But, i have not found a way to use shared memory between Pods. Is it possible by enabling HostIPC in Pod Security Policies? https://kubernetes.io/docs/concepts/policy/pod-security-policy/#host-namespaces Of course, i know that this setting is not recommended for security reasons. Did @WytrzymaΕ‚y Wiktor answer help you to solve your problem?If yes,Please consider accepting and upvoting it. What should I do when someone answers my question? Yes, you can use shared memory by setting hostIPC: true in the Pod Security Policy: hostIPC - Use the host’s ipc namespace. Optional: Default to false. Notice that you can't link 2 isolated Pods (Pods not allocated on the same Node) IPC spaces together but any hostIPC Pod would be able to use shared memory with any other hostIPC Pod. You can make sure that the Pods are scheduled together by using nodeSelector or Affinity and anti-affinity. Bear in ind that you also need to use a proper volume type. For example emptydir will not work but hostPath can be used. I know you mentioned that but I need to underline the fact that by using the hostIPC you give ability to access data used by any pods that also use the host’s IPC namespace which creates a severe security risk. Here are some examples of it. @Yuuuskeeeeeeee Does this answer your question?
common-pile/stackexchange_filtered
What is the simplest way to expand a slice to its capacity? I have a program that uses a buffer pool to reduce allocations in a few performance-sensitive sections of the code. Something like this: play link // some file or any data source var r io.Reader = bytes.NewReader([]byte{1,2,3}) // initialize slice to max expected capacity dat := make([]byte, 20) // read some data into it. Trim to length. n, err := r.Read(dat) handle(err) dat = dat[:n] // now I want to reuse it: for len(dat) < cap(dat) { dat = append(dat, 0) } log.Println(len(dat)) // add it to free list for reuse later // bufferPool.Put(dat) I always allocate fixed length slices, which are guaranteed to be larger than the maximum size needed. I need to reduce size to the actual data length to use the buffer, but I also need it to be the maximum size again to read into it the next time I need it. The only way I know of to expand a slice is with append, so that is what I am using. The loop feels super dirty though. And potentially inefficient. My benchmarks show it isn't horrible, but I feel like there has to be a better way. I know only a bit about the internal representation of slices, but if I could only somehow override the length value without actually adding data, it would be really nice. I don't really need to zero it out or anything. Is there a better way to accomplish this? "Extending" a slice to its capacity is simply a slice expression, and specify the capacity as the high index. The high index does not need to be less than the length. The restriction is: For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range. For slices, the upper index bound is the slice capacity cap(a) rather than the length. Example: b := make([]byte, 10, 20) fmt.Println(len(b), cap(b), b) b = b[:cap(b)] fmt.Println(len(b), cap(b), b) Output (try it on the Go Playground): 10 20 [0 0 0 0 0 0 0 0 0 0] 20 20 [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] Wow, I feel silly now. I swear I tried that and got out of bounds or something. But it does indeed work, as long as you stay under the capacity. You can expand a slice to its capacity with slicing: s = s[:cap(s)] Using built-in copy & append func, many operations can be done on top of this. See: https://github.com/golang/go/wiki/SliceTricks#expand
common-pile/stackexchange_filtered
Is My Reactjs Components too Granular? I am playing around with Reactjs and I am wondering if I broken out my components too much. <script type="text/babel"> class MainCompoent extends React.Component { constructor() { super(); this.state = { items : [ { name: 'Test 1', type: { value: "1"}, types: [ { value: "2"}, { value: "1} ] }, { name: 'Test 2', type: { value: "1"}, types: [ { value: "2"}, { value: "1} ] }, ] }; } componentDidMount() { } render() { return ( <div className="item-container"> { this.state.items.map((item, i) => { return <Item item={item} index={i} /> }) } </div> ) } } class Item extends React.Component { constructor() { super(); } componentDidMount() { } render() { return ( <div className="item"> <General item={this.props.item} index={this.props.index} /> <Specific1 /> <Specific2 /> </div> ) } } class Specific1 extends React.Component { constructor() { super(); } componentDidMount() { } render() { return ( <div className="Specific1-container"> <h1>Specific1 Container </h1> </div> ) } } class General extends React.Component { constructor() { super(); } componentDidMount() { } handleChange(event) { this.props.handleChange(event.target.value, this.props.index); } handleChange2(event) { this.props.handleChange2(event, this.props.index); } render() { return ( <div className="general-container"> <h1>General Container </h1> <div> <label>Name</label> <input type="text" value={this.props.item.name}/> </div> <div> <label>Type </label> <select value={this.props.item.type.value} onChange={(event) => this.handleChange(event)}> { this.props.item.types.map((type, i) => { return <option key={'type-' + i} value={type.value} >{type.value}</option>; }) } </select> </div> </div> ) } } class Specific2 extends React.Component { constructor() { super(); } componentDidMount() { } render() { return ( <div className="specific2-container"> <h1>Specific2 Container </h1> </div> ) } } ReactDOM.render(<MainCompoent />, document.getElementById("Container")); </script> The above code I stripped out everything I don't think was necessary. I am trying to do this without flux or redux. In the Item container, there are 3 components that get rendered together. The general will always be shown but only 1 of the other 2 will ever be shown(despite my similar names they are different and have to be 2 separate components). All 3 components do share properties and hence why I put the state in the top and was passing it down. The one thing though is when I have to update this state I potentially have to go up 2 parents(ie handelChange from General would have to go up to Item which would have to go to MainComponent to update the state). Is this bad? This isn't bad, but is there a reason you don't want to use flux methods? They're a nice way to keep organized. As far as keeping things flowing efficient and working well you should be fine, but it'll just be harder to organize w/o is all. Well I usually use redux myself so never had this issue before but my team is looking how to use reactjs with SalesForce, since my team does not really know reactjs and I don't really know SalesForce, I am trying to stick the basics as seems big harder to get Redux structure into SF. Gotcha, you seem to have the right idea then! My problem with my solution is, it ok have to bubble up so many times? I wondering if I can somehow cut down on it. kinda sucks that in General I have to pass in the onChange to the Item OnChange then to the MainComponent onChange. The only issue I see is that you are passing props back to the parent, e.g. this.props.handleChange(event.target.value, this.props.index). Why don't you handle that in the parent controller passing directly event => handleChange(event, index) to child? And no, it's not too granular. In my team we would probably split some of the components even more - into smart and dumb parts. Don't worry about granularity, components can have one line. Worry about the separation of concerns. Every component should be working independently. Well that is my concern as well passing back to the parent over and over again to update the state in my MainComponent. Can you go into more detail how you would solve this. What I am doing is what I saw in a tutorial where you have an event and you basically bubble it back to the parent. I'd stacked with similar question and found to my self a pretty simple answer. It all depends on what level of abstraction do you need. Eg. if Item component could not "live" without General then the better way is to include General to Item. If they are totally independent then you could simply keep General props-API stable and change itself. Passing props to the parent is OK, but the better way is to keep one source of truth. If you don't want to use any of data-flow libraries (redux, flux, whteverx) then simply make the Root component as the smartest. Let it to control of app-state changing. Here is a nice "guide" how to let React components communicate with each other (https://facebook.github.io/react/docs/lifting-state-up.html). Parent to Child via Props, Child to Parent via Callbacks.
common-pile/stackexchange_filtered
What's the correct SQL Server syntax for a script that will create a table if it doesn't exist or else alter it to add new columns? Not sure if I should have gone to DBA.StackExchange with this but I'm a software developer needing to add columns to an existing back-end database table called T with existing columns I, J, and K (all of type INT). This is so that my new front-end code will work. The table has two existing foreign keys FK_T_U, and FK_T_V, referring to other related tables U, V. All I'm doing is adding three new true/false BIT columns (X, Y, Z) to the table but I need a script to do this. Simple enough! I'm using SQL Server 2014. There's already a CREATE TABLE script present in our source repository which I thought I'd surround with an IF EXISTS and an ELSE statement and insert an ALTER TABLE sequence in the midst. This way, a future redeployment could simply ALTER the existing table, or create it if it was in fact absent. Good idea? I'm having a little trouble getting there so I thought I'd speed this effort up by asking for help on StackOverflow. Your assistance is much appreciated! Here's the existing [working] CREATE script: BEGIN TRANSACTION if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[T]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) drop table [dbo].[T] CREATE TABLE [dbo].[T] ( [I] [int] IDENTITY (1, 1) NOT NULL , [CourseK] [int] NULL , [I] [int] NOT NULL , [K] [int] NULL , CONSTRAINT [PK_T] PRIMARY KEY CLUSTERED ( [I] ) ON [PRIMARY] ) ON [PRIMARY] GRANT SELECT ON [dbo].[T] TO [OtherApplication] GRANT SELECT , INSERT ON [dbo].[T] TO [AnotherApplication] ALTER TABLE [dbo].[T] WITH NOCHECK ADD CONSTRAINT [FK_T_U] FOREIGN KEY ( [K] ) REFERENCES [U] ( [K] ) ALTER TABLE [dbo].[T] WITH NOCHECK ADD CONSTRAINT [FK_T_V] FOREIGN KEY ( [I] ) REFERENCES [V] ( [I] ) COMMIT TRANSACTION You might want to consider using DACPAC in future, which is meant to make this incremental deployment easier.. https://www.red-gate.com/simple-talk/sql/database-delivery/microsoft-and-database-lifecycle-management-dlm-the-dacpac/ BEGIN TRANSACTION IF NOT EXISTS (SELECT * FROM sys.tables t WHERE t.name='T') BEGIN CREATE TABLE [dbo].[T] ( [I] [int] IDENTITY (1, 1) NOT NULL , [CourseK] [int] NULL , [I] [int] NOT NULL , [K] [int] NULL , CONSTRAINT [PK_T] PRIMARY KEY CLUSTERED ( [I] ) ON [PRIMARY] ) ON [PRIMARY] GRANT SELECT ON [dbo].[T] TO [OtherApplication] GRANT SELECT , INSERT ON [dbo].[T] TO [AnotherApplication] ALTER TABLE [dbo].[T] WITH NOCHECK ADD CONSTRAINT [FK_T_U] FOREIGN KEY ( [K] ) REFERENCES [U] ([K]) ALTER TABLE [dbo].[T] WITH NOCHECK ADD CONSTRAINT [FK_T_V] FOREIGN KEY ( [I] ) REFERENCES [V] ([I]) END IF NOT EXISTS (SELECT * FROM sys.tables t INNER JOIN sys.columns c ON t.object_id=c.object_id WHERE t.name='T' and c.name='X') BEGIN ALTER TABLE [T] ADD [X] BIT; END IF NOT EXISTS (SELECT * FROM sys.tables t INNER JOIN sys.columns c ON t.object_id=c.object_id WHERE t.name='T' and c.name='y') BEGIN ALTER TABLE [T] ADD [Y] BIT; END IF NOT EXISTS (SELECT * FROM sys.tables t INNER JOIN sys.columns c ON t.object_id=c.object_id WHERE t.name='T' and c.name='Z') BEGIN ALTER TABLE [T] ADD [Z] BIT; END COMMIT TRANSACTION Thank you so much for your ideas! I'm a big fan of checking for an object id... IF (SELECT OBJECT_ID('DATABASENAME..TABLENAME')) IS NOT NULL BEGIN <DO THINGS HERE> END
common-pile/stackexchange_filtered
Improving braking performance of long reach Tektro R559 calipers? I've been gradually restoring an old Fuji 3-speed, and I'm looking to improve the braking performance. Right now, if I have any speed at all, I feel like I can barely get enough braking power to come to a stop. In particular, the rear brake feels very weak. I installed Tektro R559 calipers. The rear wheel has an aluminum rim (27") which I expected would improve braking performance but the rear brake feels much weaker than the front. Currently, I'm still using the original Dia-Compe levers, but I'm wondering if replacing the levers with new levers like the Tektro FL750 would improve the braking performance, or is there a better model/style of lever I should go for? I can't tell from the product specs if the Tektro FL750 would have better geometry/pull for the new calipers, as compared with my original Dia-Compe levers. What are the specs that I should look for in new levers to maximize braking power? I am also considering replacing the cables/housing (should be done regardless of whether or not I change the levers), so any recommendations on housing is also appreciated. Last question: the front wheel still has the original steel rim. Should I replace the brake pads on the front with something "steel specific"? Or would you recommend I replace the steel rim with a new aluminum rim? Here are a few photos: Update: I have replaced the brake housing and cables (Shimano Universal Brake Cable Set), as well as installed new levers. For the levers, I decided to go with Velo Orange's Grand Cru short pull levers. The brake performance was dramatically improved with the new housing. The old cables didn't slide smoothly in the housing, reducing how much force was getting applied at the wheel. The new cables/housing account for 90% of the improved braking performance. The new levers feel lovely and are very crisp, with no lateral play. I'm sure I could have gotten cheaper levers that work similarly, but these levers are a delightful treat/upgrade. I adjusted the calipers so they're as close to the rims as possible without rubbing, and the short pull levers ensure I'm getting plenty of force when I squeeze the levers even just a little bit. In the future, it would be nice to replace the front steel wheel with an alloy rim to further improve braking performance, but for now I'm happy with the braking performance, and it's probably "good enough" for the kind of riding I use this bike for (mostly flat urban environment, never at very high speeds, with only occasional rain). Side comment - yes its absolutely worth replacing the front steel rim with an aluminium rim, if you can do so. Most of your braking comes from the front brake, the rear is relatively useless normally. There are no steel/aluminium specific brake pads, they're the default. Right now, if I have any speed at all, I feel like I can barely get enough braking power to come to a stop. In particular, the rear brake feels very weak. You failed to explain why it feels weak. There are two reasons for a brake to be weak: You need unacceptably high hand force to get the desired braking You pull the lever so close to the bars that it's hard to squeeze it anymore due to the changed geometry If the brake is weak for reason (1), then you need brake levers with more mechanical advantage. I'm not sure what the mechanical advantage of your brake levers is. Unfortunately, this is not something that brake lever manufacturers openly tell. You could buy some brake levers, but you don't at all know what mechanical advantage you are going to get. However, generally the trend in levers has been towards slightly increasing mechanical advantage, so more modern levers could be worth trying. Note that generally there are two approximate pull ratios: long pull (for V brakes) and short pull (for calipers and cantilevers) but the exact pull ratio differs from lever to lever (so two levers in a same category won't be the same), so pairing V brake levers with caliper brakes could create an issue where you can't get enough braking force even if you squeeze the lever very hard. However, an old bike is unlikely to have V brake levers. Nevertheless, if you buy new levers, you have to buy short-pull levers, not any long pull / V brake levers. Finding flat bar short-pull levers today could be tricky because it's all long pull for flat bars today. If the brake is weak for reason (2), it may be that the calipers themselves are at fault, or the cabling system could have too much flex. The problem of long-reach caliper brakes is that they flex a lot, because the caliper arms need to be long and the longer a beam is, the more it flexes. Unfortunately, in this case you don't have any good solution. Cantilevers and/or V-brakes could be a solution but if your frame has caliper brake mounts, most likely it lacks the cantilever posts that are needed for both cantilevers and V-brakes. However, on mechanical brakes first diagnosis of (2) should be whether the brakes have correct pad clearance. So if the brake pads are too far away from the rims, adjust the cable tension using the barrel adjuster first and if that doesn't have any adjustment range left, you may need to re-clamp the inner cable at the brake. Also checking that pads are correctly aligned against the rim can help, because if the pads only partially touch the rim, it can cause too much flex. Racing bikes use so ridiculously short-reach brakes that you probably can't fit anything more than a 23mm tire, and forget about mounting fenders. The reason for this is that such brakes can be made very lightweight and stiff (free of flex) at the same time unlike long-reach brakes which usually can be neither. Fortunately today this is changing due to introduction of disk brakes, but unfortunately disk brakes suffer from issue (2), i.e. the brake system may have too much flex to have acceptable braking. With even perfectly bled disc brakes, it's very easy to move the lever very close to bars, making it impossible to brake with such great force that the rear wheel rises from the ground unless the cyclist is very lightweight. Note that solving issue (1) will make issue (2) worse, so if your levers have too much mechanical advantage, they will touch the bars and you are unable to get the required braking force. As for cables and housings, forget any no-name supplier and choose the genuine one, Shimano. They have SLR housing for short-pull brakes (calipers, cantilevers) that are dimensionally stable under huge forces and M-system housing for long-pull brakes (V-brakes) that has low friction needed for long pull. Also Shimano inner cables are of very good quality. Pick only stainless steel inner cables. Steel rims shouldn't be used in the wet. You will have terrible braking with almost no recovery even after many wheel rotations. As for brake pads, generally Kool Stop Salmon is considered one of the best. I understand Swiss Stop BXP is also very good. But most cyclists who use them use them on aluminum rims, I have absolutely no idea how these work for steel rims. If the brake pads are old, they could have lost their friction coefficient and installing any brand of new brake pads could improve braking. Speaking of mechanical advantage, the OP has old flat bar levers paired to Tektro brakes that have a road pull ratio. So, there’s a good chance this is right on - I say good chance because I don’t know what the pull ratio of old and low cost flat bar levers is.
common-pile/stackexchange_filtered
Comparing percent change of model coefficients I am working through step 3 of purposeful model-building from Hosmer-Lemeshow and it suggests to compare the percent change in coefficients between a full model [Iris.mod1] and a reduced model [Iris.mod2]. I would like to automate this step if possible. Right now I have the following code: #Make species a binomial DV iris = subset(iris, iris$Species != 'virginica') iris$Species = as.numeric(ifelse(iris$Species == 'setosa', 1, 0)) #Build models Iris.mod1 = glm(Species~Sepal.Length+Sepal.Width+Petal.Length+Petal.Width, data = iris, family = binomial()) Iris.mod2 = glm(Species~Sepal.Length+Petal.Length, data = iris, family = binomial()) The dataset I am actually using has about 93 variables and 1.7 million rows. But I am using the iris data just for this example. #Try to see if any coefficients changed by > 20% paste(names(which((summary(Iris.mod1)$coefficients[2: (nrow(summary(Iris.mod1)$coefficients)),1] - (summary(Iris.mod2)$coefficients[2: (nrow(summary(Iris.mod2)$coefficients)),1]/ (summary(Iris.mod1)$coefficients[2:nrow(summary(Iris.mod1)$coefficients)),1] > 0.2 == TRUE))))) However, this code is full of errors and I am lost in a sea of parenthesis. Is there an efficient way to determine which variables coefficient changed by more than 20%? Thank you in advance. Nice to see the improvements - I would add a caveat to my advice about accepting answers. It's important to do, but don't do it too fast. Often people recommend waiting 12-24 hours just to see if any other better answers come along. (With exceptions, if the answer really seems perfect go ahead and accept immediately.) The broom package is really nice for making data frames of model coefficients and terms. We can use that to get things in a workable format: library(broom) m_list = list(m1 = Iris.mod1, m2 = Iris.mod2) t_list = lapply(m_list, tidy) library(dplyr) library(tidyr) bind_rows(t_list, .id = "mod") %>% select(term, estimate, mod) %>% spread(key = mod, value = estimate) %>% mutate(p_change = (m2 - m1) / m1 * 100, p_change_gt_20 = p_change > 20) # term m1 m2 p_change p_change_gt_20 # 1 (Intercept) -6.556265 -65.84266 904.2709 TRUE # 2 Petal.Length -19.053588 -49.04616 157.4117 TRUE # 3 Petal.Width -25.032928 NA NA NA # 4 Sepal.Length 9.878866 37.56141 280.2199 TRUE # 5 Sepal.Width 7.417640 NA NA NA
common-pile/stackexchange_filtered
How can I put Kendo controls in a Partial View? I'm putting a Kendo Tabstrip in one of the areas in my C# MVC project. <div id="tabstrip"> <ul> <li class="k-state-active"> Teachers </li> <li> Students </li> </ul> <div id="teachers"> @{ Html.RenderPartial("Teachers"); } </div> <div id="students"> @{ Html.RenderPartial("Students"); } </div> </div> As you can see, there are just two tabs and I'm putting their contents in partial views. The problem is, I want to put more Kendo controls in those partial views. I want both tabs to have a Kendo Grid, AutoComplete widgets, and so on. So, I put the following code in Teachers.cshtml: <input id="products" style="width: 250px" /> <script> $(document).ready(function () { var data = { "foo": ["item 1", "test 2", "item 3"] }; $("#products").kendoAutoComplete({ filter: "contains", minLength: 2, dataSource: { data: data, schema: { data: "foo" } } }); }); </script> This is just a standard AutoComplete widget. It works fine when I just put it in one of the tabs, but if I try to put that same code in both tabs, it doesn't work. The input field on the first tab becomes as wide as the screen, and no suggestions show up when I type stuff in on the second tab. I don't really know how else to do this. How do I put Kendo controls in a Tabstrip using Partial Views? Do they have different IDs on each tab? Or is it #products on both tabs? That could be your problem. The problem is, both widgets have the same ID. I changed the ID in the second tab and it works fine.
common-pile/stackexchange_filtered
Restricting input to textbox: it only accept number and should not accept decimal value How can i restrict textbox that should only accept numbers and should not accept decimal values and alphabets? Does this answer your question? HTML text input allow only numeric input If your browsers support it, look into <input type="number"> instead of <input type="text"> to get a lot of the validation you'll want out of the box. number do allow decimal value. Better to add some more information about your question such as is it about web page, HTML or mobile platform so that others can help you better. first you need to create an input element which call a function <input type = "text" id = "a" onkeyup="myFunction(event)"/> now you define your input box which will call a function myFunction (which takes event) whenever you will press a key on your keyboard. now we need to prevent all the other key except 0-9 and without (.) becuase you don't want any decimal point. so we need to create a regex which can check the pattern and check if the typed value follows the pattern or not if it follow we will set the value in a variable if not then we will set input value to old correct value and call preventDefault. <script> let value = null; function myFunction(event) { // event.target.value = what ever you typed // /^[0-9]+$/ = regex code to prevent other letter except<PHONE_NUMBER> if (event.target.value.match(/^[0-9]+$/)) { value = event.target.value; } else { // this line will update your input box to correct value document.getElementById("a").value = value; event.preventDefault(); } } </script> @shilly is correct you can use type="number" but if that doesn't work you can look into regex and create patterns based on what you want the input to look like. Regex example for only numbers excluding decimal and letters: "^[0-9]+$"
common-pile/stackexchange_filtered
Change Redact color in Mac Preview I am running MacOS Monterey, and I want to remove some text from a PDF file using the Redact option in Preview. However, redacting the text marks it with black background with white crosses in it. Is it possible to change this color of redaction? Default sample redaction is shown below:
common-pile/stackexchange_filtered
My List of elements doesn't clear properly? I am writing a program to simulate flocking behaviour on boids. I currently have a List of behaviours which a boid uses to calculate it's next movement vector. On each update the behaviours are reset and new behaviours can be added. With a population size of 100 it all works fine, though when I increase this number my List somehow isn't cleared properly. Where I should have a list size of 4, sometimes this increases to 6 with null elements and elements which are added twice instead of once. I think this might have something to do with my program loop running too fast for the calculations but I am not sure. Is there any way I can figure this out? My Code is as follows: foreach(Vehicle boid in mainFlock) { boid.behaviours.Clear(); boid.behaviours.Add(new CohesionBehaviour(boid, mainFlock)); boid.behaviours.Add(new SeparationBehaviour(boid, mainFlock)); boid.behaviours.Add(new AlignmentBehaviour(boid, mainFlock)); boid.behaviours.Add(new SeekBehaviour(boid, mainFlockTarget.Pos)); if (boid.behaviours.Count > 4) Console.WriteLine(boid.behaviours); boid.Update(timeElapsed); } The Console.WriteLine() should never be called, though sometimes (when I increase the population size) it prints this(simplified): [cohesion, cohesion, separation, alignment, seek, seek] and some other times(simplified): [cohesion, separation, cohesion, null, alignment, seek] it alway's seems to be a total of 6 elements. Sounds like you're accessing the list from multiple threads at the same time. Don't do this: List is not thread-safe yeah, this was also a thought I had but I havn't ever used diffrent threads is there a simple way I can check which threads are accessing this variable? Sounds like you're using a timer, though? Depending on the type of timer, timer callbacks can be invoked on ThreadPool threads. Put a breakpoint on the lines which modify the list, and see what thread in the Threads window is doing that Here's a simple way I wrote to check if code is being called concurrently. You can do a similar thing in your code.
common-pile/stackexchange_filtered
MVC model binding parent child (collections) I am trying to bind a child collections from my viewmodels to the domain model in the controller and I do not know how. (I tried using automapper and did not get very far). I already have all the information on what I am working on, so to save trees I figured it might be easy to put a link, instead of repeating the same code. MVC Partial View not rendering from an EditorTemplates This is what I have in my controller so far. I know my child probably needs to be in a for loop or something. [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(ParentVM viewModel) { if (ModelState.IsValid) { var child = new Child() { Name = viewModel.Name, DOB = viewModel.DOB, Address = viewModel.Address }; var parent = new Parent() { FirstName = viewModel.FirstName, LastName = viewModel.LastName }; //Parent parent = new Parent(); //var employee = AutoMapper.Mapper.Map<Parent, ParentVM>(parent); db.Parents.Add(parent); db.Childs.Add(child); db.SaveChanges(); return RedirectToAction("Index"); } return View(viewModel); } The parent is inserted properly but the children (they are three) only insert one and the value are all null except for the parentID.
common-pile/stackexchange_filtered
Naila is a right or wrong name for a girl Is Naila a permissible name for a girl? Or is it impermissible to name a girl Naila? People usually hate that name because one of jahilia idols was named Naila but thats irrelevant because the name doesn't express the person and you can't find both good and bad persons having the same name. The Salaf (May Allah be pleased and have mercy on them) used that name. We have the Sahabia (female companion of Prophet Mohammad) Naila bintu Salama al-Ansariah, Sahabia Naila bintu Saad and Sahabia Naila bintu al-Farafissa the wife of the 3rd Khalifa Rashidun Uthman ibn Affan. The Arabic root of the name is An-nawal which means giving and it also has some other good meanings. Useful links: Wants Muslim name for children
common-pile/stackexchange_filtered
jQuery change image onclick Don't know why but I can't find a solution to this. I have 3 links that when clicked I want to change an image below using jQuery. Does anyone know of a really simple script to show me how this might work? Thanks in advance. Answer can be found in this question, though they're using hover instead of click. HTML <img id="change" src="http://www.nvidia.in/docs/CP/26740/thumbs_googleearth.jpg" /> <br> <a href="javascript:void(0)" class="gog" alt="http://www.nvidia.in/docs/CP/26740/thumbs_googleearth.jpg" >earth</a> <br> <a href="javascript:void(0)" class="gog" alt="http://www.techbusy.org/wp-content/uploads/2011/10/block-websites-google-search-100x100.jpg" >block</a> <br> <a href="javascript:void(0)" class="gog" alt="http://www.bishanindia.com/wp-content/uploads/2011/10/google-plus-l-100x100.jpg" >google plus</a> JQUERY $(document).ready(function(){ $(".gog").click(function(){ $("#change").attr("src",$(this).attr("alt")); }) }) Jsfiddle ink for the reference
common-pile/stackexchange_filtered
Unable to connect to SQL Server from Excel to generate reports. Named pipes and tcp/ip are enabled. using trusted connection Trying to connect to SQL Server from Excel by using >>Data tab, >>From other sources >> from SQL server. It came back with the attached message I made sure named pipes and TCP/IP are enabled in the SQL server configuration manager. It works on my laptop. But my friend is trying to install in her laptop and it is not working. Appreciate any ideas you can share with us. We are doing Developer Edition, custom install of the database server. Double checked the instance name and made sure remote connection is allowed. This is the error message I get Unable to connect: We encountered an error when trying to connect. Details : Microsoft SQL: A network-related or instance specific error occurred while establishing a connection to SQL-SERVER. The server was not found or was not accessible. Verify if the instance name is correct and SQL server is configured to allow remote connections. (Provided:Named Pipes Provider,error:40 Could not open a connection to SQL Server. Firewall settings? If you're using a named instance you need udp/1434 open for SSRP (SQL Server Resolution Protocol) as implemented by SQL Browser Service. This is in addition to whichever port SQL Server itself is configured to listen on, e.g.: tcp/1433 is normally used for the default .\MSSQLSERVER instance. If you're using Named Pipes instead of TCP you need several more ports open: udp/137, udp/138, tcp/139 and tcp/445. Note: a default install of Developer Edition has the TCP/IP protocol disabled in SQL Server (version) Configuration Manager > Server Protocols. Also: if you change any settings in SQL Server (version) Configuration Manager > Server Protocols you need to restart the SQL Server and SQL Browser services for the changes to be applied.
common-pile/stackexchange_filtered
Refactoring Javascript Function: Array transformation I have a constant array like this: const pie_values = [20,10,5,5,10]; The challenge is to transform the above array based on integer input. (5) => [5, 15, 10, 5, 5, 10] (21) => [20, 1, 9, 5, 5, 10] (31) => [20, 10, 1, 4, 5, 10] An input of 5 takes 5 from the first index of pie_values. But it still leaves 15. An input of 21 can take 20 from index 0 and 1 from index 2, leaving 9 I think you can see how this is going. So (0) and (50) will return the original pie_values. Now the challenge is to create a function that does this in a few lines of code, which is build on loops rather than on 5 if statements. In case pie_values is extended upon, the function should still work. I have an approach working with if statements, however the latter is undoable. What would be a good approach to these kind of problems? First I defined a helper function: //Returns summation of pie value // totalPieValues(1) = 20 // totalPieValues(2) = 30 // totalPieValues(3) = 35 // totalPieValues(4) = 40 // totalPieValues(5) = 50 function totalPieValues(max) { let result = 0; for (let i = 0; i < max; i++) { result += PIE_VALUES[i]; } return result; } Then I worked on a function getPieArray which utilizes the helper function. This is where I am stuck function getPieArray(wp) { for (let i = 0; i < PIE_VALUES.length; i++) { if (wp == 0 || wp == totalPieValues(i)) { return PIE_VALUES; } } let result = []; for (let i = 1; i <= PIE_VALUES.length; i++) { if (wp > totalPieValues(PIE_VALUES.length - i)) { result.push(PIE_VALUES[i]); } else if () { result.push(wp - totalPieValues(3)); } else { result.push(PIE_VALUES[i] - (value - totalPieValues(3))); } } return result; } The code that I have written and works is here: //Returns array of exact values needed to show in pie chart export function getPieValues(wp) { //1 => [1, 19, 10, 5, 5, 10] //24 => [20, 4, 1, 5, 5, 10] //31 => [20, 10, 1, 5, 5, 5, 10] let result; if (wp == 0) { result = PIE_VALUES; } else if (wp < totalPieValues(1)) { result = [wp - totalPieValues(0), PIE_VALUES[0] - wp, PIE_VALUES[1], PIE_VALUES[2], PIE_VALUES[3], PIE_VALUES[4]]; } else if (wp == totalPieValues(1)) { result = PIE_VALUES; } else if (wp < totalPieValues(2)) { result = [PIE_VALUES[0], wp - totalPieValues(1), PIE_VALUES[1] - (wp - PIE_VALUES[0]), PIE_VALUES[2], PIE_VALUES[3], PIE_VALUES[4]]; } else if (wp == totalPieValues(2)) { result = PIE_VALUES; } else if (wp < totalPieValues(3)) { result = [PIE_VALUES[0], PIE_VALUES[1], wp - totalPieValues(2), PIE_VALUES[2] - (wp - totalPieValues(2)), PIE_VALUES[3], PIE_VALUES[4]]; } else if (wp == totalPieValues(3)) { result = PIE_VALUES; } else if (wp < totalPieValues(4)) { result = [PIE_VALUES[0], PIE_VALUES[1], PIE_VALUES[2], wp - totalPieValues(3), PIE_VALUES[3] - (wp - totalPieValues(3)), PIE_VALUES[4]]; } else if (wp == totalPieValues(4)) { result = PIE_VALUES; } else if (wp < totalPieValues(5)) { result = [PIE_VALUES[0], PIE_VALUES[1], PIE_VALUES[2], PIE_VALUES[3], wp - totalPieValues(4), PIE_VALUES[4] - (wp - totalPieValues(4))]; } else if (wp == totalPieValues(5)) { result = PIE_VALUES; } return result; } Can you describe in more detail what the function is supposed to do? I’m not seeing it. @Ryan say you have a pie with predefined sizes. In this case 20, 10, 5, 5 and 10. Now I want to take 1/50th of the total pie, which reshapes the pie in 1, 19, 10, 5, 5 and 10. This is super overkill You can just iterate through the array and "eat" the index value and continue function pieArray(inputArray, value){ let copyOfValue = value; return inputArray.reduce((sum, input, index) => { // <-- index here copyOfValue -= input; if(copyOfValue > 0){ sum.push(input); }else{ sum.push(input+copyOfValue); sum.push(Math.abs(copyOfValue)); copyOfValue = Number.MAX_VALUE; //Hacky solution, just change value to max value } return sum; }, []); } Tests pieArray([20,10,5,5,10], 5) => [5, 15, 10, 5, 5, 10] pieArray([20,10,5,5,10], 21) => [20, 1, 9, 5, 5, 10] pieArray([20,10,5,5,10], 31) => [20, 10, 1, 4, 5, 10] Have you checked the output? It works for all except 0 and 50. But thats not a big deal. Do you also have a way to get the index? Updated it with index, yeah its just to check if the input is 0, then you do return [0].concat(inputArray) while the other is to check if we never inputted the value, then you need to remove the hacky solution Actually you can just check if the input is not equal to Number.MAX_VALUE, that would make max value fail, but do you really need it? This is my approach. We iterate over our array, keeping track of our current value - and substracting from it as we push out each element to the output array. There is 3 cases: either our current count is >= input, so we just push and move on, current count is 0, so we just push everything left current count is < input, but more than 0 - in this case we split. Here is the code: function transform(input, array) { const total = array.reduce((previous, current) => previous + current); // It wasn't specified what should happen when the input > total, so we will just throw an error. if (input > total) { throw new Error('Input cannot be bigger than the sum of elements in the array.'); } let current = input; let result = []; for (let i = 0; i < array.length; i++) { if (current >= array[i]) { result.push(array[i]); current -= array[i]; } else if (current === 0) { result.push(array[i]); } else { result.push(current, array[i] - current); current = 0; } } return result; } Some of these answers are a bit overcomplicated. If you use a recursive function, you can do this in just two lines of code. const pie_values = [20,10,5,5,10]; // The challenge is to transform the above array based on integer input. // (5) => [5, 15, 10, 5, 5, 10] // (21) => [20, 1, 9, 5, 5, 10] // (31) => [20, 10, 1, 4, 5, 10] function reshape(num, vals) { if (num < vals[0]) return [num, vals[0] - num, ...vals.slice(1)]; return [vals[0], ...reshape(num - vals[0], vals.slice(1))]; } console.log(reshape(5, pie_values)) console.log(reshape(21, pie_values)) console.log(reshape(31, pie_values)) The key is realizing that if the amount you need to take is less than the next value, then you can take it from that next value and the remainder of the array will stay the same. But if you need to take more than what's available, take as much as you can get from the first value, and then take that much less from the remainder of the array. EDIT: Note that if the number you give is larger than the sum of all the pie values, this will recurse infinitely (leading to a stack overflow). To be totally safe, you should ensure that the value is less than the total sum before calling reshape. This one's pretty simple and efficient. It doesn't iterate the whole array, only up to the point it needs to. const pie_values = [20,10,5,5,10]; function pied(n) { var i = 0; var total = pie_values[0]; while (total < n && i < pie_values.length) { i++; total += pie_values[i]; } if (i < pie_values.length) { var diff = total - n; if (diff > 0 && n > 0) { return [].concat( pie_values.slice(0, i), // the part of the array up to i pie_values[i] - diff, // the amount we used of the last element we needed diff, // the amount left over pie_values.slice(i + 1) // the rest of the array after i ); } else { // just return a copy of the original array return pie_values.slice(); } } else { // n was greater than the total of all elements of the array return "went over"; } } console.log(pied(5)); Using vanilla Javascript for-loop Look at this code snippet const pie_values = [20, 10, 5, 5, 10]; var fn = (input) => { let array = []; for (var i = 0; i < pie_values.length; i++) { var n = pie_values[i]; let calc = n - input; if (calc > 0) { array.push(n - calc); // Push how many used, i.e n = 20, input = 10. array.push(calc); // Push the remaining after subtraction. array = array.concat(pie_values.slice(i + 1)); // Add the remaining values from 'pie_values' return array; } else { array.push(n); // Push all this number because was insufficient, i.e n = 20, input = 30 input = Math.abs(calc); // Remaining for the next iteration. } } return array; }; console.log(fn(5)); console.log(fn(21)); console.log(fn(31)); console.log(fn(0)); console.log(fn(50)); You want something like that ? (Works with the examples you've given) function getPieValues(integer_input) { "use strict"; let final_arr = pie_values, array_sum = pie_values.reduce((pv, cv) => pv + cv , 0); if(integer_input !== 0 && integer_input !== array_sum) { // For the cases 50 and 0, the array won't be modified for(let i = 0; i < pie_values.length; i++) { if(pie_values[i] < integer_input) { // if the prompted number is bigger than the current value, we keep up integer_input -= pie_values[i]; } else { // When it becomes smaller, we add the remainder at the front of the current value, then we modify the next value, and finally we break it so that it doesn't happen next final_arr.splice(i, 0, integer_input); final_arr[i+1] -= integer_input; break; } } } return final_arr; } Edit : Made it a function, and made it work with 0 and 50 (sorry, first post ;-) ) const pie_values = [20,10,5,5,10]; function rebaseArr(input){ var retArr = []; var total = 0; let isDone = false; for(var i in pie_values){ let currentVal = pie_values[i]; total += currentVal; if(total > input && !isDone){ let rem = total - input; let rem1 = currentVal - rem; rem1 !== 0 ? retArr.push(rem1) : 0; retArr.push(rem); isDone = true; } else { retArr.push(currentVal); } } return retArr; } console.log(rebaseArr(31)); console.log(rebaseArr(1)); console.log(rebaseArr(10)); Can you please try with above code. Hope it helps :) I wouldn't normally advise recursion in JS however just for fun you may implement an Haskellesque pattern matching by using spread and rest operators through destructuring and may come up with something like below; It wasn't clear to me what to do when the difference is zero so being a remarkably lazy person i choose to do nothing. (Last test won't return [20,10,5,0,5,10]) var extend = ([x,...xs],n) => n && x ? x > n ? [n, x-n, ...xs] : [x, ...extend(xs, n-x)] : [x,...xs], pvs = [20,10,5,5,10]; console.log(extend(pvs,5)); console.log(extend(pvs,21)); console.log(extend(pvs,31)); console.log(extend(pvs,35)); .as-console-wrapper { max-height : 100% !important }
common-pile/stackexchange_filtered
Finding the domain of this trigonometric function how can I find the domain of this function? f(x) = (xsin(x) + cos(x) / 1 - cos(x)) + (|X| - 2 / x^2 -4) I assume we don't want the dominator to be zero so f(x)1 1 - cos(x) != 0 and x^2 - 4 != 0? What is the next step go to help and look for FunctionDomain
common-pile/stackexchange_filtered
Airflow DAG fails when PythonOperator tries to call API and download data I'm trying to configure Airflow on my laptop for the first time (without using docker, just following documentation). My goal is to set up a simple ETL job. I've written the simplest possible DAG with one PythonOperator: from datetime import timedelta from view import spotify_etl from airflow import DAG from airflow.operators.python_operator import PythonOperator from airflow.utils.dates import days_ago default_args = { 'owner': 'airflow', 'depends_on_past': False, 'start_date': days_ago(2), 'email'<EMAIL_ADDRESS> 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=1), } dag = DAG( 'airflow_dag_tutorial-new', default_args=default_args, description='A simple tutorial DAG', schedule_interval=timedelta(days=1), ) run_etl = PythonOperator( task_id='main_task', python_callable=spotify_etl, dag=dag, ) run_etl When I pass a dummy function with a print statement, the DAG runs successfully. But then, when I pass my function spotify_etl that calls Spotify API, the DAG fails. This is the function: def spotify_etl(): token = 'xxx' headers = { 'Accept' : "application/json", 'Content-Type': "application/json", 'Authorization': 'Bearer {token}'.format(token=token) } today = datetime.datetime.now() yesterday = today - datetime.timedelta(days=100) yesterday_unix_timestamp = int(yesterday.timestamp()) *1000 r = requests.get("https://api.spotify.com/v1/me/player/recently-played?after={time}".format(time=yesterday_unix_timestamp), headers=headers) data = r.json() print(data) The error I get is: [2020-11-08 12:35:23,453] {local_task_job.py:102} INFO - Task exited with return code Negsignal.SIGABRT Does anyone know how to use PythonOperator correctly for a function that calls API? What is causing this error? I tried setting: export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES in my venv (as suggested here: Airflow task running tweepy exits with return code -6 and here: https://github.com/ansible/ansible/issues/32499#issuecomment-341578864) but that doesn't seem to have fix it. Did you solve this? @arctic Yes, see the answer below It turned out that the "export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES" was not set correctly. It had to be added to .zshrc instead of .bash_profile. That solved it. @artic.queenolina Hey I'm experiencing this same issue, trying to make an API call from a python operator. What file specifically do you set "export OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES" ? My current environment is Anaconda related: https://stackoverflow.com/questions/73582293/airflow-external-api-call-gives-negsignal-sigsegv-error os.environ["no_proxy"] = "*" That didn't work for me, I tried setting this OBJC env var in a dozen different ways, I always get the SIGABRT signal for some reason...
common-pile/stackexchange_filtered
the_content() Returns post content when I want page content I'm very new to WordPress, but I'm currently doing work on a site built on the platform. I'm making my way through, but I've run into a bit of a problem. I'm trying to add content from the text editor of the site's blog page, which uses the standard index.php template. However, when I use <?php the_content(); ?> like other pages use, it returns the content of the latest post. Is there a way to get the content from the page editor instead? I've been looking all morning without really finding anything satisfactory. Any advice would be greatly appreciated! <section id="primary" > <?php the_content(); ?> <div class="content" role="main" data-target="index" > <?php if (have_posts()) : ?> <?php get_template_part('inc/loop', get_post_type() ); ?> <?php else : ?> <?php get_template_part('inc/content', 'none' ); ?> <?php endif; ?> </div><!-- end content --> </section><!-- end primary --> This WordPress Codex is invaluable to all WordPress'ers new and old. When you configure your blog (posts) page under Settings > Reading, that page becomes nothing more than a placeholder - in other words, you won't be able to grab it's title/content within index.php without a little trickery: if ( $page_id = get_option( 'page_for_posts' ) ) { echo get_the_title( $page_id ); // the_content() doesn't accept a post ID parameter if ( $post = get_post( $page_id ) ) { setup_postdata( $post ); // "posts" page is now current post for most template tags the_content(); wp_reset_postdata(); // So everything below functions as normal } } I think you want to set a page as the home page rather than a post. You can set this using wordpress settings. You have to set a selected page that will display on the site's home. Login to admin end and go to Settings -> Reading Select the 2nd option (A static page) for the setting Front page displays Then select the page from the dropdown list for Front page whichever you want to set as the home page. Save the settings. Now if you check your site, you should see a page rather than post.
common-pile/stackexchange_filtered
Coupling and Total variational distance Suppose we have two distributions: $\mu$ and $\upsilon$ on $\{1,2,3\}$. $\mu(1) = 1/2, \mu(2) = 1/3, \mu(3) = 1/6,\upsilon(1) = 1/3, \upsilon(2) = 1/6, \upsilon(3) = 1/2$. Could anyone explain to me (as simply as possible since I'm at a beginner level in stats) how I can compute the total variation distance of $\mu$ and $\upsilon$? Also, how one should go about constructing a coupling $(X,Y)$ of $\mu$ and $\upsilon$ such that $P(X\not=Y)$ is equal to the total variational distance between $\mu$ and $\upsilon$? Much thanks for helping me understand the concept and problem. There are at least 2 ways to compute the total variation distance. The first is by using the definition of Total variation distance: $TV(\mu,\nu)=\sup_{ A\in \mathcal{F}}\left|\mu(A)-\nu(A)\right|,$ where $\mathcal{F}$ is the sigma-algebra. In this (finite) case, you can think of the sigma-algebra as the power-set of your sample space $\Omega =\{1,2,3\}$, if you are unfamiliar with sigma-algebras or measure theoretic language more generally. The sigma-algebra (power-set) is $\{\{\varnothing\}, \{1\},\{2\},\{3\},\{1,2\},\{1,3\},\{2,3\},\{1,2,3\} \} $. Now if we take each of these sets 1-by-1 we calculate: $$\left|\mu(\varnothing)-\nu(\varnothing)\right| =| 0 -0|=0,$$ $$\left|\mu(1)-\nu(1)\right| =|1/2-1/3|=1/6,$$ $$\left|\mu(2)-\nu(2)\right| =|1/3-1/6|=1/6,$$ $$\left|\mu(3)-\nu(3)\right| =|1/6-3/6|=1/3,$$ $$\left|\mu(1,2)-\nu(1,2)\right| =|(3+2)/6-(2+1)/6|=1/3,$$ $$\left|\mu(1,3)-\nu(1,3)\right| =|4/6-5/6|=1/6,$$ $$\left|\mu(2,3)-\nu(2,3)\right| =|3/6-4/6|=1/6,$$ $$\left|\mu(1,2,3)-\nu(1,2,3)\right| =|1-1|=0.$$ Now we see by inspection there are 2 sets that achieve the maximum, $\{3\}$ and $\{1,2\}$, the complement of the set $\{1,2\}$. We'll see in a brief moment why the supremum is achieved on a set and the set's complement always for total variation distance. The second method to calculate the total variation distance uses the following result: $$TV(\mu,\nu)=\sup_{ A\in \mathcal{F}}\left|\mu(A)-\nu(A)\right|=\frac{1}{2}\sum_{i=1}^n\left| \mu(i) -\nu(i)\right|.$$ This can be seen by partitioning the sets $A\in \mathcal{F}$ into 2 groups; those with $\{\mu(A)>\nu(A)\}$ and those with $\{\mu(A)\leq\nu(A)\}$. Now appealing to the symmetry of the absolute value function the two sets will have the same supremum value and therefore the total variation distance will be counted twice. To account for the double counting we divide by 2. Unfortunately, whether or not to divide by 2 is not standardized so some authors omit the division by 2. Using the summation formula instead of the supremum formula, $$TV(\mu,\nu)= \sum_{i=1}^n\left|\mu(i) -\nu(i)\right| =\frac{|1/2-1/3|+|1/3-1/6|+|1/6-1/2|}{2} = \frac{2}{3}\frac{1}{2}=\frac{1}{3}. $$ The two quantities agree and this latter formula is much more amenable to computation (taking linear time on a discrete set rather than exponential time). Often times this latter formula is taken as the definition and the supremum is not even discussed. Note that in the continuous case you replace the sum with an integral over the two measures. Clearly the smallest value of the total variation distance is $0$ if the two measures are the same. If the two measures share no support in common (e.g. $\mu(1) =1$, and $\nu(2)=1$. Then the total variation distance will be $1$ and no larger value can be achieved. This answers the first part of your question; how to calculate the total variation distance on this set. The second part of the questions asks about the coupling construction so that $\Pr(X\neq Y)=TV(\mu, \nu)$ where $X\sim\mu$ and $Y\sim\nu$. Now define the cost function $c(X,Y) =\mathbb{1}_{X\neq Y}$ where $\mathbb{1}_A$ is the indicator (sometimes called characteristic in other branches of math) of the set $A$ taking the value $1$ when the argument to the indicator function is in the set $A$. The coupling construction of total variation states $$TV(\mu,\nu)=\inf_{ \pi\in X\times Y} \mathbb{E}(c(X,Y)),$$ and the product space $X\times Y$ is required to have the given marginals $\mu$ and $\nu$ for $X$ and $Y$ respectively. A graph depiction of the solution shows the amount you must move from $i$th element of $\mu$ to $j$th element of $\nu$. To achieve this on a discrete set of points like this you construct a joint probability function on the space of $X\times Y$ via a linear program with $$C = \begin{bmatrix} 0 & 1 & 1 \\ 1 & 0 & 1 \\ 1 & 1 & 0 \\ \end{bmatrix},$$ is your cost matrix, $C_{ij} = c(X_i, Y_j)$. Secondly your joint probability space will be $$P = \begin{bmatrix} p_{11} & p_{12} & p_{13} \\ p_{21} & p_{22} & p_{23} \\ p_{31} & p_{32} & p_{33} \\ \end{bmatrix}.$$ Also you'll need to define $$\vec{b} = \begin{bmatrix} \mu(1) \\ \mu(2) \\ \mu(3) \\ \nu(1) \\ \nu(2) \\ \nu(3) \\ \end{bmatrix},$$ and finally the matrix $A$, $$A = \begin{bmatrix} 1 & 0 & 0 & 1 & 0 & 0 & 1 & 0 & 0 \\ 0 & 1 & 0 & 0 & 1 & 0 & 0 & 1 & 0 \\ 0 & 0 & 1 & 0 & 0 & 1 & 0 & 0 & 1 \\ 1 & 1 & 1 & 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 1 & 1 & 1 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 & 1 & 1 & 1 \\ \end{bmatrix}.$$ Now solving the linear program $$min_{P}( vec(C)^T vec(P) \vert Avec(P) = \vec{b}), $$ will give you the total variation distance (the objective function value at optimality) and the join probability $P$ (arguments at optimality). Note here that $vec()$ denotes the $vec()$ matrix operator which takes a matrix and returns the vector that results from stacking the columns from left to right of the matrix to obtain a single column vector. The values of $C$ are not arbitrary any number instead of $1$ for all non-diagonal entries would require you need to rescale the objective function at optimality by the constant. Running the linear program through lpSolve() in R yields the same value $1/3$ for the objective function. library(lpSolve) f.obj <- c(0, 1, 1, 1, 0, 1, 1, 1, 0) f.con <- matrix (c(1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1 ), nrow=6, byrow=TRUE) f.dir <- c("=", "=", "=", "=", "=", "=") f.rhs <- c(1/2, 1/3, 1/6, 1/3, 1/6,1/2) # Now run. lpSoln <- lp ("min", f.obj, f.con, f.dir, f.rhs) lpSoln Success: the objective function is 0.3333333 lpSoln$solution [1] 0.3333333 0.0000000 0.0000000 0.0000000 0.1666667 0.0000000 0.1666667 0.1666667 [9] 0.1666667 In words the solution is intrpreted as: move $1/3$ from state $1$ to state $1$. move $1/6$ from state $2$ to state $2$. move $1/6$ from state $3$ to state $3$. move $1/6$ from state $1$ to state $3$. move $1/6$ from state $2$ to state $3$. So that the optimal matrix $$P=\begin{bmatrix} 1/3& 0 & 1/6 \\ 0 & 1/6 & 1/6 \\ 0 & 0 & 1/6 \\ \end{bmatrix}.$$ In any finite space this sort of construction, although tedious, will get you to the total variation distance. is ${1,2}$ the union of the events ${1}$ and ${2}$ or the intersection? ${ 1,2} $ is the set containing both events, so the union.
common-pile/stackexchange_filtered
How to replace a specific Word in a Text File in Python? I know this Question is already answered, but for me the Answers are not working and I dont know why. First of all this is my Code: c = open('Tasks//Task_Counter.txt', 'r+') okay = c.read().splitlines() which_task = int(okay[0]) this_task = which_task + 1 which_port = int(okay[1]) this_port = which_port + 1 c.truncate(0) c.close() c = open('Tasks//Task_Counter.txt', 'r+') okay = c.read().splitlines() c.write(str(this_task)) c.write("\n") c.write(str(this_port)) c.close() f = open("Tasks//task"+ str(this_task) +".py","w+") q = open('Tasks//task1.py', 'r+') for line in q: f.write(line) f.close() f = open("Tasks//task"+ str(this_task) +".py","w+") filedata = f.read() filedata = filedata.replace('9250', str(this_port)) with open("Tasks//task"+ str(this_task) +".py", 'w+') as file: file.write(filedata) file.close() f.close() q.close() The first Part is not really interesting, but the Program is basically just copying a Python Program and and I want to change that Python Program a bit. The Python Program contains that variable: this_browser = "9250" And I want to replace the "9250" with str(this_port). "this_port" is definied as 9260. Now we come to the Problem. If I run the Program, the new created Python File contains nothing. Does somebody know how to solve this? your f and q seem a little muddled together. What if Tasks//task1.py contains no rows? Thanks for your quick answer, the Part with f and q does work perfectly fine, in task1.py is of course something written down. The Copying of the Code from "Task1 to Tasks//task"+ str(this_task) +".py" does work aswell, just the replacing not.
common-pile/stackexchange_filtered
Can $\sin(1/x)$ be approximated pointwise by polynomials over $(0,\infty)$ Can the function $f(x)=\sin(1/x)$ on $(0,\infty)$ be approximated by a sequence of polynomials pointwise on the domain?I am sure that uniform approximation is not possible because $\lim_{x\to 0+}\sin(1/x)$ does not exist.But is there a possibility of pointwise approximation by a polynomial sequence? [Note: I am an undergraduate student and the only thing that I can use is Weierstrass polynomial approximation and any other independent idea,but I know nothing of approximation theory,so I am expecting some elementary answer.] $f(x)=\sin(1/x)$ is continuous and bounded on $\Bbb{R}^*$ thus $f_n(x)=\int_{-\infty}^\infty f(y)ne^{-\pi n^2(x-y)^2}dy$ is analytic and $f_n\to f$ uniformly on every closed interval where $f$ is continuous and for $K_n$ growing fast enough the sequence of Taylor approximations $f_{n,K_n}$ of $f_n$ satisfies your requirements. Note $f_{n,K_n}$ is continuous and uniformly bounded on $[-A,A]$ for all $A$. Short answer: Yes, because any continuous function on a compact interval can be approximated arbitrarily sharply by a polynomial. So, at step $n$ of your approximating sequence, consider the compact subset $[1/n, n]$ of $[0, \infty)$, and find (by Weierstrass approximation) a polynomial $P_n(x)$ which is at distance $\leq 1/n$ from your $\sin(1/x)$ function, uniformly on $[1/n, n]$. Then for any fixed point $x$ of $(0, \infty)$, $P_n(x)$ will converge to $\sin(1/x)$, since for $n$ large enough you will always have $x \in [1/n, n]$, and therefore $\left|\sin(1/x) - P_n(x)\right| \leq 1/n \stackrel{n \to \infty}\to 0$. Actually there is nothing specific to $\sin(1/x)$ in this argument: it works the same for any function that is continuous on any open interval of $\mathbf{R}$. I feel like you can do $\sup_{x\in[1/n,n]}|f(x)-p_{n}(x)|<1/n$ by applying Weierstrass on each $[1/n,n]$. Sure, but the result doesn't mean much. Let $I_n = [{1 \over n},n]$, this is compact and we can choose a polynomial $p_n$ such that $\sup_{x \in I_n}|p_n(x)-f(x) | < {1 \over n}$. Then for any fixed $x>0$ we have $p_n(x) \to f(x)$.
common-pile/stackexchange_filtered
How can I authorise second Html page in App Script? I am building a web app for work on App Script that renders different Html views for certain tasks. It is published as a private app and anyone from our domain should have access. The users can access the main app page no problem, which is 'MantraCMS' from the code pasted below. When they try to click on the link for 'equipment' there is an error message saying that they do not have permission to run the app. I do not have this problem as the project owner. It has me stuck, but I am assuming that it is connected to the parameters in the function doGet() Here is the code: function doGet(e) { if (e.parameters.v == 'equipment'){ return loadEquipment(); } else { return loadSwirly() } }; function loadSwirly() { var tmp = HtmlService.createTemplateFromFile('MantraCMS'); var ss = SpreadsheetApp.openById(id); var ws = ss.getSheetByName('Options'); var list = ws.getRange(1, 1, ws.getRange('A1').getDataRegion().getLastRow(), 1).getValues(); tmp.list = list.map(function(r){return r[0];}); return tmp.evaluate(); }; function loadEquipment(){ var tmp = HtmlService.createTemplateFromFile('equipment'); var ss = SpreadsheetApp.openById(id); var ws = ss.getSheetByName('equipment'); var list = ws.getRange(1, 1, ws.getRange('A1').getDataRegion().getLastRow(), 10).getValues(); tmp.list = list.map(function(r){return r[0];}); return tmp.evaluate(); }; Here is the relevant HTML code requested. I am using a Materialize navbar: <nav> <div class="nav-wrapper indigo darken-4"> <a href="#" class="brand-logo">Swirly</a> <ul id="nav-mobile" class="right hide-on-med-and-down"> <li> <a href="https://script.google.com/a/'DOMAIN'/macros/s/'SCRIPT_ID'/dev?v=cms" >Projects</a > </li> <li> <a href="https://script.google.com/a/'DOMAIN'/macros/s/'SCRIPT_ID'/dev?v=equipment" >Equipment</a > </li> <li><a href="collapsible.html">Orders</a></li> </ul> </div> </nav> Also the problem is the same whether it is executed as me or " user accessing web app" I have removed the script id and domain from the html, but they are the same for both links. The orders link is a section I have not started working on yet, hence why the href is different. Has anyone seen this kind of problem before? Many thanks. Who is the user executing the app, is it you or every user? What did you set it to when publishing? When you say "click on equipment" you are not showing us that code. Please show all the necessary and minimal code to reproduce your issue. Provide [mcve]. Minimal, but complete. I specifically want to see your html head, base target parts. Also why are you using /dev? @TheMaster I didn't notice the /dev part of the url to be honest. I obviusly didn't change between testing and publishing. That will likely explain! Consider adding a answer. See [answer]
common-pile/stackexchange_filtered
Enable Shared Pager Cache in sqlite using PHP PDO I'm studying sqlite features and I've discovered the SQLite Shared-Cache Mode which is disabled by default. Shared-Cache is: intended for use in embedded servers because it shares a single data and schema cache between threads or processes. I'm interested in using sqlite (with shared-cache) in PHP (and Python) so my questions are: 1) is every PDO connection in a PHP script to an sqlite DB considered a single isolated connection? 2) if yes, using Shared-Cache Mode could improve performance in an high concurrency scenario; to activate Shared-Cache Mode one have to call this C function: int sqlite3_enable_shared_cache(int); how to call that function through PDO? It seems almost impossible but maybe there is a solution. Best Regards, Fabio Buda Web Developer/Designer @ netdesign I've searched through the PHP source code to find an answer for you. No file in ext/pdo_sqlite/ is ever calling the sqlite3_enable_shared_cache function, which means this is not implemented. You can do the following trick to enable SQLite shared cache feature in PHP code: define( 'SQLITE3_OPEN_SHAREDCACHE' , 0x00020000 ); $sqlite = new SQLite3( 'sqlite.db3' , SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE | SQLITE3_OPEN_SHAREDCACHE ); And it works, though somewhat ugly - performance tests on 10k users database shows a little (~3%) performance degradation. Looks like this is not query (results) cache, but a memory cache of raw table data. That's why it should benefit only on really huge databases with high concurrency level. This answer is pretty awesome, however the recommended example does not show how to use the defined constant with PDO
common-pile/stackexchange_filtered
The error comes when I host my project done in codigniter My project worked in localhost, but showing error on server: check for white space before php tag or some output is generating before exicuting code Look at the fatal error first. Figure out why mysqli failed. It could be your hosting does not support the whole functionalities of the Database Drtiver you can head to Application/config/database.php and change these line from 'dbdriver' => 'mysqli', to 'dbdriver' => 'pdo', it would be nice if you post your database.php and also go to Application/Logs and open the log dated today additional error information may be in the file Try this $db['default'] = array( 'dsn' => '', 'hostname' => 'localhost', 'username' => 'root', # check username 'password' => '', # check password 'database' => 'shortagesdb', # check DB name is correct 'dbdriver' => 'mysqli', # remove mysql 'dbprefix' => '', 'pconnect' => FALSE, 'db_debug' => (ENVIRONMENT !== 'production'), # remove TRUE, 'cache_on' => FALSE, 'cachedir' => '', 'char_set' => 'utf8', 'dbcollat' => 'utf8_general_ci', 'swap_pre' => '', 'encrypt' => FALSE, 'compress' => FALSE, 'stricton' => FALSE, 'failover' => array(), 'save_queries' => TRUE or may be It is not a bug in your application, it is just a missing driver, so, you have couple of options... Go to your php init and uncomment the following: extension=php_mysqli.dll If not, try installing it at your server, it varies depending on your distribution. Try installing php5-mysqlnd If you cannot do it by hosting restrictions then just move to mysql driver (wont need to change other configurations or queries in CodeIgniter or anything else...) like this (at your config file) $db['default']['dbdriver'] = 'mysql'; (you might have mysqli now) source Codeigniter: fatal error call to undefined function mysqli_init() and CodeIgniter error when connecting to any database how we change the php.ini config in godaddy they told that this is a virtual server so they are not able to provide a tech support check this link might be help full to you http://www.webhostingtalk.com/showthread.php?t=540760 Cannot modify header information - headers already sent by (output started at /home/medmaacom/public_html/application/models/User_model.php:167) there was no problem in localhost,but in server this error comes check http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php
common-pile/stackexchange_filtered
delete detail from database using spring-data-jpa Now I am using spring-data-jpa & hibernate. I want to delete a courseDetail from the course, But after I run my code below the courseDetail is still in the database. Who can tell me how this happened? thanks in advance. @Transactional(readOnly = false) public void deleteCourseDetail(Long id, Long courseId) { Course course = courseDao.findOne(courseId); CourseDetail courseDetail = courseDetailDao.findOne(id); System.out.println(course.getCourseDetails().size()); course.getCourseDetails().remove(courseDetail); System.out.println("after: " + course.getCourseDetails().size()); courseDao.save(course); } @OneToMany(mappedBy = "course", fetch = FetchType.LAZY, cascade = {CascadeType.ALL}) public List<CourseDetail> getCourseDetails() { return courseDetails; } Now it works after I add courseDetailDao.delete(id); behind save method. but WHY? Go through http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/example-parentchild.html#example-parentchild-cascades You should have "delete orphan" as the cascade type. If not, deleting an entry in courseDetails simply means removing the relationship between Course and CourseDetail. It does not mean removing a courseDetail from DB
common-pile/stackexchange_filtered
400 error with bing news search api I'm having a couple of problems with the bing news search api, the strangest one is searching by category, according to the documentation, the category must be a string, I found multiple resources for which values it accepts so i decided to go with console (https://dev.cognitive.microsoft.com/docs/services/56b43f72cf5ff8098cef380a/operations/56b449fbcf5ff81038d15cdf/console). Once you select a category and put it your key, it works fine. The problem is when i copy the exact same URL from the console to postman, i use the same key and i get "400 Bad Request" header with this body: { "_type": "ErrorResponse", "errors": [ { "code": "RequestParameterInvalidValue", "message": "Parameter has invalid value.The category parameter is invalid.", "parameter": "category", "value": "Entertainment" } ] } any idea what i'm doing wrong here? Here's a very Hacky workaround: since the request works fine via the developer console, i inspected the request and tried to repeate it thought curl, seems to work fine, the command is as follows: curl 'https://dev.cognitive.microsoft.com/console/query' -H 'Content-Type: application/json' --data-binary '{"httpMethod":"GET","host":"api.cognitive.microsoft.com","scheme":"https","path":"bing/v5.0/news/?Category=Entertainment","headers":[{"name":"Host","value":"api.cognitive.microsoft.com","inputTypeValue":"text","revealed":false,"options":null,"required":true,"readonly":true,"custom":false},{"name":"Ocp-Apim-Subscription-Key","value":"<your key value>","inputTypeValue":"password","revealed":false,"options":[],"required":true,"readonly":false,"custom":true,"secret":true}],"parameters":[{"name":"Category","value":"Entertainment","inputType":"text","required":false,"options":["Business","Entertainment","Health","Politics","ScienceAndTechnology","Sports","US/UK","World"],"custom":false,"description":"<p>Specifies which category of news articles the caller wants returned.</p>\n","typeName":"string"}],"body":""}' The json data I'm sending is this (copied from the command above) { "httpMethod": "GET", "host": "api.cognitive.microsoft.com", "scheme": "https", "path": "bing/v5.0/news/?Category=Entertainment", "headers": [{ "name": "Host", "value": "api.cognitive.microsoft.com", "inputTypeValue": "text", "revealed": false, "options": null, "required": true, "readonly": true, "custom": false }, { "name": "Ocp-Apim-Subscription-Key", "value": "", "inputTypeValue": "password", "revealed": false, "options": [], "required": true, "readonly": false, "custom": true, "secret": true }], "parameters": [{ "name": "Category", "value": "Entertainment", "inputType": "text", "required": false, "options": ["Business", "Entertainment", "Health", "Politics", "ScienceAndTechnology", "Sports", "US/UK", "World"], "custom": false, "description": "Specifies which category of news articles the caller wants returned.\n", "typeName": "string" }], "body": "" } I'll mark this as correct for now since i can't find any other solution
common-pile/stackexchange_filtered
How can I update the 'City' dropdown based on the selected 'Country'? How can I update the 'City' dropdown based on the selected 'Country'? Is there anything built on Django to facilitate this? class Country(models.Model): name = models.CharField(max_length=50) ... class City(models.Model): name = models.CharField(max_length=50) country = models.ForeignKey(Country) class UserProfile(models.Model): ... country = models.ForeignKey(Country, default=1) city = models.ForeignKey(City, default=1) user = models.OneToOneField(User) And in my view I have: {{ profile_form.country }} {{ profile_form.city }} But all cities are shown at once. Please advise. My answer would be a bit long, so i suggest you can have a look at this implementation, which answers exactly what you are looking for. Use django-smart-selects. It includes js functionality to update your form fields, and has helped me save a lot of time writing ajax calls with javascript. The example project includes a use case similar to the one you mentioned above. It would probably look something like this for you: from smart_selects.db_fields import ChainedForeignKey class City(models.Model): name = models.CharField(max_length=50) country = models.ForeignKey(Country) class UserProfile(models.Model): country = models.ForeignKey(Country) city = ChainedForeignKey(City, chained_field="country", chained_model_field="country") From the docs: The chained field is the field on the same model the field should be chained too. The chained model field is the field of the chained model that corresponds to the model linked too by the chained field. This seems like something you might want to be doing in javascript, on the client's computer. Your webserver (the machine running Django) doesn't know when a user has made a choice on a dropdown menu until they click submit. (This makes a HTTP POST request to your webserver, passing along all the parameters of that form). In javascript, you can register a function so that when the 'Country' dropdown is changed, the 'City' dropdown list is dynamically repopulated. Hope this helps!
common-pile/stackexchange_filtered
Hypernym for "movie" and "TV series" What is the hypernym for movie and TV series? I read that medium might be possible, but it doesn't sound that good. You need to be more specific about what you're asking about. Are movie and series the same thing here? Would examples be Harry Potter, Star Wars, and Pirates of the Caribbean? Or do you by "movies" mean films such as The Polar Express, where "series" refers to a television series, like The Big Bang Theory? Also, you might want to check out our companion site for [ell.SE], where this may have been a better fit. @I edited my question. I hope it's clearer now. It is clearer now, and as a result, I think you'll get better answers now, too. Thanks for clarifying. Movies vs series is an industrial segregation. Movies that form a series are called sequels. A prequel is a member of a sequel. Film industry? Broadcasting media? The world of entertainment? Show business/showbiz? Light entertainment? video entertainment, video media I can't post an answer for some reason, but I use "Production", which makes sense, as both tv shows and movies have producers Extending on Pam's answer, Show is considered the lowest common hypernym for TV program and Movie. This can be backed up with reference to the WordNet lexical database. See several papers including: Miller, G. A. WordNet: a lexical database for English, Communications of the ACM, ACM, 1995, 38, 39-41 Miller, G. A. Nouns in WordNet: a lexical inheritance system International journal of Lexicography, Oxford Univ Press, 1990, 3, 245-264 The definition of the show synset in question (show.n.03) is: 'a social event involving a public performance or entertainment' Which is quiet far from the base words, but according to the lexigraphers that constructed (/and continue to construct) WordNet, as good as we can get. For interest of others, one can make such queries against wornet in python via NLTK: from nltk.corpus import wordnet as wn wn.synset("television_program.n.01").lowest_common_hypernyms(wn.synset("movie.n.01")) #Or equivalently (because NLTK integrates Morphy): wn.synsets("TV_show",wn.NOUN)[0].lowest_common_hypernyms(wn.synsets("movie",wn.NOUN)[0]) Its also possible to query WordNet online, though I don't know of a good way to get lowest common hypernym: Movie TV show The short of the matter is, if we are willing to trust WordNet as an authoritative source (which thousands of peer reviewed publications have), then we can be confidant that Show is the lowest common hypernym. but in the context of media - let's say someone is trying to name a media drive, it is not ideal since "Show" also refers to concerts. Also it sounds strange to call a movie a show. How about a show? Is it too broad? Hmm... could you call Harry Potter a show? @Davlog - to be fair, this answer was posted before you made your edit, so it wasn't entirely clear what you are asking about. Moreover, there are some local dialects that commonly use the word show as a synonym for "movie." NOAD defines show as a public entertainment, in particular, a play or other stage performance, esp. a musical, or a program on television or radio. That definition wouldn't preclude show from your list of candidates. Dear Astuto, the reason why I sometimes pose my "answers" in a humble rethorical interrogative fashion is that I am non-native speaker/learner, so I wish to leave space for my proposal to be debated and corrected if necessary Pam, that is fine, but all answers on this site are subject to debate and correction. No need to specifically mark them up as such. An answer must be presented as an answer, and not as a question in its own right. In American English, show can refer to a television program, a stage production, or a particular showing of a movie (e.g. the matinee show, the 10pm show)β€” but not for a film itself, except as an affectation, as in using the old-fashioned term picture show. Moreover, I've never heard of anyone mixing media; if asked to list my favorite shows, I cannot simply answer "Top Gear [TV], Into the Woods [stage musical], and The Lion in Winter [film]"; I would need to ask first what is meant by show. @choster - I've heard places where show can be used for the film itself (e.g., "We went to the movies last night?" "Oh, what show did you see?") I've only heard that in the upper midwest, though; for the most part, I'd agree with you – it's far from universal AmE. @J.R. You're right; I have heard show used that way on the coasts as well. But I think the principle that show can only refer to one medium at a time still applies. "Let's go out and see a show tonight." "There's an Ibsen festival playing at the PAC." "Oh, I was thinking Hot Tub Time Machine, not a show show." I would go with media, since it's a plural for medium. Since there are so many media - movies, TV series, newspapers, magazines, radio, etc. - it would be hard to find a single word that covers just two of them, What about the software installer section of my media library? Media is about the broadest you can get. It could even represent a piece of paper my neighbor slipped under my door.
common-pile/stackexchange_filtered
compare hashes,print values of keys having same values I want to implement this algorithm in perl 11000, 67676, -7878, 9898 11001, 67676, -7878, 7673 11789, 56565, -0909, 5555 17654, 67676, -7654, 3214 18776, 99999, -55, 4444 17765, 67676, 7878, 9898 scan *nodes hash1{node}=x,y,z invert_y=y*-1 chech invert_y existance in hash2 if exists hash2{y}=[n1,n2,n3...].append the node else hash2{y}=store node in a array and pass its reference as value foreach key in hash1 get x1,y1,z1 of this node1 (eg. hash1{key} will return x,y,z of this node1) invert_y=y*1 if exists hash2{invert_y} get all node of hash2{keys} in node_array foreach node2 in node_array get x2,y2,z2 of this node2 (eg. hash1{node2} will return x,y,z of this node2) if x1 of node1 == x2 of node2 && z1 of node1 == z2 of node2 node1 and node2 are symmetric So go ahead and implement it in Perl; but to me, your speudo-code makes no sense, so it will be a pain, I fear... I took some of your pseudo-code and perl-ized it to get you started. hash1{node}=x,y,z # value in hash is a reference to a 3-element array $hash1{$node} = [ $x, $y, $z ]; foreach key in hash1 foreach my $k (keys %hash1) get x1,y1,z1 of this node1 (eg. hash1{key} will return x,y,z of this node1) $node1 = $hash1{$k}; invert_y=y*1 I have no idea what you mean here if exists hash2{invert_y} if (exists $hash2{$invert_y} get all node of hash2{keys} in node_array eh? foreach node2 in node_array foreach $node2 (@node_array) get x2,y2,z2 of this node2 (eg. hash1{node2} will return x,y,z of this node2) $node2 = $hash1{$node2}; if x1 of node1 == x2 of node2 && z1 of node1 == z2 of node2 node1 and node2 are symmetric # x is element 0, y is 1 and z is 2 if ($node1->[0] == $node2->[0] && $node1->[2] == $node2->[2])
common-pile/stackexchange_filtered
Odoo - How add a field to view from another wizard model? I want the use a field from wizard to my form view. Let me explain with code: class CancelAppointmentWizard(models.Model): _name = "cancel.appointment.wizard" _description = "Cancel Appointment Wizard" reason = fields.Text(string="Reason") and i want the show this "reason" field inside of some form views. <record id="view_hospital_appointment_form" model="ir.ui.view"> <field name="name">hospital.appointment.form</field> <field name="model">hospital.appointment</field> <field name="arch" type="xml"> <form> <sheet> <group> <field name="reason"/> </group> </sheet> </form> </field> </record> but of course this give me error like hospital.appointment don't have a field like reason. How can show this field ? I tried to make a dummy code, i hope i was able to explain my problem. You need to add a text field named reason on hospital.appointment model to save the reason value from the wizard I assume the wizard is called from the view_hospital_appointment_form. And in the wizard view let say there is a button tag with name attribute, which is this attribute associated to python method in your wizard class. Wizard view <record id="view_cancel_appointment_wizard_form" model="ir.ui.view"> <field name="name">cancel.appointment.wizard.form</field> <field name="model">cancel.appointment.wizard</field> <field name="arch" type="xml"> <form> … … <footer> <button name="action_ok" string="Ok" type="object"/> </footer> </form> </field> </record> Python method def action_ok(self): ids = self.env.context.get('active_ids') hospital_appointment = self.env['hospital.appointment'].browse(ids) hospital_appointment.reason = self.reason return {'type': 'ir.actions.act_window_close'} That's probably the answer to the next step: how to set a value from a wizard to a record. But the error message of the question clearly states, that there is not field reason on model hospital.appointment. So probably adding the field to that model should be the first step? ;-) Yes you're correct @CZoellner. We need to add reason field in the hospital.appointment model first.
common-pile/stackexchange_filtered
Setting environment variable in /usr/bin/env hangs process on Linux While the man for env on Linux seems to indicate that you can set new environment variables before executing a command. Unfortunately, when I set new variables in a file's shebang on Linux systems, the file never executes. #!/usr/bin/env VAR1=foo bash echo $VAR1 When I execute this file on a CentOS or Ubuntu machine, it just sits there. $ ./shell-env.sh <nothing happens> What I find particularly bizarre is this works perfectly fine on OS X with BSD env. $ ./shell-env.sh foo $ Is this just a difference between BSD env and Linux env? Why do the man pages for Linux seem to say it should work the same way as on BSD? P.S. My use case here is to override the PATH variable, so I can try to find a ruby on the system but that's not on the PATH. Thank you in advance! Are you redefining the PATH? If so, does your new PATH include bash? You can use env to set a variable before executing a command from the command line, but not in the shebang on Linux. This Q may be more appropriate on the S.E. related site http://unix.stackexchange.com (Unix & Linux). Consider using the flag link at the bottom of your Q and ask the moderator to move it. Please don't post the same Q on 2 different sites. Thanks and Good Luck. I don't understand, why no just set PATH from within the script? The rules for the sheebang line on, say, Linux say that exactly one argument is used. Hence, env gets as only argument VAR1=foo, but never sees bash. It's interesting to know that BSD is doing this differently. There's a way to manipulate the environment before executing a Ruby script, without using a wrapper script of some kind, but it's not pretty: #!/bin/bash export FOO=bar exec ruby -x "$0" "$@" #!ruby puts ENV['FOO'] This is usually reserved for esoteric situations where you need to manipulate e.g. PATH or LD_LIBRARY_PATH before executing the program, and it needs to be self-contained for some reason. It works for Perl and possibly others too! This is amazing, thank you! It was exactly what I was looking for.
common-pile/stackexchange_filtered
automated text for reproducible research I am using RStudio, R Markdown, Latex, and Pandoc to clean data, construct variables, run my analysis, and report the results. I'm new to the concept of reproducible research, but I'm hooked. Makes a lot of sense. Dynamic tables and figures are no problem. Dynamic text, however, is stumping me. I can insert inline code to say that 95% of all statistics are false, but I am not sure how I can vary my language in a reproducible way. For instance, what if I have an object x=0.66 and I want to write "2 out of 3 dentists use Crest"? I can look at the current value of x, 0.66, and type "2 out of 3" in the text, but this is not reproducible. Let's say I get new data and rerun my analysis and x becomes 0.52. My text would be out of date. Sure, I could dynamically report that 52% of dentists prefer Crest, but a report gets stale when everything is reported as percentages. My thought is that I could create functions that I could call in the text when I want to vary the writing. For instance, an "out.of" function could work on if else statements to produce the text: ifelse(x < 0.09,"fewer than 1 out of 10", ifelse(x >= 0.09) & x < 0.11,"roughly 1 out of 10", ifelse(x >= 0.11 & x < 0.15,"slightly more than 1 out of 10", ifelse(x >= 0.15 & x < 0.19,"nearly 2 out of 5", ifelse(x >= 0.19 & x < 0.21,"roughly 2 out of 5", ... ifelse(x >= 0.95 & x < 0.99,"nearly all", ifelse(x >= 0.99,"all","fubar"))...) I could also create a fraction function that would do something similar for one-tenth, two-fifths, one-third... I'm sure others have tackled this issue already. Any leads? Ideas? This is a really interesting question, but I think it would really depend on what your limits are for readability. Do you, for instance, consider "1 out of 20" or "1 out of 25" to be valid options? What threshold do you want to set for the more general breaks (like "2 out of 5")? Once this is sorted out, I would suggest trying cut() and specifying labels instead of ifelse(). I don't think any of the packages will do that for you, but they should help you in getting there! When it comes to representing percentages, I think "out of 10" is the lowest I would want to go. I've learned a ton of R this year (from a baseline of zero), but not cut(). Will look into it. Thanks. So then you would have to figure out what "out of" categories are most useful. Categories like "out of {9, 8, 7, 6}" might not be very user friendly since that will tax some readers who mentally try to convert those numbers back to a percentage. Good luck! There is a package FRACTION and when you replace / by "out of", it could work. However, the output when using the number of decimals is strange: library(FRACTION) fra(0.66,j=2) # [1] "33 / 50" fra(0.66,j=1) #"7 / 1e+08" Edit by @Dieter Menne: forget this, see @Ben Bolker below. you might be able to get around this with MASS::fractions: fractions(0.66,cycles=3) (and MASS is already Recommended)
common-pile/stackexchange_filtered
How to prevent Vim from loading a specific system-wide ftplugin? I'm writing a custom ftplugin for handling systemd file type. I've copied parts of code from vim's own systemd ftplugin and now the latter conflicts with my own code: Error detected while processing BufRead Autocommands for "*/etc/systemd/*.conf"..FileType Autocommands for "*"..function <SNR>1 4_LoadFTPlugin[18]..script /usr/share/vim/vim90/ftplugin/systemd.vim: line 12: E174: Command already exists: add ! to replace it: Sman silent exe '!' . KeywordLookup_systemd(<q-args>) | redraw! From what I see, the error comes from the system-wide ftplugin. The problem is, it uses the normal b:did_ftplugin guard improperly. Instead of this: if exists("b:did_ftplugin") finish endif let b:did_ftplugin = 1 ...it does this: if !exists('b:did_ftplugin') " some code that sets b:did_ftplugin endif " some more code As such, the code that is not guarded comes into conflict with my own code. I suppose this is something that should be patched upstream, but in the meantime, is there a way to prevent Vim from loading the system-wide ftplugin/systemd.vim and only load mine? I suspect the oddness is to support :runtime ftplugin/systemd.vim, like for the Man plugin, but I haven’t checked. @D.BenKnoble My apologies, I'm fairly new to Vimscript. Could you please explain what exactly is this supposed to achieve? I just looked at it, and I was wrong. (See ftplugin/man.vim for some serious weirdness.) I'll contact the maintainer and suggest a patch. https://github.com/vim/vim/issues/13357 Introduce systemd2 What you could do is selecting another filetype for systemd (e.g. systemd2) by having a ftdetect/systemd2.vim that set it. ~/vimfiles/ftdetect/systemd2.vim " Systemd unit files au BufNewFile,BufRead */systemd/*.{automount,dnssd,link,mount,netdev,network,nspawn,path,service,slice,socket,swap,target,timer} setf systemd2 " Systemd overrides au BufNewFile,BufRead */etc/systemd/*.conf.d/*.conf setf systemd2 au BufNewFile,BufRead */etc/systemd/system/*.d/*.conf setf systemd2 au BufNewFile,BufRead */.config/systemd/user/*.d/*.conf setf systemd2 " Systemd temp files au BufNewFile,BufRead */etc/systemd/system/*.d/.#* setf systemd2 au BufNewFile,BufRead */etc/systemd/system/.#* setf systemd2 au BufNewFile,BufRead */.config/systemd/user/*.d/.#* setf systemd2 au BufNewFile,BufRead */.config/systemd/user/.#* setf systemd2 The ftplugin/systemd.vim and friends ($VIMRUNTIME/indent/systemd.vim, $VIMRUNTIME/syntax/systemd.vim, $VIMRUNTIME/compiler/systemd.vim) will not be executed anymore and you can put your code in ~/vimfiles/ftplugin/systemd2.vim and friends. Amend the standard solution Another solution is to amend the systemd standard solution by moving part your code in ~/vimfiles/after/ftplugin/systemd.vim and make use of the command! to override the Sman command if you need to change it. Thank you! It did not even cross my mind that I could just introduce another filetype :-) +1 for overriding in ~/.vim/after/ftplugin/systemd.vim This is fixed in a recent runtime commit. If you can run recent versions, you should be able to get the upstream change and continue as usual.
common-pile/stackexchange_filtered
How import jar apache commons cli I have a project that I need to run, but I can't run it because IntelliJ Idea can't find the apache commons jar. The issue is importing import org.apache.commons.cli.*; I know the issue is that IntelliJ can't recognize it. I added the jar to my project, but it can't still able to find it. I've read in other posts that I would be able to use Maven, but I don't have a pom.xml file available. Any help will be greatly appreciated. Add the jar to the classpath and it should work. I cannot reproduce. After adding JAR file to dependencies and adding an import statement on top of the class file everything worked as expected. Maybe try to change scope? Dependencies: Class file: Thank you. After I break I realized I was adding the zip and not the jar (face palm). Now everything is good, thank you!
common-pile/stackexchange_filtered
How can someone infer something does not exist? First, I came across the Penrose triangle and then a variety of impossible objects. I understand that an object might not exist in a specific domain. For example, Penrose triangle does not exist in 3 dimensional Euclidean space. However, I have difficulty to understand how we can infer something cannot exist at all in whatever imaginable domain. If something cannot exist, even as a mental state, then how could somebody study its properties and conclude that object cannot exist? Thus, whatever, we are able to imagine must exist even though only as an abstract object or as a mental state. Am I right or am I missing something? Because those objects are defined as belonging to a specified domain if they are to exist at all. Namely, three-dimensional objects, "whatever imaginable" is moot. "Whatever we are able to imagine must exist" is overly optimistic about the powers of our imagination, it is quite adept at producing much nonsense. Or, if you prefer, at extracting nonsensical descriptions from what is supposedly imagined. I'm certain you can come up with certain axioms of geometry that allow you to talk about that triangle without running into contradictions. I think the article is slightly misleading in saying that it is "impossible". Descriptions of objects can be just sets of individual properties. Like it has 4 legs, it is made of wood, it fits through a door. Such properties can freely be combined to sets. They just remain sets of individual properties. Some such sets then describe real objects, some describe possible objects, some do not describe any possible object. But they can still be thought about as individual properties. It is possible to reason about the "raw" set of properties, to decide if it is consistent within itself, or consistent with other facts of nature that we believe in. As an image, you can imagine pieces of a puzzle that do not match, so you can never finish the puzzle. But you can still have all those pieces, carry them around, check which ones fit to each other. There is no need to first complete that puzzle to decide that the puzzle cannot be completed. The individual pieces alone are sufficient for that. Thus while it might be said what we "reason about impossible objects", that's just short for saying instead that we "reason about inconsistent sets of properties that are labelled to describe objects".
common-pile/stackexchange_filtered
Separate internet router from LAN wifi I have a Linksys WRT54GL router running Tomato that I've been happy with for quite a while. I just purchased a TP-Link WDR3600 a/b/g/n + 4-port Gigabit ethernet router for better LAN throughput, and while it seems like a great performer so far, I'm quite disappointed with the factory firmware. Worse, even though it's advertized as "DD-WRT ready" it doesn't look like it's currently supported by any of the major open firmwares. So I'm thinking about keeping the Linksys as my internet router, turning off its wifi, and using the TP-Link only for wifi connectivity. My reasoning is that my internet is only 10Mbps max anyway (which is fine for me), so the 100Mbps bottleneck shouldn't make a difference, right? Are there any other pitfalls to this technique I'm not considering? I have a decent grasp on networking but am not familiar with "real-world" ramifications such as latency etc. FWIW I would then move the cable modem and Linksys physically farther from the TP-Link to keep them out of the way. As far as setup, as long as the Linksys is still set as the DHCP server and gateway, and I turn off all routing features on the TP-Link, I can just connect the latter to one of the LAN ports on the former right? Then any wireless clients will just contact the Linksys to get their DHCP lease? Just in case anyone comes across a similar situation, I tried this out and was indeed able to get it working as desired. Haven't noticed any slowdown so far. I should specify that I connected the two routers from one LAN port to another, through a gigabit switch I already had, though I probably could have used a crossover cable to link them directly.
common-pile/stackexchange_filtered
Debugging for loop in palindrome numbers code This code gets an integer n and displays all palindrome numbers less than n. But seems the for loop doesn't work; because when I enter a number except 0, 1 and negatives, nothing happens. I tried debugging, but couldn't find the problem! Sample input: 30 Sample output: 1 2 3 4 5 6 7 8 9 11 22 import java.util.Scanner; public class PalindromeNumbers { public static void main(String args[]) { Scanner input = new Scanner(System.in); int n = input.nextInt(); if (n == 0 || n == 1 || n < 0) System.out.println("There's no Palindrome Number!"); else { for (int num = 1; num < n; num++) { int reversedNum = 0; int temp = 0; while (num > 0) { // use modulus operator to strip off the last digit temp = num % 10; // create the reversed number reversedNum = reversedNum * 10 + temp; num = num / 10; } if (reversedNum == num) System.out.println(num); } } } } You run into an infinite loop: you use num in your for loop as an index, and reset it to 0 inside the loop. Use different variables, and it should work! for (int i = 1; i < n; i++) { int num = i; ... if (reversedNum == i) System.out.println(i); } You are changing your num variable inside your for loop. The next time num < n is executed, the value changed (to 0). Try something like this: for (int num = 1; num < n; num++) { int reversedNum = 0; int temp = 0; int temp2 = num; while (temp2 > 0) { // use modulus operator to strip off the last digit temp = temp2 % 10; // create the reversed number reversedNum = reversedNum * 10 + temp; temp2 = temp2 / 10; } if (reversedNum == num) System.out.println(num); } This way, you use a temp variable to calculate your reversedNum, and still keeps the value of num for the next loop iteration.
common-pile/stackexchange_filtered
Overflow-y not working in javascript? I want to make an onClick event on the link. the code: <a onclick="document.getElementById('myBodyID').style.overflow-y='hidden'" title="my title">Anchor text</a> Why isn't this working? I want to disable vertical scrolling when the link is clicked. How could I fix this code? It is not working at the moment :( Use: document.getElementById('myBodyID').style.overflowY='hidden' As CSS properties with special characters are camel cased. You can also use brackets (document.getElementById('myBodyID').style["overflow-y"]). You cannot use - inside such a property literal. Instead, use the [] notation. .style['overflow-y'] = Currently, you're fetching .style.overflow and subtracting y (as with numbers), which does not make sense here.
common-pile/stackexchange_filtered
ASP.net - Static site search We have a static website in asp.net with about 50 pages and need to implement a site search. Any suggestions/links will be appreciated. Thanks, K From the ASP.Net website - http://www.asp.net/web-pages/tutorials/email-and-search If you're looking for a quick way to get search functionality into your pre-existing, static, site, google site search would be a very simple route to go. This link might help you.http://www.codeproject.com/KB/applications/SearchDotnet.aspx or you can can use sitesearch component for asp.net sites http://www.sitesearchasp.net/ http://www.asp.net/community/control-gallery/browse.aspx?category=45 I add one more suggestion here. The UltimateSearch from Karamasoft, that is a commercial product, but you avoid the advertise and have more control over. http://www.karamasoft.com/UltimateSearch/Features.aspx Here is what we did. We reused a small crawler and parsed all content into a simple table in MS SQL database and used MSSQLs Full Text Search to show the results and sorted by relevance. Hope this helps someone.
common-pile/stackexchange_filtered
how to reverse a string of type char *? I am using the reverse function. void reverse(char s[]) { int i, j; char c; for (i = 0, j = strlen(s) - 1; i < j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } } If I pass a string of type char a[] = "abcd" then I get on the output dcba. But if I pass char *a = "abcd" the I get bus error. Can I somehow reverse the string exactly of type char *? Source code: #include <stdio.h> #include <string.h> void reverse(char s[]); int main() { char a* = "abcd"; reverse(a); printf("%s", a); } void reverse(char s[]) { int i, j; char c; for (i = 0, j = strlen(s) - 1; i < j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } } https://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s?rq=1 @Andrey You may not change a string literal. Any attempt to change a string literal results in undefined behavior. May I suggest void revprint(const char *s) { for (size_t i = strlen(s); i-- > 0; ) putchar(s[i]); } There are no strings of type char *. A string is a sequence of characters terminated with the zero-character '\0'. In this declaration (that has a typo char a* = "abcd";) char *a = "abcd"; there is declared a pointer to a string literal. The string literal itself has the type char[5]. But used as an initializer expression it is implicitly converted to a pointer to its first element of the type char *. And you are trying to change the string literal pointed to by the pointer within the function reverse. However you may not change a string literal. Any attempt to change a string literal results in undefined behavior. From the C Standard (6.4.5 String literals) 7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined. What you could do is to create a new string that will store characters of the source string literal in the reverse order. For example char * reverse_copy( const char *s ) { size_t n = strlen( s ); char *t = malloc( n + 1 ); if ( t != NULL ) { t += n; *t = '\0'; while ( *s ) *--t = *s++; } return t; } And the function can be called like char *s = "abcd"; char *p = reverse_copy( s ); if ( p != NULL ) puts( p ); free( p ); Here is a demonstration program. #include <string.h> #include <stdlib.h> #include <stdio.h> char *reverse_copy( const char *s ) { size_t n = strlen( s ); char *t = malloc( n + 1 ); if (t != NULL) { t += n; *t = '\0'; while (*s) *--t = *s++; } return t; } int main( void ) { char *s = "abcd"; char *p = reverse_copy( s ); if (p != NULL) puts( p ); free( p ); } The program output is dcba does not work: free(): invalid pointer. if I remove free it will work, but there will be memory leaks. @Andrey I am sorry. There was a typo. See the updated function. Your reverse function is ok. The problem is that you instantiated you string as a literal by doing so: char *a = "abcd"; (it's '*a' not 'a*' btw) You cannot modify string literals. To test your function you could do so: #include <stdio.h> #include <string.h> #include <stdlib.h> void reverse(char s[]); int main(){ char *a = malloc(sizeof(char) * 5); if (a == NULL) return 1; a[0] = 'a'; a[1] = 'b'; a[2] = 'c'; a[3] = 'd'; a[4] = '\0'; reverse(a); printf("%s", a); free(a); } void reverse(char s[]){ int i, j; char c; for (i = 0, j = strlen(s) - 1; i<j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } }
common-pile/stackexchange_filtered
Is WCF a good fit for this problem? I'm working to implement a data service solution that has 2 request functions but can respond with one of 3 transmission types: x12 EDI HTTP MIME multipart SOAP/XML + WSDL I would also need to include logging and username/password authentication to the services. I'm in the very early learning stages of WCF. Is WCF a good fit for this? Yes, WCF is a good fit for this. It supports everything in your list. You might want to check out FubuMVC too - at my previous job we implemented something pretty similar over that stack; it has really powerful composability, which means that you can conditionally add behaviors like logging/auditing/authentication and adding a formatter to format the output correctly is simply a matter of putting the behavior into the behavior chain. It's also convention driven, so it's very flexible. All of that said, I can say that WCF Data Services specifically isn't the right solution (one of your tags) but WCF would probably meet your needs and comes with a better support agreement than FubuMVC.
common-pile/stackexchange_filtered
How do I make the text in this menu appear on the right and the items on the left? By default, the menu label is on the left and the menu items are on the right. I want to reverse this and make the menu label on the right and the menu items on the left. How can I achieve this using SwiftUI? Menu { Button(action: { sortingType = .date }) { Label("Sort by Date", systemImage: sortingType == .date ? "checkmark.circle.fill" : "circle") } Button(action: { sortingType = .amount }) { Label("Sort by Amount", systemImage: sortingType == .amount ? "checkmark.circle.fill" : "circle") } } Provide your code. Can't debug the image. Menu { Button(action: { sortingType = .date }) { Label("Sort by Date", systemImage: sortingType == .date ? "checkmark.circle.fill" : "circle") } Button(action: { sortingType = .amount }) { Label("Sort by Amount", systemImage: sortingType == .amount ? "checkmark.circle.fill" : "circle") } } I add an answer, so please check if it's working. Try to call the label and the condition in reverse. Menu { Button(action: { sortingType = .date }) { Label(systemImage: sortingType == .date ? "checkmark.circle.fill" : "circle", "Sort by Date") } Button(action: { sortingType = .amount }) { Label(systemImage: sortingType == .amount ? "checkmark.circle.fill" : "circle", "Sort by Amount") } } (additional) How 'bout this one? Separating label and your icon. Button(action: { sortingType = .date }) { Label { Text("Sort by Date") } icon: { Image(systemImage: sortingType == .date ? "checkmark.circle.fill" : "circle") } } Button(action: { sortingType = .amount }) { Label { Text("Sort by Amount") } icon: { Image(systemImage: sortingType == .amount ? "checkmark.circle.fill" : "circle") } } Isn't still working? It didn't unfortunately, I got this error Replace 'systemImage: sortingType == .date ? "checkmark.circle.fill" : "circle", "Sort by Date"' with '"Sort by Date", systemImage: sortingType == .date ? "checkmark.circle.fill" : "circle"' Can I ask what type of error is showing? There is additional in my answer. Please try it. Thank you for your reply. Unfortunately, I encountered an error when I tried your suggestion. Here is the error message: Extraneous argument label 'systemImage:' in call, Remove 'systemImage: '. I'm sorry I couldn't help. If possible, please make an playground of your work so it can be check or debug easily.
common-pile/stackexchange_filtered
How to access C# MessageHeader Concrete types I receive a System.ServiceModel.Channels.Message from a WCF service, it has a message header that at runtime is of type System.ServiceModel.Channels.ToHeader but I can't find this type anywhere to upcast it to use the ToHeaders properties. Is this a dynamic type that can only be accessed by reflection? You shouldn't need to access the members of the ToHeader class (which is internal). The only property which cannot be accessed from the base (public) class is the To (of type Uri), which you can access via the message directly (message.Headers.To). Thanks, I'll check that when I get in on Monday.
common-pile/stackexchange_filtered
OG Meta tags not working as intended I see the OG Meta tags in the source of the rendered homepage of my site. I see the correct image/location displayed in the code. But, when I hit the LIKE button > the displayed image on the Facebook page is incorrect. Also, I have individual settings for "Liking" individual products on our site. The settings look to be setup correctly. But I cannot get the OG Meta tags to show in the rendered HTML. Thanks Show us your like button code and the URL of the page. Facebook is using a cache on the OG data. Put your URL in this form https://developers.facebook.com/tools/debug It will clear Facebook's cache.
common-pile/stackexchange_filtered
Android app start up animation i just need to know how is it possible to create a start-up animation in your app. When the app is launched I would like it to go through custom animation and then it reaches the content of the app (main activity) ... Thanks for all your help It is possible, but kittens and unicorns die every time and Android app has a SplashScreen... That's not entirely true, the kittens and unicorns die only if you set a timer to purposely show the splashscreen longer :) If you really want a "startup" screen, just load up another activity before the MainActivity and display that screen for x amount of time: public class SplashScreen extends Activity { // Splash screen timer private static int TIME_OUT = 5000; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splash_layout); new Handler().postDelayed(new Runnable() { @Override public void run() { Intent i = new Intent(SplashScreen.this, MainActivity.class); startActivity(i); finish(); } }, TIME_OUT); } }
common-pile/stackexchange_filtered
WP8 App Not correctly reading from isolated storage I currently have this code. This is the code I actually use to read the file: public ObservableCollection<Esame> rigaEsame = new ObservableCollection<Esame>(); private void ReadFile() { Esami.ItemsSource = rigaEsame; IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication(); IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("exams.txt", FileMode.OpenOrCreate, FileAccess.Read); string tmp; string tmp2; using (StreamReader reader = new StreamReader(fileStream)) { while (!reader.EndOfStream) { tmp = reader.ReadLine(); tmp2 = reader.ReadLine(); rigaEsame.Insert(0, new Esame(tmp,tmp2)); Debug.WriteLine(tmp); } } } This code is the one I use to write to the file: private void InsertEntry_click(object sender, RoutedEventArgs e) { IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication(); using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("exams.txt", FileMode.Append, FileAccess.Write, myIsolatedStorage))) { writeFile.WriteLine(Subject.Text); writeFile.WriteLine(Date.Text); writeFile.Close(); } NavigationService.Navigate(new Uri("/Views/MainPage.xaml",UriKind.Relative)); } and this is the class file: public class Esame { public string nomeEsame { get; set; } public string descrizioneEsame { get; set; } public string Name { get { return nomeEsame; } set { nomeEsame = value; } } public Esame(string esame, string descrizione) { nomeEsame = esame; descrizioneEsame = descrizione; } } I am currently able to write the text from the TextBlock "Subject" and place it into my "Esami" LongListSelector. Still, I am currently unable to correctly read/write the second text string, coming from the TextBlock named "Date". How may I do that? I suppose there is something wrong with the class itself or the way I use it when putting it into my LongListSelector list item. How may i fix that? Unlike forum sites, we don't use "Thanks", or "Any help appreciated", or signatures on [so]. See "Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?. what did you mean exactly by "unable to correctly read/write the second text string, coming from the TextBlock named "Date""? how you know you're unable to do so. debug your application and narrow down scope of code that possibly cause the problem (at which line of code it begin to produce unexpected result)
common-pile/stackexchange_filtered
How can I split up a really long application form on a mobile website? If the number of questions this form asks is fixed by legal/business reasons (it's a loan application form for a bank), what is a good way to break it down into bite sized chunks? The two options I see are either paged or something like a vertical accordion. Personally I don't like forms that are broken over several pages which take time to load. I also don't like a form that's a mile long. See this very useful UX Booth article - http://www.uxbooth.com/articles/mobile-form-design-strategies/ accordion is not going to work. when the user will try to go to the 2nd form the 1st will collapse and the user will have to scroll all the way up, or there will be some auto animation that would bring them up... to much moving up and down. I would suggest to keep it opened. then the user can decide if they want to do it over the phone or leave it for later. How about tabs - vertical/horizontal, if the number of tabs are minimal? Group the information fields into categories and put the categories in a multi-page form with a progress indicator/page counter. Every page filled must be persisted to the back-end or cached such that the user can return and finish later. Welcome to the UX SE Justjyde! Can you explain why this option is different from Issac's answer? Can you provide any evidence that this method of chunking will work better than others? This method mimics the real life scenario. Imagine you are filling in a multi-page paper form. Once you are done with a page, you shift to the next. However you can return to the previous page and everything will still be there! You can put your form away and return later to finish it up. This method mimics what the user is used to and IMHO she/he will be more willing to accept that. I recently designed a form like this that was overwhelming to have so much in one view that it may frighten users and prevent them from signing upβ€” it was a sign-up and software installation wizard. So I grouped the options / questions into slides. Then have js navigate to the next slide once the previous / current slide's questions were answered. They were grouped into 2-3 related questions. I definitely agree that a long form wouldn't go over well, even an accordian style. I'd go with tabs at the bottom for each part with a small check to display if that particular part has been completed. Can you elaborate on your answer a bit? It would be even more helpful if you provide a mockup of your suggestion. Why do you believe tabs and a checkbox is better than a long form? You'll actually find that the responses for UI (and your question) is variable and based on both gender and age. To design a form that will appeal to an older generation, you'll want to avoid peripheral information. This is a design decision that Apple stumbled upon - and with the passing of Steve Jobs, it appears that apple marketing is attempting to capitalize on this "discovery". So - what is a good way to break it down? That depends on your demographic. Younger users will be more tolerant to smaller chunks. Older users will interpret smaller chunks as peripheral (and distracting) information. If reducing application abandonment is the fundamental issue, Good design that is relevant to your key demographic will increase form completion. If the customers have already committed to the process and it is a mandatory process that just happens to be done online? Then the UX is more than just UI preference.
common-pile/stackexchange_filtered
The method parseInt(String) in the type Integer is not applicable for the arguments (boolean) I am getting the error The method parseInt(String) in the type Integer is not applicable for the arguments (boolean) Here is the code } else if (Integer.parseInt(answerField.getText() == null)) { JOptionPane.showMessageDialog(null, "You did not enter an answer!"); } I have also tried this but it doesn't work: (Integer.parseInt(answerField.getText().equals(""))) & (Integer.parseInt(answerField.getText().length()) == 0) I just want to check to see if nothing has been entered and if so display a JOptionPane. Edit: The var answerField is a JTextField, where the user inputs an answer of a mathematical question. So the ActionListener then determines if the answer is correct, hence the parseInt (because of it being a mathematical operation) do { checkButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (Integer.parseInt(answerField.getText()) == correctAnswer) { count++; JOptionPane.showMessageDialog(null, "Correct"); } else if (Integer.parseInt(answerField.getText().length()) == 0) { JOptionPane.showMessageDialog(null, "You did not enter an answer!"); } else { count++; JOptionPane.showMessageDialog(null, "Incorrect!"); System.exit(0); } } }); } while (count < 11); You're passing a boolean expression to parseInt(), that expects a String. Don't try to do everything in a single line. Check if the string is empty/null, then parse it (if it needs to be parsed). But given what you're saying, all you need is if (answerField.getText().isEmpty()) Why do you want to use Integer.parseInt() ?? In order to check if there is text you need to use this `if (answerField.getText() == null || answerField.getText().equals("")) Note that if answerField is a JTextField or a JTextArea, its getText() method will never return null. I'm not well versed with Java, but I know there is a casting syntax to be used when doing type conversion, it may help in your case.. all of the values inside of your parse int method return a boolean becuase they are performing a comparison between two values that result in either true or false. You should use Boolean.parseBoolean() to return either "true" or "false" strings If all you want to do is check to see if there's some string contained in answerField, then all you need to do is check to see if it's not null or empty. if(!("".equals(answerField.getText()) || null == answerField.getText()) { // other, non-integer-handling code here } You do not want to handle parsing the integer if there's an empty string or if it's null, since that could result in a NullPointerException. I am not sure why you want to call Integer.parseInt, because you already have a boolean expression in your condition: } else if (answerField.getText() == null) { JOptionPane.showMessageDialog(null, "You did not enter an answer!"); } Note that if conditions in Java can only accept boolean expressions, and you couldn't pass in an integer or whatever else you'd think of as truthy or falsy (unlike C or Javascript, for example). Lets analise the code you have (Integer.parseInt(answerField.getText() == null)) the parameter answerField.getText() == null return a boolean and the method Integer.parseInt(bool) is not defined in the Integer class. It looks like you want to do: else if (someConditionHere) { Integer.parseInt(answerField.getText()); JOptionPane.showMessageDialog(null, "You did not enter an answer!"); }
common-pile/stackexchange_filtered
How to round numbers given by cmath For the sake of practice, I am trying to build a simple function that solves quadratic roots - including complex roots and returns a nice and rounded result. However, neither the round() function or f-string formatting seems to work. Here is the code I wrote: from cmath import sqrt a = float(input("Input ax^2: ")) b = float(input("Input bx: ")) c = float(input("Input c: ")) def quadratic_roots(a,b,c): x_1 = (-b - sqrt((b ** 2) - (4 * a * c))) / (2 * a) x_2 = (-b + sqrt((b ** 2) - (4 * a * c))) / (2 * a) return x_1,x_2 print(f"--- {a}x^2 {b}x + {c} = 0 ----") #Attempting to use round() fuction. print(f"x_1 = {round(quadratic_roots(a,b,c)[0],2)}") #Produces error print(f"x_2 = {round(quadratic_roots(a,b,c)[1],2)}") #Produces error #Attempting to use f-string formatting .to round up to three digits. print(f"x_1 = {quadratic_roots(a,b,c)[0]:.3d}") #Produces error print(f"x_2 = {quadratic_roots(a,b,c)[1]:.3d}") #Produces error And here is the output/error message I'm getting: print(f"x_1 = {round(quadratic_roots(a,b,c)[0],2)}") TypeError: type complex doesn't define __round__ method Is there anyone out there who can help me sort this out and return the result as a nice and rounded result? Any help is welcomed and appreciated :-) what was your input values? I can't reproduce your issue, it works fine on my computer: print(f"x_1 = {quadratic_roots(1,1,1)[0]:.3f}") x_1 = -0.500-0.866j @Sabil: My input was just 1, 1,1 Wich gives a complex number as an result @stef: Haha, you are absolutely right! I just figured out my own (stupid) mistake. I used f"{:.d}" which produces the error I posted about, rather than f"{:.f} (which is what I posted, and which does actually work) @Stef: So I basically solved my own problem while posting my own post. Haha. But thanks for helping out anyway! I resolved your issue @fredericoamigo. Hope now it will work for you If it works for you then please accept my answer and give an upvote. :) The issue was with round. I fix the issue and hope it will work now. Code: from cmath import sqrt a = float(input("Input ax^2: ")) b = float(input("Input bx: ")) c = float(input("Input c: ")) def quadratic_roots(a,b,c): x_1 = (-b - sqrt((b ** 2) - (4 * a * c))) / (2 * a) x_2 = (-b + sqrt((b ** 2) - (4 * a * c))) / (2 * a) return x_1, x_2 print(f"--- {a}x^2 {b}x + {c} = 0 ----") x_1, x_2 = quadratic_roots(a,b,c) #Attempting to use round() print(f"x_1 = {round(x_1.real, 3) + round(x_1.imag, 3) * 1j}") print(f"x_2 = {round(x_2.real, 3) + round(x_2.imag, 3) * 1j}") #Attempting to use f-string formatting .to round up to three digits. print(f"x_1 = {x_1:.3f}") print(f"x_2 = {x_2:.3f}") Input: Input ax^2: 1 Input bx: 1 Input c: 1 Output: --- 1.0x^2 1.0x + 1.0 = 0 ---- x_1 = (-0.5-0.866j) x_2 = (-0.5+0.866j) x_1 = -0.500-0.866j x_2 = -0.500+0.866j You can round the real and imaginary parts separately and then join them print(f"x_1 = {round(quadratic_roots(a,b,c[0].real,2)}+{round(quadratic_roots(a,b,c)[0].imag,2)*1j}") print(f"x_2 = {round(quadratic_roots(a,b,c)[1].real,2)}+{round(quadratic_roots(a,b,c)[1].imag,2)*1j}") Your answer is suggesting computing FOUR TIMES all the roots? Why not compute just once, and assign the result to variable names? @Stef: You're probably rigth. There are absolutely better ways to do this, but as I wrote in the description, this is purely for the sake of practice. I'm just a noob who tries to learn how to code:-) Complex numbers have a real part and an imaginary part. Try: x_1 = quadratic_roots(a, b, c)[0].real + quadratic_roots(a, b, c)[0].imag x_2 = quadratic_roots(a, b, c)[1].real + quadratic_roots(a, b, c)[1].imag print(f"x_1 = {round(x_1,2)}") print(f"x_2 = {round(x_2,2)}") After some help from the comments, this problem was fixed this by using print(f"x_1 = {quadratic_roots(a,b,c)[0]:.3f}") print(f"x_2 = {quadratic_roots(a,b,c)[1]:.3f}") The problem was that I used the wrong f-string formatting: I tried to use f"{:.d}", which didn't work. Replacing this with f"{:.f}" worked just fine. However, as suggested in the comments, there are better ways of solving this problem. A massive thank you to everyone who helped out and contributed!
common-pile/stackexchange_filtered
When do Blue Jays form their crests? I've noticed that not all Blue Jays appear to have a crest. I know that at certain times the crest may be down and less visible, but I notice in most images of juvenile Blue Jays they don't appear to have a crest. I'm curious if the crest forms later on or if Blue Jays are born with a crest? Short answer It seems like blue jays form their crests as adolescents, after their first post-juvenal molt before their first winter. Longer answer The top of the head of a bird is called the pileum, with the very top called the crown. As far as I can tell there is no particular distinction between "crown feathers" and "crest feathers", rather the presence of a "crest" is because the crown feathers are longer and stand out from the rest of the head. Juvenal plumage Blue jays born with their natal down will molt within the first two weeks to get their juvenal plumage. Dwight (1900) is quite descriptive of the juvenal plumage, but does not mention any crest, only that the pileum is a "flax-flower blue separated from the blue-tinged white forehead and white superciliary line by a narrow black line". Crown feathers are longer after the first prebasic molt, forming a crest The first prebasic molt refers to the (partial) loss of the juvenal feathers. Bancroft & Woolfenden (1982), examining young birds captured in Florida, found 8% in the first prebasic molt of the crown/head area in the first half of August, 89% in the second half of August, 78% in the first half of September, and 54% in the second half of September. So it seems most birds are getting through this molt by mid-September. Dwight (1900) writes that "young birds become practically indistinguishable from adults" around this time and that compared to the juvenal plumage, bold mine: the blue of head, back and wing coverts now distinctly barred with black and much brighter, and the crest feathers longer I haven't found mention of crest feathers rather than crown feathers in descriptions of the juvenal plumage, with one exception I'll get to below, so I'll tentatively say that a blue jay forms its crest as part of this first prebasic molt in which the first winter plumage is evident. Blue jay crest in behavior The crest position of blue jays differs across behavioral contexts, ranging from erect to pressed against the head. Conant (1972) mentions the crest specifically as part of several different postures/behavioral contexts (parentheses are my paraphrasing): In neutral posture, the crest and plumage are relaxed While a Blue Jay is asleep, the crest is relaxed and the body plumage is usually fluffed (while "investigating"): the crest is fluffed (during "mild aggression"): the crest is fluffed (during "intense aggression"): crest is fully erect or ruffled (during avoidance/submissive posturing): the crest is relaxed or sleeked (during "courtship feeding solicitation"): the crest is relaxed or sleeked And finally, the one section that makes me a little uncertain, Conant (1972) describes the "nestling alarm freeze" behavior of nestlings when their nest is disturbed or they hear an alarm call: The crest and body plumage are sleeked, wings closely appressed to the body, and tail closed. My guess is that she's using "crest" here to mean the crown feathers, and just referring to them as the "crest" since that's the word used when describing the other behaviors that primarily involve birds with adult plumage. However, it raises a bit of doubt and perhaps the other descriptions missed that there is also a crest in the juvenal plumage, hidden in the alarm/sleeked position under the watchful presence of predators scientists. Dr. Sheila Conant is now Professor Emerita at the University of Hawai'i at Manoa; one could ask her, but I think it has been awhile since she studied blue jays closely. Bancroft, G. T., & Woolfenden, G. E. (1982). The molt of scrub jays and blue jays in Florida. Ornithological Monographs, (29), iii-51. Conant, S. (1972). Visual and acoustic communication in the blue jay, Cyanocitta cristata (Aves, Corvidae). The University of Oklahoma. Dwight, J. (1900). The sequence of plumages and moults of the passerine birds of New York. New York Academy of Sciences.
common-pile/stackexchange_filtered
Open Graph in posts loop page I have a loop where all the posts have their own like button, when i click it the facebook window appears but it does not show the right post thumbnail. I think this is normal because in a posts loop the thumbnails are multiple so the script can not figure which one goes where - on the contrary the like button works perfectly on my single post pages. So my question: is it possible to have the facebook like button work correctly on a loop page so that it grabs the right post thumbnail even if there are, say 10 posts in that page? Maybe i should have multiple Open Graph metas, a set for each post in the loop, but i guess this would just cause a mess, is there something that i can do? Had you researched if Facebook supports this in first place? Details on what they allow and how would be pre-requisite for implementing it in WordPress. As far as I know this is not possible the way you're trying to get it to work. You can specify an image for Facebook to use in the <meta> tag, but that's about it. One thing you can try is use JavaScript to invoke the Facebook feed dialog. It has a picture parameter: picture The URL of a picture attached to this post. The picture must be at least 50px by 50px (though minimum 200px by 200px is preferred) and have a maximum aspect ratio of 3:1 The Javascript Example section at the link above is pretty self-explanatory.
common-pile/stackexchange_filtered
How to store data in Bixby Here are the steps that I want to be able to do in Bixby: 1. User says an utterance. 2. The Capsule then makes an API Call. 3. Store the returned data from the API Call locally. 4. User says a different utterance. 5. The API Call will send a piece of the stored data to the Endpoint. I want to be able to store data so I can reuse it for future utterances. How can I do this? I can only find this to be possible if the utterances are sequential by calling the functions consecutively however in my use case it is possible to be not sequential and I want to be able to re-use those values in other Bixby sessions as well. You would need to store this state via an external API call as the state is not maintained after exiting the capsule or across the request. See "Capsule and Context State", but here is the relevant info ... Context between capsules is not stateful, meaning that if the user leaves the capsule for another capsule or if the user leaves Bixby altogether, then any context for the first capsule is not guaranteed to be remembered. If your capsule does need to remember context between various states, you should use the content provider. You can store as much information on the content provider side as needed. You can always use remote endpoints and set up your service how you want.
common-pile/stackexchange_filtered
Eigen3: How to access matrix coefficients in performance critical operations? I am trying to optimize critical operations in C++ which rely on Eigen3. It is not clear for me what type of coefficient access operations would lead to runtime performance costs, or when would the compiler will make a good job. To try to pinpoint the source of my confusion I'm posting an example below implemented in a few different ways, together with some hypothesis for each. Here a few more details: The matrix M will remain constant throughout most of the program critical_function is indeed called many times and this is why it is inlined Could someone clarify which approach would be the best one in terms of performance? I might be confused on the impact cost of references, dereferencing, etc. Option 1: Directly accessing matrix coefficients #include <Eigen/Dense> class A{ A(){ // Assume M has the right numbers } // This function will be called many many times, inside loops inline void critical_function() { // Do many operations using M(1, 1), for example: double y = 1 / M(1, 1); // ... some more code using M(1, 1) } private: Eigen::Matrix3d M; }; Hypothesis: M(1,1) leads to constant dereferencing, incurring costs, as cycles will be added to computing an offset (this is not an array, but it is not clear how the compiler is managing this) Option 2: Creating a copy of the coefficient we care about #include <Eigen/Dense> class A{ A(){ // Assume M has the right numbers x = M(1, 1); } // This function will be called many many times, inside loops inline void critical_function() { // Do many operations using x, for example: double y = 1 / x; // ... some more code using x } private: double x; Eigen::Matrix3d M; }; Hypothesis: Accessing x generates less cycles than accessing M(1, 1), thus it is preferable to Option 1. x indeed contains the same value as M(1,1) but carries the important risk of ensuring this data is duplicated, so this needs to be avoided for code maintenance. Option 3: Making use of references #include <Eigen/Dense> class A{ A(){ // Assume M has the right numbers } // This function will be called many many times, inside loops inline void critical_function() { auto & x = M(1, 1); // Do many operations using x, for example: double y = 1 / x; // ... some more code using x } private: Eigen::Matrix3d M; }; Hypothesis: Having a single reference x will generate less cycles than constantly referring to M(1,1) inside the scope of the function. This potential optimization has an impact only inside critical_function, but will not carry over in an external scope, such as a loop calling the function many times. Edit The types were corrected to double (from int or float), to be consistent with Matrix3d. You'll most likely won't see any difference cause M(1, 1) will be in the cache anyway. Hypothesis: you are trying to do premature optimization without knowing where your code spends the most time. In other words: There is no 100% general answer to your questions. You will always have to profile your own code to find out what is best in your situation. In your case, it might make no difference at all because the compiler transforms things behind the scenes anyway. Here's a tip: One division costs one to two orders of magnitude more CPU time than what you are worrying about right now. Thank you both for the answers. True that caching will have a positive impact, yet, accessing a coefficient while in cache still would generate more cycles that accessing an scalar in cache (eg. a float)? Or not? I agree that profiling is the right approach and yes maybe I'm being picky and there are more impactfull operations, I'm just trying to understand well the concepts such that I can use the best practices. As I mentioned, critical_function is called many times. Could you please refer to the hypothesis that I stated and either confirm or correct my understanding? Is x intentionally an int instead of double in option 2? Option 3 is unlikely making a difference, since M(1,1) will be simplified at compile time to something equivalent to ((double*)(this))[4] No, it was a mistake, thanks for pointing that out. I've corrected the code to be consistently doubles. Are operations with x (Option 2) faster than the access to ((double*)(this))[4] (Option 1)? ((double*)this)[4] would be UB, don't do that. Also, the compiler might just inline M(1, 1) for you anyway, so until you look at the generated code and measure, you can't know for sure which option is faster. It's probably not 3 though. The big takeaway here is don't focus on "micro-optimizations", that is what compilers are far better at doing. Only after you have completed your code and profiled to find any hot-spots would you need to look and see whether there is anything there you can do better that what the compiler has done (and the answer will usually be "No", optimization wasn't the issue, logic was... In short, don't bother and write M(1,1). If you're dealing with compile-time matrices like Matrix3d and indices known at compile-time, then the indexing computations involved in M(1,1) will be completely optimized away by any compiler. In other words, the two following snippets will generate the same assembly: struct A { Matrix3d M; void foo() { double x = M(1,1); } }; struct A { double a, b, c, d, e, f, g, h, i; void foo() { double x = e; } }; So option 2 will be worse, and option 3 might also reduce performance because you introduce a pointer.
common-pile/stackexchange_filtered
Execute Python code in new environment Some time ago I've written an IDE for Python on iOS for my iPod Touch using PyObjC (ported to iOS by Saurik, installed via Cydia). I use the 'exec' statement to evaluate the code that I entered in the Textfield. But when subclassing an Objective-C class, i run into trouble when executing. The classes must not be declared two times, doing so raises a SystemError. SystemError: NULL result without error in PyObject_Call Is there a way to execute the code in a new environment while I'm still able to transfer some variables to it ? Currently I execute it using a copy of globals(). Thanks, Niklas Assuming it works on ios, you can put any objects into the globals/locals dicts which you pass to the exec statement. This does unfortunately not work. As I already said i use a copy of globals() with the exec statement. It seems like subclasses are some kind of registered anywhere. Even This does not work: class Foo(NSObject): pass \n del Foo. Pressing Execute Button twice raises the same error. i don't think you should be able to use exec() in iOS at all Why do you think so ? Everything works well, except subclassing ObjC Classes. I read somewhere, that it is only possible to declare an ObjC class only once with a name per Python process, and this is exactly the problem. I'd need to create a new process of python that runs the code, but I don't know how.
common-pile/stackexchange_filtered
Modify Windows Form with treeview or radiobutton I'm creating a GUI and I would like an app that changes on based which item in a treeview or which item is selected on a radio button. I know how to know which item is selected, but how do i change the interface based on the item? What should I try? Multiple panels? Some hidden? Imagine the app like and MMC, the right side changes based on what do i select on right. I used something like Button1.Visible = true and Button2.Visible = false in the event, but how do I group the elements in the right side? In the desingner mode I will see every object overlapping others? I would have a single panel for the content pane. Then create two user controls, create a NEW instance of the right one when an item is selected, dispose of the current one (if there is one in the panel), and parent the new one to the panel. Assuming you're referring to something like a menu (menu options on the left; when one is clicked, the right side of the window is filled with the corresponding settings), just create a separate control for each 'window' (non-technical use of the word) on the right. When an entry on the left side is selected, handle the Click event by calling BringToFront() on the corresponding control in the right panel. If you're not referring to a menu, and are instead referring to something much more granular (where each selection on the left side operates on the same central display-unit, and each selection may only affect one small portion), then divide the central display-unit into panels, one for each unit that may be affected by the left-side selection, and Show and Hide them according to the left-side selection. Thank you. It looks like what I need. How do I create this controls? In the toolbox I dont see them http://img805.imageshack.us/img805/3255/controlh.png. They're essentially new code units that you'd add to your project. 'Control' can refer both to the atoms of a form (buttons, groupboxes, etc), as well as larger composites (such as a button + combobox, or five textboxes organized vertically). Once you've made one of these controls (say, by 'Add New Control' in the Solution Explorer), and once that control has been built, you can add it to your form in exactly the same way that you would add any of the other .NET-provided controls. The usual way to handle this is to have a panel on the right side of the screen, and each of the different views have their own UserControl created. Then when the tree view selection changes, you clear the children of the panel, create the relevant UserControl instance, add it to the panel, and set its Dock to Fill. Something like the pseudo-code below: private void treeView1_AfterSelect(object sender, TreeViewEventArgs e) { panel1.Controls.Clear(); UserControl uc = new MyUserControl(); uc.DataToShow = (MyObject)treeView1.SelectedNode.Tag; uc.Dock = DockStyle.Fill; panel1.Controls.Add(uc); } What about using somehting like tabs? This is not possible uising the Designer, rigth? You can do it in the designer, but there are two main problems. Firstly, most people that do it that way then want to hide all of the tabs except the current one. WinForms doesn't do that properly (although you can fudge it a bit). Secondly, if you have a lot of tabs they all get created when your program starts up, thereby slowing it down.
common-pile/stackexchange_filtered
Compiling a groovy scripts that come from a Database Groovy scripts are placed in a Database entry (data type BLOB). I can read the bytes and convert to a String object. How can I use GroovyClassLoader or GroovyScriptEngine to compile and execute the script? I need to track dependencies between scripts so that if any dependent script is modified, the whole tree will be recompiled and reloaded. Say you take the text to string scriptAsString Eval.me(scriptAsString) Perhaps you should store the script(s) as bytecode so you can use them with classLoader and make sure dependent scripts are up-to-date. extends GroovyClassLoader overeide loadClass(), and add your implemetation @Override public Class loadClass(String name, boolean lookupScriptFiles, boolean preferClassOverScript) throws ClassNotFoundException, CompilationFailedException { // TODO Auto-generated method stub try { Class<?> loadedClass = super.loadClass(name, lookupScriptFiles, preferClassOverScript); if (loadedClass !=null) { return loadedClass; } } catch (ClassNotFoundException e) { } int indx = name.lastIndexOf('.'); String substr = name; if (indx != -1) { substr = name.substring(indx + 1); } String groovyFileName = substr + ".groovy"; String path = "C:\\" + groovyFileName; try { return parseClass(new File(path).toString(), groovyFileName); } catch (CompilationFailedException exception) { throw exception; } } Compiling "main" source from database etc is easy. But problem is when this script imports other. I intensively search solution to compile it "in fly", without success. Class GroovyResourceLoader knows what import is required (I check it, good) but I can't resolve next problems. I receive very good answer (plus my own tests) in http://stackoverflow.com/questions/32033980/how-compile-groovy-source-but-not-from-filesystem
common-pile/stackexchange_filtered
Why are British Airways wings so dirty? I often fly through Heathrow, and British Airways airplanes, particularly their 777s, always look so dirty. For example, there is often a kind of dark oily stain on the wings and flight surface. So - why are BA planes so dirty compared to the others? And what exactly is this dirty anyway? (image from this YouTube video) Related: Do airlines ever clean their planes? What evidence do you have that this is a significant issue on BA aircraft only? Or is it a 777 issue? Or a BA 777 only issue? One image from one video seems to lead to an unsubstantiated claim of "always". Maybe next time you're through LHR, take a pic of every plane parked at every gate you can get to and do a count to see if BA is really the dirtiest airline. As it stands, this seems to be unsubstantiated speculation... @FreeMan I fly through Heathrow at least eight times a year, and have been doing so for the past 20 years. As I have said in the post, I observe dirt on BA planes, particularly on their 777 fleet, that stand out compared to other airlines. I attached an image that is a representative sample of my observations. If you choose not to believe me, that is fine - I am simply looking for a plausible explanation. It's probably because they want them to match the dirty interior. BA is not known for the quality of their housekeeping, and I have flown them in the US, the EU, the Middle East and Africa. @JuanJimenez It's a shame that a flag carrier, of a country known for its aviation heritage, should present itself in such an unappealing way :( To match their 'tricks' - https://en.wikipedia.org/wiki/Dirty_Tricks_(scandal)
common-pile/stackexchange_filtered
How to check for field existance in Thymeleaf? <nav th:if="${page} and ${page?.totalPages != null} and ${page?.totalPages > 1}"/> What if the page object does not have a getTotalPages() method or totalPages field? Then I get the following error: Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "page.totalPages != null" Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'totalPages' cannot be found on object of type 'org.springframework.data.domain.SliceImpl' - maybe not public or not valid? Question: how can I tell thymeleaf to validate if the property exists at all? I think the answer is: What you are seeing is how it works, for the reasons given here: How to handle "Property or field cannot be found on object in SpEL"? okay, while I don't get the difference between a field that is null in contrast to a missing field, obviously for thymeleaf it's not the same - which I thought. I assume it's more about how Java handles these things, since Thymeleaf delegates invocation of the method to Java (using reflection, I assume). Your error is the error you get if you try to invoke a non-existent method (using reflection) with pure Java. Also, Thymeleaf does not have any try-catch syntax - which is what you would probably need, if you wanted to somehow handle the exception in your Thymeleaf template. (Someone with more knowledge about Thymeleaf internals can correct me where I may be wrong.) @andrewJames You are right about Thymeleaf using reflection to access public properties and methods. @membersound And that's why you get the message "maybe not public or not valid?" in your stacktrace : public access not found or method does not exists or invalid with more or less params (as an example). And they did not give deeper explanations in stacktrace because it is really easy and fast to check that kind of stuff as a developer.
common-pile/stackexchange_filtered
Graph for derivative function Please help. I can't display a graph for the derivative of a function. Ls = 1.27; Is = 1.1; S = 3.6; B = 0.136; A = 2; i[t_] := A Sin[2 50 \[Pi] t]; \[Psi][t_] := Ls i[t]/Is (1 + (Abs[i[t]/Is])^S)^(-1/(S + B)) ; d\[Psi][t_] := D[\[Psi][t], t]; Plot[{\[Psi]'[t]}, {t, 0.001, 0.04}] Plot[{d\[Psi][t]}, {t, 0.001, 0.04}] tried to use: With[{f = d\[Psi][t]}, Plot[f, {t, 0, 0.04}]] ReleaseHold@HoldForm[Plot][d\[Psi][t], {t, 0, 0.04}] Thank you for your attention, I will be glad for any help. $Version (* "13.3.1 for Mac OS X ARM (64-bit) (July 24, 2023)" *) Clear["Global`*"] Abs is a complex function and you cannot take its derivative, use RealAbs Ls = 1.27; Is = 1.1; S = 3.6; B = 0.136; A = 2; i[t_] := A Sin[2 50 Ο€ t]; ψ[t_] := Ls i[t]/Is (1 + (RealAbs[i[t]/Is])^S)^(-1/(S + B)); For dψ use Set rather than SetDelayed dψ[t_] = D[ψ[t], t]; Plot[ψ'[t], {t, 0.001, 0.04}] Plot[dψ[t], {t, 0.001, 0.04}]
common-pile/stackexchange_filtered
impossible lengths of a train toy made by two types of wooden pieces. A train toy is made of a series of any number of wooden pieces, each piece is either 6 cm or 7 cm long. how can I -mathematically- prove that the train can never be 29 cm long? Any thoughts? If nothing else, $29$ is a very small number. Brute force solves the thing quite quickly. Start off with an equation $6a+7b=29$, then try to solve for any integer solutions, then show why there cannot be any. Search the site for numerical semigroups. I highly recommend this post for a local, more general argument. The general result tells that 29 is the longest impossible length @TedShifrin, thanks for the hints. I will change it. Constructing a train out of 6- and 7-inch cars is equivalent to taking some number of 6-inch cars and then adding a number of 1-inch pieces no greater than the number of 6-inchers. That is, you want to find nonnegative integers $m$ and $n$ such that $6m+n=29$ and $m\ge n$. Clearly, $m\le4$, but what does this mean for $n$? You could try to prove that the equation below (where $x, y$ represent the number of pieces of length $7,6$), has no integer solution for $x, y$ - Here we insist on integer values because the values represent pieces that have to be used as a whole and can't be cut to fit (at least I assume so): $$7 x + 6 y=29 \tag1$$ If you don't want to get into number theory, and you don't want to try it by varying $x, y$, you can draw the line representing (1) (in this case it is the red one) You will notice that at the intersection of integer values of $x,y$, the point on the line is not an integer. As an example of a case where you can find integer $x,y$ values, and how would they look like on the line graph, take the case of the Blue line provides a case where you can construct a train using $2$ pieces each of $7cm$ and $3$ pieces each of $6cm$. To plot these lines you could do this: 1-Put $x=0$ to get the value of y-intercept 2-Put $y=0$ to get the value of x-intercept 3-Draw the line between the above $2$ points. First, you should check the numbers in the original question. Second, you didn't write an equation! @TedShifrin, thanks for your comment. I edited the answer.
common-pile/stackexchange_filtered
Exposed and private/local members in CommonJS modules I was testing this framework and got these issues, idk why they happen and couldn't find the answer neither in Node.js docs nor in global search. init.js const { f1, v1, v2, f2 } = require('./1.js') f2() 1.js module.exports = { f1: function (v1) { f1(v1) }, v1: 1, v2: this.v1 + 1, f2: function () { f1(this.v2) }, // * error: outputs NaN . // f2: function () { this.f1(this.v2) }, // * error: when called from importing script, crashes with `TypeError: this.f1 is not a function` . // // This function works if `<<name for Object>> = require('<<path>>')` syntax is used . } function f1 (v1) { console.log(v1) } Specific questions are: How to use exposed functions and variables in other exposed functions? Is it possible to achive with module.exports = { syntax? If you want to preserve the syntax of defining everything inside of module.exports object, you can refer to it in other functions' bodies either through this or through module.exports: module.exports = { f1: function () { // … }, f2: function () { this.f1() }, f3: function () { module.exports.f1() }, } You can't refer to the object by module.exports for variables (non-function properties). This is because while the property value is being calculated, module.exports does not exist yet. You also can't refer to it by this, mainly for the same reasons: this refers to a different thing, not the object. All of this trouble can be easily avoided (with added benefits, like making the value read-only, more fine-grained visibility control – and many more) if you define things separately from exporting them: const v1 = 1 let v2 = v1 + 1 function f1(arg) { console.log(arg) } function f2() { f1(v2) } module.exports = { v1, v2, f1, f2 } <<unexpected value>> + 1 == NaN , ty. It appears that remaining benefits worth less than scalability of ES modules. _ _ By the way, <<name for Object>> = require('<<path>>') syntax is required for 1st part of your answer. Yes, in both cases, you access the values like require('path/to/file').f1(arg)
common-pile/stackexchange_filtered
How to do Silverlight Validation in a web service I am currently trying to implement the built-in Silverlight 3 validation against objects that are accessed via a web service. I have tried to follow the examples listed on SilverLight.net (Jesse Liberty's tutorial) and have had no luck. In fact, I could not get the tutorial to work after I downloaded it unless I started it without debugging. Currently my code looks like this [DataContract] public class Email { [DataMember] public string EMailID; [DataMember] public string EMailTypeID; [DataMember] public string EMailTypeName; [DataMember] public string UserID; [DataMember] public string EMailAddress; [DataMember] public string ActiveRecordFlag; [DataMember] public string Created; [DataMember] public string Modified; } I tried the INotifyChange changes, all to no avail. Has anyone done this before, or seen a tutorial on how to use objects that are accessed via web services with the built in validation? Thanks ~Steve I had a similar problem with Jesse Liberty's tutorial. Like you said, it works if you run it without debugging. If you had the same problem I had then you can try my solution. The problem was that a validation check against a field with an invalid input throws a ValidationException that the debugger picks up. It shouldn't do this since it is the validation framework that should handle this exception automatically and show the result on screen. To get around this, you have to add an exception to visual studio to get it to ignore the exception. To do this, in top menu bar, select 'Debug' and then select 'Exceptions...'. In the window that appears click the 'Add...' button. Select 'Common Language Runtime Exceptions' from the 'Type' combo box and enter 'System.ComponentModel.DataAnnotations.ValidationException' in the 'Name' field and click OK. The tutorial should work now. Hopefully it should be enough to follow on from there like I did
common-pile/stackexchange_filtered
How to detect position of Vive base stations? So I'm completely new to Unity and VR but for a project I need to detect the positions of the base stations. I tried googling, but since I don't know all the lingo I don't really know where and what to look for. All I can find is how to detect the controllers. I doubt this is info is exposed, because OpenVR is an abstract API for a variety of hardware. Not all hardware has base stations, e.g. Rift tracks with cameras. Other headsets may use inside-out tracking that doesn't require external sensors/lighthouses at all. This is a hidden implementation detail of tracking. Just noticed this in the openvr.h header: enum ETrackedDeviceClass { ... TrackedDeviceClass_TrackingReference = 4, // Camera and base stations that serve as tracking reference points ...}. So you can get their positions. The GetSortedTrackedDeviceIndicesOfClass method should give the indices for the poses array. Well, that's if you're accessing the API directly - don't know about Unity. Here's one way, all with Unity code: var nodeStates = new List<XRNodeState>(); InputTracking.GetNodeStates(nodeStates); foreach (var trackedNode in nodeStates.Where(n => n.nodeType == XRNode.TrackingReference)) { bool hasPos = trackedNode.TryGetPosition(out var position); bool hasRot = trackedNode.TryGetRotation(out var rotation); } In OpenVR, base stations are "tracked devices", just like the controllers and HMD. The standard SteamVR plugin for Unity already has a way to get the position of any tracked device, see for example how the controllers are implemented in the standard [CameraRig] prefab. The only problem is that you need to provide the "index" of the device, which may change every time you reconnect your headset. SteamVR plugin handles this with the SteamVR_ControllerManager component, but as the name suggests - it handles only controllers. You should be able to implement something similar, or just edit the script and find the lines if (deviceClass == ETrackedDeviceClass.Controller || deviceClass == ETrackedDeviceClass.GenericTracker) and add ETrackedDeviceClass.TrackingReference to this list. You should then be able to copy the controller objects and attach them in the "additional objects" array in SteamVR_ControllerManager to have the base stations appear in your scene.
common-pile/stackexchange_filtered
Doctrine querybuilder :parameter BETWEEN prop1 AND prop2 Hey i have a question about the querybuilder. IΒ΄m inside an EntityRepository this code finds all between from and to public function getBySpan($from,$to) { $from = new \DateTime($from->format("Y-m-d")." 00:00:00"); $to = new \DateTime($to->format("Y-m-d")." 23:30:00"); $qb = $this->createQueryBuilder("e"); $qb ->andWhere('e.date BETWEEN :from AND :to') ->setParameter('from', $from ) ->setParameter('to', $to) ; $result = $qb->getQuery()->getResult(); return $result; } what i try to archieve is find all where $date is between e.from AND e.to public function getByDate($date) { $date = new \DateTime($date->format("Y-m-d")." 00:05:50"); $qb = $this->createQueryBuilder("e"); $qb /* HOW TO PUT THIS LINE TO WORK ? */ ->andWhere(':date BETWEEN e.from AND e.to') ->setParameter('date', $date) ; $result = $qb->getQuery()->getResult(); return $result; } for any help thanks in advance I am not so familiar with this query builder but you can try something like this ->andWhere('e.from <= :date') ->andWhere('e.to >= :date') ->setParameter('date', $date); This is something similar to what you are trying to achieve.
common-pile/stackexchange_filtered
Why do I get a error in leetcode submission but pass in IDE using the same code? I am solving LeetCode question: 234. Palindrome Linked List: Given the head of a singly linked list, return true if it is a palindrome. Example 1: Input: head = [1,2,2,1] Output: true Example 2: Input: head = [1,2] Output: false Constraints: The number of nodes in the list is in the range [1, 10⁡]. 0 <= Node.val <= 9 Follow up: Could you do it in O(n) time and O(1) space? Using C++ I get the error below: ================================================================= ==42==ERROR: AddressSanitizer: heap-use-after-free on address 0x602000000098 at pc 0x00000037ac7d bp 0x7ffc1760fda0 sp 0x7ffc1760fd98 READ of size 8 at 0x602000000098 thread T0 #2 0x7f5a8c3e70b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2) 0x602000000098 is located 8 bytes inside of 16-byte region [0x602000000090,0x6020000000a0) freed by thread T0 here: #3 0x7f5a8c3e70b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2) previously allocated by thread T0 here:...... Here is my code: /*code only in VS #include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} };*/ class Solution { public: bool isPalindrome(ListNode* head) { if (!head->next) { return true; } ListNode* slow = head; ListNode* fast = head; while (fast && fast->next) { fast = fast->next->next; slow = slow->next; } ListNode* prev = slow; ListNode* current = prev->next; while (current) { ListNode* temp = current->next; current->next = prev; prev = current; current = temp; } while (head != slow) { if (head->val != prev->val) { return false; } head = head->next; prev = prev->next; } return true; } }; /*code only in VS int main() { ListNode* a = new ListNode(1); ListNode* b = new ListNode(0); ListNode* c = new ListNode(3); ListNode* d = new ListNode(4); //[1,0,3,4,0,1] ListNode* e = new ListNode(0); ListNode* f = new ListNode(1); a->next = b; b->next = c; c->next = d; d->next = e; e->next = f; Solution solution; cout << solution.isPalindrome(a); }*/ I can run it and get the right answer in my IDE (Visual Studio 2019 Community), but get an error in the LeetCode submission. Any idea why this would happen? That message reads like a pointer problem. Have you tested other test-cases than the one published on the so-called "competition" site? How about corner-cases like null pointer input? Have you tried to step through the code using a debugger (while monitoring variables and drawing the operations using pen and paper) to see that your code really does what you intended it to do? That's undefined behavior for you, the fact that a program seems to run doesn't mean it is correct. Your code does have a bug: accessing memory that was previously deleted. As long as that memory is not overwritten you may still get the expected results, but it is by no means guaranteed. The leet-code compiler just does a better job at detecting that you do this and will give you the error. Why is isPalindrome() modifying the list in the 2nd while loop? Checking for a Palindrome should be a read-only operation. @RemyLebeau cuz this question requires O(1) space complexity in follow up and reversing half of the list seems a good choice. Please read the help pages, take the SO [tour], read [ask], as well as this question checklist. Questions needs to be self-contained. All information should be in the question itself, not as external links (which can change, go stale or disappear). You should probably make your code more like what the checker is going to do, e.g. delete the list after the test, check lists that have both odd and even length etc. @AlanBirtles I tested edge cases like length 1 and both even and odd cases,it seems ok in IDE so I really don't know what's going on..In leetcode I can't pass a single test case. Have you tried iterating through the list and deleting nodes like the test probably does? The error occurs when the Leet Code test system will try to release the memory used by the previous test case, before launching the next one. Your code leaves the list in a state where it will run in cycles: the node that follows slow has been rewired by your code to point back to slow. We can imagine how the Leet Code clean-up code will free the node that slow refers to, then free the next node's memory, and then arrive again at slow which was already freed/deleted. This is the cause of this error. It is therefore important that you leave the list in a consistent state, where it has the original number of nodes, and there are no cycles. To resolve the error quicly, just add this line before the last loop: slow->next = nullptr; However, this leaves the second (reversed) half of your list unreachable for Leet Code to clean up. That's not really fair (although fast). To do it properly, make slow stop at the left side of the center when the list size is even (by moving fast one step ahead), and then rewire the tail of the first half with the (new) head of the second half (which was reversed): class Solution { public: bool isPalindrome(ListNode* head) { if (!head->next) { return true; } ListNode* slow = head; ListNode* fast = head->next; // Stop loop sooner when size is even while (fast && fast->next) { fast = fast->next->next; slow = slow->next; } ListNode* prev = nullptr; // this will be assigned to the new tail ListNode* current = slow->next; while (current) { ListNode* temp = current->next; current->next = prev; prev = current; current = temp; } slow->next = prev; // link tail of first half to head of reversed part while (prev) // Continue the walk in second half until the list's end { if (head->val != prev->val) { return false; } head = head->next; prev = prev->next; } return true; } }; test cases 85 / 85 passed.Thanks alot,having been stuck in this problem for a day and didn't know this whole test system implementation before.you really saved my day!
common-pile/stackexchange_filtered
Fastapi - Correct way of validating fields on crud level I'm working on small fast api project (pizza delivery). At some point I need to validate things on database level before I create new object. For instance pizza order - the pizza name comming from that order (if this pizza exists in database). I've noticed that some people perform this kind of validation using pydantic (on schema level). I'm a bit worried it's incorrect way as schema should be just schema and shouldn't touch database at this point (Too many responsibilities). I've come up with my own way and separated database validation on extra layer. Validator abstract + decorator using this abstract: class Validator(Protocol): """Validator abstract class""" def validation(db: Session): ... def validator(validator: Validator): """Decorator for dynamic validator allocation""" def decorator(func): @wraps(func) def wrapper(*args, **kwargs): try: db: Session = args[0] schema: schemas = args[1] except IndexError: raise AttributeError("Insufficient amount of arguments for validator") exception = validator(schema).validation(db) if exception: raise exception return func(*args, **kwargs) return wrapper return decorator Implementation of abstract: class PizzaExistsValidator: def __init__(self, order: schemas.Order): self.order = order def validation(self, db: Session): if not all(get_pizza(db, ordered_pizza.pizza.name) != None for ordered_pizza in self.order.pizzas): return PizzaExistenceException("Pizza does not exist") Usage on db level: @validator(PizzaExistsValidator) def create_order(db: Session, order: schemas.Order): total_price = order.price order.pizzas = jsonable_encoder(order.pizzas) db_order = models.Order(**dict(order), price=total_price) db.add(db_order) db.commit() db.refresh(db_order) return db_order I'm new in fastapi so maybe I'm not aware about any another, better way of doing the above? Appreciate any hints / feedback :) I usually recommend moving this outside of any validators; they should be concerned with making sure the input is valid, not that it's correct according to business reasons. The decision of whether the requested order is acceptable should be handed over to an OrderService, which receives the pydantic model and then makes sure that the order is acceptable according to business rules. Otherwise you'll end up having multiple business rules inside your "validator" function, such as how many pizzas someone can order, etc. Let the service decide business issues, as long as the input is valid. Agree with the above comment
common-pile/stackexchange_filtered
Java code is seems to be ignored I have a problem with Java/HIBERNATE. Here is some lines of code: quickOrder.setResultUrl(resultUrl); quickOrder.setStatus(QuickOrder.OrderedCampaignStatus.READY); quickOrder.setPerformDate(DateTime.now()); em.merge(quickOrder) In 99% cases it works fine. Everything is changed and written into a database. But I started to realize that sometimes the line quickOrder.setStatus(QuickOrder.OrderedCampaignStatus.READY); is seems to be ignored and the status isn't changed. Everything else is written and merged, exclude this line. What problem can it be? Entity: @Entity(name = "quick_orders") public class QuickOrder { @Id @GeneratedValue private Integer id; @OneToOne(cascade = {CascadeType.ALL}) @JoinColumn(name = "id") private OrderedCampaign orderedCampaign; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "bloggerId", nullable = false, referencedColumnName = "id") private WebUser blogger; @Enumerated(EnumType.STRING) private OrderedCampaignStatus status; what is your entity and how configured? (from @user2120275) Check that the status field on whatever Hibernate entity quickOrder represents is not marked updatable=false I added entity to the main question Are you sure you don't happen to have 2 processes that concurrently are updating the same row? I see no @Version to control optimistic locking, so it is certainly a possibility. Naros, I am sure and I am using Pessimistic_Write locktype while working with the row in this java method. Try to narrow down the scenarios in which this does happen. For example, does this happen only when you assign something to status from null? Or from something to null? Could you please post the declaration of OrderedCampaignStatus?
common-pile/stackexchange_filtered
Filter using lodash I want to add element to array if there is no element with the same type and format. I did it with for loop, but it looks bad. for (i = 0; i < this.model.array.length; i++) { const selectedElement = this.model.array[ i ] if (selectedElement.value.format === item.value.format && selectedElement.value.type === item.value.type) { this.model.array.splice(i, 1) this.model.array.push(item) break } if (i === this.model.array.length - 1) { this.model.array.push(item) } } Could you tell me how can I do this lodash filter? I tried something like this: let filter = _.filter(this.model.array, function (o) { return ((o.value.type !== item.value.type) && (o.value.format !== item.value.format)) }) but it does not work, it returns 0 array every time. My idea was to filter these elements (but it's just one) which type and format is the same as items and then push something using this filtered array. Or maybe there is another way how can I add elements if condition is met? Item looks like this: provide data or even better, a runnable example @Vulwsztyn hey, I posted structure of item. looks to me like you need || instead of && - you have (not A) and (not B) == not(A or B) when I think what you really need is not(A and B) which == (not A) or (not B) @Alnitak yes thats it. Thanks so much! in other words, you want to retain those elements where either of the two (negated) conditions fail, not those where both do. You have the wrong boolean operation in your filter. Consider your original condition to find matching entries in a loop: selectedElement.value.format === item.value.format && selectedElement.value.type === item.value.type Let's call the two tests (or "predicates") A and B, such that the expression reduces to: A && B Within your filter call you want to retain the entries that do not match, i.e.: !(A && B) which De Morgan's Laws say is equivalent to: !A || !B However what you've actually written is: !A && !B which is equivalent to: !(A || B)
common-pile/stackexchange_filtered
How to configure PHP basedir for Joomla running on IIS shared hosting I have the following setup: IIS 10 with Plesk Onyx 17.8.11. Joomla 3.8.13/PHP 7.2.10. The website is hosted in shared hosting provider. After installing Gantry 5 I get the following warning on the Joomla Control Panel page: SplFileInfo::isFile(): open_basedir restriction in effect. File(gantry-themes:/\beez3) is not within the allowed path(s): (D:/Inetpub/vhosts/xxx\;C:\Windows\Temp) Looking at the PHP Settings tab of the Joomla System Information page I see the following setting: Open basedir D:/Inetpub/vhosts/xxx\;C:\Windows\Temp\ As far as I can tell, the D:/Inetpub/vhosts/xxx\ is incorrect since the root folder of the website is: D:/Inetpub/vhosts/xxx/yyy In fact, I had to set the Path to Temp Folder to D:/Inetpub/vhosts/xxx/yyy/tmp in the Joomla Global Configuration Server Settings in order to install Gantry using the Joomla Install From Folder method. On the other hand, I cannot find a way to modify the value of Open basedir setting either from Plesk or otherwise. As a result, the Gantry component page reports the same error: Twig_Error_Runtime An exception has been thrown during the rendering of a template ("SplFileInfo::isFile(): open_basedir restriction in effect. File(gantry-themes:/\beez3) is not within the allowed path(s): (D:/Inetpub/vhosts/xxx\;C:\Windows\Temp)"). Please note, that I refer to Gantry as an example; The same problem occurs for every other Joomla extension I tried to install. Is there a way to properly configure Joomla/PHP on my setup?
common-pile/stackexchange_filtered
Nifi convertRecord CSV to JSON truncate number values I have the following CSV file in entry and I convert CSV to JSON using a convertRecord with csvReader and JsonRecordSetWriter key,x,y,latitude,longitude 123,722052.172555174,6555555.17858555,42.0422004518503,2.21755344237117 but my float values are truncated {"key":123,"x":722052.2,"y":6555555.0,"latitude":42.042202,"longitude":2.2175534} How to get them all without truncating them ? It's possible to achieve that with an explicit schema (CSV Reader service): Schema Access Strategy: Use 'Schema Text' Property Schema Text: { "type" : "record", "name" : "MyClass", "fields" : [ { "name" : "key", "type" : "long" }, { "name" : "x", "type" : "double" }, { "name" : "y", "type" : "double" }, { "name" : "latitude", "type" : "double" }, { "name" : "longitude", "type" : "double" } ] } Output JSON with explicit schema: { "key" : 123, "x" :<PHONE_NUMBER>55174, "y" : 6555555.17858555, "latitude" : 42.0422004518503, "longitude" : 2.21755344237117 }
common-pile/stackexchange_filtered
Texture management / pointer question I'm working on a texture management and animation solution for a small side project of mine. Although the project uses Allegro for rendering and input, my question mostly revolves around C and memory management. I wanted to post it here to get thoughts and insight into the approach, as I'm terrible when it comes to pointers. Essentially what I'm trying to do is load all of my texture resources into a central manager (textureManager) - which is essentially an array of structs containing ALLEGRO_BITMAP objects. The textures stored within the textureManager are mostly full sprite sheets. From there, I have an anim(ation) struct, which contains animation-specific information (along with a pointer to the corresponding texture within the textureManager). To give you an idea, here's how I setup and play the players 'walk' animation: createAnimation(&player.animations[0], "media/characters/player/walk.png", player.w, player.h); playAnimation(&player.animations[0], 10); Rendering the animations current frame is just a case of blitting a specific region of the sprite sheet stored in textureManager. For reference, here's the code for anim.h and anim.c. I'm sure what I'm doing here is probably a terrible approach for a number of reasons. I'd like to hear about them! Am I opening myself to any pitfalls? Will this work as I'm hoping? anim.h #ifndef ANIM_H #define ANIM_H #define ANIM_MAX_FRAMES 10 #define MAX_TEXTURES 50 struct texture { bool active; ALLEGRO_BITMAP *bmp; }; struct texture textureManager[MAX_TEXTURES]; typedef struct tAnim { ALLEGRO_BITMAP **sprite; int w, h; int curFrame, numFrames, frameCount; float delay; } anim; void setupTextureManager(void); int addTexture(char *filename); int createAnimation(anim *a, char *filename, int w, int h); void playAnimation(anim *a, float delay); void updateAnimation(anim *a); #endif anim.c void setupTextureManager() { int i = 0; for(i = 0; i < MAX_TEXTURES; i++) { textureManager[i].active = false; } } int addTextureToManager(char *filename) { int i = 0; for(i = 0; i < MAX_TEXTURES; i++) { if(!textureManager[i].active) { textureManager[i].bmp = al_load_bitmap(filename); textureManager[i].active = true; if(!textureManager[i].bmp) { printf("Error loading texture: %s", filename); return -1; } return i; } } return -1; } int createAnimation(anim *a, char *filename, int w, int h) { int textureId = addTextureToManager(filename); if(textureId > -1) { a->sprite = textureManager[textureId].bmp; a->w = w; a->h = h; a->numFrames = al_get_bitmap_width(a->sprite) / w; printf("Animation loaded with %i frames, given resource id: %i\n", a->numFrames, textureId); } else { printf("Texture manager full\n"); return 1; } return 0; } void playAnimation(anim *a, float delay) { a->curFrame = 0; a->frameCount = 0; a->delay = delay; } void updateAnimation(anim *a) { a->frameCount ++; if(a->frameCount >= a->delay) { a->frameCount = 0; a->curFrame ++; if(a->curFrame >= a->numFrames) { a->curFrame = 0; } } } You may want to consider a more flexible Animation structure that contains an array of Frame structures. Each frame structure could contain the frame delay, an x/y hotspot offset, etc. This way different frames of the same animation could be different sizes and delays. But if you don't need those features, then what you're doing is fine. I assume you'll be running the logic at a fixed frame rate (constant # of logical frames per second)? If so, then the delay parameters should work out well. A quick comment regarding your code: textureManager[i].active = true; You probably shouldn't mark it as active until after you've checked if the bitmap loaded. Also note that Allegro 4.9/5.0 is fully backed by OpenGL or D3D textures and, as such, large bitmaps will fail to load on some video cards! This could be a problem if you are generating large sprite sheets. As of the current version, you have to work around it yourself. You could do something like: al_set_new_bitmap_flags(ALLEGRO_MEMORY_BITMAP); ALLEGRO_BITMAP *sprite_sheet = al_load_bitmap("sprites.png"); al_set_new_bitmap_flags(0); if (!sprite_sheet) return -1; // error // loop over sprite sheet, creating new video bitmaps for each frame for (i = 0; i < num_sprites; ++i) { animation.frame[i].bmp = al_create_bitmap( ... ); al_set_target_bitmap(animation.frame[i].bmp); al_draw_bitmap_region( sprite_sheet, ... ); } al_destroy_bitmap(sprite_sheet); al_set_target_bitmap(al_get_backbuffer()); To be clear: this is a video card limitation. So a large sprite sheet may work on your computer but fail to load on another. The above approach loads the sprite sheet into a memory bitmap (essentially guaranteed to succeed) and then creates a new, smaller hardware accelerated video bitmap per frame. Are you sure you need a pointer to pointer for ALLEGRO_BITMAP **sprite; in anim? IIRC Allegro BITMAP-handles are pointers already, so there is no need double-reference them, since you seem to only want to store one Bitmap per animation. You ought to use ALLEGRO_BITMAP *sprite; in anim. I do not see any other problems with your code. The ALLEGRO_BITMAP isn't a pointer, but you are otherwise correct. Since he is using a sprite sheet (one bitmap with multiple pictures), he'll only need a single pointer to a single bitmap.
common-pile/stackexchange_filtered
Neo4j: Trying to find strings that follow a specific word or pattern in different blocks of data but can't figure out the right query to achieve that I'm trying to find the values of a particular attribute contained inside the data of a particular type of node in our database. I think what I need in order to do that is to match for a certain string that always precedes these values, and then extract those values from the block of data. So, I'm trying to do something like this: MATCH (c:course)-[:PARENT_OF*]->(n:item) WHERE n.data CONTAINS "some string" RETURN {the text immediately following "some string"} Sorry for being a little vague... Not sure I can be specific for various reasons. Basically, I want to find – say if the block of data is 'Hello my name is Sally and I really could go for some fries right now' – the name in the block of data, so, Sally. Additionally, if there's still another name in the data, that follows the pattern "my name is ___", I want to find that too. Does that make sense? Is that possible to do in Neo4j? I know there's a way to return the entire contents of/data contained in a node, and I also now know that there is a way to return a portion of the contents in that node, but that's where I get stuck, because I can only get - from the above sparse example, let's say - Neo4j to return only some substring of the string I provided, not anything following it. I've tried ... RETURN substring(n.data,100,500) to find a portion of the data, starting at the 100th character in the data, and stopping at the 500th character. I also have tried ... RETURN right('hello', 3) to find a portion of the substring in quotes ('hello'), and specifically starting after the 3rd character in that substring (so that I'd get a result like 'llo'). I guess I don't know how to query a pattern in Neo4j such that it can give me what follows that pattern. To expand on HΓ₯kan's answer a bit. If you say that there may be more than one name in the same string, e.g. "Hello my name is John and my sisters name is Jane and we both likes fries", and you want to extract all names that follows the key "name is " then this might do the trick WITH "name is " AS key MATCH (n:item) WHERE n.data CONTAINS key WITH key, n.data AS text, apoc.text.indexesOf(n.data, key) AS indexes UNWIND indexes AS index WITH key, text, index+size(key) AS nameindex RETURN substring(text, nameindex, apoc.text.indexOf(text, " ", nameindex)-nameindex) One caveat is that this version doesn't work if there is a name at the end of the text (since it requires a space to follow the names). Need to think a bit more on how to solve that case as well. Edit: Here is a version that solves that special case as well (a name appears at the end of the string, without a subsequent space): WITH "name is " AS key MATCH (n:Person) WHERE n.data CONTAINS key WITH key, n.data AS text, apoc.text.indexesOf(n.data, key) AS indexes UNWIND indexes AS index WITH key, text, index+size(key) AS nameindex, apoc.text.indexOf(text, " ", index+size(key)) AS endindex RETURN CASE endindex WHEN -1 THEN substring(text, nameindex) ELSE substring(text, nameindex, endindex-nameindex) END By the way, this requires that you have the "APOC Core" library installed (it is installed by default on Aura, but if you run your own instance you need to install it. This is simply done by moving the file apoc-5.X.X-core.jar from the labs folder to the plugins folder and then restarting). You can leverage the core APOC function apoc.text.regexGroups to use a regular expression that searches case-insensitively and ignores non-alphanumeric characters surrounding the name. For example: UNWIND [ "Hello my name is Sally and I really could go for some fries right now. Did I mention that my name is Sally?", "My name is Waldo but sometimes I say my name is Charlie, and sometimes I say my name is **Fido**. Arf!" ] AS s UNWIND apoc.text.regexGroups(s, '(?i)my name is \W*(\w+)') AS group RETURN s, apoc.coll.flatten(COLLECT(TAIL(group))) AS names returns: ╒═══════════════════════════════════════╀════════════════════════════╕ β”‚s β”‚names β”‚ β•žβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•ͺ════════════════════════════║ β”‚"Hello my name is Sally and I really coβ”‚["Sally", "Sally"] β”‚ β”‚uld go for some fries right now. Did I β”‚ β”‚ β”‚mention that my name is Sally?" β”‚ β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚"My name is Waldo but sometimes I say mβ”‚["Waldo", "Charlie", "Fido"]β”‚ β”‚y name is Charlie, and sometimes I say β”‚ β”‚ β”‚my name is **Fido**. Arf!" β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ I agree. I've found ChatGPT is pretty good at suggesting the regex if you frame the question well and give an example. If you're not a regex ninja, I'd suggest it. If you expect the text to start with your text fragment you could do like this: UNWIND [ "Hello my name is Sally and I really could go for some fries right now", "Hello my name is Ben and I really could go for a burger right now" ] AS text WITH text, "Hello my name is" as q WHERE text starts with q RETURN trim(right(text, size(text)-size(q))) If instead you only expect the text to contain the text fragment, you need to use apoc.text.indexOf: UNWIND [ "Hello my name is Sally and I really could go for some fries right now", "Hello my name is Ben and I really could go for a burger right now" ] AS text WITH text, "my name is" as q WHERE text contains q RETURN trim(right(text, size(text)-apoc.text.indexOf(text,q)-size(q)))
common-pile/stackexchange_filtered
Force trailing slash before an anchor tag I'm looking for a way to force adding a trailing slash before an anchor tag whenever there is an anchor tag without a trailing slash . Could it be achieved with htaccess? Example : localhost/pp/pages#edit/12 localhost/pp/pages/manage#edit/file/12 ---> localhost/pp/pages/#edit/12 localhost/pp/pages/manage/#edit/file/12 Thanks. It's abit cheaky but use you favorite Javascript lib or go raw todo something like: $(document).ready(function() { // get all internal anchor tags that dont have trailing slash $('a[href^="/"]').not('[href$="/"]').each(function() { $(this).attr('href', function(i, link) { return link +'/'; }); }) }); Sure! but i want it to be done even if i type it in the browser. Both will work? I assume this is just for vanity when navigating around your site
common-pile/stackexchange_filtered
'RelatedManager' object has no attribute 'pk' I have a model that looks like this class Connections(models.Model): following = models.ForeignKey( User, related_name='following' ) followers = models.ForeignKey( User, related_name='followers' ) def __unicode__(self): return u'%s, %s' % (self.following.username, self.followers.username) class Meta: unique_together = (('following', 'followers'), ) And then in TastyPie I am using the following code to extract the following users class ConnectionsResource(ModelResource): user_following = fields.ForeignKey(UserResource, 'following') user_follower = fields.ForeignKey(UserResource, 'followers') class Meta: queryset = Connections.objects.all() resource_name = 'connections' def prepend_urls(self): return[ url(r"^(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('connections'), name="api_connections"), ] def connections(self,request,**kwargs): if request.user and request.user.is_authenticated(): #Scribble Comments if request.GET.get('followers', ''): user = request.user followers = [connections.following for connections in user.followers.all()] followers_count = 1 if followers_count > 0: paginator = Paginator(followers, 20) try: page = paginator.page(int(request.GET.get('page', 1))) except InvalidPage: return self.create_response(request, { 'success': False, 'reason':'no more pages' }) objects = [] for result in page.object_list: bundle = self.build_bundle(obj=result, request=request) bundle = self.full_dehydrate(bundle) objects.append(bundle) followers_list = { 'followers_count': followers_count, 'followers' : objects, 'success': True, } self.log_throttled_access(request) return self.create_response(request, followers_list) else: return self.create_response(request, { 'success': False, 'reason':'No Followers' }) else: return self.create_response(request, { 'success': False, 'reason':'Wrong Query'}) else: return self.create_response(request, { 'success': False, 'reason':'User not Logged in'}) def determine_format(self, request): return 'application/json' But I keep on getting the 'RelatedManager' object has no attribute 'pk' error. I am not sure why Traceback: traceback: "Traceback (most recent call last): File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/resources.py", line 202, in wrapper response = callback(request, *args, **kwargs) File "/Users/jonathan/virtualenvs/myproject/bin/django_worksquid/scribbler/api.py", line 547, in connections bundle = self.full_dehydrate(bundle) File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/resources.py", line 837, in full_dehydrate bundle.data[field_name] = field_object.dehydrate(bundle) File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/fields.py", line 729, in dehydrate return self.dehydrate_related(fk_bundle, self.fk_resource) File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/fields.py", line 557, in dehydrate_related return related_resource.get_resource_uri(bundle) File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/resources.py", line 784, in get_resource_uri return self._build_reverse_url(url_name, kwargs=self.resource_uri_kwargs(bundle_or_obj)) File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/resources.py", line 763, in resource_uri_kwargs kwargs.update(self.detail_uri_kwargs(bundle_or_obj)) File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/resources.py", line 2371, in detail_uri_kwargs kwargs[self._meta.detail_uri_name] = getattr(bundle_or_obj.obj, self._meta.detail_uri_name) AttributeError: 'RelatedManager' object has no attribute 'pk' " Edit When I changed followers_count = 1 to followers_count = followers.count() it gives me "count() takes exactly one argument (0 given)" error Edit I finally realized that followers is a list not an object, so I changed my code a bit to def connections(self,request,**kwargs): if request.user and request.user.is_authenticated(): #Scribble Comments if request.GET.get('followers', ''): user = request.user followers = [connections.following for connections in user.followers.all()] users_id = [s.id for s in followers] users=User.objects.filter(id__in = users_id) users_count = users.count() users_list = { 'users_count': users_count, 'users' : users, 'success': True, } return self.create_response(request, users_list) else: return self.create_response(request, { 'success': False, 'reason':'Wrong Query'}) else: return self.create_response(request, { 'success': False, 'reason':'User not Logged in'}) Now I do get the output, but I get it in terms of objects, like success: true, users: "[<User: abc>, <User: test>, <User: abc2>, <User: test2>]", users_count: 4 Instead of this, I want my object to show the email addresses and all of the user instead of just this object. Can you include a stack trace with the rest of the error message? @Ric please have a look at the edit For the principle I quite agree with Ric, I don’t understand why it doesn’t work with his answer. However with your followers_count problem you should do something like followers_count = sum([query.count() for query in followers]). The solution was easy. It turs out, that I was supposed to use ToManyField for User objects not ForeignKey, and that fixed everything! 'RelatedManager' object has no attribute 'pk' probably means TastyPie was expecting an object but instead you gave it a RelatedManager which is like connections.following I would make sure that result in for result in page.object_list is an object, you may need to iterate through all the connections.following users. for result in page.object_list: print result for following_user in result.all(): print following_user bundle = self.build_bundle(obj=following_user, request=request) bundle = self.full_dehydrate(bundle) objects.append(bundle) Also have you considered just using a ManyToMany field either by also have a Profile model that has a OneToOne relationship with the User or upgrading to Django 1.5 which allows extending the user model? That way instead of implementing your own ManyToMany relationship, you can use all the benefits of Django's built-in one such as just saying user.followers.all() and getting all the users that are following that user. Something like this would work for extracting the information users = [{ 'email': u.email, 'name': u.name, ... } for u in User.objects.filter(id__in = users_id)] Although you should probably try using build_bundle as well users = [self.full_dehydrate(self.build_bundle(obj=u, request=request)) for u in User.objects.filter(id__in = users_id)] I'm not sure what is happening either, sorry. @Jonathan Please take a look at my new answer. that doesnt seem to work either. also, since result is supposed to be a user object, how would result.all() work? as its just one object. also, please look at my edit Also, people who are voting down this answer, it'll be highly appreciated if you answer the question if you know what is going on, instead of voting someone else's efforts down. Can you post the output with the print statements in my answer and the error? Is the exception on the full_dehydrate included in my answer? followers.count() should probably be len(followers) Not sure what the -1 was for, this has fixed my issue. I can help with at one issue: followers = [connections.following for connections in user.followers.all()] You can't call .count() on that, because you're putting the results of your query into a list. Use len(followers) or User.objects.get(following__followers=user). The rest of the code is pretty odd, but I can't see a sure issue with it either. Perhaps the issue is in UserResource? You'll probably want to look at line 837.
common-pile/stackexchange_filtered
Holder of German National Visa (Type D). Can my first point of entry be through Switzerland? We are moving to Germany on a long-stay national visa (Type D). The easiest route would be to land in Basel, Switzerland, where someone would pick us up from there. Are there any restrictions which would require the first country of entry to be Germany and not Switzerland? You can enter the Schengen Area via any Schengen country, so France or Switzerland are fine. During the validity of your D visa you can also at any time spend up to 90 days out of 180 in other Schengen countries. Note that BSL (the Basel-Mulhouse-Freiburg Euro-Airport) is actually in France. There are French and Swiss sides of the airport, but when arriving from a non-EU country you can pick which side you exit to (since both Switzerland and France are now in Schengen this only changes things for customs purposes, but it probably makes more sense to exit on the French side if you are going to Germany). Note also that we have had a few reports that some Turkish Airlines agents in IST incorrectly think that you need to fly directly to the country which issued the visa. This may occasionally occur elsewhere. This is not correct, and you should (politely but firmly) insist that they check on their terminal or call a supervisor if they tell you so. Do make sure to be at the correct sector for whoever picks you up. Ask them what is easiest for them (French or Swiss sector) and then take the exit accordingly.
common-pile/stackexchange_filtered
CloudFormation - Attached VPC Lambda stuck in DELETE_IN_PROGRESS - can't delete ENI I have a Lambda attached to a VPC in a CF stack and when I try to delete the stack the lambda will get stuck in DELETE_IN_PROGRESS for hours. If I try to manually delete the ENI it won't let me, with an error message eni is use by another service. If I run the AWS script to detect what is using the ENI, I get a response that the ENI is not being used by any service. I can confirm that the lambda was deleted by going to the Lambda UI. The only solution is to wait for a couple of hours until the ENI is deleted. This is very bad for us as we create a CF stack for our e2e tests before a new release and we can't wait for hours until is deleted. Any workaround for this problem? The lambda role is only deleted after the Lambda is deleted. I am facing the same problem with yours during my deployment with CloudFormation as well. And the provided helper script was not helpful in my case as well. I believe that there is no way that we can disturb AWS managed ENIs which are created for your Lambda function. Maybe, I think they manage the deletion process over some signals sending to SQS queues or RabbitMQ. Here is how I manage this: Firstly, I manage this by manually removing any VPC configuration from my Lambda functions. Then, I move forward with CloudFormation deletion or replacement. This can solve waiting issues but will need to write some bash script to remove VPC configuration from those functions.
common-pile/stackexchange_filtered
How to clear form behind modal window with javascript? Just like the question says, I'm trying to clear a form from a modal window while the modal stays up. I've tried: if (myDocument.title == "Modal Window") { parent.document.getElementById("textbox") } (I need it to do more than 1 tb, but used that just to try to get there. No luck. It is contained within an iFrame, so I tried: if (myDocument.title == "Modal Window") { var ifr = document.getElementById("iFrame") var form = ifr.document.getElementById("form") ClearForm(form) } The ClearForm(form) function I stole from another Stack Overflow answer: function ClearForm(form) { $(':input', form).each(function () { var type = this.type; var id = this.id; if (type == 'text' && id != 'text2') this.value = ""; }); } That 'text2' is one specific tb that we need to remain populated. Any idea what I'm missing? I've been plagued with this bug for weeks. What error are you getting? See this answer for how to access elements in an iframe (assuming it's loading the document from the same origin). That's the problem - I'm not getting any errors, it's just not working. [Arguably more frustrating than getting a js error.] Well do you know where the code is breaking? (do a search on how to debug JavaScript). If that doesn't work try putting the code in fiddle because I think we need more information. I'm going to do some more research now and try to update in a few minutes. I'm very new to js. I expect your issue is that the form is within an iFrame - most browsers won't allow you to modify elements within an iFrame, from the parent page, if they aren't from the same origin (or if the server is set up to deny it, or if you're looking at the page locally... see here for more details) To double-check, try moving the form markup into the same page as the modal is in and run your function ClearFormfrom there. I expect that you'll then find it works. Your only way around this would be to include the ClearForm function within the iFrame'd page, and then trigger it from the parent. "most browsers won't allow you to modify elements within an iFrame, from the parent page." Can you elaborate? With the exception of the same origin policy, I don't think that's true. Sure. Have a read here. In order to do as is being asked, the ClearForm function would need to reside within the iFrame'd page (rather than the parent). They both use the same js, but have different htm's if that helps at all. @johnkavanagh The same origin policy prevents the script from parent document A from accessing document B loaded from a different origin - not if the script in the parent document doesn't exist in document B. However, that seems to be what you're suggesting, which I don't think is correct. Am I misunderstanding anything here?
common-pile/stackexchange_filtered
Pyomo Blocks: Performance of indexed blocks I am setting up a big time-dependent energy optimization problem over many timesteps with pyomo.The problem is formulated using indexed blocks, as proposed in the Pyomo Book in chapter 8.6.2., where the model object contains a block for each timestep. I notice now that the model creation using indexed blocks takes much longer than the creation of a model with a simple formulation without blocks. I could not find any remarks on the performance of indexed blocks vs. standard formulation in the pyomo book or other posts. Do you agree on these findings that standard formulation is faster then indexed blocks in case of biggish optimization problems with many timesteps? Here is my code example for a PV-Battery system with cost minimzation. The standard formualation follows the indexed Block formulation. import pyomo.environ as pyo from pyomo.common.timing import TicTocTimer import random ##% Generate some random data for PV and Load pv = [random.randint(0, 5) for _ in range(8760)] pv_dict = (dict(enumerate(pv,1))) load_el = [random.randint(0, 8) for _ in range(8760)] load_el_dict = (dict(enumerate(load_el,1))) #%% # Create standard formulation pyomo model timer = TicTocTimer() timer.tic('Start Sandard formulation') ## Define model model = pyo.ConcreteModel() # Define timeperiod set model.T = pyo.RangeSet(len(pv_dict)) # Define model parameters model.pv = pyo.Param(model.T, initialize=pv_dict) model.load_el= pyo.Param(model.T, initialize=load_el_dict) model.grid_cost_buy = pyo.Param(model.T, initialize=0.4) model.battery_eoCH = pyo.Param(initialize=1.0) model.battery_eoDCH = pyo.Param(initialize=0.1) model.battery_capacity = pyo.Param(initialize=5) # Define the variables model.battery_power_CH = pyo.Var(model.T, domain=pyo.NonNegativeReals) # battery charging power model.battery_power_DCH = pyo.Var(model.T, domain=pyo.NonNegativeReals) # battery discharging power model.battery_soc = pyo.Var(model.T, bounds=(model.battery_eoDCH, model.battery_eoCH)) # battery soct with end of ch/DCH levels model.grid_power_import = pyo.Var(model.T, domain=pyo.NonNegativeReals) # grid import power model.grid_power_export = pyo.Var(model.T, domain=pyo.NonNegativeReals) # grid export power ## Define battery constraints # Battery end of CH/ constraints def battery_end_of_CH_rule(m, t): return m.battery_soc[t] <= model.battery_eoCH model.battery_eoCH_c = pyo.Constraint(model.T, rule=battery_end_of_CH_rule) # Battery end of DCH constraints def battery_end_of_DCH_rule(m, t): return m.battery_soc[t] >= model.battery_eoDCH model.battery_eoDCH_c = pyo.Constraint(model.T, rule=battery_end_of_DCH_rule) # Define battery SoC constraint def battery_soc_rule(m, t): if t == m.T.first(): return m.battery_soc[t] == ((m.battery_power_CH[t] - m.battery_power_DCH[t]) / model.battery_capacity) return m.battery_soc[t] == m.battery_soc[t-1] + ((m.battery_power_CH[t] - m.battery_power_DCH[t]) / model.battery_capacity) model.battery_soc_c = pyo.Constraint(model.T, rule=battery_soc_rule) # Define balanced electricity bus rule def balanced_bus_rule(m, t): return (0 == (m.pv[t] - m.load_el[t] + m.battery_power_DCH[t] - m.battery_power_CH[t] + m.grid_power_import[t] - m.grid_power_export[t])) model.bus_c = pyo.Constraint(model.T, rule=balanced_bus_rule) ## Define the cost function def obj_rule(m): return sum(m.grid_power_import[t]*m.grid_cost_buy[t] for t in m.T) model.obj = pyo.Objective(rule=obj_rule, sense=1) timer.toc('Built model') ## Solve the problem solver = pyo.SolverFactory('gurobi') results = solver.solve(model)#, report_timing=True)#, tee=True) timer.toc('Wrote LP file and solved') print('Total operation costs:',pyo.value(model.obj)) #%% # Create time indexed Block formulation timer.tic('Start Indexed Block formulation') # Define model model = pyo.ConcreteModel() # Define timeperiods model.T = pyo.RangeSet(len(pv_dict)) def block_rule(b, t): # Define model parameters b.pv = pyo.Param(initialize=pv_dict[t]) b.load_el = pyo.Param(initialize=load_el_dict[t]) b.grid_cost_buy = pyo.Param(initialize=0.4) b.battery_eoCH = pyo.Param(initialize=1.0) b.battery_eoDCH = pyo.Param(initialize=0.1) b.battery_capacity = pyo.Param(initialize=5) # define the variables b.battery_power_CH = pyo.Var(domain=pyo.NonNegativeReals) # battery charging power b.battery_power_DCH = pyo.Var(domain=pyo.NonNegativeReals) # battery discharging power b.battery_soc = pyo.Var(bounds=(b.battery_eoDCH, b.battery_eoCH)) # battery soct with end of ch/DCH levels b.battery_soc_initial = pyo.Var() # Initial battery soc b.grid_power_import = pyo.Var(domain=pyo.NonNegativeReals) # grid import power b.grid_power_export = pyo.Var(domain=pyo.NonNegativeReals) # grid export power # define the constraints # Balanced electricity bus rule def balanced_bus_rule(_b): return (0 == (_b.pv - _b.load_el + _b.battery_power_DCH - _b.battery_power_CH + _b.grid_power_import - _b.grid_power_export)) b.bus_c = pyo.Constraint(rule=balanced_bus_rule) # Battery end of CH/ constraints def battery_end_of_CH_rule(_b): return (_b.battery_eoCH >= _b.battery_soc) b.battery_eoCH_c = pyo.Constraint(rule=battery_end_of_CH_rule) # Battery end of DCH constraints def battery_end_of_DCH_rule(_b): return (_b.battery_eoDCH <= _b.battery_soc) b.battery_eoDCH_c = pyo.Constraint(rule=battery_end_of_DCH_rule) # Battery SoC constraint def battery_soc_rule(_b): return (_b.battery_soc == _b.battery_soc_initial + ((_b.battery_power_CH - _b.battery_power_DCH) / _b.battery_capacity)) b.battery_soc_c = pyo.Constraint(rule=battery_soc_rule) # Initialize Blocks for each timestep defined in T model.pvbatb = pyo.Block(model.T, rule=block_rule) # link the battery SoC variables between blocks # setting the initial SoC of one block equal to the final SoC of the previous block def battery_soc_linking_rule(m, t): if t == m.T.first(): return m.pvbatb[t].battery_soc_initial == 0 return m.pvbatb[t].battery_soc_initial == m.pvbatb[t-1].battery_soc model.battery_soc_linking = pyo.Constraint(model.T, rule=battery_soc_linking_rule) ## define the cost function def obj_rule(m): return sum(m.pvbatb[t].grid_power_import * m.pvbatb[t].grid_cost_buy for t in m.T) model.obj = pyo.Objective(rule=obj_rule, sense=1) timer.toc('Built model') ## solve the problem solver = pyo.SolverFactory('gurobi') results = solver.solve(model)#, report_timing=True) timer.toc('Wrote LP file and solved') print('Total operation costs:',pyo.value(model.obj)) This is the output, which shows that model creation takes about 4x more time with indexed blocks then standard formulation. This further creases with model complexity. [ 0.00] Start Sandard formulation [+ 0.92] Built model [+ 3.37] Wrote LP file and solved Total operation costs: 5706.199999999935 [ 4.31] Start Indexed Block formulation [+ 12.50] Built model [+ 4.62] Wrote LP file and solved Total operation costs: 5706.199999999934 Thank you so much for your support! Sorry for the not very compact example. Fabian the question needs sufficient code for a minimal reproducible example: https://stackoverflow.com/help/minimal-reproducible-example Using blocks will incur an overhead over a "flat" model: both in memory (more modeling objects, and a larger number of "non slotized" objects), and in processing time (the hierarchy has to be traversed looking for objectives, constraints, and variables). That said, if the overhead is "significant", the development team would be interested / appreciate you sharing the complete model to use as a test case to aid in performance profiling. @jsiirola The total model is still in development, so I can not yet share it with you. But it will be open source so you may use it in the future. The performance difference I noticed so far with my current model was factor 20 for the model building step. Interesting. I'm curious why this construct would be suggested in "the book." It would not occur to me to make blocks in a time-stepped problem that can be simply & elegantly expressed with basic time indexing. Of course if there is any overhead at all with the Vars and other elements (likely a lot), the blocked model is going to be massive compared to flat. In the flat, you have 5 variables. In the blocked, you have ~54,000. There are several cases where blocks can be useful. The most common modeling case is when developing frameworks or a hierarchy of models: e.g., I have a model for a process, then I want to make it a multiperiod process. I can rewrite the model and add time indices to all the Vars/Params/Constraints, or I can reuse the original model verbatim and place copies of it on time-indexed blocks. There is overhead (mostly memory) because while VarData objects are slotized (making them pretty compact), general containers (e.g., ScalarVar and IndexedVar) are not (and consume more memory) @jsiirola I like the encapsulation concept ^^^. That makes good sense. Maybe I should get the book. :/
common-pile/stackexchange_filtered
Re-ordering Columns in Datagridview VB.net I'm trying to swap columns 1&2 with columns 6&7 for display. This is the code I have but it doesn't work? dgvListings.Columns(1).DisplayIndex = 6 dgvListings.Columns(2).DisplayIndex = 7 dgvListings.Columns(6).DisplayIndex = 1 dgvListings.Columns(7).DisplayIndex = 2 You need to set the property dgvListings.AutoGenerateColumns = false; prior to setting the column order.
common-pile/stackexchange_filtered
ASPxGridView and LinqServerModeDataSource: Inserting and updating rows without showing all columns in grid How do I use a LinqServerModeDataSource to insert or edit rows of the underlying data table when I do not show all fields of that table in the ASPxGridView? Similar questions have been asked, but this is not a duplicate. For example, this one asks about a LinqServerModeDataSource and the accepted answer tells how to use an ordinary SqlDataSource. I have an ASPxGridView hooked up to a table via a LinqServerModeDataSource. But I do not show all columns in the grid. For example, there are columns for the date created and some others that the user doesn't need to know about. I am allowing inline editing in the grid, but in the Inserting or Updating event, the new values passed are just a dictionary of the values displayed in the grid. What about the other values? I would expect to be able to set any of the values for the underlying data row programmatically in the event handler, regardless of whether they are displayed and thus edited by the user. How do I get access to them and set the other values in the events of the LinqServerModeDataSource? I am having no luck reading the devexpress documentation. I'm guessing that there must be a Linq class that hooks into the table that I can use in those events, similarly to the Selecting event. But how? Here's what the Selecting event handler looks like... Is there not some similar interface I can use to access the underlying data in the other events? protected void dsRecipients_Selecting(object sender, DevExpress.Data.Linq.LinqServerModeDataSourceSelectEventArgs e) { SmsRecipientsDataContext context = new SmsRecipientsDataContext(); IQueryable<NotificationParty> val = context.NotificationParties; int notificationGroupID = Convert.ToInt32(Context.Session["NotificationGroupID"]); val = val.Where(n => n.NotificationGroupID == notificationGroupID && n.Active); e.KeyExpression = "ID"; e.QueryableSource = val; } As much as I hate answering my own question... I can't figure out how to get this control to do what I want. However, a simple workaround is to handle the insert and update on the grid itself. So, it's working now. I set the EnableUpdate and EnableInsert properties on the LinqServerModeDataSource to false, and simply handle the grid's RowInserting and RowUpdating events, where I go directly to the database. For example, my inserting event handler is this: protected void recipientsGrid_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e) { using (SqlConnection connection = new SqlConnection(App_Logic.Wrappers.DatabaseConnectionString())) { connection.Open(); using (SqlCommand command = new SqlCommand()) { command.Connection = connection; command.Transaction = connection.BeginTransaction(); try { command.CommandText = " INSERT INTO NotificationParty(NotificationGroupID, FirstName, LastName, CellNumber, Active, UserCreated, DateCreated) VALUES " + "(@NotificationGroupID, @FirstName, @LastName, @CellNumber, @Active, @UserCreated, GETDATE())"; command.Parameters.AddWithValue("@NotificationGroupID", Convert.ToInt32(Context.Session["NotificationGroupID"])); command.Parameters.AddWithValue("@FirstName", e.NewValues["FirstName"]); command.Parameters.AddWithValue("@LastName", e.NewValues["LastName"]); command.Parameters.AddWithValue("@CellNumber", e.NewValues["CellNumber"]); command.Parameters.AddWithValue("@Active", 1); command.Parameters.AddWithValue("@UserCreated", Session["UID"]); command.ExecuteNonQuery(); command.Transaction.Commit(); } catch { command.Transaction.Rollback(); } } } recipientsGrid.CancelEdit(); e.Cancel = true; } And my updating event handler is this: protected void recipientsGrid_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e) { using (SqlConnection connection = new SqlConnection(App_Logic.Wrappers.DatabaseConnectionString())) { connection.Open(); using (SqlCommand command = new SqlCommand()) { command.Connection = connection; command.Transaction = connection.BeginTransaction(); try { command.CommandText = " UPDATE NotificationParty SET FirstName = @FirstName, LastName = @LastName, CellNumber = @CellNumber, UserModified = @UserModified, DateModified = GETDATE() WHERE ID = @ID"; command.Parameters.AddWithValue("@ID", e.Keys[0]); command.Parameters.AddWithValue("@FirstName", e.NewValues["FirstName"]); command.Parameters.AddWithValue("@LastName", e.NewValues["LastName"]); command.Parameters.AddWithValue("@CellNumber", e.NewValues["CellNumber"]); command.Parameters.AddWithValue("@UserModified", Session["UID"]); command.ExecuteNonQuery(); command.Transaction.Commit(); } catch { command.Transaction.Rollback(); } } } recipientsGrid.CancelEdit(); e.Cancel = true; }
common-pile/stackexchange_filtered
AutoFixture AutoMoq adding items to an ObservableCollection does not raise CollectionChanged event I'm just starting out using AutoFixture and I'm enjoying the features just now. But I've just created an AutoMoqDataAttribute as Mark Seemann describes here. But now I'm trying to mock an object that contains an ObservableCollection of items and in my Sut I am subscribing to the CollectionChanged event and handling when new items are added. My Sut looks like: public class Foo { public Foo(IBar barWithObservableCollection) { barWithObservableCollection.Items.CollectionChanged += this.OnItemsChanged; } public ObservableCollection<IFooThing> FooThings { get; private set; } private void OnItemsChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs) { // Handle the new object and build a new IFooThing with it. ... this.FooThings.Add(fooThing); } } My IBar interface is simple and basically only contains the ObservableCollection: public interface IBar { ObservableCollection<IBarThings> Items { get; } } So in my original implementation of the test to make sure that new items were handled was with full mocking of the objects using Moq and tying everything together myself (I'll leave this out as it's unnecessary for my question). But as said I've attempted to move this to using AutoFixture and now my tests looks like: [Theory, AutoMoqData] public void TestNewIBarThingsAreCorrectlyHandled([Frozen]IBar bar, [Frozen]IBarThing barThing, Foo sut) { bar.Items.Add(barThing); Assert.Equal(1, sut.FooThings.Count); } So I was expecting that the IBar.Items was auto setting up an ObservableCollection which it is and this was being subscribed to, which it also is. But when I do the call to bar.Items.Add the collection changed handler is not not called, although I can see that the Items count is incremented on the IBar object. Is there something that I'm doing wrong? Have I got the wrong end of the stick and I will have to manually setup the collection as before, I'd rather not have to do this as I'm enjoying the cleaner syntax? EDIT: After the comment below I checked that the IBar object provided to the tests and to the Sut were the same, but it turns out that these are not the same object. I was under the impression that the [Frozen] attribute specified that each time that object was requested the same object reference would be returned? Are bar and the instance passed to the Foo constructor the same object\reference? Ah that looks like what the issue is, the IBar (bar object) in the test does have the item added but the one stored within the Foo object does not after the Add. I believed that the Frozen attribute specified that you would have the same instance of the object on each request to the Fixture? Based on the information given here, I can't get the code to compile. Please provide a Minimal, Complete, and Verifiable example.
common-pile/stackexchange_filtered