text
stringlengths
64
89.7k
meta
dict
Q: Конвертирование строки с числом заданой длины в значение времени Нужно конвертировать строку, в которой 4-х значные числа (например, '0625') в строку времени формата "часы:минуты" (то есть, '06:25' в данном случае). В таблице есть строчные колонки: TIME с 4-х значными числами TIME2 куда нужно занести результат Пробовал через функцию TO_DATE, но при следующий пример выдает неправильный результат: UPDATE ATEST SET TIME2 = TO_DATE("TIME", 'HH24:MI') WHERE ID > 0 A: Попробуйте так: ALTER SESSION SET NLS_TIMESTAMP_FORMAT = 'HH24:MI:SS'; UPDATE ATEST SET time2 = TO_TIMESTAMP(time, 'HH24MI') WHERE id > 0; Результат:
{ "pile_set_name": "StackExchange" }
Q: How to upgrade from Ubuntu 14.04 to Xubuntu 16.04? I'm having Ubuntu 14.04 LTS on my desktop but now I want to upgrade to Xubuntu 16.04. My software updater gave me a 15.10 update but it gave me error of repositories. How to manually update Ubuntu 14.04 to Xubuntu 16.04 without losing any data? A: I don't think you can update from Ubuntu to Xubuntu. But you can simply sudo apt install xubuntu-desktop to get everything that xubuntu would install. About your upgrade: (X)Ubuntu 16.04 isn't released yet. You could force the update on the dev version by running sudo do-release-upgrade -d. But since you had to ask that, I would recommend holding off another couple of weeks until it's stable. (and then maybe another couple of weeks while the early adopter update :-))
{ "pile_set_name": "StackExchange" }
Q: Remove Accents DB2 Does someone knows how to get rid of accents words in DB2 ? I got that one bellow : select UPPER( 'test' || 'DescricaoDomino' || NVL('SiglaDomino', 'X')) from tbProcTeste ; And i got that result : 1 ------------------------------- TESTDESCRICAODOMINOSIGLADOMINO However i could receive a string with accents like this one "!": select UPPER( 'test!' || 'DescricaoDomino' || NVL('SiglaDomino', 'X')) from tbProcTeste ; And id like to get a same result above . Someone knows how do i do that ? Result that i expected 1 TESTDESCRICAODOMINOSIGLADOMINO I dont have huge DB2 background . DB2 Version 11,1 Sincerly A: Based on the mapping in this post https://stackoverflow.com/a/9667817/9525344 the following Db2 function will replace most(?) of the possible Unicode characters with diacritic marks with their simple Latin equivalent (which may, or may not be what is actually used as a replacement in a given language. E..g in German, ü is usually replaced with ue, not u) CREATE OR REPLACE FUNCTION DB_STRIP_DIACRITICS(string VARCHAR(32000)) RETURNS VARCHAR(32000) LANGUAGE SQL CONTAINS SQL DETERMINISTIC NO EXTERNAL ACTION RETURN REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE( REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE( REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE( REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE( REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE( REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE( REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE( REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE( REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE(REGEXP_REPLACE( string, '[ÁĂẮẶẰẲẴǍÂẤẬẦẨẪÄǞȦǠẠȀÀẢȂĀĄÅǺḀȺÃⱯᴀ]', 'A'), '[Ꜳ]', 'AA'), '[ÆǼǢᴁ]', 'AE'), '[Ꜵ]', 'AO'), '[Ꜷ]', 'AU'), '[ꜸꜺ]', 'AV'), '[Ꜽ]', 'AY'), '[ḂḄƁḆɃƂʙᴃ]', 'B'), '[ĆČÇḈĈĊƇȻꜾᴄ]', 'C'), '[ĎḐḒḊḌƊḎDzDžĐƋꝹᴅ]', 'D'), '[DZDŽ]', 'DZ'), '[ÉĔĚȨḜÊẾỆỀỂỄḘËĖẸȄÈẺȆĒḖḔĘɆẼḚƐƎᴇⱻ]', 'E'), '[Ꝫ]', 'ET'), '[ḞƑꝻꜰ]', 'F'), '[ǴĞǦĢĜĠƓḠǤꝽɢʛ]', 'G'), '[ḪȞḨĤⱧḦḢḤĦʜ]', 'H'), '[ÍĬǏÎÏḮİỊȈÌỈȊĪĮƗĨḬɪ]', 'I'), '[IJ]', 'IJ'), '[Ꝭ]', 'IS'), '[ĴɈᴊ]', 'J'), '[ḰǨĶⱩꝂḲƘḴꝀꝄᴋ]', 'K'), '[ĹȽĽĻḼḶḸⱠꝈḺĿⱢLjŁꞀʟᴌ]', 'L'), '[LJ]', 'LJ'), '[ḾṀṂⱮƜᴍ]', 'M'), '[ŃŇŅṊṄṆǸƝṈȠNjÑɴᴎ]', 'N'), '[NJ]', 'NJ'), '[ÓŎǑÔỐỘỒỔỖÖȪȮȰỌŐȌÒỎƠỚỢỜỞỠȎꝊꝌŌṒṐƟǪǬØǾÕṌṎȬƆᴏᴐ]', 'O'), '[Œɶ]', 'OE'), '[Ƣ]', 'OI'), '[Ꝏ]', 'OO'), '[Ȣᴕ]', 'OU'), '[ṔṖꝒƤꝔⱣꝐᴘ]', 'P'), '[ꝘꝖ]', 'Q'), '[ꞂŔŘŖṘṚṜȐȒṞɌⱤʁʀᴙᴚ]', 'R'), '[ꞄŚṤŠṦŞŜȘṠṢṨꜱ]', 'S'), '[ꞆŤŢṰȚȾṪṬƬṮƮŦᴛ]', 'T'), '[Ꜩ]', 'TZ'), '[ÚŬǓÛṶÜǗǙǛǕṲỤŰȔÙỦƯỨỰỪỬỮȖŪṺŲŮŨṸṴᴜ]', 'U'), '[ɅꝞṾƲṼᴠ]', 'V'), '[Ꝡ]', 'VY'), '[ẂŴẄẆẈẀⱲᴡ]', 'W'), '[ẌẊ]', 'X'), '[ÝŶŸẎỴỲƳỶỾȲɎỸʏ]', 'Y'), '[ŹŽẐⱫŻẒȤẔƵᴢ]', 'Z'), '[áăắặằẳẵǎâấậầẩẫäǟȧǡạȁàảȃāąᶏẚåǻḁⱥãɐₐ]', 'a'), '[ꜳ]', 'aa'), '[æǽǣᴂ]', 'ae'), '[ꜵ]', 'ao'), '[ꜷ]', 'au'), '[ꜹꜻ]', 'av'), '[ꜽ]', 'ay'), '[ḃḅɓḇᵬᶀƀƃ]', 'b'), '[ćčçḉĉɕċƈȼↄꜿ]', 'c'), '[ďḑḓȡḋḍɗᶑḏᵭᶁđɖƌꝺ]', 'd'), '[dzdž]', 'dz'), '[éĕěȩḝêếệềểễḙëėẹȅèẻȇēḗḕⱸęᶒɇẽḛɛᶓɘǝₑ]', 'e'), '[ꝫ]', 'et'), '[ḟƒᵮᶂꝼ]', 'f'), '[ff]', 'ff'), '[ffi]', 'ffi'), '[ffl]', 'ffl'), '[fi]', 'fi'), '[fl]', 'fl'), '[ǵğǧģĝġɠḡᶃǥᵹɡᵷ]', 'g'), '[ḫȟḩĥⱨḧḣḥɦẖħɥʮʯ]', 'h'), '[ƕ]', 'hv'), '[ıíĭǐîïḯịȉìỉȋīįᶖɨĩḭᴉᵢ]', 'i'), '[ij]', 'ij'), '[ꝭ]', 'is'), '[ȷɟʄǰĵʝɉⱼ]', 'j'), '[ḱǩķⱪꝃḳƙḵᶄꝁꝅʞ]', 'k'), '[ĺƚɬľļḽȴḷḹⱡꝉḻŀɫᶅɭłꞁ]', 'l'), '[lj]', 'lj'), '[ḿṁṃɱᵯᶆɯɰ]', 'm'), '[ńňņṋȵṅṇǹɲṉƞᵰᶇɳñ]', 'n'), '[nj]', 'nj'), '[ɵóŏǒôốộồổỗöȫȯȱọőȍòỏơớợờởỡȏꝋꝍⱺōṓṑǫǭøǿõṍṏȭɔᶗᴑᴓₒ]', 'o'), '[ᴔœ]', 'oe'), '[ƣ]', 'oi'), '[ꝏ]', 'oo'), '[ȣ]', 'ou'), '[ṕṗꝓƥᵱᶈꝕᵽꝑ]', 'p'), '[ꝙʠɋꝗ]', 'q'), '[ꞃŕřŗṙṛṝȑɾᵳȓṟɼᵲᶉɍɽɿɹɻɺⱹᵣ]', 'r'), '[ꞅſẜẛẝśṥšṧşŝșṡṣṩʂᵴᶊȿ]', 's'), '[st]', 'st'), '[ꞇťţṱțȶẗⱦṫṭƭṯᵵƫʈŧʇ]', 't'), '[ᵺ]', 'th'), '[ꜩ]', 'tz'), '[ᴝúŭǔûṷüǘǚǜǖṳụűȕùủưứựừửữȗūṻųᶙůũṹṵᵤ]', 'u'), '[ᵫ]', 'ue'), '[ꝸ]', 'um'), '[ʌⱴꝟṿʋᶌⱱṽᵥ]', 'v'), '[ꝡ]', 'vy'), '[ʍẃŵẅẇẉẁⱳẘ]', 'w'), '[ẍẋᶍₓ]', 'x'), '[ʎýŷÿẏỵỳƴỷỿȳẙɏỹ]', 'y'), '[źžẑʑⱬżẓȥẕᵶᶎʐƶɀ]', 'z')
{ "pile_set_name": "StackExchange" }
Q: 73-usb-net-by-mac.rules issue with net.ifnames I am seeing strange issue with 73-usb-net-by-mac.rules file. This udev rule file has the check if the net.ifnames is defined in kernel command line then it will go to the end and skip the rules in between as below: IMPORT{cmdline}="net.ifnames", ENV{net.ifnames}=="0", GOTO="usb_net_by_mac_end" Somehow this is not working at my end. I mean I have net.ifnames=0 in my kernel command line and still the usb net naming rule is executed. If I split the above rule line like below then it works fine as it supposed to work: IMPORT{cmdline}="net.ifnames" ENV{net.ifnames}=="0", GOTO="usb_net_by_mac_end" Is it like the udev doesn't parse the keys after IMPORT key on the same line? Could you please let me know if am doing something wrong or the rule needs to be changed? A: This is a problem with the version of 73-net-by-mac.rules in ubuntu (and debian) which has been fixed in tag debian/233-5 of the pkg-systemd source. The binary packages resulting from these changes don't appear to have made it into the debian or ubuntu apt repos yet. For reference, the corrected file is found here: https://anonscm.debian.org/cgit/pkg-systemd/systemd.git/tree/debian/extra/rules/73-usb-net-by-mac.rules?h=debian/233-5 In reply to user.dz: I am actually using Debian 8.7. I do not know which distro the OP was using, but I presume that both ubuntu and debian would have the same problem (since both seem to use packages derived from the same source). The installed name of the file is /lib/udevd/rules.d/73-usb-net-by-mac.rules. It is owned by the udev package.
{ "pile_set_name": "StackExchange" }
Q: How do i make mysql fail to insert a row when some column is not set? I'm running into a problem where it is possible to insert a row into a table whithout specifically setting an INT NOT NULL column (defaults to 0 which is invalid for my purposes) I create the table this way: CREATE TABLE inventorycontrol ( ID INT NOT NULL UNIQUE AUTO_INCREMENT ,nodeID INT NOT NULL CHECK (nodeID > 0) ,custom1 VARCHAR(128) NOT NULL DEFAULT '' ,custom2 VARCHAR(128) NOT NULL DEFAULT '' ,custom3 VARCHAR(128) NOT NULL DEFAULT '' ,custom4 VARCHAR(128) NOT NULL DEFAULT '' ,articlekey VARCHAR(32) NOT NULL ,amount INT NOT NULL ,orderID INT NULL ,supplierID INT NULL ,customerID INT NULL ,datecreated DATETIME NOT NULL ,expectedcompletion DATETIME NOT NULL ,datecompleted DATETIME NULL ,PRIMARY KEY (articlekey, datecreated) ) GO CREATE INDEX ix_InventoryArticle ON inventorycontrol ( articlekey ) GO CREATE INDEX ix_InventoryArticle_Custom ON inventorycontrol ( nodeID, custom1, custom2, custom3, custom4 ) GO CREATE INDEX ix_InventoryAmount ON inventorycontrol ( amount ) GO CREATE INDEX ix_InventoryCreated ON inventorycontrol ( datecreated ) GO CREATE INDEX ix_InventoryCompleted ON inventorycontrol ( datecompleted ) GO ALTER TABLE inventorycontrol ADD FOREIGN KEY fk_nodeID (nodeID) REFERENCES node(ID) GO I would expect this insert to fail: INSERT INTO inventorycontrol ( articlekey, amount, datecreated, expectedcompletion, datecompleted ) VALUES ( 'abc', -10, '2009-01-27', '2009-01-27', NULL ) GO Unfortunately, this just works. (there is no node WHERE ID=0) Is there any way i can force this insert to fail short of creating a trigger for inserts? Thanks in advance, Kris P.S. i am using mysql Ver 14.12 Distrib 5.0.45, for redhat-linux-gnu (x86_64) using readline 5.0 A: You need to put MySQL into strict mode In your configuration file: sql-mode="STRICT_ALL_TABLES" EDIT: You can also set it locally (and put it back) using this query: SET @mode = @@SESSION.sql_mode; SET sql_mode = "STRICT_ALL_TABLES"; INSERT...; SET sql_mode = @mode;
{ "pile_set_name": "StackExchange" }
Q: Trigger a build in teamcity build server from visual svn Is there a way to notify teamcity when ever someone does a commit to a repository on visual svn? This is so every time someone commits to the repository a build in teamcity will trigger immediately without the developer having to wait for polling to kick in on its set time interval. A: You could probably do something using Subversion hooks to achieve that, but is it really worthwhile? You could set your TeamCity server to poll every 10 seconds, which is nothing in terms of a performance hit to the SVN repository and probably nothing much in terms of the wait for developers. (I mean, how long does your build take?)
{ "pile_set_name": "StackExchange" }
Q: Data structure for retrieving strings that are close by Levenshtein distance For example, starting with the set of english words, is there a structure/algorithm that allows one fast retrieval of strings such as "light" and "tight", using the word "right" as the query? I.e., I want to retrieve strings with small Levenshtein distance to the query string. A: The BK-tree data structure might be appropriate here. It's designed to efficiently support queries of the form "what are all words within edit distance k or less from a query word?" Its performance guarantees are reasonably good, and it's not too difficult to implement. Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: ColdFusion loop through struct with key evaluation fails! What am i missing? I have this code in my cfm, which works <cfif not StructIsEmpty(form)> <cfset larray = user.getArray() /> <cfloop collection="#form#" item="key"> <cfif left(key,4) eq "UPD_"> <cfset x = listLast(key,"_") /> <cfset y = evaluate(0,key) /> <cfloop index="j" from="1" to="#arrayLen(larray)#"> <cfif (larray[j][1] eq x) and (larray[j][3] neq y)> <cfset larray[j][3] = y /> <cfif not LSIsNumeric(larray[j][3])> <cfset larray[j][3] = "0" /> </cfif> <cfset larray[j][4] = "update" /> </cfif> </cfloop> </cfif> </cfloop> <cfloop collection="#form#" item="key"> <cfif left(key,4) eq "DEL_"> <cfset x = listLast(key,"_") /> <cfloop index="k" from="1" to="#arrayLen(larray)#"> <cfif larray[k][1] eq x> <cfset larray[k][4] = "delete" /> </cfif> </cfloop> </cfif> </cfloop> <cfset user = createObject("component", "cfc.User").init( identifier = FormatBaseN(form.id,10), array = larray ) /> </cfif> <form name="usform" method="POST"> <cfset array = user.getArray() /> <cfoutput> <cfloop index="i" from="1" to="#arrayLen(array)#"> <table> <tr> <td><input type="text" name="upd_#array[i][1]#" maxlength="6" size="6" value="#array[i][3]#" /></td> <td><input type="checkbox" name="del_#array[i][1]#" /></td> </tr> </table> <input type="hidden" name="id" value="#user.getIdentifier()#" /> </cfoutput> </form> I have put it into a cfc to seperate my logic and my view and i am trying to make it more generic <cfcomponent name="ArrayManager" output="false"> <cffunction name="init" hint="constructor" output="false" returntype="ArrayManager"> <cfargument name="user" type="User" required="true" hint="User bean" /> <cfargument name="form" type="Struct" required="true" /> <cfset variables.instance.array = arguments.user.getArray() /> <cfset variables.instance.form = arguments.form /> <cfreturn this /> </cffunction> <cffunction name="update" access="public" output="true" returntype="boolean"> <cfargument name="structstring" type="String" required="true" /> <cfargument name="seperator" type="String" required="true" /> <cfset var x = "0" /> <cfset var y = "0" /> <cfloop collection="#variables.instance.form#" item="key"> <cfif key eq "#arguments.structstring#"> <cfset x = listLast(key,"#arguments.seperator#") /> <cfset y = evaluate(0,key) /> <cfloop index="j" from="1" to="#arrayLen(variables.instance.array)#"> <cfif (variables.instance.array[j][1] eq x) and (variables.instance.array[j][3] neq y)> <cfset variables.instance.array[j][3] = y /> <cfif not LSIsNumeric(variables.instance.array[j][3])> <cfset variables.instance.array[j][3] = "0" /> </cfif> <cfset variables.instance.array[j][4] = "update" /> </cfif> </cfloop> </cfif> </cfloop> <cfset arguments.user.init(array = variables.instance.array) /> <cfreturn true /> </cffunction> <cffunction name="delete" access="public" output="false" returntype="boolean"> <cfargument name="structstring" type="String" required="true" /> <cfargument name="seperator" type="String" required="true" /> <cfset var x = "0" /> <cfloop collection="#variables.instance.form#" item="key"> <cfif key eq "#arguments.structstring#"> <cfset x = listLast(key,"#arguments.seperator#") /> <cfloop index="k" from="1" to="#arrayLen(variables.instance.array)#"> <cfif variables.instance.array[k][1] eq x> <cfset variables.instance.array[k][4] = "delete" /> </cfif> </cfloop> </cfif> </cfloop> <cfset arguments.user.init(array = variables.instance.array) /> <cfreturn true /> </cffunction> </cfcomponent> And my new cfm <cfif not StructIsEmpty(form)> <cfset arraymanager = createObject("component","cfc.ArrayManager").init(user,form) /> <cfset seperator = "_" /> <cfset structstring = "UPD" /> <cfset arraymanager.update(structstring,seperator) /> </cfif> ... It fails, i get this error message The CFML compiler encountered an unexpected coldfusion.compiler.CompilerInternalException exception. The reason for this was: Unable to complete CFML to Java translation. Occurred at: . . . The error occurred in C:\path\to\document\root\cfc\ArrayManager.cfc: line 21 Called from C:\path\to\document\root\cfc\update-emp.cfm: line 66 Called from C:\C:\path\to\document\root\cfc\update-emp.cfm: line 66 19 : <cfif key eq "#arguments.structstring#"> 20: 21 : <cfset y = evaluate(0,key) /> 22: 23 `: What am i doing wrong or is there a better way to accomplish what i am trying to do (showing database content in a table and updating(Update and Delete) the database content through the same table) A: The error message you've posted indicates that you're misusing the Evaluate function. According to the docs, it works like this: Evaluates one or more string expressions, dynamically, from left to right. (The results of an evaluation on the left can have meaning in an expression to the right.) Returns the result of evaluating the rightmost expression. But you've got other problems, too. For starters, you're not duplicating the logic correctly when you move the code into the CFC. In your working code, you use the conditional: <cfif left(key,4) eq "UPD_"> But in your CFC you have: <cfif key eq arguments.structString> This should be: <cfif left(key,4) eq arguments.structString> Next, you aren't using the best syntax for evaluate, and you probably don't want to use it at all. The statement: y = evaluate(0,key) can be rewritten as: y = evaluate(key) Since the value of key is "UPD_something", this can be rewritten as: y = [variables|arguments|etc].UPD_Something (Since you're not explicitly specifying a variable scope, CF will attempt to find the variable in a set of scopes in a certain order; which is why I used the syntax [a|b|...]) You probably don't mean this, you probably want the value from the form. And since the key name is dynamic, you should access it this way (instead of using evaluate): y = variables.instance.form[key] I think that may fix it. So, to summarize: Replace your statement <cfif key eq arguments.structString> with <cfif left(key,4) eq arguments.structString> (And make sure that the value you pass as "structString" includes the underscore!) Replace your use of evaluate with: y = variables.instance.form[key] I hope that fixes your problems... After you get it working, start thinking about your variable names. "Array" is a terrible variable name because it is practically a reserved word in CFML. And using "x" and "y" is not descriptive at all. These types of problems are what made this question hard to answer. A: I fully agree to Adam Tuttle's post. I've removed the "solution part" part of my answer in favor of his. So here's my two cents regarding the "general part": Avoiding Evaluate() altogether is the best thing you can do. There is no reason to use it apart from actually evaluating pieces of code (which is another bag of hurt that should be avoided). If that's not what you are doing, then there is no situation that could not be resolved through something more appropriate than Evaluate(), e.g.: <cfset foo = Evaluate("FORM.#foo#")> is equal to: <cfset foo = FORM[foo]> All of the "conveniency" misuses of Evaluate() can be addressed like this. A few more tips: Avoid meaningless variable names like "x" or "y" (unless you refer to 2D-coordinates, of course). Don't do "#variable#" - you can simply use variable instead. Use Structs wherever you can when you need to access items with a key, e.g. <cfif array[i][1] eq SomeValue> is a lot less elegant than <cfif array[i]["FieldName"] eq SomeValue> You don't really need "variables.instance" - every component instance has it's own VARIABLES scope. Whatever you stick in there is "instance-only" by default. No need to pass in the FORM scope to a component. The scope is global, so CFCs can see it anyway. Why do you store database stuff in an extra array instead of using the Query object you got when you retrieved them? No need to self-close ("/>") CFML statements - you are not writing XML (though that's a matter of taste).
{ "pile_set_name": "StackExchange" }
Q: How can I publish NUnit test results using Jenkins Pipeline? Trying to use the nifty Jenkins Pipeline, I had problems finding out how to publish NUnit test results. I am able to run the tests by specifying the following command in the pipeline script: stage 'Test' bat '"C:\\Program Files (x86)\\NUnit 2.6.4\\bin\\nunit-console-x86.exe" "ProjectName\\bin\\Release\\UnitTests.net.dll"' But how to make Jenkins "publish" the test results is not obvious. The Snippet Generator only suggests junit, and that does not seem to work. A: I used nunit plugin version 0.21 and was able to publish results using stage("PublishTestReport"){ nunit testResultsPattern: 'TestResult.xml' } (TestResult.xml is at the root of jenkins workspace in this above example) A: Investigating the NUnit plugin for Jenkins led me on to this issue, where I found the solution: step([$class: 'NUnitPublisher', testResultsPattern: 'TestResult.xml', debug: false, keepJUnitReports: true, skipJUnitArchiver:false, failIfNoResults: true]) Adding this to the pipeline script worked for me! However, it seemed the following should also work (but at the present, apparently, it does not): Using the Snippet Generator, select this: step: General Build Step Publish NUnit test result report This generates the following in the Pipeline script: step <object of type hudson.plugins.nunit.NUnitPublisher> This fails!
{ "pile_set_name": "StackExchange" }
Q: ExpressionEngine: How do I block direct access to templates that I am using for embeds only I have a template group that I am using to store embeds like header and footer. I do not want people to be able to directly access those templates by going to www.domain.com/embeds/header. I want that to redirect to the 404 page. How do I go about this? Is there a way to block template groups from direct access? Would this be better done in .htaccess? Thanks for any help. A: In versions of EE2 prior to 2.9 if you start the template name with a dot it will not be directly accessible. In the just-released EE 2.9 you can specify a different character instead of dot and the default has been changed to underscore. Documentation on this feature (currently describes 2.9 handling): http://ellislab.com/expressionengine/user-guide/templates/hidden_templates.html I don't believe EE has a mechanism for blocking direct access on the template-group level. If you needed that then you would probably want to do on the server level (.htaccess rewrites).
{ "pile_set_name": "StackExchange" }
Q: Bootstrap 4: How to align my header with my wrapper I'm trying to align my header with my 1024px wrapper. Here is the Code: https://codepen.io/anon/pen/wLRgyN i try to align the 300x100 to the right and the navigation to the left of each wrapperside to make it look even across the board and trying to keep it responsive. i tried with padding, margin and float but that didnt seem to do the trick <nav class="navbar navbar-expand-lg navbar-light bg-light border-top border-bottom border-dark"> <a class="navbar-brand" href="#"><img class="w-50"src="https://i.imgur.com/YoN2enU.png"></a> <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="container navbar-collapse collapse" id="navbarSupportedContent" style=""> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="#">start <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">über uns</a> </li> <li class="nav-item"> <a class="nav-link" href="#">kontakt</a> </li> </ul> </div> </nav> A: So there are some already defined flex classes on the elements Try adding a Div around your logo area and give it a class of flex-mobile-nav - See css below for this class Add .nav-container-nav wrapping the logo and nav options - CSS updated as well <div class="nav-container-nav"> //// Add this <div class="flex-mobile-nav"> <a class="navbar-brand" href="#"><img class="w-50"src="https://i.imgur.com/YoN2enU.png"></a> <button class="navbar-toggler collapsed" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> </div> <div class="navbar-collapse collapse" id="navbarSupportedContent" style=""> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="#">start <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">über uns</a> </li> <li class="nav-item"> <a class="nav-link" href="#">kontakt</a> </li> </ul> </div> </div> //// end container Also remove .mr-auto class from the .navbar-nav <nav class="navbar navbar-expand-lg navbar-light bg-light border-top border-bottom border-dark"> and remove .container from the (navbar-collapse collapse) <div class="navbar-collapse collapse" id="navbarSupportedContent" style=""> Add to css .navbar { display:flex; justify-content:space-between; } .navbar-collapse { flex-grow:0; } .navbar-expand-lg .navbar-collapse { justify-content: flex-end; } .flex-mobile-nav { display: flex; justify-content: space-between; width: 100%; } .nav-container-nav { max-width: 1024px; margin: 0 auto; width: 100%; display: flex; } .col { background:#000; text-align:center; } Codepen: https://codepen.io/aystarz52/pen/RzEyaE?editors=1000
{ "pile_set_name": "StackExchange" }
Q: Calling $wakanda.init multiple times from different Angular controllers I am developing a mobile application built in Wakanda Digital App Factory 1.0.3 using Ionic and AngularJS with a 4D backend database. I have two different 4D methods available through 4D-Mobile via two separate 4D tables that are accessed via two different Angular controllers: .controller('homeCtrl', function($scope, $wakanda) { $wakanda.init('servers').then(function(ds) { ds.servers.www4DMionicHomeOverview().$promise.then(function(event) { $json = event.result; $scope.overview = $json.servers; $scope.healthCheck = $json.healthCheck; }, function(err) { debugger console.log(err); }); }, function(err) { debugger console.log(err); }); }) .controller('errorLogCtrl', function($scope, $wakanda) { $wakanda.init('server_log').then(function(ds) { ds.server_log.www4DMionicErrorLog().$promise.then(function(event) { $json = event.result; $scope.errors = $json; }, function(e) { debugger console.log(e); }); }, function(e) { debugger console.log(e); }); }) I am noticing a strange issue calling these 4D methods in that the first one will work but the second one will fail, regardless of which one i call first. That is, if i call ds.server_log.www4DMionicErrorLog() first it works but then subsequent calls to ds.servers.www4DMionicHomeOverview() fail until i refresh the browser. The opposite is also true in that if i call ds.servers.www4DMionicHomeOverview() first then it works but subsequent calls to ds.server_log.www4DMionicErrorLog() fail. The error i get for the second method is: ionic.bundle.js:25642 TypeError: Cannot read property 'www4DMionicHomeOverview' of undefined or ionic.bundle.js:25642 TypeError: Cannot read property 'www4DMionicErrorLog' of undefined Depending on which of the two methods I call first. I am curious if this may be related to how i am calling $wakanda.init from each controller. The documentation does not say it is bad to do this. Would it be better to setup an Angular service and resolve $wakanda in the service? A: Replace $wakanda.init('servers').then(function(ds) {... by $wakanda.init().then(function(ds) {... And do the same for all in your controllers. In your case, I recommend you to use $wakanda.init()
{ "pile_set_name": "StackExchange" }
Q: Can a vampire use its slam attack while full-handed? Suppose a vampire is two-weapon fighting. Does it have to drop a weapon to use its slam attack or can it use other body parts - kicking or elbow striking for example - to attack with a slam? I ask this because usually a creature must forgo one natural attack for each weapon clutched in a limb, but slam attacks are a little more nebulous. A: You probably cannot make attacks with two weapons and slam as well with a vampire. The rules are a little unclear what exactly constitutes a slam attack because it is the Natural Attack that is granted to creatures with no appendages. However it also seems to be the Natural Attack granted to creatures with arms but not Claws. This is supported by the Natural Attacks description which includes ...although often a creature must forgo one natural attack for each weapon clutched in that limb, be it a claw, tentacle, or slam). Of course, they had to include that word "often" so you can rule that's not the case. I don't recommend using the Slam when you're also using multiple weapons, both for narrative and balance concerns.
{ "pile_set_name": "StackExchange" }
Q: Tridion 2011: Changing a page's file name as it's being published Good day! I allow my content editors to store CSS as very basic components (usually containing a single, multi-line field called "code" that they paste into), and these are then added as Component Presentations into a Page with a .css file extension. When creating the page, users are able to set a few configuration values: minify output (bool), file name prefix, and file name suffix. The intent of those last two is that if the user has selected to minify the CSS on its way out the door, the file name can be different sitting on the presentation server. I've got everything working except the modification of the file name. I don't want to change the file name in the CM; only as it resides out on the presentation server. I assume this can be done in a TBB placed into the CSS Page Template. I took a crack at it, but want to be sure that there's not something I'm missing. The following example is just the shorthand with some configurable values hard-coded for brevity. // Create a reference to the Page object in the package. Page page = this.GetPage(); // Retrieve a reference to the page's file name. string currentFileName = Utilities.GetFilename(page.FileName); // Set the published file name on its way out the door. page.FileName = currentFileName + "_min"; // ??? // Profit. A: I'm assuming that you're doing static publishing only, i.e. not using the Tridion Content Broker. You should be able to do this with the new TOM.NET-based Tridion Event System and subscribe to the Publishing event at the Initiated phase. This means that just before the page is starting to publish, you will catch the event and modify the page filename. However, this will make the page have the new name in the CME. So again, using another event phase after the publish transaction goes through, the TransactionCommitted phase, you can change the name of the page back. You can also write a custom deployer extension to do this, which will rename the page. However, you will need to also have code to manage the "unpublishing" of the renamed page as well. See Jaime's blog post on how to write a Deployer extension: http://sdltridionworld.com/articles/sdltridion2011/tutorials/Deployer_Extensions_With_Eclipse_1.aspx A: Reading your answers to @Dylan's response, you might consider creating a Binary Variant at publish time which contains the output of your minimized code. In it's simplest form, you would create a text file with the output of your page, and then call .AddBinary() specifying the contents of your file, a file name, a variant name (I suggest the Page URI for this), URI of the current StructureGroup and the URI of a Component to bind this too (probably the Component on the Page). You can see some binary variant examples on Mihai's blog here Binary binary = m_Engine.PublishingContext.RenderedItem.AddBinary( resizedStream, newFilename, variantId, mmc, binaryContent.MultimediaType.MimeType); This will publish a file containing the output of the page in addition to the actual page. When you unpublish the page, you will unpublish the extra file as well.
{ "pile_set_name": "StackExchange" }
Q: What event should I use to submit a form asynchronously in jQuery? I recently started using jQuery/AJAX for submitting data to my PHP API. Currently what I'm using is an input type="button" in the html and then a .click() jQuery function to submit it. I'm not quite sure it's the best way to do it though, should I use a input type="submit" with preventDefault() instead ? A: It's better to use .submit() on the form instead of .click() on the submit button. In both cases preventDefault is necessary though. The reason for that is that the user could submit the form by pressing Enter while editing some field and if you subscribed to the .click event of a button, this event won't fire.
{ "pile_set_name": "StackExchange" }
Q: Google AppEngine Python Cron job urllib I'm in need of setting up a cron job using Google AppEngine which will use urllib2 to execute a web page hosted on another server of mine. I know that the script is executing (checked the logs) but my logging inside my python script never seems to be outputted. #!/usr/bin/env python from google.appengine.ext import webapp from google.appengine.ext.webapp import util import logging import urllib import urllib2 class MainHandler(webapp.RequestHandler): def get(self): logging.info('Starting backups.') def main(): application = webapp.WSGIApplication([('/', MainHandler)], debug=True) util.run_wsgi_app(application) urlStr = "http://example.com/cron.php" request = urllib2.Request(urlStr) try: response = urllib2.urlopen(request) logging.info("Backup complete!") except URLError, e: logging.error('There was an error %s', e.reason) if __name__ == '__main__': main() Can anyone see anything wrong with this? A: main() should end after util.run_wsgi_app(application). The rest of that belongs in your handler class.
{ "pile_set_name": "StackExchange" }
Q: Check if a NuGet Package is compatible with Package Reference style I want to update my solution to use the NuGet Package Reference style[1] (as opposed to using packages.config). There are some compatibility issues[2] that can affect this transition. Is there a way to easily what packages in my solution might suffer from compatibility issues, or do I have to do this manually? [1] https://docs.microsoft.com/en-gb/nuget/consume-packages/migrate-packages-config-to-package-reference [2] https://docs.microsoft.com/en-gb/nuget/consume-packages/migrate-packages-config-to-package-reference#package-compatibility-issues A: Is there a way to easily what packages in my solution might suffer from compatibility issues, or do I have to do this manually? In fact, when you migrate all installed nuget packages from packages.config to PackageReference, there will be no error during the process. The compatibility issue you mentioned is only for the nuget packages that will be installed later in the project, in the new form of PackageReference. So if you just care about these installed nuget package, I think you do not need to worry about this.If you want to install new nuget packages after migration, I think you should note these below: 1) If you want to install a .Net Framework nuget package which you created yourself, you need to be careful about the Package compatibility issues and these are known issues which are provided by Microsoft. They are looking for a solution to this compatibility, so please be patient. For now, you can try the following tips: First, If you want to add some extra files into the new project by nuget, Packages.config format will read the Content folder and copy its files into the new project while PackageReference will copy files from the folder called ContentFiles. So you should add these files in xxxx.nuspec to pack these files into ContentFiles folder. <package > <metadata> ..... <contentFiles> <files include="xxxx\xxxx" buildAction="content" copyToOutput="true" flatten="true" /> </contentFiles> </metadata> <files> <file src="xxxx\xxxx" target="ContentFiles\any\any" /> <file src="xxxx\xxxx" target="Content" /> </files> </package> Second, PackageReferencce does not support install.ps1 or uninstall.ps1. And if you create some nuget packages, please do not use them. Therefore, when you create the nuget packages, you should notice these and avoid these points. 2) If you install some nuget packages from the nuget gallery, you can check the nuget dependencies in the manage nuget package UI.See this: Basically, if these nuget packages support .NetStandard at the same time, which means you can install it by using either PackageReference or Packages.config format with any errors. Hope it could help you.
{ "pile_set_name": "StackExchange" }
Q: ASP.NET Core app to Linux on Azure App Service I'm deploying the Linux based ASP.NET core app using Azure Web App, exactly same thing follow which mention in this blog post. But when i accessing the hosted URL getting error - Service Unavailable Not sure what is causing the issue to run application. Here is log info which i get from kudu services. 2018-01-04 12:20:05.716 ERROR - Container dotnetlinuxapp_1 for site dotnetlinuxapp has exited, failing site start 2018-01-04 12:20:18.304 INFO - Starting container for site 2018-01-04 12:20:18.305 INFO - docker run -d -p 24936:8080 --name dotnetlinuxapp_1 -e WEBSITE_SITE_NAME=DotNetLinuxApp -e WEBSITE_AUTH_ENABLED=False -e WEBSITE_ROLE_INSTANCE_ID=0 -e WEBSITE_INSTANCE_ID=fdcd5b5339be6bb353a84764edb2155ae6bb8d934d2d889b883ef65bcb729a44 -e HTTP_LOGGING_ENABLED=1 appsvc/dotnetcore:1.1.2_1709181723 /home/site/wwwroot/Meetup.Web.dll 2018-01-04 12:20:19.646 ERROR - Container dotnetlinuxapp_1 for site dotnetlinuxapp has exited, failing site start A: I have reviewed your issue and found that you are referring blog have not latest information and cause of that you are facing this issue. Please append "dotnet " in starting of text which you are entering into startup file. "dotnet" it will take as command. so your startup file become like... dotnet /home/site/wwwroot/{yourDLLName}.dll Definitely it will resolve your issue, Cheers ! Hope This Helps !
{ "pile_set_name": "StackExchange" }
Q: I want to delete last integers value swift I want to delete only integer value from any string. Is it possible or not? let string = "kjgd5676idbh123456" i want to result this string = kjgd5676idbh I want to delete only the last integer value. How to remove the last integer value? A: Search backwards for the first non-digit character and drop the trailing digits let string = "kjgd5676idbh123456" let result : String if let range = string.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted, options: .backwards) { result = String(string[..<range.upperBound]) } else { result = Int(string) == nil ? string : "" }
{ "pile_set_name": "StackExchange" }
Q: NSFetchedResultsController and TableViews I'm trying to use Core Data with a NSFetchedResultsController. The data model is devided into "tree levels". Parent -> (Many) Children -> (Many) Grandchildren In a table view I would like to show all the Childs of the parent as sections and the GrandChildrens as cells. I'm having a hard time figuring out how to solve this. Any advice would be appreciated. EDIT Data Model: Parent: name NSString* Id NSNumber* child NSSet* (set of childs) Child: name NSString* childId NSNumber* parent Parent* childrensChilds NSSet* (set of childrensChilds) ChildrensChild: name NSString* ChildrensChildId NSNumber* parentChild *Child FetchRequest: NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Child" inManagedObjectContext:moc]; [fetchRequest setEntity:entity]; NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"ChildId" ascending:NO]; [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parent.parentId = %@", self.parentId]; [fetchRequest setPredicate:predicate]; [fetchRequest setFetchBatchSize:20]; NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:moc sectionNameKeyPath:nil cacheName:@"Childrens"]; self.fetchedResultsController = theFetchedResultsController; fetchedResultsController.delegate = self; [fetchRequest release]; [theFetchedResultsController release]; Then i would like to create section headers with Child names and the cells to be named after childrenschild. A: When using a fetched results controller (FRC) with a tableview, you set the fetch entity to the entity that will populate the rows. After all, sections are optional but rows are always required. The first thing you need to do is to set reciprocal relationships in your data model like so: Parent<-->>Child<-->>GrandChild ... this allows you to transverse the object starting with any entity e.g. if you have a Grandchild object, you use the keypath 'parentChild.parent' (or whatever you call the relationships) to reach the related Parent object by transversing the Child object. To configure the tableview as you wish, you would set the fetch entity to GrandChild, the predicate to something like parentChild.parent.id=%@ and then set the FRC sectionNameKeyPath to parentChild.name. However, you probably want to rethink your entire design. A simpler data model for a tree structure would be: Person{ name:string id:number parent<<-->Person.children children<-->>Person.parent } With grandchild being a child two traverses down and grandparent being a parent two traverses up. Once you had any particular Person object, then displaying in a tableview would be trivial. The section names would be a sorted array of the 'children' relationship and the rows would be sorted arrays of the each child's own children. You would need to fiddle with fetches at all.
{ "pile_set_name": "StackExchange" }
Q: Negation for \ze \zs in Vim In Vim, cat\zsdog will match dog in catdog cat\zedog will match cat in catdog How can I use negation for \zs and \ze For example, How can I match pattern cat not following by dog And How can I match pattern dog not preceding by cat A: Search for cat\(dog\)\@! Get help on this using :help /\@!
{ "pile_set_name": "StackExchange" }
Q: What happens to an email in Google Inbox if I star it in Gmail? I starred an email in Gmail. I now can't seem to find it in Google Inbox. Obviously I can search for it, but I would have thought that it might be easier to find than that. Am I missing something? A: Inbox by Gmail and the Gmail web app present different user experience paradigms, but you can still interact easily between the two. It is obvious that the Gmail team doesn't want you to have problems switching back and forth. From Inbox, find your starred messages by adding in:starred to your search. Here is me searching for a starred message from Joshua. From Gmail, find your pinned messages by adding label:pinned to your search. Here is me searching for a coupon from the On The Border restaurant that I had pinned: A: Inbox by Gmail (IbG) and Gmail itself are two different web applications. They have access to the same mailbox, some features are the same, some are similar and there are several that are unique to each of them. Star is one of the features that have a similar feature in Inbox: Pin a message. You can't find starred messages in IbG, and can't find pinned messages in Gmail. References An inbox that works for you - Gmail Official Blog How Inbox works with Gmail - Inbox by Gmail Help
{ "pile_set_name": "StackExchange" }
Q: Is it possible to transfer ownership from a void* to a unique_ptr? I am currently using the dlopen functions for some plugin project. This function handle returns a void* and then I save all the handle to a map named handles: void* handle = dlopen(path.c_str(), RTLD_LAZY); handles[file] = handle; My goal is to pass the ownership to the map, I was thinking of a unique_ptr, but not sure if this is even possible. If it's not possible what other alternatives do I have ? A: If I understand correctly you can do something like Define a close function and an alias for the pointer type: auto closeFunc = [](void* vp) { dlclose(vp); }; using HandlePtr = std::unique_ptr<void, decltype(closeFunc)>; std::map<std::string, HandlePtr> handles; and then create the handles and add to the map: void* handle = dlopen(path.c_str(), RTLD_LAZY); HandlePtr ptr( handle, closeFunc ); handles[file] = std::move( ptr ); Then closeFunc will be called when the unique ptr goes out of scope The raw pointer can be prevented by combining the two lines above: HandlePtr handle(dlopen(path.c_str(), RTLD_LAZY), closeFunc ); handles[file] = std::move( handle ); This makes use of the second argument to the std::unique_ptr that specifies the deleter to use. PS: maps and unique_ptrs don't play well as-is, you might need some emplaces or moves depending on the C++ standard you are using. Or use shared_ptr instead.
{ "pile_set_name": "StackExchange" }
Q: Autogenerate Columns from data in grid control I set the datasource for a WPF dxg:GridControl to that of a hard coded list. gridControl1.ItemsSource = new List<Entity> { new Entity() { Name = "1" }, new Entity() { Name = "2" }, new Entity() { Name = "3" } }; I have to specify each column in the XAML: <dxg:GridControl.Columns> <dxg:GridColumn FieldName="Name" Name="gridColumn1" /> <dxg:GridColumn FieldName="Column2" Name="gridColumn2" /> </dxg:GridControl.Columns> How can I get the columns to autogenerate instead of specifying XAML? I tried removing the columns. That displayed nothing. The data actually comes from a WCF service at runtime, so the "Populate Columns" button in design mode is probably not going to work either. A: A bit of a stab in the dark, but other grids in WPF usually have something like this... <dxg:GridControl AutoPopulateColumns ="True"> (edit to get actual property name)
{ "pile_set_name": "StackExchange" }
Q: Value set according to another value in the same dictionary, python How would I solve this issue? d = { 'a':3, 'b':(d['a']*3) } print(d) results in an error because I try to set the value of 'b' using the name of the dictionary, and apparently python does not like that. How would I get around this? Also: l = [[2], [(l[0][0]*2)]] print(l) has the same issue. A: Given how assignment works - the RHS expression is eval'd first, and only then is the resulting object bound to the LHS -, that was to be expected : you cannot reference a name that has not been yet created in the current scope. The solutions are either to use an intermediate variable for the value you want to reuse, as explained in lambo's answer, or to first build the dict (or list or whatever) with the first key or index/value pair then build the other, ie: d = {"a", 3} d["b"] = d["a"] * 3
{ "pile_set_name": "StackExchange" }
Q: Calculate number of rows affected by batch query in PostgreSQL First of all, yes I've read documentation for DO statement :) http://www.postgresql.org/docs/9.1/static/sql-do.html So my question: I need to execute some dynamic block of code that contains UPDATE statements and calculate the number of all affected rows. I'm using Ado.Net provider. In Oracle the solution would have 4 steps: add InputOutput parameter "N" to command add BEGIN ... END; to command add :N := :N + sql%rowcount after each statement. It's done! We can read N parameter from command, after execute it. How can I do it with PostgreSQL? I'm using npgsql provider but can migrate to devard if it helps. A: DO statement blocks are good to execute dynamic SQL. They are no good to return values. Use a plpgsql function for that. The key statement you need is: GET DIAGNOSTICS integer_var = ROW_COUNT; Details in the manual. Example code: CREATE OR REPLACE FUNCTION f_upd_some() RETURNS integer AS $func$ DECLARE ct int; i int; BEGIN EXECUTE 'UPDATE tbl1 ...'; -- something dynamic here GET DIAGNOSTICS ct = ROW_COUNT; -- initialize with 1st count UPDATE tbl2 ...; -- nothing dynamic here GET DIAGNOSTICS i = ROW_COUNT; ct := ct + i; -- add up RETURN ct; END $func$ LANGUAGE plpgsql; Call: SELECT * FROM f_upd_some(); A: My solution is quite simple. In Oracle I need to use variables to calculate the sum of updated rows because command.ExecuteNonQuery() returns only the count of rows affected by the last UPDATE in the batch. However, npgsql returns the sum of all rows updated by all UPDATE queries. So I only need to call command.ExecuteNonQuery() and get the result without any variables. Much easier than with Oracle.
{ "pile_set_name": "StackExchange" }
Q: Show some tabs ahead from selected tab in a JavaFx 8 TabPane header I'm trying to modify the TabPage control in JavaFx 8, to make it reveal to the viewport some tabs ahead (to the right) of the current selected one, or if the selected tab is at the extreme left of the header, it shows the nearby tabs before the current one. How it is now: How I'm trying to make it behave like: When the user selects the tab of index X, the tab pane header reveals another 2 or 3 nearby tabs. This is what I tried so far, with no success, apparently the code bellow is too fast to make the interface thread sync the tab selections on time (the idea was to select a tab ahead and then fallback to the one selected by the user, making the header reveal the tabs after the selected tab): import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; public class TabSelectionListener implements ChangeListener<Tab> { protected TabPane owner; protected boolean lock; protected int nextItems; TabSelectionListener(TabPane listenTo){ owner = listenTo; lock = false; nextItems = 2; } TabSelectionListener(TabPane listenTo, int minimalInFront){ owner = listenTo; lock = false; nextItems = minimalInFront; } @Override public void changed(ObservableValue<? extends Tab> list, Tab old, Tab newT) { int maxTab; int curTab; int i; // Locks this listener, because the selections owner.getSelectionModel().select(X) // will call this listener again, and we are calling those from here. if(!lock){ lock = true; maxTab = owner.getTabs().size() - 1; curTab = owner.getSelectionModel().getSelectedIndex(); for(i = 0; i < nextItems && curTab + i < maxTab; i++); owner.getSelectionModel().select(i); // int overload owner.getSelectionModel().select(newT); lock = false; } } } The tabPane calls it for every tab selection: tabPane.getSelectionModel().selectedItemProperty().addListener(new TabSelectionListener(tabPane,3)); I have been reading some topics here, and it appears to me that the header is actually a StackPane, and can be obtained by executing: StackPane region = (StackPane) tabPane.lookup(".headers-region"); It works, but after that I have no idea how to access the properties that implements the default behaviour. Any suggestions? Thanks for reading. A: I finally did it. Found out the class I was looking for was com.sun.javafx.scene.control.skin.TabPaneSkin @ jfxrt.jar, it has a method to make the selected tab visible, it runs everytime a selected tab at a TabPane is not fully visible, I overwrote it. TabPaneSkin is the default Skin of TabPane, it applies some behaviours to the TabPane control. /* * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * Hopefully Oracle will not mind... Pick your TabPane, and make... tabPane.setSkin(new TabPaneNewSkin(tabPane)); ... to overwrite Oracle's default TabPaneSkin with this one I wrote that shows nearby tabs. Original Oracle's code for repositioning tabs when one is selected to make it visible: private void ensureSelectedTabIsVisible() { // work out the visible width of the tab header double tabPaneWidth = snapSize(isHorizontal() ? getSkinnable().getWidth() : getSkinnable().getHeight()); double controlTabWidth = snapSize(controlButtons.getWidth()); double visibleWidth = tabPaneWidth - controlTabWidth - firstTabIndent() - SPACER; // and get where the selected tab is in the header area double offset = 0.0; double selectedTabOffset = 0.0; double selectedTabWidth = 0.0; for (Node node : headersRegion.getChildren()) { TabHeaderSkin tabHeader = (TabHeaderSkin)node; double tabHeaderPrefWidth = snapSize(tabHeader.prefWidth(-1)); if (selectedTab != null && selectedTab.equals(tabHeader.getTab())) { selectedTabOffset = offset; selectedTabWidth = tabHeaderPrefWidth; } offset += tabHeaderPrefWidth; } final double scrollOffset = getScrollOffset(); final double selectedTabStartX = selectedTabOffset; final double selectedTabEndX = selectedTabOffset + selectedTabWidth; final double visibleAreaEndX = visibleWidth; if (selectedTabStartX < -scrollOffset) { setScrollOffset(-selectedTabStartX); } else if (selectedTabEndX > (visibleAreaEndX - scrollOffset)) { setScrollOffset(visibleAreaEndX - selectedTabEndX); } } Code I wrote into my custom TabPane skin: // This function was overwritten private void ensureSelectedTabIsVisible() { // work out the visible width of the tab header double tabPaneWidth = snapSize(isHorizontal() ? getSkinnable().getWidth() : getSkinnable().getHeight()); double controlTabWidth = snapSize(controlButtons.getWidth()); double visibleWidth = tabPaneWidth - controlTabWidth - firstTabIndent() - SPACER; // and get where the selected tab is in the header area double offset = 0.0; double selectedTabOffset = 0.0; double selectedTabWidth = 0.0; // OVERWRITE // Makes the nearby 3 tabs for each side of the selected tab visible. ObservableList<Node> headersRegionChildren = headersRegion.getChildren(); boolean nextTabs = false; int nextTabsCount = 0; int current = 0; int numOfTabsToShowNext = 3; int numOfTabsToShowBefore = 3; double tabHeaderPrefWidth; TabHeaderSkin tabHeader; for (Node node : headersRegionChildren) { tabHeader = (TabHeaderSkin)node; tabHeaderPrefWidth = snapSize(tabHeader.prefWidth(-1)); if (selectedTab != null && selectedTab.equals(tabHeader.getTab())) { selectedTabWidth = tabHeaderPrefWidth; // OVERWRITE: Finds the offset of the first tab in the limit numOfTabsToShowBefore before the selected one to be shown for(int i = current - 1; i >= 0 && numOfTabsToShowBefore > 1; i--, numOfTabsToShowBefore--){ tabHeader = (TabHeaderSkin)headersRegionChildren.get(i); tabHeaderPrefWidth = snapSize(tabHeader.prefWidth(-1)); offset -= tabHeaderPrefWidth; selectedTabWidth += tabHeaderPrefWidth; } selectedTabOffset = offset; // OVERWRITE: Sets the flag to start counting in the next 3 nearby tabs. nextTabs = true; } // OVERWRITE: Sums the width of the next nearby tabs with the // width of the selected tab, so it will scroll enough to show // them too. if(nextTabs && nextTabsCount < numOfTabsToShowNext){ selectedTabWidth += tabHeaderPrefWidth; nextTabsCount++; }else if(nextTabsCount == numOfTabsToShowNext){ break; } offset += tabHeaderPrefWidth; current++; } // END OVERWRITE final double scrollOffset = getScrollOffset(); final double selectedTabStartX = selectedTabOffset; final double selectedTabEndX = selectedTabOffset + selectedTabWidth; final double visibleAreaEndX = visibleWidth; if (selectedTabStartX < -scrollOffset) { setScrollOffset(-selectedTabStartX); } else if (selectedTabEndX > (visibleAreaEndX - scrollOffset)) { setScrollOffset(visibleAreaEndX - selectedTabEndX); } } Code above reveals the 3 nearest tabs at each side from the selected tab (if one of those is out of the screen and exists), for every tab selection. So that was it. com.sun.javafx.scene.control.skin.TabPaneSkin was not supposed to be extended, almost every method is private, so I made a copy of it and changed only the function mentioned above, and renamed it to TabPaneNewSkin, and it is at my package.
{ "pile_set_name": "StackExchange" }
Q: How to speedup delete from table with multiple references I have a table which depends on several other ones. When I delete an entry in this table I should also delete entries in its "masters" (it's 1-1 relation). But here is a problem: when I delete it I get unnecessary table scans, because it checks a reference before deleting. I am sure that it's safe (becuase I get ids from OUTPUT clause): DELETE TOP (@BatchSize) [doc].[Document] OUTPUT DELETED.A, DELETED.B, DELETED.C, DELETED.D INTO @DocumentParts WHERE Id IN (SELECT d.Id FROM @DocumentIds d); SET @r = @@ROWCOUNT; DELETE [doc].[A] WHERE Id IN (SELECT DISTINCT dp.A FROM @DocumentParts dp); DELETE [doc].[B] WHERE Id IN (SELECT DISTINCT dp.B FROM @DocumentParts dp); DELETE [doc].[C] WHERE Id IN (SELECT DISTINCT dp.C FROM @DocumentParts dp); ... several others But here is what plan I get for each delete: If I drop constraints from document table plan changes: But problem is that I cannot drop constraints because inserts perform in parallel in other sessions. I also cannot lock a whole table becuase it's very large, and this lock will also lock a lot of others transactions. The only way I found for now is create an index for every foreign key (which can be used instead of PK scan), but I wanted to avoid this scan at all (indexed or not), becuase I am SURE that documents with such ids doesn't exists becuase I used to delete them. Maybe there is some hint for SQL or some way to disable a reference check for one transaction insead of whole database. A: SQL Server is rather stubborn in preserving the referential integrity, so no, you cannot "hint" to disable the check. The fact that you deleted the referencing rows doesn't matter at all (in a high transactional environment, there was plenty of time for some process to modify the tables between the deletes). Creating the proper indexes is the way to go.
{ "pile_set_name": "StackExchange" }
Q: Create login with PHP, MySQL, and MD5 Issue has been resolved. Thank you to all whom posted and helped me out. The column type was to short (varchar(25)) - I extended it and was able to login. Everyone's comments were appreciated. I am having some issues when I try to log in using a test account I created. I am trying to make my own CMS. Right now I have the register page complete and working on the login page. I have MD5'd the user's password on register. When I go to try and login using this account the hash generated on the login page NEVER matches the hash stored in my SQL database. Here is my PHP code and MySQL query: $username = mysql_real_escape_string($_REQUEST['username']); $password = mysql_real_escape_string($_REQUEST['password']); $query = mysql_query("SELECT username FROM records WHERE username='".$username."'") or die(mysql_error()); $result= mysql_fetch_array( $query ); if($result[0] == $username) { $query = mysql_query("SELECT password FROM records WHERE username='".$username."'") or die(mysql_error()); $result = mysql_fetch_array( $query ); $passHash = md5($password); echo "Hash: ".$passHash."<br/>"; echo "User's hash: ".$result[0]; if($result[0] == $passHash) { echo "XXXXX: WIN"; } else { echo "fail"; } I have an account called "alex" the MD5 that was generated on the register page is "1c13465e24d91aca4d3ddaa1b" the MD5 hash generated on the login page is "1c13465e24d91aca4d3ddaa1bc3e7027" Here is my registration page code: $username = mysql_real_escape_string($_REQUEST['username']); $password = mysql_real_escape_string($_REQUEST['password']); $md5_pass = md5($password); mysql_real_escape_string(mysql_query("INSERT INTO records (username, password, ) VALUES('$username', '$md5_pass' ) ") or die(mysql_error())); What am I doing wrong? I have been searching on here and looked at: md5 hash login with php and mysql but no luck. Any help is greatly appreciated! A: Most likely the column that stores the password hash is too short, e.g. VARCHAR(25). Make it bigger: CHAR(32) or BINARY(16). See also: What data type to use for hashed password field and what length? Best practices for efficiently storing md5 hashes in mysql
{ "pile_set_name": "StackExchange" }
Q: Event for multiple div's with same ID EDIT: I needed to use a class, thanks for pointing that one out to me I have the following div's: <div class="section-link" id="section-tooltip" data-content="Popup with option trigger" rel="popover" data-placement="right"> <div class="section-features" style="display: none;"> Content </div> </div> <div class="section-link" id="section-tooltip" data-content="Popup with option trigger" rel="popover" data-placement="right"> <div class="section-features" style="display: none;"> Content </div> </div> <div class="section-link" id="section-tooltip" data-content="Popup with option trigger" rel="popover" data-placement="right"> <div class="section-features" style="display: none;"> Content </div> </div> As you can see they are all using the same id, I am trying to make a popover in bootstrap with the following JQuery however it is only doing it for one div and I am trying to have it do it for them all without having to set individual id's. $('#section-tooltip').each(function(){ $(this).popover({ trigger: "hover", html : true, content: function() { return $(this).children('div:first').html(); } }); }); A: Convert the ID to a class, then modify your code: <div class="section-link section-tooltip" data-content="Popup with option trigger" rel="popover" data-placement="right"> <div class="section-features" style="display: none;"> Content </div> </div> $('.section-tooltip').each(function(){ $(this).popover({ trigger: "hover", html : true, content: function() { return $(this).children('div:first').html(); } }); }); This is assuming that you have other elements using the same class (.section-link) to which you do not wish this behaviour to apply. Otherwise just use that class instead.
{ "pile_set_name": "StackExchange" }
Q: Unlock file on Windows Server 2003 by remote desktop without rebooting We've several Windows Server 2003 machines running, each with its own purposes. There are scheduled jobs which synchronizes some files over SFTP using WinSCP. Very sometimes a newly copied file is left locked in the "inbox" folder without any reason. The machine's own background task (programmed in Java) can't move it to the "processed" folder anymore after processing it. Manually moving it only yields the well known error message Cannot move [filename]: it is being used by another person or program. I tried Unlocker which works fine locally at WinXP, but doesn't work at those Win2K3 machines by remote desktop (unlock option doesn't show up in rightclick context menu). I tried Process Explorer as well as described in this blog article, but it caused the server to crash and reboot (not sure if that's because it's executed through remote desktop). The only resort is to reboot the machine, but we would of course like to avoid that. Any suggestions? A: What happens if you restart the FileZilla Server service? You could exec net start/stop "FileZilla Server" service from your Java application if it fails to move the file.
{ "pile_set_name": "StackExchange" }
Q: REST with hypermedia frameworks for .NET Looking to start a web API project and wondering which of the (two?) frameworks would allow me to go further in Richardson Maturity Model with the least amount friction. Perhaps a link to a HOWTO? A: You can apply many of the practices mentioned by Richardson in almost all the existing HTTP oriented frameworks like ASP.NET Web API, NancyFX or ServiceStack to name a few. Here is an article I wrote describing how to build hypermedia services with ASP.NET Web API http://msdn.microsoft.com/en-us/magazine/jj883957.aspx
{ "pile_set_name": "StackExchange" }
Q: Birkat hamazon w/ cup of wine Vs. Prohibition on wine during shavua shechal bo For one whose custom is to drink wine (or grape juice) after reciting Birkat Ha-Mazon and to refrain from eating wine during shavua she-chal bo Tisha b'Av: Does the requirement to use a cup trump the prohibition of not consuming wine, or should one continue to bentch al ha-kos? A: By asking about Shavu'a sheChal Bo, I assume you are looking for a Sephardi perspective. Maran writes (Shulchan Aruch OC 551:10): ומותר לשתות יין הבדלה וברכת המזון.‏ It is permitted to drink the wine of Havdalah and Birkat haMazon. The Rama there notes the Ashkenazi practice of refraining from drinking both of those and instead letting a child drink it (see our discussion here). The Kaf haChaim (a Sephardi) notes a later Sephardi practice to be stringent like the Ashkenazim only in regards to Birkat haMazon but not in regards to Havdalah. The Mishna Berurah (sk 71) notes for Ashkenazim that in a case where no child is available, one should rely on those who do not require wine for bentching and bentch without wine (as opposed to Havdalah where he rules you should drink the wine yourself.)
{ "pile_set_name": "StackExchange" }
Q: Fastest way to quickly execute an array of many PHP pages? What is the fastest way to execute many PHP pages. I will not need to see them (i.e. scrape or retain any information from any html that is output), but they need to load. The PHP code within each page needs to be executed. I first started out doing foreach (...){echo <iframe src=.... (very ugly and took very long and very bad idea) Now I'm thinking to set a jquery timer to keep loading ajax requests and go through an array. Is there a better way to go about this? A: Multi-threading is going to let you call URL's as fast as possible as you can have multiple loading at the exact same time. PHP doesn't really have good support for multi-threading but we can have it do multi-processing. This will allow you to kick off a URL request and immediately kick off more without waiting for any of the pages to load. The following code is an example of how to accomplish this using wget. This will be fast but does have the downside of not letting you know about a success or failure. <?php foreach($pages as $page){ exec('/usr/bin/wget '.$page.' > /dev/null 2>&1 &'); } ?> This could be taken a step further to call your own php script instead of wget. In which case your program can log the urls that failed to load. So a complete example could be something like the following: run.php <?php foreach($pages as $page){ exec('loadPage.php '.$page.' > /dev/null 2>&1 &'); } ?> loadPage.php <?php $handle = curl_init($url); curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE); $response = curl_exec($argv[1]); $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); if($httpdCode != '200'){ $fp = fopen('error.log', 'w'); fwrite($fp, 'The URL '.$url.' had an issue. It returned a '.$httpCode.' error.'); fclose($fp); } ?>
{ "pile_set_name": "StackExchange" }
Q: Are enums allowed to have setters in Java? I have an enum and it has a parameter (field) that is a String. Am I allowed to have a setter for this field? public enum Blah { Monday("a"), Tuesday("b"); } private final String letter; Blah(String letter){ this.letter = letter; } Am I allowed to do the following? public String setLetter(String letter){ this.letter = letter; } A: You need to remove the final modifier of the field in order for it to be settable: public enum Blah { Monday("a"), Tuesday("b"); private String letter; private Blah(String letter){ this.letter = letter; } public void setLetter(String letter){ this.letter = letter; } } http://ideone.com/QAZHol Having mutable state in an enum is generally not recommended, however. A: This doesn't work because the field is marked as final. In principle, there is nothing preventing enums from having mutable fields. However, this is rarely if ever a good idea. A: Update: It's possible to have setters in enum types. public class Main { public enum Account { ACCOUNT("NAME"); private String name; private Account(String name){ this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public static void main(String[] args) { System.out.println(Account.ACCOUNT.getName()); // print NAME Account.ACCOUNT.setName("NEW"); System.out.println(Account.ACCOUNT.getName()); // print NEW } }
{ "pile_set_name": "StackExchange" }
Q: could not create merged face I asked a similar question here Part of mesh goes outside but the solution for merging the faces doesn't work on this model. The model is here: Basically, the problem with the turtle is in the picture: The right leg of the turtle gets distached from the main body of the turtle. I tried joining the faces of the turtle like the recommendation in the earlier question I posted the link to, but I get the error message of "could not create merged face". So I need to find what's causing this. Also on another note, the left leg while it doesn't get detached from the mesh, it still gets deformed in not a nice way. Thank you in advance! :) A: Instead of creating new faces I used the merge vertices function of blender, here's the final result: I noticed where the leg of the turtle meets the body of the turtle they are not connected. All the vertices looked like the second vertex down, on both sides. How to fix First of all go to where the right leg and body meet, in edit mode. From their select one vertex attached to the body. Then select the corresponding vertex on the leg like this: Once there press Alt + M and finally press A. Once completed do the same to all the vertices, on both sides of the leg. If you play the animation now the leg will be deformed, to fix this simply re-set the parent of the mesh to the armature. I did this using automatic weights. Happy Blendering!
{ "pile_set_name": "StackExchange" }
Q: Combine pandas DataFrames by single column in axis 0 I would like to combine several pandas DataFrames such as these: (All inputs have a first column P plus a uniquely named second column.) df_b3 = pd.DataFrame({'P': ['l1','l3'], 'b3': ['+','+']}, index=[0,1]) df_ka = pd.DataFrame({'P': ['l1','l2','l3'], 'ka': ['+','+','+']}, index=[0,1,2]) df_kb = pd.DataFrame({'P': ['l2','l3'], 'kb': ['+','+']}, index=[0,1]) The output should be like this: (It should have as many columns as there are inputs, plus one column for P, and there should be only one row for each value in a column P in any input.) P b3 ka kb 0 l1 + + NaN 1 l2 NaN + + 2 l3 + + + A simple pd.concat([df_b3, df_ka, df_kb]) gives me too many rows and NaNs: P b3 ka kb 0 l1 + NaN NaN 0 l1 NaN + NaN 1 l2 NaN + NaN 0 l2 NaN NaN + 1 l3 + NaN NaN 2 l3 NaN + NaN 1 l3 NaN NaN + How can this best be achieved with pandas? A: I think need set_index for each DataFrame for align by P column in concat: dfs = [df_b3, df_ka, df_kb] dfs1 = [x.set_index('P') for x in dfs] #same as #dfs1 = [df_b3.set_index('P'), df_ka.set_index('P'), df_kb.set_index('P')] df = pd.concat(dfs1, axis=1).rename_axis('P').reset_index() print (df) P b3 ka kb 0 l1 + + NaN 1 l2 NaN + + 2 l3 + + +
{ "pile_set_name": "StackExchange" }
Q: Búsqueda por GET ASP.NET MVC5 Tengo una tabla con un listado de trabajadores y necesito que al darle clic en Ver familiares aparezcan solo los familiares de ese trabajador estoy llevando en la URL el cod_colaborador: Ejemplo: http://localhost:50210/familiares/Index/1212 El cod_colaborador es 1212, lo estoy llevando mediante URL, necesito que en el Index de los familiares me filtre automáticamente por el cod_colaborador que envío por URL. Mi Controller es este: private sioldmutualEntities db = new sioldmutualEntities(); // GET: familiares public ActionResult Index() { return View(db.tb_familiares.ToList()); } Mi View es esta: @model IEnumerable<WebApplicationSIOldMutual.SI.tb_familiares> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.nombres) </th> <th> @Html.DisplayNameFor(model => model.documento_identidad) </th> <th> @Html.DisplayNameFor(model => model.fecha_nacimiento) </th> <th> @Html.DisplayNameFor(model => model.sexo) </th> <th> @Html.DisplayNameFor(model => model.parentesco) </th> <th> @Html.DisplayNameFor(model => model.celular) </th> <th> @Html.DisplayNameFor(model => model.telefono) </th> <th> @Html.DisplayNameFor(model => model.cod_colaborador) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.nombres) </td> <td> @Html.DisplayFor(modelItem => item.documento_identidad) </td> <td> @Html.DisplayFor(modelItem => item.fecha_nacimiento) </td> <td> @Html.DisplayFor(modelItem => item.sexo) </td> <td> @Html.DisplayFor(modelItem => item.parentesco) </td> <td> @Html.DisplayFor(modelItem => item.celular) </td> <td> @Html.DisplayFor(modelItem => item.telefono) </td> <td> @Html.DisplayFor(modelItem => item.cod_colaborador) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.id_familiar }) | @Html.ActionLink("Details", "Details", new { id=item.id_familiar }) | @Html.ActionLink("Delete", "Delete", new { id=item.id_familiar }) </td> </tr> } </table> A: Si deseas listar los familiares que corresponden a un colaborador, tienes que envíar y recibir el Id del colaborador a listar y luego, filtrar condicionando a ese Id: public ActionResult Index(int Id) { return View(db.tb_familiares.Where(t => t.cod_colaborador == Id).ToList()); } Con esto, en el Index solo estarías mostrando la información de los familiares que corresponde a cada colaborador.
{ "pile_set_name": "StackExchange" }
Q: SQLite UWP Error with Mobile EMulator Windows 10 I am getting the following error when I run the Mobile Emulator while trying to compile and run a VS 2015 UWP app. The app runs fine when using the Local Machine or Simulator. System.TypeInitializationException was unhandled by user code HResult=-2146233036 Message=The type initializer for 'SQLitePCL.raw' threw an exception. Source=SQLitePCL.raw TypeName=SQLitePCL.raw StackTrace: at SQLitePCL.raw.sqlite3_open_v2(String filename, sqlite3& db, Int32 flags, String vfs) at SQLite.SQLiteConnection..ctor(String databasePath, SQLiteOpenFlags openFlags, Boolean storeDateTimeAsTicks) at SQLite.SQLiteConnection..ctor(String databasePath, Boolean storeDateTimeAsTicks) at App3.MainPage.LoadSQLData() at App3.MainPage..ctor() at App3.App3_XamlTypeInfo.XamlTypeInfoProvider.Activate_0_MainPage() at App3.App3_XamlTypeInfo.XamlUserType.ActivateInstance() InnerException: HResult=-2146233052 Message=Unable to load DLL 'sqlite3': The specified module could not be found. (Exception from HRESULT: 0x8007007E) Source=SQLitePCL.raw TypeName="" StackTrace: at SQLitePCL.SQLite3Provider.NativeMethods.sqlite3_win32_set_directory(UInt32 directoryType, String directoryPath) at SQLitePCL.SQLite3Provider..ctor() at SQLitePCL.raw..cctor() I have the following references: SQLite for Universal Windows 3.9.1 sqlite-net-pcl Microsoft Visual C++ 2013 Runtime Package for Universal Windows The code where the error occurs in the "using (var db......: int recCtr = 0; var root = Windows.Storage.ApplicationData.Current.LocalFolder.Path; var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "BaseBallOU.db"); List<string> NHLCollection = new List<string>(); using (var db = new SQLite.SQLiteConnection(dbPath)) { var NHLlist = db.Table<Teams>().ToList(); foreach (var item in NHLlist) { recCtr++; NHLCollection.Add(item.TeamName.ToString()); } } I see a number of similar posts, but some are dated and not using the most recent SQLite libs and pcls. I'm looking for the correct SQLite dlls, sqlite pcls, runtimes (e.g. VC++ 2013? And version numbers that can be used to compile and run a UWP app on both the local machine and phone emulator. TIA A: Following is how I work with SQLite: Download and install Sqlite visual studio extension from http://sqlite.org/download.html Create a new blank c# Universal Windows Platform app. Right click on the References of project -> Add Reference -> Universal Windows -> Extension -> add SQLite for Universal App Platform and its dependency Visual C++ 2015 Runtime for Universal Windows Right click on the project node -> Manage NuGet packages -> Search SQLite.Net-PCL -> Install the default version 3.0.5 Change your code to the following: using (var db = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), dbPath)) { ... }
{ "pile_set_name": "StackExchange" }
Q: Random Number Between 2 Values Hi i wanna generate a random number between 2 values. I have 2 variables. This is the default value: (MIN = MAX = 1) Later this value can change! I have use this: rand()%(max-min)+min; But i got debug about division for zero. Any ideas? Edit: With the default value the number generated must be 1. A: In your initial case (max-min) is 0 and modulus by zero is undefined behavior. From the C++ draft standard section 5.6 Multiplicative operators says: The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined. [...] As for generating a random number between min and max you should use the random header and uniform_int_distrubution: #include <iostream> #include <random> int main() { std::random_device rd; std::mt19937 e2(rd()); int min = 1, max = 1 ; std::uniform_int_distribution<int> dist(min,max); for (int n = 0; n < 10; ++n) { std::cout << dist(e2) << ", " ; } std::cout << std::endl ; } If for some reason C++11 is not an option then the C FAQ gives us the proper formula when using rand in the section How can I get random integers in a certain range? which indicates to generate random numbers in the range [M, N] you use the following: M + rand() / (RAND_MAX / (N - M + 1) + 1)
{ "pile_set_name": "StackExchange" }
Q: SecurityUser in Async Spring Listeners I am facing a problem and hope that someone can give me some advice. I have a restful Spring application which allows HTTP-requests. I am using spring security and offer oauth2. In my basic service, called by a controller, I am fetching the currently logged user via: SecurityUser loggedUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); So far, that's all working fine. Furthermore, I am using events and event listeners implementing the org.springframework.context.ApplicationListener interface. I configured the application event multicaster the way that events are handled asynchronously (using a SimpleAsyncTaskExecutor). The (obvious) problem arises when I try to use my service (and methods which rely on the currently logged user) in my listeners. They cannot access the context as they are working asynchronous. Hence, I cannot fetch the current user. Can you give any advice how to solve the problem? Are there more options than to save and extend the context somehow so that the async listeners can still access it? if so, how to do it? change all the services methods to hand over the user via a parameter (instead of the service fetching the current user itself) and store its id e.g. in the event. Thank you very much. Myself A: You can use a DelegatingSecurityContextAsyncTaskExecutor instead of a SimpleAsyncTaskExecutor. The problem is that you only can get the user's context when the user is logged.
{ "pile_set_name": "StackExchange" }
Q: CancellationToken vs CancellationChangeToken What are the differences between CancellationToken and CancellationChangeToken? When do I use which one? It seems that they can be used for the same purpose. What am I missing? A: Short answer: CancellationChangeToken is a thin wrapper around CancellationToken, which exposes the token's cancellation state through the HasChanged property. Since CancellationChangeToken implements the IChangeToken interface, it can be passed to any object that reacts to token changes, for example an IMemoryCache: Each cache entry can be set to expire under a specific set of conditions, which are abstracted by IChangeToken instances. These conditions may be, for example, configuration changes, or explicit invalidation requests by the user. The CancellationChangeToken wrapper can be passed to one or more cache entries, in order to evict them upon cancellation. The devs could also have decided to directly take a CancellationToken; this would however have complicated the internal logic and the external API, compared to the abstraction through IChangeToken, which is very clean, extensible and working just as well. Long answer: Interface IChangeToken IChangeToken defines a means to track some kind of token, check whether it has changed (HasChanged), and possibly automatically trigger some callbacks once it has changed. There are various implementations for IChangeToken; for example, they track files or configuration options. What CancellationChangeToken does A look at the source code quickly shows that the CancellationChangeToken is a thin IChangeToken wrapper around CancellationToken: public bool HasChanged => Token.IsCancellationRequested; So its "changed" state directly corresponds to the underlying token's cancellation state. On first sight, this seems quite odd: A CancellationToken already offers support for registering automatic callbacks, so why introduce a wrapper that exposes much less functionality? Well, there is actually at least one use case where an abstracted way of observing token states is needed: Caching ASP.NET Core offers different means of caching; I will use IMemoryCache as an example here, which offers a simple built-in memory-based key/value cache, and is usable with minimal effort. To reduce performance impact for each request, it makes sense to cache frequently needed, expensive computations. However, one needs a way to keep track of active cache entries in order to evict them as soon as they become outdated. The problem is, that the cache entries can have very different conditions for becoming outdated, e.g. they depend on configuration values or local files (and need to be updated as soon as these configuration values or local files change), or have a regular time out. The IChangeToken interface offers a simple way to abstract these eviction conditions away, such that the cache only has to check the state of the given IChangeToken object, instead of directly watching files, timers, and so on. The cache might even register a callback, such that a change of the token state directly triggers the eviction logic, so no polling is needed. Back to our CancellationChangeToken A CancellationToken allows to set a delay until it is automatically cancelled, so after wrapping it with a CancellationChangeToken, we can pass it to a cache entry for automated eviction: public IActionResult Index() { if(!_memoryCache.TryGetValue("entry1", out DateTime cachedValue)) { cachedValue = DateTime.Now; var cacheOptions = new MemoryCacheEntryOptions() .AddExpirationToken(new CancellationChangeToken(new CancellationTokenSource(5000).Token)); _memoryCache.Set("entry1", cachedValue, cacheOptions); } return View("Index", cachedValue); } In this example, we cache the current timestamp. After 5 seconds, the cancellation token is cancelled, and the timestamp gets evicted. However, this is does not yet justify the use of a CancellationToken, since the IMemoryCache already offers a way to set an expiration time through MemoryCacheEntryOptions. Now we get to the real strengths of the token-based eviction: We can combine multiple IChangeToken instances into one CompositeChangeToken, and thus evict a cache entry once any of these instances change. use the same token for multiple cache entries, thus evicting them all at once. The latter case is particularly interesting for us: Some cache entries might depend on each other, so when one becomes invalid, we might want to evict all of them. This can be achieved by assigning a shared CancellationToken to their values, and a corresponding CancellationChangeToken to the entries themselves. Once one of the cached values notices that it has become outdated (e.g. by being polled by some other part of the application), it cancels the token. The cancellation propagates to all cache entries that track the corresponding change token, and thus invalidates them all at once.
{ "pile_set_name": "StackExchange" }
Q: Let $f:[0,1] \rightarrow\mathbb R$ be a continuous map such that $f(0)=f(1)$ Let $f:[0,1] \rightarrow \mathbb R$ be a continuous map such that $f(0)=f(1) .$ Let $n \geq 2$ Show that there is some $x \in[0,1]$ such that $f(x)=f\left(x+\frac{1}{n}\right) .$ My attempt. Assume $f(x)\neq f(x+1/n)$ for all $x$. Then either $f(x)<f(x+1/n)$ or $f(x)>f(x+1/n)$. WLOG, assume $f(x)<f(x+1/n)$. Then $f(0) So how can I get a contradiction? May you help? A: WLOG you assumed that $f(x) < f\left(x+\frac1n\right)$ for all $x \in [0,1]$. Therefore we get $$f(0) < f\left(\frac1n\right) < f\left(\frac2n\right) < \cdots < f\left(\frac{n-1}n\right) < f\left(\frac{n}n\right) = f(1)$$ which is a contradiction. A: Let $g(x)=f(x)-f(x+\frac 1 n)$. If this continuous functions is never $0$ then it is always positive or always negative. Suppose it is always positive. Write $0=f(1)-f(0)$ as $[f(\frac 1 n) -f(0)]+[f(\frac 2 n)-f(\frac 1 n)]+...+[f(\frac {n-1} n)-f(1)]$. You get a contradiction since each term is $<0$. Similar argument works when $g(x) <0$ for all $x$.
{ "pile_set_name": "StackExchange" }
Q: In-page responsive CSS? I'm trying to figure out if there's a way using only HTML and CSS to build elements within a page that are responsive to the other elements, rather than to the browser size as is with @media and traditional responsive design. For example, I have an element that is 900px wide. It can sometimes contain 1, 2 or 3 child elements. I want the child elements to style and display additional elements depending on how many sibling elements there are. Eg <div id="parent"> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div> vs <div id="parent"> <div class="child"></div> <div class="child"></div> </div> The child elements would appear differently - different widths, different padding, borders... and they would also have child elements which would be hidden in the first sample, but display in the second. I know this can be done with JS, PHP... but I'm trying to see if there's a way to do it without it. Since I also want to hide/show specific elements depending on the existence of other child elements, using relative sizes (eg %) doesn't cut it. Thanks A: It's possible with CSS3, it took me a couple of minutes to figure it out. Check out http://jsfiddle.net/Vdz7s/. HTML: <h1>One:</h1> <div class="parent"> <div class="child">1</div> </div> <h1>Two:</h1> <div class="parent"> <div class="child">1</div> <div class="child">2</div> </div> <h1>Three:</h1> <div class="parent"> <div class="child">1</div> <div class="child">2</div> <div class="child">3</div> </div>​ CSS: .parent .child:nth-last-child(1) { border:1px solid yellow; } .parent .child:nth-last-child(2), .parent .child:nth-last-child(2) ~ .child { border:1px solid orange; } .parent .child:nth-last-child(3), .parent .child:nth-last-child(3) ~ .child { border:1px solid red; } ​ I think that the code is pretty self-explanatory, then you just need to target the children childs and do whatever you want with them.
{ "pile_set_name": "StackExchange" }
Q: Are continued fractions ever of use in physics? Do you know of any instance when a continued fraction is of help or necessary do describe a natural phenomenon? A: Here's a connection that I suspect minimizes the number of intermediate steps between the physics and the continued fractions: If you want to study angular momentum, then you want to study the representation theory of $SU(2)$. This will force you to study Clebsch-Gordan coefficients, Wigner symbols, Racah symbols, etc. Locating the zeros of such symbols often requires solving one or more Pell equations (i.e. Diophantine equations of the form $X^2-nY^2=1$). The solutions to $X^2-nY^2=1$ form a free abelian group of rank 1, so to find all solutions, it suffices to find a generator of that group. That solution can be found as a convergent of the continued fraction for $\sqrt{n}$.
{ "pile_set_name": "StackExchange" }
Q: Issues updating Xamarin: unable to resolve dependencies I recently decided to update everything in my Xamarin workspace, including all NuGet packages, and Xamarin.Forms. I first installed all the newest Xamarin.Android.Support packages, which clashed with the current version of Xamarin.Forms that I had, so I decided that I needed to update Xamarin.Forms anyway. I removed it and installed all the other packages (which worked lovely) and now I am trying to reinstall Xamarin.Forms again, but I am receiving: Unable to resolve dependencies. 'Xamarin.Android.Support.Design 23.4.0.1' is not compatible with 'Xamarin.Forms 2.3.0.107 constraint: Xamarin.Android.Support.Design (= 23.3.0)'. Any suggestions? A: I'm quoting James Montemagno from the Xamarin Forums here. Xamarin.Forms locks in a very specific version of the support libraries and google play services. You can't update them because Xamarin.Forms isn't compatible with them as it would need to be re-compiled. Xamarin.Android.Support.v4 (= 23.0.1.3) Xamarin.Android.Support.Design (= 23.0.1.3) Xamarin.Android.Support.v7.AppCompat (= 23.0.1.3) Xamarin.Android.Support.v7.CardView (= 23.0.1.3) Xamarin.Android.Support.v7.MediaRouter (= 23.0.1.3) See the = 23.0.1.3, which means it is only compatible with that version number. This is just how NuGet works. When Xamarin.Forms updates these packages will auto update. Forms gets 'linked' to a specific version of the Android libraries so it can be guaranteed that it will work together as it should. At this point, Xamarin.Forms (stable) isn't updated yet to use the latest Android Support packages. So you probably want to go with a somewhat older version of Forms, or check if there is a Forms pre-release which already has a reference to the newer Android Support libraries. Of course; using these is not recommended in a production environment. They added it in the official FAQ A: You can't update Xamarin.Forms and Xamarin.Android at the same time. As It has dependency issues with versions. So first, Select only Xamarin.Forms 2.3.0.107 and update. After that, Select rest of the Xamarin.Android.support lists and update.
{ "pile_set_name": "StackExchange" }
Q: foreach and GetEnumerator / asp.net mvc 2 Hi I've got problem with foreach statement. I have my controller method: public ActionResult ShowComments(int id) { EntryBox entrybox = new EntryBox(); entrybox.entry = (from e in BlogDB.Enteries where e.id == id select e) as Entry; entrybox.comments = (from c in BlogDB.Comments where c.EntryID == id select c) as List<Comment>; Captcha captcha = new Captcha(); ViewData.Model = entrybox; return View(); } my viewModel: public class EntryBox { public Entry entry; public List<Comment> comments; } and when I want to display list of my comments I'm not able to because of this error: Error 2 foreach statement cannot operate on variables of type 'void' because 'void' does not contain a public definition for 'GetEnumerator' c:...\Views\Home\ShowComments.aspx My 3 first line of View: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<BlogMaker_v06.viewModels.EntryBox>" %> <%@ Import Namespace="BlogMaker_v06.Models" %> <asp:Content ID="Content1" ContentPlaceHolderID="ContentHolder" runat="server"> <% User LoggedAs = HttpContext.Current.Session["LoggedAs"] as User; %> <div style="width: 90%"> <b>Treść komentowanego wpisu: <br /><br /></b> <p style="text-indent: 10px; text-align: justify;"> <%= Model.entry.EntryContent.TagsParse() %> </p> <% Html.BeginForm("AddComment/" + ViewData["id"].ToString(), "Home"); { %> Write your comment: <br /> <table> <tr><td>Name:</td><td><input type="text" name="Author" id="Author" value="<%= LoggedAs.Login %>" onfocus="javascript:this.value='';" <% if (LoggedAs.id != 2) {%> disabled <%}%>/></td></tr> <tr><td>Website:</td><td><input type="text" name="AuthorWebsite" id="AuthorWebsite" value="http://" /></td></tr> <tr><td>Przepisz cyframi: <%= ViewData["captcha"] %></td><td><input type="text" name="Captcha" id="Captcha" /></td></tr> </table> <textarea name="CommentContent" id="CommentContent" rows="5" cols="25" style="width: 100%; height: 10%; border: 1px solid #C0C0C0"></textarea><br /> <input type="submit" value="Add comment" /> <% } %> <br /><br /> <b>Komentarze użytkowników:</b> <% foreach (var comment in ViewData.Model.comments.Reverse()) { Html.RenderPartial("~/Views/Home/CommentTemplate.ascx", comment); } %> </div> I know it isnt good way to displaying data but I'm about refactory my whole project. foreach displaying commentTemplate.ascx causes problem. Captcha is my simple way to authorize human being. and I'm sure it works well. A: Edit after seeing your foreach loop. Reverse() returns a void - it alters the list by reversing it, and does not return the list. You are trying to "foreach" over the return value of Reverse(), which is void - hence the error. You can either remove your call to Reverse() (and populate it in reverse order), or add something like this to the controller: entrybox.comments.Reverse(); Or put it in your view if you must: <% ViewData.Model.comments.Reverse(); foreach (var comment in ViewData.Model.comments) { Html.RenderPartial("~/Views/Home/CommentTemplate.ascx", comment); } %>
{ "pile_set_name": "StackExchange" }
Q: How can I export my Putty configuration? How can I export all my settings in Putty (e.g. Saved Sessions Configurations) from one machine and import them on another computer? Both machines are running Windows. A: Simply export the registry key at HKEY_CURRENT_USER\Software\SimonTatham as a .reg file, and double-click it on another machine to merge it.
{ "pile_set_name": "StackExchange" }
Q: Exception is raised in J2ME when calling a webservice which calls a PHP function selecting accentuated letters from a MySQL table column I want to call a webservice from a J2ME application : public String alimenterBaseDeDonneesEtapeProsp( String login, String password,String adresse,String site) { Object resultatRequeteSOAP = null; SoapObject objetSOAPEtapeProsp; HttpTransport connexionServeur; SoapSerializationEnvelope envelope; String nomService = "urn:Client"; String urlService = adresse+"/"+site+"/webservice/InterfaceTransfererClient.php"; String methodeChoisie = "getEtapeProsp"; try { connexionServeur = new HttpTransport(urlService ); connexionServeur.debug = true; objetSOAPEtapeProsp = new SoapObject(nomService, methodeChoisie ); objetSOAPEtapeProsp.addProperty("user", login); objetSOAPEtapeProsp.addProperty("motpasse",password); System.out.println(objetSOAPEtapeProsp); envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11); envelope.bodyOut = objetSOAPEtapeProsp; connexionServeur.call(null,envelope); resultatRequeteSOAP = envelope.getResponse(); return String.valueOf(resultatRequeteSOAP); } catch (Exception aE) { return aE.getMessage(); } } The ksoap2-j2me-core-2.1.2.jar file is already added to the J2ME project. The wsdl file is : <?xml version="1.0" encoding="utf-8"?> <definitions name="Client" targetNamespace="urn:Client" xmlns:typens="urn:Client" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/"> <!-- partie 2 : Types--> <types> <xsd:schema xmlns="http://www.w3.org/2001/XMLSchema" targetNamespace="urn:Client"> </xsd:schema> </types> ... <message name="getEtapeProspRequest"> <part name="user" type="xsd:string"/> <part name="motpasse" type="xsd:string"/> </message> <message name="getEtapeProspResponse"> <part name="return" type="xsd:anyType"/> </message> ... <portType name="ClientPort"> ... <operation name="getEtapeProsp"> <input message="typens:getEtapeProspRequest"/> <output message="typens:getEtapeProspResponse"/> </operation> </portType> <binding name="ClientBinding" type="typens:ClientPort"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> ... <operation name="getEtapeProsp"> <soap:operation soapAction="EtapeProspAction"/> <input name="getEtapeProspRequest"> <soap:body use="encoded" namespace="urn:Client" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </input> <output name="getEtapeProspResponse"> <soap:body use="encoded" namespace="urn:Client" encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"/> </output> </operation> </binding> <!-- partie 7 : Service --> <service name="ClientService"> <documentation></documentation> <!-- partie 8 : Port --> <port name="ClientPort" binding="typens:ClientBinding"> <soap:address location="http://192.168.1.123/imfmobile/webservice/InterfaceTransfererClient.php"/> </port> </service> </definitions> The PHP code containing the function which the webservice calls is : <?php header('Content-Type: text/plain; charset=utf-8'); ini_set("soap.wsdl_cache_enabled", "0"); $serveurSOAP = new SoapServer('Client.wsdl'); $serveurSOAP->addFunction('getClient'); $serveurSOAP->addFunction('getCredit'); $serveurSOAP->addFunction('getEcheancier'); $serveurSOAP->addFunction('getUrlPhotos'); $serveurSOAP->addFunction('getModificationClient'); $serveurSOAP->addFunction('getModificationCredit'); $serveurSOAP->addFunction('getModificationEcheance'); $serveurSOAP->addFunction('getAllPhotoNames'); $serveurSOAP->addFunction('getEtapeProsp'); if ($_SERVER['REQUEST_METHOD'] == 'POST') { $serveurSOAP->handle(); } else { echo 'désolé, je ne comprends pas les requêtes GET, veuillez seulement utiliser POST'; } ... function verifyUser($user, $motpasse) { $ok = null ; $connec = mysql_connect("192.168.1.123:3306", "root", "mysqlroot"); mysql_select_db("finance",$connec); $query=mysql_query("SELECT user_code FROM utilisateur WHERE user_login = '".$user."' AND user_passwd = md5('".$motpasse."')"); if (mysql_num_rows($query)== 1) { $ligne = mysql_fetch_array($query); $ok = $ligne['user_code'] ; } return $ok; } ... function getEtapeProsp($user,$motpasse) { $user_code = verifyUser($user, $motpasse) ; $resultat=""; if ( $user_code != null) { $datejour = date("Y-m-d"); $connec = mysql_connect("192.168.1.123:3306", "root", "mysqlroot"); mysql_select_db("finance",$connec); $query = mysql_query("SELECT * FROM etape_prospection INNER JOIN type_prospection ON etape_prospection.type_prosp_id = type_prospection.type_prosp_id WHERE prosp_id IN (SELECT prosp_id FROM transfert WHERE user_code ='".$user_code ."' AND date_transfert='".$datejour."') order by etape_prospection.prosp_id"); while($ligne = mysql_fetch_array($query)) { $resultat .= $ligne['etape_prosp_id'].';'; $resultat .= $ligne['type_prosp_lib'].';'; $resultat .= convertDateFormatHH($ligne['etape_prosp_date']).';'; $resultat .= $ligne['etape_prosp_comment'].';'; // this is the column containing the accentuated letters $resultat .= $ligne['prosp_id'].';'; $resultat .= "\r\n"; } } else { $resultat = "Login ou mot de passe incorrect" ; } return $resultat; } ?> As you can see I set the encoding/charset both in the wsdl and the PHP. So why this exception is raised when running the J2ME application : expected: END_TAG {http://schemas.xmlsoap.org/soap/envelope/}Body (position:END_TAG </{http://schemas.xmlsoap.org/soap/envelope/}SOAP-ENV:Fault>@2:299 in java.io.InputStreamReader@e5125d64) A: You need to tell your mysql database / client that you expect to have UTF-8 encoded values (because you insert them as UTF-8 into the SOAP response that is UTF-8 encoded). Otherwise the SOAP client would see an invalid byte-squence for the letter in question and throw the exception. Please consult your mysql client library manual to specify the encoding. $connec = mysql_connect("192.168.1.123:3306", "root", "mysqlroot"); mysql_set_charset('utf8', $connec); The mb_convert_encoding function is only a workaround and you don't fix the root cause, and it can have side-effects you don't want to have.
{ "pile_set_name": "StackExchange" }
Q: ToolStripButton does not contain a definition for 'Transparent' I get the following error: Error 4 'System.Windows.Forms.ToolStripButton' does not contain a definition for 'Transparent' and no extension method 'Transparent' accepting a first argument of type 'System.Windows.Forms.ToolStripButton' could be found (are you missing a using directive or an assembly reference?) C:\Users\E1\Desktop\text editor\Editor\Editor\Form1.cs 321 34 Editor I'm trying to implement the following code: protected void PaintTransparentBackground(Graphics graphics, Rectangle clipRect) { graphics.Clear(Color.Transparent); if ((this.Parent != null)) { clipRect.Offset(this.Location); PaintEventArgs e = new PaintEventArgs(graphics, clipRect); GraphicsState state = graphics.Save(); graphics.SmoothingMode = SmoothingMode.HighSpeed; try { graphics.TranslateTransform((float)-this.Location.X, (float)-this.Location.Y); this.InvokePaintBackground(this.Parent, e); this.InvokePaint(this.Parent, e); } finally { graphics.Restore(state); clipRect.Offset(-this.Location.X, -this.Location.Y); } } } It says the toolstrip button doesn't contain that definition. I want to do it for tabs, but it doesn't seem to work. Never experienced such an problem. Any hints? A: Try adding System.Drawing in front of Color.Transparent. My guess is that you have a property defined as Color in your form class. graphics.Clear(System.Drawing.Color.Transparent); If this does the trick, then I suggest you rename your Color property to something more specific like ColorButton or whatever.
{ "pile_set_name": "StackExchange" }
Q: How to export database schema using Hibernate SchemaExport with BeanValidation constraints? please see my requirement: using SchemaExport to export database schema that appiled BeanValidation constraints(eg, @Length(32) will create DB constraints: column(32)). In Hibernate 4.1.x, i can using the hack code post here: https://forum.hibernate.org/viewtopic.php?f=1&t=1024911&view=previous but the Ejb3Configuration class that required in above hack code was removed in Hibernate 4.3.5. so how can i export database schema that appiled BeanValidation constraints without using Ejb3Configuration? A: i found an temporary solution by using HibernationConfiguration build by EntityManagerFactoryBuilderImpl. it uses the JPA configuration to emit the schema script(with bean-validator constraints). public final class JpaSchemaExporter { public JpaSchemaExporter(String utilName, String packageName, Properties properties, DialectType dialect, Path outputPath) throws Exception { this.dialect = dialect; this.outputPath = outputPath; if (Files.exists(outputPath) && !Files.isDirectory(outputPath)) { throw new IllegalArgumentException( "Given path already exist and is not a directory! the path:" + outputPath); } Files.createDirectories(outputPath); pud = new ParsedPersistenceXmlDescriptor(Resources.getResourceURL("META-INF")); pud.setName(utilName); pud.addClasses(Resources.getClasseNames(packageName)); pud.addMappingFiles("META-INF/orm.xml"); properties.setProperty("hibernate.dialect", dialect.getDialectClass()); ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory(); factoryBuilder = new EntityManagerFactoryBuilderImpl( pud, properties ); factoryBuilder.withValidatorFactory(validatorFactory).build().close(); // create HibernateConfiguration instance this.injectBeanValidationConstraintToDdlTranslator(); validatorFactory.close(); } private void injectBeanValidationConstraintToDdlTranslator() { try { Configuration hibernateConfiguration = factoryBuilder.getHibernateConfiguration(); ValidatorFactory validatorFactory = (ValidatorFactory) factoryBuilder.getConfigurationValues().get(AvailableSettings.VALIDATION_FACTORY); // private class in hibernate Method applyRelationalConstraints = Class.forName("org.hibernate.cfg.beanvalidation.TypeSafeActivator") .getMethod("applyRelationalConstraints", ValidatorFactory.class, java.util.Collection.class, Properties.class, Dialect.class); applyRelationalConstraints.setAccessible(true); Dialect dialectInstance = (Dialect) Class.forName(dialect.getDialectClass()).newInstance(); applyRelationalConstraints.invoke(null, validatorFactory, Arrays.asList(Iterators.toArray(hibernateConfiguration.getClassMappings(), PersistentClass.class)) , hibernateConfiguration.getProperties(), dialectInstance); } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") public void create() throws IOException { Configuration cfg = factoryBuilder.getHibernateConfiguration(); cfg.setProperty("hibernate.hbm2ddl.auto", "create"); SchemaExport export = new SchemaExport(cfg); export.setDelimiter(";"); export.setOutputFile(Paths.get(outputPath.toString(), "ddl_create_" + dialect.name().toLowerCase() + ".sql").toString()); export.execute(true, false, false, true); if (!export.getExceptions().isEmpty()) { System.out.println(); System.out.println("SOME EXCEPTIONS OCCURED WHILE GENERATING THE UPDATE SCRIPT:"); for (Exception e : (List<Exception>) export.getExceptions()) { System.out.println(e.getMessage()); } } } @SuppressWarnings("unchecked") public void update() throws IOException { Configuration cfg = factoryBuilder.getHibernateConfiguration(); cfg.setProperty("hibernate.hbm2ddl.auto", "update"); SchemaUpdate updater = new SchemaUpdate(cfg); updater.setDelimiter(";"); updater.setOutputFile(Paths.get(outputPath.toString(), "ddl_update_" + dialect.name().toLowerCase() + ".sql").toString()); updater.execute(true, false); if (!updater.getExceptions().isEmpty()) { System.out.println(); System.out.println("SOME EXCEPTIONS OCCURED WHILE GENERATING THE UPDATE SCRIPT:"); for (Exception e : ((List<Exception>) updater.getExceptions())) { System.out.println(e.getMessage()); } } } public void validate() { Configuration hibernateConfiguration = factoryBuilder.getHibernateConfiguration(); hibernateConfiguration.setProperty("hibernate.hbm2ddl.auto", "validate"); SchemaValidator validator = new SchemaValidator(hibernateConfiguration); validator.validate(); } public static void main(String[] args) throws Exception { Properties prop = new Properties(System.getProperties()); prop.setProperty("hibernate.connection.driver_class", "value in your env"); prop.setProperty("hibernate.connection.url", "value in your env"); prop.setProperty("hibernate.connection.username", "value in your env"); prop.setProperty("hibernate.connection.password", "value in your env"); Path path = Paths.get("schema output path in your env"); String packageName = prop.getProperty("package names of jpa classes"); String unitName = prop.getProperty("jpa Unit Name"); String[] dialects = "HSQL,MYSQL".split(","); for(String dialect : dialects){ DialectType dialectType = DialectType.valueOf(dialect); JpaSchemaExporter ddlExporter = new JpaSchemaExporter(unitName, packageName, prop, dialectType, path); ddlExporter.update(); ddlExporter.create(); } } }
{ "pile_set_name": "StackExchange" }
Q: _NT_SYMBOL_PATH adplus windbg issue, not able to set name In command line I have run the following command: C:> set _NT_SYMBOL_PATH=srvc:\symbolshttp://msdl.microsoft.com/download/symbols But when I run the following command in adplus.exe C:\Program Files (x86)\Debugging Tools for Windows (x86)>ADPlus -crash -pn w3wp .exe -o C:\dumps I always get this warning: A: When you run the set command in a CMD shell it will only set the environment variable for that particular CMD instance and typically child processes. From your question it looks like you may be running the set and ADPlus commands from different CMD consoles. If that's the case this is the source of the problem. In order to set a permanent environment variable do the following Click on the Start Menu Right click on Computer and select Properties Select Adavanced System Settings Click Environment Variables Click New on User variables for ... Add the _NT_SYMBOL_PATH value there
{ "pile_set_name": "StackExchange" }
Q: How to replace all Capital letters with asterisk? This is what i have under button 1.. I am entirely new to this program. am I missing something? there is no errors but button does no fill its purpose and doesn't change "A" to asterisk aka *. I eventually want to replace all capital letters in a word with *, but for now I just want to learn how to do the letter "A". string orgstring = textBox1.Text; string Asteriskstring = textBox1.Text.Replace("A","//*"); A: You're doing it, although I don't know what the forward slashes are for, and orgstring is redundant in this example; the result is held by Asteriskstring, so assuming you want to display that value you will need to update the UI: textBox1.Text = Asteriskstring;
{ "pile_set_name": "StackExchange" }
Q: Excel IF(AND Multiple conditions I am trying to use an IF statement to determine if a program is in violation based on the number of weeks the program is at. If MIC, MIE, CIE is over 4 weeks, "Violation". IF Field Events is over 6 weeks "Violation". If either are under the 4 and 6 week thresholds then "No Violation" I thought it would look something like this but I cant make it work and I dont know how to write out the second part with Field Events: IF(OR(A2="MIE", A2="CIE", A2="MIC")AND(F2>4), "Violation", "No Violation")) The above formula is a stab in the dark. A: It is not quite clear what you want to achieve. If you want to nest AND and OR functions, you need to do it like this: =IF(AND(F2>4,OR(A2="MIE", A2="CIE", A2="MIC")), "Violation", "No Violation")) Translated: if F2 is greater than 4 and at the same time A2 is either "MIE" or "CIE" or "MIC", then it's a violation.
{ "pile_set_name": "StackExchange" }
Q: Print 2 columns in python df_heartdis = pd.read_csv('processed.cleveland.data.csv', na_values='?') df_heartdis.columns['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach', 'exang', 'oldpeak', 'slope',\ 'ca', 'thal', 'num'] print('class labels = {}'.format(df_heartdis(['num'],['chol']))) In my dataframe I have 14 columns, out of that, I want to print 2 columns side by side. I tried using print('class labels = {}'.format(df_heartdis(['num'],['chol']))) but it is throwing error, though one column can be printed by using print('class labels = {}'.format(df_heartdis(['num']))) A: Supply the column headers in the creation of the dataframe. Selecting specific columns is done using the .loc function. Below code should work: df_heartdis = pd.read_csv('processed.cleveland.data.csv', na_values='?', names = ['age', 'sex', 'cp', 'trestbps', 'chol', 'fbs', 'restecg', 'thalach','exang', 'oldpeak', 'slope','ca', 'thal', 'num']) print('class labels = {}'.format(df_heartdis.loc[:, ['num', 'chol']])) Here, the .loc function selects all rows (:) of the num and chol columns.
{ "pile_set_name": "StackExchange" }
Q: javascript dialogbox not showing Top data I have following javascript function function getPopup1(redirectString) { window.showModalDialog(redirectString , null, 'status:no;dialogWidth:700px;dialogHeight:900px;dialogHide:true;help:no;scroll:1;edge:sunken'); } The redirect string is redirecting to an .aspx page. The page has a lot of contant so I enabled the scroll bars, but I am getting the page scrolled to end on pageload. How can I show the data from top. A: when the page loads in popup , add this to page for scrolling upto top window.scrollTo(0,0)
{ "pile_set_name": "StackExchange" }
Q: Setup a Proxy with a Cordova / Ionic Android App (aka Open Source version of PhoneGap ) We're doing a security assessment on a Cordova / Ionic Mobile Application (APK & IPA). Even though we've imported our proxies Certificate Authority to the device and we can intercept SSL in the default web browser without certificate errors, the application is erroring out whenever we have a proxy configured on the device and an HTTPS call is being made. The development team is telling us they don't have any certificate pinning or other protections in place besides what is on by default in the framework. Has anyone bypassed this before with an Ionic application and can give some tips? I'm focusing on the Android build first and the traditional overriding of the SSL error to cause it to continue by modifying the Dalvik byte code is not being successful for me. Searching through the artifacts I'm not seeing a custom CA authority list in anything, nor a hash of a certificate etc; as a result I really don't understand why this isn't working. Any information you can give me which helps to be able to proxy the application would greatly be appreciated. A: I figured this out. It turned out that the issue was with Android Nugat and there actually was nothing wrong / built in to prevent the interception. Switching to JellyBean resolved the issue and allow the interception to happen.
{ "pile_set_name": "StackExchange" }
Q: http.HandleFunc always match "/" Code: http.HandleFunc("/", api.Index) http.HandleFunc("/list", api.FileList) http.HandleFunc("/api/upload", api.UploadFile) http.HandleFunc("/api/delete", api.DeleteFile) http.Handle("/files", http.StripPrefix("/files/", http.FileServer(http.Dir(settings.FilesPath)))) http.ListenAndServe(":1234", nil) Result 1: http://localhost:1234/ http://localhost:1234/list http://localhost:1234/files match "/" api.index (It's wrong for the second and third) Result 2: http://localhost:1234/api/upload http://localhost:1234/api/delete match "/api/xxx" api.xxx (It's right) env: go 1.13.5 windows/amd64 What should I do to fix this problem? A: try to use "/list/" replace "/list" more information: https://pkg.go.dev/net/http?tab=doc#ServeMux
{ "pile_set_name": "StackExchange" }
Q: Multi scale CNN Network Python I created a multi-scale CNN in python keras. The network architecture is similar to the diagram. Here, same image is fed to 3 CNN's with different architectures. The weights are NOT shared. I coded the following multiscale CNN in keras which loosely resembles the architecture in the diagram. But I keep getting "Out of memory ERROR" even when the train_dir has 2 images. Would appreciate help... #main CNN model - CNN1 main_model = Sequential() main_model.add(Convolution2D(32, 3, 3, input_shape=(3, 224, 224))) main_model.add(Activation('relu')) main_model.add(MaxPooling2D(pool_size=(2, 2))) main_model.add(Convolution2D(32, 3, 3)) main_model.add(Activation('relu')) main_model.add(MaxPooling2D(pool_size=(2, 2))) main_model.add(Convolution2D(64, 3, 3)) main_model.add(Activation('relu')) main_model.add(MaxPooling2D(pool_size=(2, 2))) # the main_model so far outputs 3D feature maps (height, width, features) main_model.add(Flatten()) #lower features model - CNN2 lower_model1 = Sequential() lower_model1.add(Convolution2D(32, 3, 3, input_shape=(3, 224, 224))) lower_model1.add(Activation('relu')) lower_model1.add(MaxPooling2D(pool_size=(2, 2))) lower_model1.add(Flatten()) #lower features model - CNN3 lower_model2 = Sequential() lower_model2.add(Convolution2D(32, 3, 3, input_shape=(3, 224, 224))) lower_model2.add(Activation('relu')) lower_model2.add(MaxPooling2D(pool_size=(2, 2))) lower_model2.add(Flatten()) #merged model merged_model = Merge([main_model, lower_model1, lower_model2], mode='concat') final_model = Sequential() final_model.add(merged_model) final_model.add(Dense(64)) final_model.add(Activation('relu')) final_model.add(Dropout(0.5)) final_model.add(Dense(1)) final_model.add(Activation('sigmoid')) final_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) print 'About to start training merged CNN' train_datagen = ImageDataGenerator(rescale=1./255, shear_range=0.2, zoom_range=0.2, horizontal_flip=True) train_generator = train_datagen.flow_from_directory(train_data_dir, target_size=(224, 224), batch_size=32, class_mode='binary') test_datagen = ImageDataGenerator(rescale=1./255) test_generator = test_datagen.flow_from_directory(args.test_images, target_size=(224, 224), batch_size=32, class_mode='binary') final_train_generator = zip(train_generator, train_generator, train_generator) final_test_generator = zip(test_generator, test_generator, test_generator) final_model.fit_generator(final_train_generator, samples_per_epoch=nb_train_samples, nb_epoch=nb_epoch, validation_data=final_test_generator, nb_val_samples=nb_validation_samples) UPDATE 1: Providing more system info I am using Theano-0.9.0.dev5 | Keras-1.2.1 | Python 2.7.12 | OSX Sierra 10.12.3 (16D32) | Macbook Pro 16GB RAM | CPU mode ~/.keras/keras.json contents { "image_dim_ordering": "th", "epsilon": 1e-07, "floatx": "float64", "backend": "theano" } Dont have .theanorc file Please note individual CNN models are training fine. Only the merged code above causes issues. UPDATE 2: on 27th January, 2017. Tried the following - Reduced the no. of parameters of the CNN from 53 million to 100K. But still no use. The network eventually fails to train due to memory issues. Reduced the batch size of images training to 8. The network training fails with the same reason. No working solution at the time of writing this update... A: You could use the following function to determine how much memory your model requires: def get_model_memory_usage(batch_size, model): import numpy as np from keras import backend as K shapes_mem_count = 0 for l in model.layers: single_layer_mem = 1 for s in l.output_shape: if s is None: continue single_layer_mem *= s shapes_mem_count += single_layer_mem trainable_count = np.sum([K.count_params(p) for p in set(model.trainable_weights)]) non_trainable_count = np.sum([K.count_params(p) for p in set(model.non_trainable_weights)]) total_memory = 4.0*batch_size*(shapes_mem_count + trainable_count + non_trainable_count) gbytes = np.round(total_memory / (1024.0 ** 3), 3) return gbytes I copied this from ZFTurbo's answer on this post.
{ "pile_set_name": "StackExchange" }
Q: Custom function gets executed before OnInit in umbraco 4.9 I have the below code in the master page which allows user to select the country and it call the GetCountryCode() function written in the master page code behind <umbraco:Macro ID="Lang" Alias="SelectCountry" runat="server" countryCode="<%$ WEB: GetCountryCode() %>" /> But when i am debugging the GetCountryCode() function is called first even before OnInit() function. I need to do some initalisation on OnInit() function. Does any one has any idea why the custom function is called before the OnInit() function A: My first thought would be that the inline code is executed by umbraco when it renders the macros, which would happen prior to the code for the page is run. If you could elaborate on what you're trying to accomplish, we might be able to look at a workaround?
{ "pile_set_name": "StackExchange" }
Q: User Control Page_Load event not reading variable passed from main page I have problem passing a variable from a main page containing a user control to the user control itself. Although the passed variable is available generally in the code-behind of the user control the page_load event can't seem to read it. My code - In the main page code-behind: protected void FindCCFsButton_Click(object sender, EventArgs e) { if (CustomerDropDown.SelectedIndex != 0) { SearchUcCCFList.SetCustID(CustomerDropDown.SelectedValue); } } (SearchUcCCFList is the instance of the user control in the main aspx page). In the user control code behind: public partial class ucCCFList : System.Web.UI.UserControl { public string srchCust { get; set; } public void SetCustID(string custID) { srchCust = custID; testCustLabel.Text = GetCustID(); //this works } public string GetCustID() { return srchCust; } protected void Page_Load(object sender, EventArgs e) { CCFGridView.DataSource = DAL.SearchCCFs(custID : GetCustID()); //doesn't work CCFGridView.DataBind(); test2CustLabel.Text = GetCustID(); //doesn't work } In the Page_Load event GetCustId() doesn't return anything (so the records aren't filtered and all get returned) although it can be read in the methods outside the Page_Load. I'm probably making a beginners error but any help would be appreciated. Edit - following Alan's suggestion in the comments I stepped through the page loading sequence & it appears that the user control's Page_Load event is running BEFORE the code in the main page's button click so the variable is not yet available. The sequence after clicking the button is: User control Page_Load runs Code in button event on main page Other code (outside Page_Load) in user control runs hence variable is available here. This seems a bit weird, is there another way to pass the variable into the user controls Page_Load? A: In this case, your click handling even on the main page is called after the user control page load call. Your variable is being set, but not until after your data binding in the user control. Either switch the user control to declarative binding which will handle calling methods in the correct order for you. Or the easier fix in this case is to change the user control data binding from Page_Load to Page_PreRender, which is called later in the life cycle, after the main page click handling call. protected void Page_PreRender(object sender, EventArgs e) { CCFGridView.DataSource = DAL.SearchCCFs(custID : GetCustID()); // will work now CCFGridView.DataBind(); test2CustLabel.Text = GetCustID(); // will work now } For a more thorough answer, read up on the ASP.NET page life cycle including the interaction with user controls' life cycle.
{ "pile_set_name": "StackExchange" }
Q: How to go about containing scrollable views within a ScrollView I wrote a FragmentActivity app with the use of the v4 support library, consisting of a fragment with a layout that contains a listview (list fragment), and a reusable fragment that changes its layout based on the list item selected (detail fragment). In the layout for large screens, I have a fragment tag for the list fragment and a scrollview as a fragment container for the detail fragment, to allow fragments whose layouts overflow out of the screen. Originally, for small screens, I used a basic ScrollView as the fragment container. But, since the listview in the list fragment is a scrollable fragment and there cannot be scrollable views in a ScrollView, it couldn't be scrolled; though the other fragments could be scrolled. So, I changed the ScrollView to a FrameLayout instead, and while fragments with scrollable views can scroll, the fragments that overflowed the screen could not be scrolled. How would I go about this problem, with the intention of enabling both fragments with scrollable views and overflowing fragments to scroll in a one-panel fragment view? Thanks in advance EDIT: I might be able to use ScrollView in the dynamic layouts used by the detail fragment as I see fit, using it where there are no scrollable views, but are there any better solutions? A: Ok, I guess this does require the ScrollView to be used only in layouts in which there are no scrollable views. I stopped using ScrollView as the root element in the fragment activity layout, and I manually used ScrollViews where applicable, and it's working now. A better way is still welcome and appreciated.
{ "pile_set_name": "StackExchange" }
Q: API Suggestion: suppress http error code when jsonp is specified Conclusion: fast response by Kevin enables the JSONP functionality of the API to assume it's rightful description of awesome. http://soapi.info/Code/JS/Stable/ErrorTest.htm The JSONP functionality is great, but implementation differences between browsers severely cripple any efforts to respond to error conditions. In most browsers, a non 200 will not result in injection of the response text. Notice that JQuery does not support error callbacks for JSONP. The only way to assume an error is to use a timeout. See SOAPI-EXPLORE for an example. Input bogus params and submit - no return. If, when JSONP is specified, the API would send the error json with a 200 we could receive the error and respond appropriately. There is no way to reliably receive a JSONP result with an http status != 200, rendering the JSONP functionality of the API unreliable. Demonstration http://soapi.info/Code/JS/Stable/ErrorTest.htm Results: WebKit (Chrome, Safari): the browser passes the response and we can examine the jsob to determine whether it is an error. IE, Opera, Firefox: no result. dead. only option is to implement a timeout. UPDATE: WebKit only lets the 500 error through. 404 and the 4000's are all swallowed by the browser, making the case for a 200 status for jsonp errors. A: Done. Compare: http://api.stackoverflow.com/0.8/errors/4002 and http://api.stackoverflow.com/0.8/errors/4002?jsonp=wrapperFunc
{ "pile_set_name": "StackExchange" }
Q: Passing a Var and List to Controller via Ajax I have a Text Box and a Select Options Multiple, i store all the selected items using knockout selectedOptions in a viewModel. If I try to pass the captured information to my Controller using ajax I'm unable to recieve my MetricsChosenModel. var MetricsChosenModel= window.vm.MetricsChosenModel(); var ApplicationsNameValue = $.trim($("#add-Applications").val()); if (ApplicationsNameValue.length <= 0) { $("#text-add-Applications").popover('show'); } $.ajax({ url: '/Admin/AddApplications', type: "POST", dataType: "JSON", data: { ApplicationsName: ApplicationsNameValue, MetricsChosenModel: MetricsChosenModel }, success: function (returndata) { if (returndata == true) { } else { } }, error: function () { } }); My Controller public ActionResult AddApplications(string ApplicationsName,List<string> MetricsChosenModel) { //Code here return View(); } My MetricsChosenModel stores data in following format MetricsChosenModel[0] => 5 MetricsChosenModel [1] => 6 why am i not able to recieve the list value of MetricsChosenModel , I'm able to recieve the ApplicationsName though, Also it would be great if some one can explain, how am i wrong here, Thanks, A: Without knowing what your routing looks like, it's hard to pinpoint the exact source of the problem. If I had to guess, I'd say that you're getting the ApplicationsName value through the URL (routing or querystring parameter). If that's the case, you could probably add the [FromBody] attribute to the MetricsChosenModel. Note, however, that you're only allowed one FromBodyAttribute per method signature. If you need more variables, a simple solution to this problem is to create a model which contains each of the properties you're looking to receive in your controller action. Hope that helps!
{ "pile_set_name": "StackExchange" }
Q: Simplest way to shrink transaction log files on a mirrored production database What's the simplest way to shrink transaction log file on a mirrored production database? I have to, as my disk space is running out. I will make a full database backup before I do this, so I don't need to keep anything from the transaction log (right? I have daily full database backup, probably never need point-in-time restore, though I'll keep the option open if I can - that's all the .ldf is really for, correct?). Solved: OK, after doing 2 backups through SSMS (not TSQL) of just the log, creating a totally new backup set, the Shrink-Files-Log dialog in SSMS finally actually worked, freeing some disk space. Not sure why 2 backups where needed, or why TSQL didn't work, and there was no difference in the reported "space available to be reclaimed" in the shrink dialog (it was at 99% for all the shrink attempts after the first backup too, but still didn't free any space), but problem solved for now. Thanks all. A: This is an older question, but there are some things that were not explained well and this will hopefully shed some light. The how to shrink was answered, mostly, but this will explain the "why" part of what you are actually doing. Backups, specifically log backups, do several things. The data is written to disk as a backup set to be used or discarded later as needed. Each subsequent backup is added to that set, in a Fully logged DB. Truncating the log or starting a new backup set breaks the chain and inhibits, or in many cases, negates your ability to restore to a point in time before the chain was broken. The data in the log is not actually deleted, nor is the log file shrunk during a backup. The active VLFs are marked inactive, except for those that cannot be fully committed - they remain active. Inactive VLFs are able to be rewritten, making your log circular, in effect like a snake eating its own tail. A checkpoint is issued, as part of the backup, which tells the DB to start writing to the beginning of the log, once the current VLF fills up. If you perform a shrink at this point, you will gain back all the space at the end of the log, up to the point of the active VLF. The reason a second backup seems to "do the trick" is because the active VLF typically fills up during this time and the log is being written from the beginning. When you take the second backup, the active VLF is written to disk as part of the backup set (or not), and the VLF is marked inactive. Since this was the tail end of the log due to the previous shrink, performing a shrink now frees up all the space to the beginning of the log, up to the currently active VLF. All of this assumes a couple of things, 1.) you don't have massive VLFs that take hours or days to fill up and 2.) your database is fairly inactive and there aren't a bunch of transactions being written to the log. If either of these conditions are an issue for you, shrinking your log will also be an issue. All of this is true for both unmirrored and mirrored databases. The difference is that you only need to perform the maintenance on the primary in a mirrored scenario, assuming your mirror is built identically. A: Do a transaction log backup, with whatever method you feel most comfortable with. This will cause the transaction logs that have already been committed to the database to be deleted from disk. Ideally, you should actually create a database maintenance task to do this for you on a recurring basis for precisely this reason - to eliminate the old transaction logs so you don't fill up your disk. Per the other bit of your question... no, not really. Yes, they perform that function, but not only that function. Databases are not backed up (or written to) in the traditional fashion that other files are, because the database file itself is constantly in use and constantly changing. So a single "point in time" back up would either require taking the database offline to "freeze it" in a consistent state or result in different parts of the backup containing different data than was there when the backup started. What transaction logs are is records of every "transaction" the database performed. Rather than writing to the database file every time a record is changed, updated, added, removed, etc., those actions are written to a separate file, a transaction log, and then committed into the database file when the SQL server determines it's safe to do so without bringing any activity to a halt. So transaction logs are, in effect, where changes to the database go before they actually become changes to the database [file]. So, if you need to get back to a given database state, or point in time, the transaction logs are "replayed." Essentially, not copying the file data, but going to the most recent point-in-time state found for the database and then doing all the same things that got the database to the specified [later] state. But, it's important to note that at any given time, your transaction logs will contain transactions that will not have been committed to the database yet. So they're more than just the ability to perform a point-in-time restore. They contain [some] changes that are being made, or will shortly be made to the database. This is why you're forced to do a backup before purging the transaction logs - once that backup's done, the system has a point-in-time copy of the database to reference for any future restores, and is able to determine which transactions have been committed to the database, and which have not. And with that information, the system knows which obsolete transaction logs to delete for you and which not to. This can, however, take some time, depending on the size of your transaction logs. If you've never done one before, brace yourself it'll take a while.
{ "pile_set_name": "StackExchange" }
Q: C++ cast object to its original type What i want to achieve is this following behavior: int main(){ vector<Component*>v = {...}; draw(dynamic_cast< ??? >v[0]); } void draw(const Image& i){...} void draw(const Text& i){...} void draw(const Link& i){...} where Image, Text, Link are derive classes from Component, but i don't know what to put inside the < > of the dynamic cast, or at least if there is another way to do this. For the moment, what i was thinking is to use variant, but to get the element i need to call std::get where i have to specify the type, and so at the same point. So at this point i think that the only way is to create a list of if(dynamic_cast<>(v[0]) with all the possible type... A: There is nothing to cast to, because vector<Component> can only contain objects of type Component. It cannot contain any derived objects. Static type can differ from the dynamic type only through indirection. Now, if we had a case that you had a reference to base class for example, there would be no way at compile time to know the dynamic type, thus there is nothing that you could write into dynamic_cast<???> that would make this work. The way dynamic polymorphism is achieved through inheritance is to instead pass a reference to base into the draw function, and then use virtual member functions of Component in order to have different behaviour based on the dynamic type. A: If you do end up using a variant, you can use std::visit to work out which form of your draw function to call as long as you don't need other arguments, or they all take the same arguments after the type: for ( auto & vitem : in v ) // where v is a vector of variant std::visit([](auto && shape){ draw( shape ); }, vitem); See https://en.cppreference.com/w/cpp/utility/variant/visit for more details.
{ "pile_set_name": "StackExchange" }
Q: Implementing scopes in Pundit I am using the Pundit gem (with Devise and Rolify) to restrict access to information based on logged-in user roles. At this time I have three roles for my User model defined: Admin, Client Admin, and Customer Admin. A User belongs_to a Customer. Customer has_many Users. I have successfully implemented a Pundit policy when indexing the Customer model. Admins and Client Admins can see all Customers. Customer Admin can only see their OWN record. The problem lies when I am trying to restrict the show method of the Customer controller. Admins and Client Admins can see all Customers. However, the Customer Admin should only be able to see his own record. But as it stands the Customer Admin can input any id in the URL and see any Customer record. I'm fuzzy on the scoping. It's my understanding that the Policy methods (i.e. index? and show?) are to restrict WHO can perform these actions and the Scoping methods restrict WHICH RECORDS can be obtained. I'm having trouble composing the correct scope for the above scenario. Here's the Customer controller: class CustomersController < ApplicationController before_action :set_customer, only: [:show, :edit, :update, :destroy] after_action :verify_authorized # GET /customers # GET /customers.json def index @customers = policy_scope(Customer) authorize Customer end # GET /customers/1 # GET /customers/1.json def show authorize @customer end # GET /customers/new def new @customer = Customer.new authorize @customer end # GET /customers/1/edit def edit authorize @customer end # POST /customers # POST /customers.json def create @customer = Customer.new(customer_params) authorize @customer respond_to do |format| if @customer.save format.html { redirect_to @customer, notice: 'Customer was successfully created.' } format.json { render :show, status: :created, location: @customer } else format.html { render :new } format.json { render json: @customer.errors, status: :unprocessable_entity } end end end # PATCH/PUT /customers/1 # PATCH/PUT /customers/1.json def update authorize @customer respond_to do |format| if @customer.update(customer_params) format.html { redirect_to @customer, notice: 'Customer was successfully updated.' } format.json { render :show, status: :ok, location: @customer } else format.html { render :edit } format.json { render json: @customer.errors, status: :unprocessable_entity } end end end # DELETE /customers/1 # DELETE /customers/1.json def destroy authorize @customer @customer.destroy respond_to do |format| format.html { redirect_to customers_url, notice: 'Customer was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_customer @customer = Customer.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def customer_params params.require(:customer).permit(:name, :parent_customer_id, :customer_type, :active, :currency) end end And here is the Customer policy: class CustomerPolicy < ApplicationPolicy def index? # Admins, ClientAdmins, and CustomerAdmins can index customers (see Scope class for filters) @user.has_role? :admin or @user.has_role? :client_admin or @user.has_role? :customer_admin end def show? # Admins, ClientAdmins, and CustomerAdmins can see any customer details @user.has_role? :admin or @user.has_role? :client_admin or @user.has_role? :customer_admin end def update? # Only Admins and ClientAdmins can update customer details @user.has_role? :admin or @user.has_role? :client_admin end def destroy? @user.has_role? :admin or @user.has_role? :client_admin end class Scope < Struct.new(:user, :scope) def resolve if (user.has_role? :admin or user.has_role? :client_admin) # Admins and ClientAdmins can see all Customers scope.where(:parent_id => nil) elsif user.has_role? :customer_admin # Customer Admins can only see their own Customer scope.where(:id => user.customer) # THIS DOES NOT APPEAR TO GET INVOKED BY THE SHOW METHOD OF THE CONTROLLER end end def show? # NOT SURE WHAT TO PUT IN HERE end end end Success!! Thanks to the headstart given to me by railscard, the trick was to modify the show? method in the Customer policy file like the following: def show? # Admins, ClientAdmins, and CustomerAdmins can see any customer details # Students cannot see customer details return true if user.has_role?(:admin) || user.has_role?(:client_admin) return true if user.customer_id == @record.id && user.has_role?(:customer_admin) false end Note that I had to use the @record instance variable, as that's what the Application policy class uses to refer to the record being passed in by the authorize method. Thanks!! A: To get Pundit's scoping working for the show action, Pundit's policy_scope helper (or policy_scope!) could be used, or you could just inherit show? from the generated ApplicationPolicy. The index action is already using policy_scope correctly, we just need to do something similar for the show action. Here are some options: Option 1: Modify the show action to def show # Also remove :show from the :only option where # before_action :set_customer, only: ... is called. @customer = policy_scope(Customer).find(params[:id]) authorize @customer end OR Option 2: Modify set_customer to def set_customer @customer = policy_scope(Customer).find(params[:id]) end OR Option 3: Modify CustomerPolicy#show? to def show? # scope call here will return the # result of CustomerPolicy::Scope#resolve # This is the same implementation generated # in the default ApplicationPolicy so you could # just delete this method here and inherit instead. scope.where(:id => record.id).exists? end Here's the code that generates the default ApplicationPolicy#show? method. See Pundit's README section on Scopes for additional details. I think you can safely delete the empty show? method you have in CustomerPolicy::Scope, I don't believe it will be called. A: I think you don't need scope to restrict access for show action. def show? return true if user.has_role? :admin || user.has_role? :client_admin return true if user.customer_id == customer.id && user.has_role? :customer_admin false end Pundit scopes usually used to fetch a list of records which user have access to. In case of show method (or any other method in controller, where you call authorize) Pundit instantiates policy class with current user and given customer and then simply calls show? method to check user permissions, i.e. CustomerPolicy.new(current_user, @customer).show?
{ "pile_set_name": "StackExchange" }
Q: Looping through checked check-boxes then displaying result I'm making an exercise where the user has to check correct answers from a list then press submit to see how well he/she did. However, my submit button does not seem to be working. Nothing happens when it is clicked. Here is the script: <script> //Returns how many correct answers were checked $('#submitButton').click(function(){ var arrayScore = []; var tempScore = 0; $('.confirmContainer').remove(); $('.toggleConfirmList:checked').each(function(){ arrayScore.push($(this).val()); }); for(var i=0; i<arrayScore.length; i++) { tempScore = arrayScore[i] + tempScore; } $('feedback').show(); $("#scoreArea").val(tempScore); }); </script> Basically I want to disable the input container and then display the feedback after calculating the users score. Here is the HTML code that the script uses: <ol class="toggleConfirmList" start="1"> <!-- Start of toggleConfirm question --> <li class="toggleConfirm"> <p class="question">What is your citizenship? </p> <div class="toggleInputContainer"> <input type="checkbox" value="1"> </div> </li> <li class="toggleConfirm"> <p class="question">What is the purpose of your trip</p> <div class="toggleInputContainer"> <input type="checkbox" value="1"> </div> </li> <li class="toggleConfirm"> <p class="question">How long will you be staying in Canada?</p> <div class="toggleInputContainer"> <input type="checkbox" value="0"> </div> </li> <li class="toggleConfirm"> <p class="question">Where will you be staying?</p> <div class="toggleInputContainer"> <input type="checkbox" value="0"> </div> </li> <li class="toggleConfirm"> <p class="question">What is your occupation?</p> <div class="toggleInputContainer"> <input type="checkbox" value="0"> </div> </li> <li class="toggleConfirm"> <p class="question">Do you have any family in Canada?</p> <div class="toggleInputContainer"> <input type="checkbox" value="1"> </div> </li> <li class="toggleConfirm"> <p class="question">How will you support yourself in Canada?</p> <div class="toggleInputContainer"> <input type="checkbox" value="0"> </div> </li> <li class="toggleConfirm"> <p class="question">Do you intend to work or study while you are in Canada?</p> <div class="toggleInputContainer"> <input type="checkbox" value="0"> </div> </li> <li class="toggleConfirm"> <p class="question">Have you ever been convicted of a criminal offence?</p> <div class="toggleInputContainer"> <input type="checkbox" value="0"> </div> </li> <li class="toggleConfirm"> <p class="question">Do you suffer from any medical conditions?</p> <div class="toggleInputContainer"> <input type="checkbox" value="0"> </div> </li> <li class="toggleConfirm"> <p class="question">Have you ever been refused a visa to Canada?</p> <div class="toggleInputContainer"> <input type="checkbox" value="0"> </div> </li> <li class="toggleConfirm"> <p class="question">In which country do you reside permanently?</p> <div class="toggleInputContainer"> <input type="checkbox" value="1"> </div> </li> </ol> <div class="confirmContainer"> <input type="button" id="submitButton" value="Submit"> </div> <div class="feedback"> <strong>Answer:</strong>In the exercise you checked <span id="scoreArea">0</span> correct questions </div> A: for setting value to a span element you should use text() method instead of val(): //Returns how many correct answers were checked $('#submitButton').click(function(){ var arrayScore = []; var tempScore = 0; $('.confirmContainer').remove(); $(':checkbox:checked').each(function(){ // for selecting checkboxes you can use ":checkbox" selector arrayScore.push(parseInt($(this).val())); // parseInt() the values }); for(var i=0; i<arrayScore.length; i++) { tempScore = arrayScore[i] + tempScore; } $('.feedback').show(); // class selectors should have '.' $("#scoreArea").text(tempScore); // use text() instead of val() }); http://jsfiddle.net/EWgzq/2/
{ "pile_set_name": "StackExchange" }
Q: Clean the muddy quartata-fish This challenge is in honor of the Rookie of the Year category winners of Best of PPCG 2015: muddyfish (for I'm not the language you're looking for!) and quartata (for Implement a Truth-Machine). Congratulations! Background In the deepest trenches of the ocean, there lives a rare and elusive square-shaped fish called the quartata-fish. It looks like the glider from the Game of Life cellular automaton. Here are two quartata-fish of different sizes: -o- --o ooo --oo-- --oo-- ----oo ----oo oooooo oooooo You have managed to snap a photo of the quartata-fish, but the fish is rather hard to see since it's covered in mud. Now you'll have to write a program to clean up the photo. Input Your input is a rectangular 2D grid of the characters .-o#, given as a newline-separated string. If you want, you can use pipes | instead of newlines as the separators, and you may assume one trailing and/or preceding separator. The input will contain exactly one quartata-fish of some side-length 3*n, where n ≥ 1 is a positive integer, surrounded by periods . that represent the ocean floor. The fish will always be in the orientation depicted above. Overlaid on this grid, there will be exactly one non-empty rectangular region of hashes #, which represents a blob of mud. The blob may cover the quartata-fish partially or entirely. An example input would be ............ ..--oo--.... ..--oo--.... ..---#####.. ..---#####.. ..ooo#####.. ..oooooo.... Output Your output shall be generated from the input by replacing all the hashes with the characters .-o, so that the grid contains exactly one quartata-fish. There will always be a unique way to perform this replacement properly; in particular, the blob of mud will cover the fish entirely only if its size is 3×3. The output shall use the same separator as the input. For the above input, the correct output would be ............ ..--oo--.... ..--oo--.... ..----oo.... ..----oo.... ..oooooo.... ..oooooo.... Rules and scoring You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed. There are no time bounds: if your submission would eventually halt given unlimited time and resources, you're fine. Test cases Input: ....... ...-o-. ...--o. ##.ooo. ##..... Output: ....... ...-o-. ...--o. ...ooo. ....... Input: ...-o-. ...-#o. ...ooo. ....... Output: ...-o-. ...--o. ...ooo. ....... Input: ......... .###..... .###..... .ooo..... Output: ......... .-o-..... .--o..... .ooo..... Input: ..... .###. .###. .###. Output: ..... .-o-. .--o. .ooo. Input: ...... ...... ...... ...### ...### ...### Output: ...... ...... ...... ...-o- ...--o ...ooo Input: ###o--.... ###o--.... ###-oo.... ###-oo.... ###ooo.... ###ooo.... ###....... Output: --oo--.... --oo--.... ----oo.... ----oo.... oooooo.... oooooo.... .......... Input: ............ ..--oo--.... ..--oo--.... ..---#####.. ..---#####.. ..ooo#####.. ..oooooo.... Output: ............ ..--oo--.... ..--oo--.... ..----oo.... ..----oo.... ..oooooo.... ..oooooo.... Input: ...--oo--.... .#########... .#########... .#########... ...oooooo.... ...oooooo.... ............. ............. Output: ...--oo--.... ...--oo--.... ...----oo.... ...----oo.... ...oooooo.... ...oooooo.... ............. ............. Input: .............. .............. .########..... .########..... .########-.... .########-.... .########o.... .########o.... .########o.... .########o.... .########..... .............. Output: .............. .............. .............. .............. ....--oo--.... ....--oo--.... ....----oo.... ....----oo.... ....oooooo.... ....oooooo.... .............. .............. Input: ................. ................. ..---ooo---...... ..--#########.... ..--#########.... ..--#########.... ..--#########.... ..--#########.... ..oo#########.... ..oo#########.... ..oo#########.... ....#########.... Output: ................. ................. ..---ooo---...... ..---ooo---...... ..---ooo---...... ..------ooo...... ..------ooo...... ..------ooo...... ..ooooooooo...... ..ooooooooo...... ..ooooooooo...... ................. Input: ......................... ......................... ....----oooo----......... ....----########......... ....----########......... ....----########......... ....----########......... ....----########......... ....----########......... ....----########......... ....oooo########......... ....oooo########......... ....oooooooooooo......... ....oooooooooooo......... ......................... Output: ......................... ......................... ....----oooo----......... ....----oooo----......... ....----oooo----......... ....----oooo----......... ....--------oooo......... ....--------oooo......... ....--------oooo......... ....--------oooo......... ....oooooooooooo......... ....oooooooooooo......... ....oooooooooooo......... ....oooooooooooo......... ......................... A: Python 2, 433 411 bytes import re;i,o,l,j=input(),range,lambda s,r:s.replace(*r),"".join;i=l(l(l(i,".1"),"#."),"| ");s=o(len(i)) for x in s: for y in s: for q in s: r=map(list,l(l(i,"o."),"-.").split(" ")) try: for v in o(q):r[x+v][y:y+q]=["".join(c*(q/3)for c in b)for b in["-o-","--o","ooo"]][3*v/q] m=re.match(i," ".join(j(i)for i in r)) except:0 if sum("-"in p for p in r)and m:print"|".join(l(j(i),"1.")for i in r);_ Exits with a NameError. Takes input pipe separated. I'm mixing tabs and spaces here. SE doesn't render tabs properly. '###o--....|###o--....|###-oo....|###-oo....|###ooo....|###ooo....|###.......' --oo--....|--oo--....|----oo....|----oo....|oooooo....|oooooo....|.......... '.....|.###.|.###.|.###.' .....|.-o-.|.--o.|.ooo. '...-o-.|...-#o.|...ooo.|.......' ...-o-.|...--o.|...ooo.|....... (Note extra spaces at the start are for prettiness only and aren't actually printed) A: JavaScript (ES6), 291 bytes g=>eval('w=g.search`\n`;h=g.length/w|0;for(n=(w<h?w:h)/3|0;s=n*3;n--)for(x=w+1-s;x--;)for(y=h+1-s;y--;[...g].every((c,i)=>c==o[i]|c=="#")?z=p:0)for(p="",i=h;i--;)p=(l=[,"-o-","--o","ooo"][(i-y)/n+1|0],l?"."[t="repeat"](x)+l.replace(/./g,c=>c[t](n))+"."[t](w-x-s):"."[t](w))+(p?`\n`:"")+p;z') Explanation Takes input grid as a newline separated string. Not completely golfed, will do more when I get time. It works by: Getting every possible position and size of a fish in the bounds of the input grid. For each position/size, it builds a grid string with a fish in that position. Checks if this is the correct output by iterating over every character. If each character either matches or is a hash, it outputs the built string. var solution = g=> eval(` // Get size of input grid w=g.search\`\n\`; h=g.length/w|0; // Check every possible size (n) and position (x and y) of fish for(n=(w<h?w:h)/3|0;s=n*3;n--) for(x=w+1-s;x--;) for(y=h+1-s;y--; // Check if possible solution matches input grid [...g].every((c,i)=>c==p[i]|c=="#")?z=p:0 ) // Create possible solution grid for(p="",i=h;i--;) p=( l=[,"-o-","--o","ooo"][(i-y)/n+1|0], l? "."[t="repeat"](x)+ l.replace(/./g,c=>c[t](n))+ "."[t](w-x-s) :"."[t](w) )+(p?\`\n\`:"")+p; z `) <textarea id="input" rows="6" cols="40">.............. .............. .########..... .########..... .########-.... .########-.... .########o.... .########o.... .########o.... .########o.... .########..... ..............</textarea><br /> <button onclick="result.textContent=solution(input.value)">Go</button> <pre id="result"></pre> A: Python 2, 325 bytes def f(s): s=map(list,s.split());R=range;L=len(s);M=len(s[0]) for h in R(L/3*3,0,-3): for x in R(M-h+1): for y in R(L-h+1): if all(s[v%L][v/L]in".-#o #"[0<=v%L-y<h>v/L-x>=0::2]for v in R(L*M)): for k in R(h*h):s[y+k/h][x+k%h]="-o"[482>>k/h*3/h*3+k%h*3/h&1] return'\n'.join(map(''.join,s)).replace('#','.') A badly golfed solution for now – the for .. in range(...)s are an utter train wreck. Inputs/outputs newline separated strings. The byte count currently assumes space indents only – I'll switch to mixed tabs/spaces later when I'm done golfing, if necessary.
{ "pile_set_name": "StackExchange" }
Q: How to read from channel while go routines are running I am looking to fire off an unknown number of goroutines. In this example adding to the number channel. Then read messages off the messages channel as they roll in. Why am I only seeing one message when I would expect to see all 100 messages in this code? How do I see the messages for all of the numbers added? Go Playground package main import ( "fmt" ) func Run(numbers chan int, messages chan string) { stuff := <-numbers messages <- fmt.Sprintf("Ran %d", stuff) } func main() { var numbers = make(chan int) var messages = make(chan string) go Run(numbers, messages) for i := 0; i < 100; i++ { go func(i int) { numbers <-i }(i) } msg := <-messages fmt.Println(msg) } A: Because Run reads one message from numbers, writes one message to messages, and terminates. Try this instead: func Run(numbers chan int, messages chan string) { for stuff := range numbers { messages <- fmt.Sprintf("Ran %d", stuff) } } This will run until numbers is closed.
{ "pile_set_name": "StackExchange" }
Q: Parallel.For interruption Suppose you have an array of 1000 random integer numbers and you need to loop over it to find the number 68 for example. Using the new Parallel.For on a quad core CPU would improve speed considerably, making each core to work only 250 array items. The question is: is it possible to interrupt the Parallel.For loop when the following condition is met? if (integerArray[i] == 68) break; Thanks. A: If you want to stop after the current executing iteration are done (but iterations before the current WILL be executed - that is, the iterations with a lower index = i) Parallel.For(0, 100, (i, s) => { s.Break(); }); or if you want to stop after the current and interations before this (in terms of index = i) should also stop Parallel.For(0, 100, (i, s) => { s.Stop(); }); but in BOTH cases it is good practice to check if the work should be aborted if the iteration can take a while s.ShouldExitCurrentIteration read more here Parallel.For Method (Int32, Int32, Action(Int32, ParallelLoopState))
{ "pile_set_name": "StackExchange" }
Q: How do I do a conditional join or with? Laravel 5 I have a model items. Items hasMany templateItems. The relationship uses items.id as the foreign key in template_items. I am trying to return all items but only include the related templateItems where template_items.template equals a $id. I have tried this; $items = Item::with('templateItems', function($query) use ($id) { $query->where('template_items.template', $id); })->get(); I get: ErrorException in Builder.php line 1150: explode() expects parameter 2 to be string, object given What am I missing or is there a better way? Thanks. A: Your query should be like this: $items = Item::with(['templateItems' => function($query) use ($id) { $query->where('template_items.template', $id); }])->get();
{ "pile_set_name": "StackExchange" }
Q: SQL JOIN multiple ID's First Table |product_name | category_ids | |---------------------------------| |- apple | 1, 2 | |- extra_apple | 1, 3 | Second Table |category_id | category_name | |---------------------------------| |- 1 | fruit | |- 2 | cheap | |- 3 | expensive | How can I join this, so I get something like this | product_name | category_names | -------------------------------------------- | apple | fruit, cheap | | extra_apple | fruit, expensive | A: To make it right, add another table: product_categories table ------------------------ product_id category_id It contains one record for each category a product has.
{ "pile_set_name": "StackExchange" }
Q: Crystal Reports - Poor performance on ReportDocument.Load We're having some performance problems with our app where Crystal Reports (XI) is hosted in a WCF-service. With a help of a performance profiler we were able to find out that the call to ReportDocument.Load is taking over 10 seconds. If we dig deeper, the most problematic point is in ReportClientDocumentClass.Open-method, which is taking the whole 10 seconds. We're calling the Load-method like this: dim doc As ReportDocument = New CrystalDecisions.CrystalReports.Engine.ReportDocument doc.Load("filename") The report file is hosted on the same server than the service. The "stack trace" for ReportDocument.Load looks like this: ReportDocument.Load ReportClientDocumentWrapper.EnsureDocumentIsOpened ReportClientDocumentWrapper.Open ReportClientDocumentClass.Open And like I mentioned above, the call to ReportClientDocumentClass.Open is the one "hanging". Any ideas which could cause this? A: The original problem was pinpointed to the printers. The call to Open-method tries to connect to the printer which was used when the report was designed. When the report was deployed, the printer wasn't available anymore but it took Crystal around 15 seconds to notice that. Opening the report and setting it to use no printer fixed this particular performance problem.
{ "pile_set_name": "StackExchange" }
Q: Redirect stderr and stdout from ffmpeg to a file in Python with subprocess I am trying to redirect both the stderr and stdout of a ffmpeg command to a file and to suppress them when executing the Python script. This is my code: import subprocess, shlex cmd = 'ffmpeg -hide_banner -i input.mp4 -c:v libx264 -b:v 2M -c:a copy enc_out.mp4' with open("ffmpeg_out.txt", 'w') as log: ffmpeg_cmd = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE) ffmpeg_stdout = ffmpeg_cmd.communicate() for i in range(len(ffmpeg_stdout) - 1): log.write(str(ffmpeg_stdout[i]) + "\n") So in general I want to do something similar to ffmpeg -hide_banner -i input.mp4 -c:v libx264 -b:v 2M -c:a copy enc_out.mp4 &> ffmpeg_out.txt. So currently in the ffmpeg_stdout I have only (b'', None) and the stdout and stderr are both printed when executing the script. A: oguzismail's answer is probably superior in this particular case, but just for the record, it's not hard at all. with open("ffmpeg_out.txt", 'w') as log: ffmpeg_cmd = subprocess.run(shlex.split(cmd), stdout=log, stderr=log) Notice also the preference for subprocess.run() over raw Popen. (Probably add check=True as well.)
{ "pile_set_name": "StackExchange" }
Q: Firefox 3.6.24 does not see Java plugin 6 Jan 2012 v.puzzled, Ubuntu 10.04 Lucid Lynx, Firefox 3.6.24, sun-java6-plugin 6.26-2lucid1: Firefox does not seem to even know that the java plugin is there (it is installed, and re-installed), i.e., it does not show up in Firefox's tools -> addons -> plugins, nor does it run. (It did, until some recent update.-) A: Try installing the open source java plugin sudo apt-get install icedtea6-plugin It works for me.
{ "pile_set_name": "StackExchange" }
Q: Application monitoring performance in scala I have a web service written in scala and built on top of twitter finagle RPC system. Now we are hitting some performance issues. We have external API components and database layer. I am planning of installing Zipkin in order to have a service level tracing system. This will allow me to know where the bottleneck is at the service level. I am wondering though if there are framework out there to monitor the performance inside my application layer. The application is a suite of filters that are applied consecutively to my data and I would like to know which filter take time to compute. I heard about JVM profiling but it seems a little overkill for what I want to do. What would you recommend ? Thanks for your help. A: Well before starting digging into JVM stuff or setting up all the infrastructure needed by Zipkin you could simply start by measuring some application-level metrics. You could try the library metrics via this scala api. Basically you manually set up counters and gauges at specific points of your application that will help you diagnose your bottleneck problem.
{ "pile_set_name": "StackExchange" }
Q: Saving values of variables in files I'm making a program that uses a lot of variables and changes them constantly. How to save those variables into another file from inside the program? A: You have to use io.open(filename, mode) to create a file handle, then use :write(linecontent) and :read("*line") to write and read in order. From there you can "load" and "save" variables by keeping track of the line orders for each variable you use: local f = assert(io.open("quicksave.txt", "w")) f:write(firstVariable, "\n") f:write(secondVariable, "\n") f:write(thirdVariable, "\n") f:close() local f = assert(io.open("quicksave.txt", "r")) firstVariable = f:read("*line") secondVariable = f:read("*line") thirdVariable = f:read("*line") f:close()
{ "pile_set_name": "StackExchange" }
Q: Quick sort code explanation This is code that I came across implementing the quick sort algorithm. Can you please explain how the recursion works here? void quickSort(int arr[], int left, int right) { int i = left, j = right; int tmp; int pivot = arr[(left + right) / 2]; /* partition */ while (i <= j) { while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (i <= j) { tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } } /* recursion */ if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } And please note, this is not homework. A: Not sure what you mean with "explain how the recursion is working". But here you go: The function you posted takes an array of ints and two indexes. It will not sort the whole array, but only the part of it between the two indexes, ignoring anything that is outside them. This means the same function can sort the whole array if you pass the first and last indexes, or just a sub array if you pass a left value that is not the index of the first element of the array and/or a right value that is not the index of the last element. The sorting algorithm is the well known quicksort. The as pivot it uses the central element (it could as well have used any other element). It partitions the array into the less than (or equal to) pivot subarray and the greater than (or equal to) pivot subarray, leaving an element equal to the pivot between the two partitions. Then it recursively calls itself to sort the two partitions, but only does it if it is necessary (hence the ifs before the recursive calls). The implementation works, but is sub-optimal in many ways, and could be improved. Here are some possible improvements: switch to another sorting algorithm if the array is sufficiently short chose the pivot value as median of three values (generally first, last and mid) initially move one pivot value out of the array (put it in first or last position and reduce the focus to the rest of the array) then change the tests to pass over values that are equal to the pivot to reduce the number of swaps involving them. You'll put the pivot value back in with a final exchange at the end. This is especially useful if you do not follow suggestion 2 and chose the firs/last element instead of the mid one as in this implementation. A: late reply but I just added some prints and it might help whoever comes across this understand the code. #include<iostream> using namespace std; void quickSort(int arr[], int left, int right) { int i = left, j = right; int tmp; int pivot = arr[abs((left + right) / 2)]; cout<<"pivot is"<<pivot<<endl; /* partition */ while (i <= j) { while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (i <= j) { cout<<"i and j are"<<i<<" "<<j<<"and corresponding array value is"<<arr[i]<<" " <<arr[j]<<endl; tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; cout<<"entering first big while loop"<<endl; for(int i=0;i<7;i++) cout<<arr[i]<<" "<<endl ; } } cout<<"recursion"<<endl; /* recursion */ if (left < j) quickSort(arr, left, j); if (i< right) quickSort(arr, i, right); } int main(){ int arr[7]= {2,3,8,7,4,9,1}; for(int i=0;i<7;i++) cout<<arr[i]<<" " ; quickSort(arr,0,6); cout<<endl; for(int i=0;i<7;i++) cout<<arr[i]<<" " ; int wait; cin>>wait; return 0; }
{ "pile_set_name": "StackExchange" }
Q: Seeing two accept events on epoll I'm playing around with epoll on Linux for the first time and see some strange behavior. Specificall, when I connect with a client to a socket, I see two events emitted by epoll_wait on the server side. When I call accept on the second attempt I get a "temporary unavailable" error. Here's the simple client code: #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> const char* msg = "friendly ping"; int main(int argc, char** argv) { if (argc != 2) { fprintf(stderr, "Usage: %s <socket>\n", argv[0]); exit(-1); } int sock = socket(AF_UNIX, SOCK_STREAM, 0); if (sock < 0) { perror("socket"); exit(-1); } struct sockaddr_un addr; addr.sun_family = AF_UNIX; strncpy(addr.sun_path, argv[1], sizeof(addr.sun_path) - 1); if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) == -1) { perror("Error connecting"); exit(-1); } write(sock, msg, strlen(msg)); close(sock); return 0; } The server code is the following: #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/epoll.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> const int kMaxEvents = 100; const char *kSocketFile = "dummy_socket"; void MakeNonBlocking(int fd) { int flags, s; flags = fcntl (fd, F_GETFL, 0); if (flags == -1) { perror ("fcntl"); exit(-1); } flags |= O_NONBLOCK; s = fcntl (fd, F_SETFL, flags); if (s == -1) { perror ("fcntl"); exit(-1); } } void AcceptConnections(int sock, int epoll_fd) { struct epoll_event event; event.data.fd = sock; event.events = EPOLLIN; int insock = accept(sock, NULL, NULL); if (insock < 0) { perror("Error accepting connection"); exit(-1); } MakeNonBlocking(insock); int s = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, insock, &event); if (s < 0) { perror("Epoll error adding accepted connection"); exit(-1); } printf("Connection processed.\n"); } int main(void) { int sock, efd, n; struct sockaddr_un addr; struct epoll_event event; struct epoll_event *events; char buf[1024]; if ((sock = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { perror("Error creating socket."); exit(-1); } addr.sun_family = AF_UNIX; strncpy(addr.sun_path, kSocketFile, sizeof(addr.sun_path) - 1); if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) == -1) { perror("Error binding name to socket"); exit(-1); } if (listen(sock, SOMAXCONN) < 0) { perror("Error listening on socket"); exit(-1); } MakeNonBlocking(sock); if ((efd = epoll_create1(0)) < 0) { perror("Epoll initialization error"); exit(-1); } event.data.fd = sock; event.events = EPOLLIN; if (epoll_ctl(efd, EPOLL_CTL_ADD, sock, &event) < 0) { perror("Epoll error adding socket"); exit(-1); } events = (struct epoll_event*) calloc(kMaxEvents, sizeof(event)); if (!events) { perror("Error allocating event buffers"); exit(-1); } while(1) { printf("Calling epoll_wait\n"); if ((n = epoll_wait(efd, events, kMaxEvents, -1)) == -1) { perror("epoll_wait failure"); exit(-1); } for (int i = 0; i < n; ++i) { printf("Checking event for fd = %d\n", events[i].data.fd); if (sock == events[i].data.fd) { AcceptConnections(sock, efd); continue; } int count = read(events[i].data.fd, buf, 100); if (count == 0) { close(events[i].data.fd); } write(1, buf, count); } } free(events); close(efd); close(sock); unlink(kSocketFile); return 0; } When I run the server and connect to the client I get: Calling epoll_wait Checking event for fd = 3 Connection processed. Calling epoll_wait Checking event for fd = 3 Error accepting connection: Resource temporarily unavailable In other words, I see two events on the listening socket. Any ideas? A: To fix, change AcceptConnections to: void AcceptConnections(int sock, int epoll_fd) { struct epoll_event event; event.events = EPOLLIN; int insock = accept(sock, NULL, NULL); if (insock < 0) { perror("Error accepting connection"); exit(-1); } // This is the important change. event.data.fd = insock; MakeNonBlocking(insock); int s = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, insock, &event); if (s < 0) { perror("Epoll error adding accepted connection"); exit(-1); } printf("Connection processed.\n"); } epoll is sometimes funny... The issue is with the way you register the event in AcceptConnections. epoll accepts two different fd values, one in event.data.fd (user opaque data value) and the other in the beginning of the epoll_ctl function call (the fd controlling the event). The event.data.fd can be anything, and it's the actual data you read in your event loop... ... in your original code, you set it to the listening socket instead of the client socket. So, when the client socket has data ready to be read, an event is raised with event.data.fd pointing at the listening socket instead of the client socket. Since you don't clear the event (for the client socket), it's repeatedly raised with the data you set (the listening socket fd). Good Luck!
{ "pile_set_name": "StackExchange" }
Q: opengl texture filtering low quality On my windows machine I see no difference between next settings: glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); and glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); and both are of quite bad quality. Am I missing some settings in pipeline? And if this is some kind of oddity what are my options to overcome this by the means of opengl without using custom scaling? Don't sure about windows tag. ) A: For minifictation, you likely want to enable mipmapping. See GL_LINEAR_MIPMAP_LINEAR, otherwise you will get very noticeable aliasing in high frequency textures, when you zoom in more than 2x. Of course, you need to generate mipmaps, do use this!
{ "pile_set_name": "StackExchange" }
Q: How to find which method calls currently selected method in Eclipse? In Eclipse, when you click on a method name and press the F3 button, it takes you to that method. How can I do the reverse of this? I have a method that's overloaded (probably about 12 different instances of it), and I would like to quickly find if this particular one is being called from anywhere else. I know you can click on the method, press Ctrl+ H, and Search for this Method in the Workspace. Is there a simpler keyboard shortcut for this? A: Click on the method and press Ctrl+Shift+G to perform a Search for References in Workspace. A: Ctrl+Alt+H opens the Call Hierarchy, which sounds like what you're looking for.
{ "pile_set_name": "StackExchange" }
Q: Comprobar checkbox marcaados con un atributo similar tengo una pequeña duda. Quiero saber como hago para impedir que un checkbox se pueda marcar cuando hay otro checkbox marcado con una caracteristica similar. Por ejemplo: Tengo el siguiente codigo: <td> <label for="check1"> Valor1 <input id="check1" type="checkbox" serial="1324" /> </label> <label for="check2"> Valor2 <input id="check2" type="checkbox" serial="1324" /> </label> </td> Lo que quiero hacer es que si por ejemplo yo tengo el #check1 marcado, me muestre una alerta al intentar marcar el #check2 ya que tiene el mismo serial que el #check1 La forma en que estoy haciendolo ahora es con el siguiente codigo : $(this).closest("td").find(":checkbox:not(:checked)").prop("disabled", $(this).is(":checked")); Que lo que hace es que me deshabilita el siguiente checkbox dentro del pero no me funciona de manera optima ya que pueden haber otros inputs dentro del mismo Espero puedan ayudarme, muchas gracias de antemano A: Intenta lo siguiente: var $this = $(this); var prop = $this.attr('serial'); $this.closest("td").find(":checkbox:not(:checked)[serial="+prop+"]").prop("disabled", $(this).is(":checked")); Si deseas mostrar una alerta si ya existe uno marcado con el mismo serial, puedes probar lo siguiente: var $this = $(this); var prop = $this.attr('serial'); var marcadoYa = $this.closest("td").find(":checkbox:checked[serial="+prop+"]").length; if (marcadoYa) { alert('Ya se ha seleccionado otra opción con el serial: '+prop); $this.prop('checked', false); }
{ "pile_set_name": "StackExchange" }
Q: Linear Operators, Representative Matrices and Change of Basis This is a follow up to a previous question, Change of Basis and Row Operations. I'm making this concrete to make it a bit easier to write up, but I'm actually interested in the more general case. Given a linear operator $T:R^3 \rightarrow R^2$ and ordered bases' $B=(b_1,b_2,b_3)$ and $C=(c_1, c_2)$. Let's say I have the images of the basis vectors from $B$, but I don't have any explicit formula for $T$. Now to get the representative matrix I would just take the coordinates of each image and put them in the appropriate columns like so: $T=[T]^B_C=\begin{bmatrix} [T(b_1)]_C & [T(b_2)]_C & [T(b_3)]_C \end{bmatrix} $ So here's the follow up question. Let's say I want to convert to new bases without calculating a change of basis matrix and applying it. Assume that the new input basis can be easily arrived at via elementary operations on $B$. For instance $B'=(b_1+2b_3, b3, b2)$ So I should be able to take: \begin{bmatrix} b_1 & T(b_1) \\ b_2 & T(b_2) \\ b_3 & T(b_3) \end{bmatrix} perform row operations like so: \begin{bmatrix} b_1+2b_3 & T(b_1)+2T(b_3) \\ b_3 & T(b_3) \\ b_2 & T(b_2) \end{bmatrix} Now I can just transpose the right hand side and take the new coordinate vectors and I've got the new representative matrix: $T=[T]^{B'}_C=\begin{bmatrix} [T(b_1)+2T(b_3)]_C & [T(b_3)]_C & [T(b_2)]_C \end{bmatrix} $ Also, I think I can get the explicit formula for $T$ according to the new base $B'$ by adding the rows of the row oriented matrix that I did the operations on. So is all this generally correct? When is it a good idea? A: I was just writing up notes for this in connection with a section on Smith Normal Form in my abstract algebra course. I'll summarize the results here. Row operations on the matrix change the input basis and column operations on the matrix change the output basis. First, let $\{u_1, u_2, \ldots, u_n\}$ denote the input basis. Row operation: $r_i \to r_i + k r_j$. Effect: Replace $u_j$ with $u_j - k u_i$. (Note that the $i$ and $j$ switch, and there is a sign change.) Row operation: $r_i \leftrightarrow r_j$. Effect: Swap $u_i$ and $u_j$. Row operation: $r_i \to k r_i$, where $k$ is a unit. Effect: Replace $u_i$ with $k^{-1} u_i$. Next, let $\{v_1, v_2, \ldots, v_m\}$ be the output basis. Column operation: $c_i \to c_i + k c_j$. Effect: Replace $v_i$ with $v_i - k v_j$. (Here there's just a sign change.) Column operation: $c_i \leftrightarrow c_j$. Effect: Swap $v_i$ and $v_j$. Column operation: $c_i \to k c_i$, where $k$ is a unit. Effect: Replace $v_i$ with $k^{-1} v_i$. Actually, for Smith Form if you know the Smith form and either the final input basis or the final output basis, you can find the other basis easily. All of this assumes you're doing the ``easy'' case of a Euclidean domain; you need a fourth type of operation over a PID.
{ "pile_set_name": "StackExchange" }
Q: Seq.generate_using is MIA I'm trying to use the Seq.generate_using function but unfortunately, I don't seem to be able to find it. I thought it would be living here: Microsoft.FSharp.Collections.Seq.generate_using But it doesn't. I am getting the error listed below. C:\Users\Owner\Documents\Visual Studio 2008\Projects\fsharp1\Program.fs(54,63): error FS0039: The value, constructor, namespace or type 'generate_using' is not defined. A construct with this name was found in FSharp.PowerPack.dll, which contains some modules and types that were implicitly referenced in some previous versions of F#. You may need to add an explicit reference to this DLL in order to compile this code. A: According to the Sept 2008 CTP Release Notes: The F# library is split into two components. FSharp.Core.dll: Contains the core F# libraries, which will be stabilized and versioned infrequently. FSharp.PowerPack.dll: Contains additional useful F# libraries and tools which will version more frequently, and allow continued innovation on top of the core F# language and libraries. Some methods in the Seq module were moved into the FSharp.PowerPack assembly, so you can only get those methods by doing the following: If you're using Visual Studio, open your Solution Explorer, right-click on the project file, choose "Add Reference", and add "FSharp.PowerPack.dll". If you're using a script file or fsi, then type #r "FSharp.PowerPack";; to load the assembly. Now you should be able to call Seq.generate_using.
{ "pile_set_name": "StackExchange" }
Q: Maximum font size a page can render What is the maximum font size that can be rendered in a web page? Does it depend on the machine, or the application (browser)? A: It differs from browser to browser.For example Mac/IE4+ doesn't render fonts specified >255px.Opera 5 freaks after 510px.Mozilla appears to be able to handle values up to 9362px, which just happens to be Netscape 4's limit as well. A: Yes. Every device has some set of fonts and font sizes it supports. For a desktop computer both sets are very large, but for a phone or other small device, the sets may be fairly limited. For a device with a text-only screen, there might only be one font at one size.
{ "pile_set_name": "StackExchange" }
Q: PyQt set enabled property of a row of QComboBox How can I set the enabled property of a row of a QComboBox? I want it to have some disabled and some enabled rows. A: Here is a working example of a QComboBox, where items 1 and 4 (as specified in the list disable) are disabled. I used this example. See also the documentation for the setData method. from PyQt4 import QtCore, QtGui import sys class Foo(QtGui.QMainWindow): def __init__(self): QtGui.QMainWindow.__init__(self) items = ['foo', 'bar', 'yib','nuz', 'pip', 'rof'] cb = QtGui.QComboBox(self) for i in items: cb.addItem(i) disable = [1,4] for i in disable: j = cb.model().index(i,0) cb.model().setData(j, QtCore.QVariant(0), QtCore.Qt.UserRole-1) if __name__ == "__main__": app = QtGui.QApplication([]) foobar = Foo() foobar.show() sys.exit(app.exec_())
{ "pile_set_name": "StackExchange" }
Q: Why is the energy of a particle in both a 2D and 3D box proportional to $\frac{1}{L^2}$? The energy of a particle in a 2D and 3D box is given by $$E= \frac{n^2 \hbar^2 \pi^2}{2 m L^2}$$ where $L$ is the length of the square/cubic box. I would have expected $L^2$ for 2D and $L^3$ for 3D. Why is it $L^2$ for both? A: For a particle in a box of size $L$, $L$ is the only lengthscale, thus the energy has to go like $\frac{\hbar^2}{ mL^{2}}$ by dimensional analysis, in any dimensions. Same thing in 1D too.
{ "pile_set_name": "StackExchange" }
Q: Is there a way to put a client side generated file in the browser's cache? This is kind of a shot-in-the-dark question, but I'm going to ask it anyway -- to satisfy my curiosity. Is there a way to put a client-side generated file in the browser's cache? Let's say for instance that I want to create a little json.txt file of the user's selections, and next time the page is loaded I can perhaps do an ajax get that would produces the file from cache? I'm trying to avoid HTML local storage for the time being only because I may want to use that for something else. Edit: I missed one point: let's assume I need to store something like 400kb from this file generated on the client -- yes I know this is a lot for "user's selections". A: HTML5 can do this in some browsers, you can read about it here - http://www.html5rocks.com/en/tutorials/offline/storage/ Google also tried something like this as well called Gears but have abandoned the project for the native HTML5 versions.
{ "pile_set_name": "StackExchange" }
Q: Find Gridview ID from within its RowCommand event I have three GridViews whose IDs are: grdvwFilteredNo1, grdvwFilteredNo2, grdvwFilteredNo3 each with its own RowCommand event (each fired off by a LinkButton, on a row) grdvwFilteredNo1_RowCommand(object sender, GridViewCommandEventArgs e) grdvwFilteredNo2_RowCommand(object sender, GridViewCommandEventArgs e) grdvwFilteredNo3_RowCommand(object sender, GridViewCommandEventArgs e) I'm looking to consolidate code by having all three Gridviews call the same RowCommand event. (The event code for all three is the same, except for this line where I identify the gridview by it's ID. Here's the line from the first event; Int32 intSelectedEEid = (Int32)grdvwFilteredNo1.DataKeys[rowIndex].Values["EmployeeID"];) I was thinking I could use a variable instead of the gridview ID, but I can't seem to grab the gridview ID. Using this GridView gView = ((Control)e.CommandSource).Parent.Parent as GridView; gView.ID comes back null. I was thinking the parent of the LinkBtn was the row and the parent of the row was the gridview. How do I find the gridview id from within its RowCommand event? Thanks for the help. A: To reach the GridView from the RowCommand event you should use something like this GridViewRow row = ((e.CommandSource as LinkButton).NamingContainer) as GridViewRow; GridView grd = row.NamingContainer as GridView; Using Parent doesn't work because the parent of your LinkButton is probably not directly the GridViewRow but its ItemTemplate, instead the NamingContainer will walk the chain of the ancestors until it finds one that implements the INamingContainer interface.
{ "pile_set_name": "StackExchange" }
Q: Firebase Unity password authentication failed The creation of a user with email and password fails and I can't find the source of the problem. I'm using "Firebase Unity SDK" with the auth and database packages. I followed this tutorial on the Firebase web page. This is the C# code I use in my Unity project. using UnityEngine; using Firebase.Auth; public class FirebaseAuthEmail : MonoBehaviour { public string email = "[email protected]"; public string password = "abccbe123321"; void Start() { FirebaseAuth auth = FirebaseAuth.DefaultInstance; auth.CreateUserWithEmailAndPasswordAsync(email, password).ContinueWith( task => { if (!task.IsCanceled && !task.IsFaulted) { // User created Debug.Log("User created"); } else { // User creation failed Debug.Log("User creation failed"); } if (task.IsCanceled) { Debug.Log("Task canceled"); } if (task.IsFaulted) { Debug.Log("Task faulted"); } }); } } When I press the play button i get "User creation failed" and "Task faulted". I've successfully managed to add entries to the database but not to create an authenticated user. And yes I've enabled Email/Password in the Firebase console. Thanks in advance A: Firebase Auth doesn't work on Unity Editor. https://github.com/firebase/quickstart-unity/issues/3
{ "pile_set_name": "StackExchange" }
Q: How can you programmatically order categories in the Xceed PropertyGrid? As shown in the example here, what I'm trying to achieve is ordering categories in the Xceed PropertyGrid control. As that example shows (copied here for reference), you can specify this information at compile-time by adding attributes to the class, like so... [CategoryOrder("General", 1)] [CategoryOrder("Advanced", 2)] [CategoryOrder("Other", 3)] public class MyClass { [Category("General")] public string Property1 { get; set; } [Category("Advanced")] public int Property2 { get; set; } [Category("Other")] public double Property3 { get; set; } [Category("General")] public string Property4 { get; set; } [Category("Advanced")] public int Property5 { get; set; } [Category("Other")] public double Property6 { get; set; } } And it would appear in the PropertyGrid like this... What I'm trying to do however is set the CategoryOrderAttribute values at runtime. Here's what I'm trying, but it's not working... // Note: This gets executed *prior* to assignment to the PropertyGrid TypeDescriptor.AddAttributes(typeof(MyClass), new CategoryOrderAttribute("General", 1), new CategoryOrderAttribute("Advanced", 2), new CategoryOrderAttribute("Other", 3) ); Like I said, this doesn't work and the categories still appear in alphabetical order. Any idea why that doesn't work? A: Turns out there are two bugs in the source. One, they aren't overriding TypeID in CategoryOrderAttribute, and two, they aren't using TypeDescriptor.GetAttributes. I've submitted bugs for both... https://github.com/xceedsoftware/wpftoolkit/issues/1522
{ "pile_set_name": "StackExchange" }
Q: plot data have aready be statisticed with ggplot original data a = as.data.frame((cbind(c('a','a','b','a'),c(0,0,1,1)))) a V1 V2 1 a 0 2 a 0 3 b 1 4 a 1 plot a bar ggplot(data=a,aes(x=V1,fill=factor(V1))) + geom_bar() then i got this but if i convert the data to this a V1 V2 V2.number 1 a 0 2 2 a 1 1 3 b 1 1 i do this is becuse data is too big,i have to summary it how could i get a picture like before? A: Use column V2.number as y values and add argument stat="identity" to geom_bar(). ggplot(a,aes(V1,V2.number,fill=factor(V2)))+geom_bar(stat="identity")
{ "pile_set_name": "StackExchange" }
Q: Don't allow to select other option if selected specific value with select2 As you can see i have select box with the select2 (multiple) select feature, with some option like <option value="All"> All </option> <option value="[email protected]"> User 1</option> <option value="[email protected]"> User 2 </option> <option value="[email protected]"> User 3 </option> is that possible that if i choose the option All from the select box then select box dose't not allow me to choose the other option from the given options until and unless i remove it. I want to restrict the user to select either choose All or select the multiple users from the options. i am ready to use jQuery or javascript to achieve this. A: Working fiddle. You could set the value of select to All when the option All is presented : $("#my-select").select2(); $("#my-select").on('change', function(){ var selected = $(this).val(); if(selected != null) { if(selected.indexOf('All')>=0){ $(this).val('All').select2(); } } }) Hope this helps. $("#my-select").select2(); $("#my-select").on('change', function(){ var selected = $(this).val(); if(selected != null) { if(selected.indexOf('All')>=0){ $(this).val('All').select2(); } } }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.min.js"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.2/select2.css" rel="stylesheet"/> <select multiple id="my-select" style="width:300px"> <option value="All"> All </option> <option value="[email protected]"> User 1</option> <option value="[email protected]"> User 2 </option> <option value="[email protected]"> User 3 </option> </select>
{ "pile_set_name": "StackExchange" }
Q: Pass ID of current record to apex controller from Visualforce So I have a few issues that I don't know how to resolve. The first is when a button is pressed, I need to pass the current record id to method1. As seen below method1 is expecting an id and I do not know how to pass a argument from Visualforce. The second issue is once a value is returned from method1, if it is 0, call method2 (in apex class). How do I call an apex method from JS? Just as an FYI - I cannot change method1 as it is already in use. I realize I am doing a lot of extra work but this is because method1 is currently in prod. I wrote method2. Visualforce controller: <apex:page controller="customObject" extensions="apexClass"> <apex:form > <apex:commandButton action="{!method1}" value="aNumber" id="theButton"/> <!--NEED TO PASS IN ID OF CURRENT RECORD to method 1 --> <apex:actionFunction action="{!method2}"/> </apex:form> <script> if(value of method1 == 0) { call method2 //NO arguments required } else if(value of method1 == 1) { alert("Cannot do this!"); } else alert("error!"); </script> </apex:page> Apex class: Global class apexClass{ Public customObject(ApexPages.StandardController controller) { } WebService static Integer method1(Id someID) { if(everythings ok) return 0; return 1; } public pagereference method2() { try{ pagereference newPageRef=new pagereference('/one/one.app#/home'); newPageRef.setRedirect(true); return newPageRef; } catch(Exception ex1) { ApexPages.addMessages(ex1); return null; } } } A: There's no reason to go through all of this work, as far as I can tell. You could restructure your class as follows: public class apexClass{ Id recordId; Public customObject(ApexPages.StandardController controller) { recordId = controller.getId(); } public PageReference method1() { if(everythingIsOkay) { return new PageReference('/one/one.app#/home').setRedirect(true); } else { ApexPages.addMessage( new ApexPages.Message(ApexPages.Severity.ERROR, 'You cannot do this')); return null; } } } If you absolutely insist on using two methods, then you'd use a @RemoteAction for the initial call, followed by an actionFunction to redirect: <apex:page controller="customObject" extensions="apexClass"> <apex:form > <script> function methodCall1() { apexClass.method1('{!$CurrentPage.parameters.Id}', function(result, event) { if(event.status && result == 0) { method2(); } else { if(result == 1) { alert('Not allowed'); } } alert('Error'); } } </script> <apex:commandButton onclick="methodCall1(); return false;" value="aNumber" id="theButton"/> <apex:actionFunction name="method2" action="{!method2}"/> </apex:form> <script> if(value of method1 == 0) { call method2 //NO arguments required } else if(value of method1 == 1) { alert("Cannot do this!"); } else alert("error!"); </script> </apex:page> Global class apexClass{ Public customObject(ApexPages.StandardController controller) { } @RemoteAction static Integer method1(Id someID) { if(everythings ok) { return 0; } return 1; } public pagereference method2() { pagereference newPageRef=new pagereference('/one/one.app#/home'); newPageRef.setRedirect(true); return newPageRef; } This is probably the worst possible solution, and I'd recommend that you avoid it unless you absolutely need to.
{ "pile_set_name": "StackExchange" }
Q: fetchedResultsController not updating row one properly I'm testing a simple Core Data project with Entity "Customer" and attribute "name". I'm using a modified version of the Master Detail template; the Master contains a tableview of the names, and the detail is used to enter the name. In Master's prepareForSegue, I set Details' Customer object as follows: ... else if ([segue.identifier isEqualToString:@"Add Customer"]) { [[segue destinationViewController] setDelegate:self]; [[segue destinationViewController] setCust:(Customer *) [NSEntityDescription insertNewObjectForEntityForName:@"Customer"inManagedObjectContext:self.managedObjectContext]]; } Master's insertNewObject adds a generic name: ... [newManagedObject setValue:sender forKey:@"name"]; ... In Detail, the name is added through a delegate: - (IBAction)save:(UIBarButtonItem *)sender { self.cust.name = self.customerName.text; [self.delegate addNameController:self selectedSave:YES]; Master's delegate method: - (void)addNameController:(AddNameController *)controller selectedSave:(BOOL)save { if (!save) { [self.managedObjectContext deleteObject:controller.cust]; } NSError *error = nil; if (![self.managedObjectContext save:&error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } [self dismissViewControllerAnimated:YES completion:nil];} This all works fine and the tableview updates properly for all new name entries except any entry that, sort wise, becomes the first entry. In that case, although the name is added to the db, a blank entry is placed in the tableview's first row. I'm able to reveal the name by either tapping the Edit button or by adding a new name that sorts ahead of the invisible name. To get around this problem, I've forced a reload in Master: - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.tableView reloadData];} This seems like a bit of a hack to me. It was my understanding that Core Data would take care of properly updating the display in response to any content changes. Is there an issue with the way I'm implementing this or is this an idiosyncrasy with Core Data? Thanks. A: Actually, the table will have to be explicitly updated, unless you have a method linked to the NSFetchedResultsController delegate where you do this. (The delegate method would be controllerDidChangeContent:.) A more convenient and obvious way would be to do it right in your master's delegate callback when dismissing the detail view. This is not a "hack".
{ "pile_set_name": "StackExchange" }
Q: Lat Long won't show on Heatmap with ipyleaflet I'm displaying congestion on a map with ipyleaflet. For some reason I can't get a heatmap layer to show over the coordinate I have chosen. Unsure what it is I am doing wrong. from ipyleaflet import Map, Heatmap from random import uniform m = Map(center=(-37.814, 144.96332), zoom=11) heatmap = Heatmap( locations=[[(-37.735018, 144.894947)]], radius=20 ) m.add_layer(heatmap); m This is the code. To be clear - I'm trying to have the heat show at a certain detector which is at the location above (37.735018, 144.894947). Thanks! A: The locations attribute of a Heatmap layer is a list of lists. Each sublist contains [latitude, longitude, intensity]. Please take a look at the documentation and try the example from this page: https://ipyleaflet.readthedocs.io/en/latest/api_reference/heatmap.html. Your code should look like this for example: from ipyleaflet import Map, Heatmap from random import uniform m = Map(center=(-37.814, 144.96332), zoom=11) heatmap = Heatmap( locations=[ (-37.735018, 144.894947, 4), # lat, lng, intensity (-38, 145, 5), # lat, lng, intensity ], radius=20 ) m.add_layer(heatmap); m
{ "pile_set_name": "StackExchange" }
Q: How do I get values from list of object based on selected value in Wpf Updated with a simple example in the end I have a list of objects that are rendered into a canvas. This objects holds another object that are an base class public class FooBase() { } public class Foo1 : FooBase() { } public class Foo2 : FooBase() { public ICollection<Bar> BarList() { get;set; } } public class Bar { public BarIdentifier BarIdentifier {get; set;} public int Value1 {get; set;} public string Value2 {get; set; } } public class HolderClass() { public FooBase FooClass() { get; set; } public int PosX {get;set;} public int PosY {get;set;} } In my Model I also have an selection of an active Bar class. This is set by using a dropdown. I also have a List of HolderClasses public BarIdentifier SelectedBar {get;set;} public List<ValveSystemOverviewGridContent> HolderList {get;set;} In my markup/xaml I have this <ItemsControl ItemsSource="{Binding HolderList}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemContainerStyle> <Style TargetType="ContentPresenter"> <Setter Property="Canvas.Left" Value="{Binding Path=XPos, Mode=OneWay}" /> <Setter Property="Canvas.Top" Value="{Binding Path=YPos, Mode=OneWay}" /> </Style> </ItemsControl.ItemContainerStyle> </ItemsControl> and the datatemplates as this <UserControl.Resources> <DataTemplate DataType="{x:Type entities:Foo1 }" > <Border BorderBrush="Black" BorderThickness="1"> <StackPanel Orientation="Horizontal" > <Label Content="FooClass 1" /> </StackPanel> </Border> </DataTemplate> <DataTemplate DataType="{x:Type entities:Foo2 }"> <Border CornerRadius="4" Background="White" BorderThickness="2" BorderBrush="{DynamicResource NormalBorderBrush}" > <StackPanel Orientation="Vertical"> <Label Content="Foo Class 2" /> <Label Content="{Binding ????" /> </StackPanel> </Border> </DataTemplate> <DataTemplate DataType="{x:Type entities:HolderClass }"> <StackPanel Orientation="Horizontal" > <Label Content="This is Holder Class" FontWeight="Bold" /> <ContentControl Content="{Binding Path=FooClass}" /> </StackPanel> </DataTemplate> </UserControl.Resources> What I would like to do in the FooBar2 datatemplate is to get one of the items in BarList that matches to the SelectedBar. This would I do normally by using BarList.First(b => b.BarIdentifier.Id == modelView.SelectedBar.Id); Is there any way to accomplish this filter/selection in my data template and display the Value1 and Value2 of Bar in effective way? If I change the dropdown in main view I would like to display the Bar that matches that BarIdentifier Update with example As requested I tried to do a short example. Included a function GetCalcDataForCondition how to filter out the CalcData based on selected Condition. MainWindow.xaml.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace FilterSample { public class CalcData { public Condition Condition { get; set; } public int Diameter { get; set; } public string Name { get; set; } } public class Condition { public int Id { get; set; } public string Name { get; set; } } public class BaseClass { public string Name { get; set; } } class TagClass : BaseClass { } class ConnectionClass : BaseClass { public List<CalcData> CalcData { get; set; } } public class Holder { public int PosX { get; set; } public int PosY { get; set; } public BaseClass Content { get; set; } } /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public List<Condition> Conditions { get; set; } public List<Holder> Holders { get; set; } public int SelectedConditionId { get; set; } private void GenerateData() { Conditions = new List<Condition>(); Conditions.Add(new Condition() { Id = 1, Name = "Condition 1" }); Conditions.Add(new Condition() { Id = 2, Name = "Condition 2" }); Conditions.Add(new Condition() { Id = 3, Name = "Condition 3" }); Conditions.Add(new Condition() { Id = 4, Name = "Condition 4" }); Conditions.Add(new Condition() { Id = 5, Name = "Condition 5" }); Holders = new List<Holder>(); Holders.Add(new Holder() { PosX = 10, PosY = 10, Content = new TagClass() { } }); Holders.Add(new Holder() { PosX = 10, PosY = 110, Content = GenerateConnectionClass(1, Conditions) }); Holders.Add(new Holder() { PosX = 10, PosY = 210, Content = new TagClass() { } }); Holders.Add(new Holder() { PosX = 10, PosY = 310, Content = GenerateConnectionClass(2, Conditions) }); Holders.Add(new Holder() { PosX = 10, PosY = 410, Content = new TagClass() { } }); } private ConnectionClass GenerateConnectionClass(int index, List<Condition> conditions) { var conn = new ConnectionClass(); conn.Name = "Connection " + index; conn.CalcData = new List<CalcData>(); foreach (var c in conditions) { conn.CalcData.Add(new CalcData() { Condition = c, Name = "Calc values for condition " + c.Id, Diameter = c.Id * 100 }); } return conn; } private CalcData GetCalcDataForCondition(ConnectionClass conn, Condition condition) { return conn.CalcData.First(c => c.Condition.Id == condition.Id); } public MainWindow() { GenerateData(); SelectedConditionId = 1; InitializeComponent(); DataContext = this; } } } MainWindow.xaml <Window x:Class="FilterSample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:FilterSample" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <DataTemplate DataType="{x:Type local:TagClass }" > <Border BorderBrush="Black" BorderThickness="1"> <StackPanel Orientation="Horizontal" > <Label Content="Tag Class" /> </StackPanel> </Border> </DataTemplate> <DataTemplate DataType="{x:Type local:ConnectionClass }"> <Border CornerRadius="4" Background="White" BorderThickness="2" BorderBrush="{DynamicResource NormalBorderBrush}" > <StackPanel Orientation="Vertical"> <Label Content="Connection Class" /> <Label Content="HERE I WANT TO DISPLAY related CalcData.Name" /> </StackPanel> </Border> </DataTemplate> <DataTemplate DataType="{x:Type local:Holder }"> <StackPanel Orientation="Horizontal" > <Label Content="This is Holder Class" FontWeight="Bold" /> <ContentControl Content="{Binding Path=Content}" /> </StackPanel> </DataTemplate> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="50" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <StackPanel Orientation="Horizontal"> <Label Content="Select condition " Height="24" /> <ComboBox ItemsSource="{Binding Conditions}" SelectedValue="{Binding SelectedConditionId}" DisplayMemberPath="Name" SelectedValuePath="Id" Width="200" Height="24" /> </StackPanel> <ItemsControl ItemsSource="{Binding Holders}" Grid.Row="1"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemContainerStyle> <Style TargetType="ContentPresenter"> <Setter Property="Canvas.Left" Value="{Binding Path=PosX , Mode=OneWay}" /> <Setter Property="Canvas.Top" Value="{Binding Path=PosY, Mode=OneWay}" /> </Style> </ItemsControl.ItemContainerStyle> </ItemsControl> </Grid> </Window> A: Basically, you need some way to transfer your selected condition Id to the inner data templates. My suggestion: Make the DataTemplate for Holder depend on the selected condition (move it from resources into the content as <ItemsControl.ItemTemplate>) and create a UserControl for Holder. Add a SelectedConditionId to the usercontrol and assign it: <Window ...> <Grid x:Name="grid1"> <Grid.RowDefinitions> <RowDefinition Height="50" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <StackPanel Orientation="Horizontal"> <Label Content="Select condition " Height="24" /> <ComboBox x:Name="condSelector" ItemsSource="{Binding Conditions}" SelectedValue="{Binding SelectedConditionId}" DisplayMemberPath="Name" SelectedValuePath="Id" Width="200" Height="24" /> </StackPanel> <ItemsControl ItemsSource="{Binding Holders}" Grid.Row="1"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas /> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemContainerStyle> <Style TargetType="ContentPresenter"> <Setter Property="Canvas.Left" Value="{Binding Path=PosX , Mode=OneWay}" /> <Setter Property="Canvas.Top" Value="{Binding Path=PosY, Mode=OneWay}" /> </Style> </ItemsControl.ItemContainerStyle> <!-- Here it is --> <ItemsControl.ItemTemplate> <DataTemplate> <local:HolderControl DataContext="{Binding}" SelectedConditionId="{Binding ElementName=condSelector,Path=SelectedValue}"/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid> </Window> Move most of your things into the holder control and use its SelectedConditionId with a MultiBinding to get the selected CalcData: <UserControl .... x:Name="uc1"> <UserControl.Resources> <local:SelectedCalcDataConverter x:Key="calcDataSelector"/> <DataTemplate DataType="{x:Type local:TagClass }" > <Border BorderBrush="Black" BorderThickness="1"> <StackPanel Orientation="Horizontal" > <Label Content="Tag Class" /> </StackPanel> </Border> </DataTemplate> <DataTemplate DataType="{x:Type local:ConnectionClass }"> <Border CornerRadius="4" Background="White" BorderThickness="2" BorderBrush="{DynamicResource NormalBorderBrush}" > <StackPanel Orientation="Vertical"> <StackPanel.DataContext> <MultiBinding Converter="{StaticResource calcDataSelector}" Mode="OneWay"> <Binding Path="CalcData"/> <Binding ElementName="uc1" Path="SelectedConditionId"/> </MultiBinding> </StackPanel.DataContext> <Label Content="Connection Class" /> <!--Label Content="HERE I WANT TO DISPLAY related CalcData.Name" /--> <Label Content="{Binding Name}"/> </StackPanel> </Border> </DataTemplate> </UserControl.Resources> <Grid> <StackPanel Orientation="Horizontal" > <Label Content="This is Holder Class" FontWeight="Bold" /> <ContentControl Content="{Binding Path=Content}" /> </StackPanel> </Grid> </UserControl> Code behind: public partial class HolderControl : UserControl { public HolderControl() { InitializeComponent(); } public int? SelectedConditionId { get { return (int?)GetValue(SelectedConditionIdProperty); } set { SetValue(SelectedConditionIdProperty, value); } } // Using a DependencyProperty as the backing store for SelectedConditionId. This enables animation, styling, binding, etc... public static readonly DependencyProperty SelectedConditionIdProperty = DependencyProperty.Register("SelectedConditionId", typeof(int?), typeof(HolderControl), new FrameworkPropertyMetadata()); } And the converter: public class SelectedCalcDataConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var items = values[0] as IEnumerable<CalcData>; var selectedId = values[1] as int?; if (items != null) { var result = items.FirstOrDefault(x => x.Condition.Id == selectedId); return result; } return null; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } There are other approaches to transport the selected ID around, but this one is relatively easy to understand.
{ "pile_set_name": "StackExchange" }
Q: How can I check if element is json object or json array in android? i want to access AmenityCodes you can see in the image for 0 position Amenity Codes is Array but on 49 positiin is json object so how to chek this is object or json array MyActivity.java for(int r=0;r<results.length();r++) { HashMap<String, String> map = new HashMap<String, String>(); hotelrating=results.getJSONObject(r).get(TAG_STARRATING).toString(); deeplink=results.getJSONObject(r).get(TAG_HOTELDEEPLINK).toString(); JSONArray amenityarray=results.getJSONObject(r).getJSONArray(TAG_AMENITYCODES); Log.e("Amenitiescode","-->"+amenityarray); } A: Replace: JSONArray amenityarray=results.getJSONArray(r); With: JSONArray amenityarray=results.getJSONObject(r).getJSONArray("AmenityCodes");
{ "pile_set_name": "StackExchange" }
Q: How do you access the element HTML from within an Angular attribute directive? The Angular docs provide an example for creating an attribute directive that changes the background color of an element: https://angular.io/docs/ts/latest/guide/attribute-directives.html <p myHighlight>Highlight me!</p> import { Directive, ElementRef } from '@angular/core'; @Directive({ selector: '[myHighlight]' }) export class HighlightDirective { constructor(el: ElementRef) { el.nativeElement.style.backgroundColor = 'yellow'; } } Can I also use el.nativeElement to get the content of the element (e.g. Highlight me!), modify this and update the element? A: So actually, my comment that you should do a console.log(el.nativeElement) should have pointed you in the right direction, but I didn't expect the output to be just a string representing the DOM Element. What you have to do to inspect it in the way it helps you with your problem, is to do a console.log(el) in your example, then you'll have access to the nativeElement object and will see a property called innerHTML. Which will lead to the answer to your original question: let myCurrentContent:string = el.nativeElement.innerHTML; // get the content of your element el.nativeElement.innerHTML = 'my new content'; // set content of your element Update for better approach: Since it's the accepted answer and web workers are getting more important day to day (and it's considered best practice anyway) I want to add this suggestion by Mark Rajcok here. The best way to manipulate DOM Elements programmatically is using the Renderer: constructor(private _elemRef: ElementRef, private _renderer: Renderer) { this._renderer.setElementProperty(this._elemRef.nativeElement, 'innerHTML', 'my new content'); } Edit Since Renderer is deprecated now, use Renderer2 instead with setProperty Update: This question with its answer explained the console.log behavior. Which means that console.dir(el.nativeElement) would be the more direct way of accessing the DOM Element as an "inspectable" Object in your console for this situation. Hope this helped. A: I suggest using Render, as the ElementRef API doc suggests: ... take a look at Renderer which provides API that can safely be used even when direct access to native elements is not supported. Relying on direct DOM access creates tight coupling between your application and rendering layers which will make it impossible to separate the two and deploy your application into a web worker or Universal. Always use the Renderer for it will make you code (or library you right) be able to work when using Universal or WebWorkers. import { Directive, ElementRef, HostListener, Input, Renderer } from '@angular/core'; export class HighlightDirective { constructor(el: ElementRef, renderer: Renderer) { renderer.setElementProperty(el.nativeElement, 'innerHTML', 'some new value'); } } It doesn't look like Render has a getElementProperty() method though, so I guess we still need to use NativeElement for that part. Or (better) pass the content in as an input property to the directive. A: This is because the content of <p myHighlight>Highlight me!</p> has not been rendered when the constructor of the HighlightDirective is called so there is no content yet. If you implement the AfterContentInit hook you will get the element and its content. import { Directive, ElementRef, AfterContentInit } from '@angular/core'; @Directive({ selector: '[myHighlight]' }) export class HighlightDirective { constructor(private el: ElementRef) { //el.nativeElement.style.backgroundColor = 'yellow'; } ngAfterContentInit(){ //you can get to the element content here //this.el.nativeElement } }
{ "pile_set_name": "StackExchange" }