text
stringlengths
175
47.7k
meta
dict
Q: OCP: Which two are true about LGWR? A. LGWR always writes to the redo logs each time a COMMIT occurs. B. LGWR always writes to the redo logs each time a ROLLBACK occurs. C. LGWR never writes a single COMMIT to the redo logs. D. LGWR may write to the redo logs when DBWR writes a dirty buffer. E. Multiple COMMITs can be written by LGWR in the same write request. F. LGWR always writes to the redo logs when DBWR writes a dirty buffer. The answer is DE. But why? Why A and F is wrong? A: Why A and F is wrong? It's not obvious, but the Oracle Concepts guide does have explanations. You should check it out. Anyway.... A. LGWR always writes to the redo logs each time a COMMIT occurs. A user committing a transaction is one of the things which triggers LGWR to write to the redo log. So it might seem that A is correct. But the Concept Guide says: "When activity is high, LGWR can use group commits". If several users commit their transactions while LGWR is still writing to the redo log those commits are kept in the redo buffer and then all of them are written when LGWR frees up. So, there isn't one write for every commit. That's why E is correct. F. LGWR always writes to the redo logs when DBWR writes a dirty buffer. The Concept Guide says: "Before DBW can write a dirty buffer, the database must write to disk the redo records associated with changes to the buffer (the write-ahead protocol). If DBW discovers that some redo records have not been written, it signals LGWR to write the records to disk, and waits for LGWR to complete before writing the data buffers to disk." So F is not true because the LGWR does not always have to write when DBWR writes, just sometimes. That's why D is correct.
{ "pile_set_name": "StackExchange" }
Q: Carrying remote VLAN via 2 routers to the local gateway I have a serverA (192.168.15.1) from site A and VLAN is 15, however the VLAN 15 gateway is set at site B (192.168.15.254). There are two ISP routers as a metro role to connect each other by subnet 10.0.0.0/30. My question is how can I get past those two routers? Could any one give an example to accomplish this? Thanks. PS. I can ping from serverA (192.168.15.1) to an interface f0/0@R1(10.0.0.1), no more further. A: You can use Ether in IP, defined in RFC 3398 to tunnel ethernet through IP, if you equipment supports it. It's similar to the VxLAN approach, but a little simpler and older. If you don't have those and it's desperate, you could think about proxy ARP. It is really not recommended. Do you have a particular reason to bridge like this? I'd suggest you strongly consider renumbering so you can just use ordinary IP routes. Perhaps you are nearly there already, if 192.168.15.0/25 is left and 192.168.15.128/25 is right? Renumbering R1 f0/1 (.126?), change masks, add routes to R1 and R2. A: You can use VxLAN, defined in RFC7348, to span a VLAN onto different sites. Basically it encapsulates a VLAN into IP. This off course add some overhead, and your routers at each endpoint need to support VxLAN
{ "pile_set_name": "StackExchange" }
Q: Why does は refer to a particular rather than general in some cases? The sentence I am asking about is the following [魚]{さかな}が[好]{す}きじゃない[人]{ひと}は、[肉]{にく}が[好]{す}きだ 」 Person who does not like fish like meat Source: Tae Kim's Guide to Learning Japanese My understanding, which is probably flawed in some aspect, is that は after 「[魚]{さかな}が[好]{す}きじゃない[人]{ひと}」 should make the sentence mean "People (in general) who do not like fish like meat", since は would mean in general as opposed to a particular occurrence (が). How, then, would the general form be conveyed (i.e. "People (in general) who do not like fish like meat")? A: You are correct and that website is incorrect on this matter. Upon hearing/reading the sentence: 「​魚 {さかな} ​が​好 {す} ​きじゃない​人 {ひと} ​は、​肉 {にく} ​が​好 {す} ​きだ。 」 Practically all Japanese-speakers will take the 「人」 to mean "people in general". It is just extremely unnatural to form that sentence when the speaker/writer is referring to one particular person. To alter the sentence so it talks about a particular individual, one could say: 「魚が好きじゃない〇〇さんは、肉が好きだ。」 or more naturally, 「〇〇さんは、魚は好きじゃないけど、肉は好きだ。」←Uses a pair of the contrastive 「は's」.
{ "pile_set_name": "StackExchange" }
Q: Comment traduire « learning from others » / « to learn from others » ? J'ai récemment écrit dans une rédaction: J'aime apprendre des autres. Ma prof l'a encerclé, disant « reformuler ». Franchement je n'arrive pas à comprendre pourquoi ça ne marche pas. L'anglais est ma première langue donc peut-être j'essaie de traduire directement de l'anglais. Ce que je voulais dire était (dans le contexte de l'éducation): I like learning from other people. La seule autre traduction qui me parait possible est: J'aime apprendre des autres gens. ou bien J'aime apprendre des autres personnes. A: Apprendre des autres se dit en français, est tout à fait correct et n'est pas ressenti comme une traduction. Quelques exemples : Extrait d'un livre paru en 2009 : Il s'agit d'apprendre ensemble, d'apprendre des autres, d'apprendre aux autres dans un processus d'interaction. Une revue en formation des adultes a fait paraître un numéro qui s'intitulait Apprendre des autres. Un article de journal : Apprendre des autres et leur communiquer son savoir. Une phrase souvent citée de Philippe Meirieu (chercheur et écrivain français spécialiste des sciences de l'éducation) : apprendre des autres est nécessaire parce que nous ne pouvons pas recréer le monde chacun à notre tour... Ceci dit tu pourrais essayer de jouer sur « les autres » et de voir si « j'aime apprendre d'autrui » plaît plus à ta professeure.
{ "pile_set_name": "StackExchange" }
Q: Javascript/jQuery : Slide image based on click I have 3 images. I would like to slide the image based on click. Image should be slide to left side of the div in the phone. $( document ).ready(function() { $('#image1').click( function (){ }); }); .phone_contain_div{ position:relative; } .phone_contain_div .image_div{ position:absolute; border: thin #000 solid; top: 16%; bottom: 0; left: 12.7%; right: 0; width: 46%; height: 64.4%; } .phone_contain_div .image_div img{ max-width:100%; max-height:100%; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="image1"> Image 1</div> <div id="image2"> Image 2</div> <div id="image3"> Image 3</div> <div class="phone_contain_div"> <img src="https://i.imgur.com/pzG9Elb.png"> <div class="image_div"> <img src="https://i.imgur.com/PtuiQo8.jpg"> <img src="https://i.imgur.com/fCOoKNU.jpg"> <img src="https://i.imgur.com/rm3BCnn.jpg"> </div> </div> Any help would be great. Thank You. A: This should help you get started. Added some css transition. $(document).ready(function() { $('.image_click .image').click(function() { $(this).siblings('.image').removeClass('active'); $(this).addClass('active'); $('.image_div').find('img').css('left', '100%'); $('.image_div').find('img').eq($(this).index()).css('left', '0'); }); }); .phone_contain_div { position: relative; } .phone_contain_div .image_div { position: absolute; border: thin #000 solid; top: 16%; bottom: 0; left: 12.7%; right: 0; width: 46%; height: 64.4%; overflow: hidden; } .phone_contain_div .image_div img { max-width: 100%; max-height: 100%; box-sizing: border-box; overflow: hidden; transition: all .2s; } .image_click>.image.active { color: red; } .image_div img { position: absolute; left: 100%; top: 0; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="image_click"> <div class="image"> Image 1</div> <div class="image"> Image 2</div> <div class="image"> Image 3</div> </div> <div class="phone_contain_div"> <img src="https://i.imgur.com/pzG9Elb.png"> <div class="image_div"> <img src="https://i.imgur.com/PtuiQo8.jpg"> <img src="https://i.imgur.com/fCOoKNU.jpg"> <img src="https://i.imgur.com/rm3BCnn.jpg"> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: TypeScript generated JS files encoding I am using VS2015 and latest TypeScript (1.6.3). The generated JavaScript and map files are generated in Windows-1252 encoding. The source TypeScript files are UTF-8 with BOM. I do need the generated files to be UTF-8 with BOM as well in order to pass Windows Store certification. Once I manually fix encoding of the generated files it's fine. But then I must include the generated files in source control and fix any newly added files. There doesn't seem to be any settings to change the encoding. Is this a bug in the compiler? The project type is jsproj, which doesn't seem to support tsconfig.json according to https://github.com/Microsoft/TypeScript/issues/3124 A: Once I manually fix encoding of the generated files it's fine. But then I must include the generated files in source control and fix any newly added files. Use the emitBOM and charset options in tsconfig.json: { "compileOnSave": true, "compilerOptions": { //... other stuff "emitBOM": true, "charset": "utf8" }, // ... } See schema : http://json.schemastore.org/tsconfig A: Unfortunately TypeScript is not fully supported in VS2015 in its current state (will update this answer if it changes in future). In some project types you can use tsconfig.json and the compiler will then use the config. To do that you need to edit your project file and add element TypeScriptModuleKind with amd or commonjs specified to property group of the config file. If your project type is for example jsproj there is not way to use the config file at the moment. Then you must must Gulp/Grunt or just simply call tsc manually fro command line. Or you can run a Powershell script to fix the encoding: (Get-ChildItem ".\" -Recurse -Include ('*.js', '*.js.map')) | Foreach-Object { (Get-Content $_.FullName) | Set-Content -Encoding UTF8 $_.FullName }
{ "pile_set_name": "StackExchange" }
Q: Failed to create an ipc port; access is denied in MySQL Workbench I'm getting an error when I try to open MySQL Workbench: "failed to create an ipc port : access is denied" This is the dialog shown by the error A: What if you give a reboot to your machine, and then try opening up your workbench instance. According to this, the above issue is due to a locked resource.
{ "pile_set_name": "StackExchange" }
Q: blank file while copying a file in python I have a function takes a file as input and prints certain statistics and also copies the file into a file name provided by the user. Here is my current code: def copy_file(option): infile_name = input("Please enter the name of the file to copy: ") infile = open(infile_name, 'r') outfile_name = input("Please enter the name of the new copy: ") outfile = open(outfile_name, 'w') slist = infile.readlines() if option == 'statistics': for line in infile: outfile.write(line) infile.close() outfile.close() result = [] blank_count = slist.count('\n') for item in slist: result.append(len(item)) print('\n{0:<5d} lines in the list\n{1:>5d} empty lines\n{2:>7.1f} average character per line\n{3:>7.1f} average character per non-empty line'.format( len(slist), blank_count, sum(result)/len(slist), (sum(result)-blank_count)/(len(slist)-blank_count))) copy_file('statistics') It prints the statistics of the file correctly, however the copy it makes of the file is empty. If I remove the readline() part and the statistics part, the function seems to make a copy of the file correctly. How can I correct my code so that it does both. It's a minor problem but I can't seem to get it. A: The reason the file is blank is that slist = infile.readlines() is reading the entire contents of the file, so when it gets to for line in infile: there is nothing left to read and it just closes the newly truncated (mode w) file leaving you with a blank file. I think the answer here is to change your for line in infile: to for line in slist: def copy_file(option): infile_name= input("Please enter the name of the file to copy: ") infile = open(infile_name, 'r') outfile_name = input("Please enter the name of the new copy: ") outfile = open(outfile_name, 'w') slist = infile.readlines() if option == 'statistics': for line in slist: outfile.write(line) infile.close() outfile.close() result = [] blank_count = slist.count('\n') for item in slist: result.append(len(item)) print('\n{0:<5d} lines in the list\n{1:>5d} empty lines\n{2:>7.1f} average character per line\n{3:>7.1f} average character per non-empty line'.format( len(slist), blank_count, sum(result)/len(slist), (sum(result)-blank_count)/(len(slist)-blank_count))) copy_file('statistics') Having said all that, consider if it's worth using your own copy routine rather than shutil.copy - Always better to delegate the task to your OS as it will be quicker and probably safer (thanks to NightShadeQueen for the reminder)!
{ "pile_set_name": "StackExchange" }
Q: Start and end date of a current month I need the start date and the end date of the current month in Java. When the JSP page is loaded with the current month it should automatically calculate the start and end date of that month. It should be irrespective of the year and month. That is some month has 31 days or 30 days or 28 days. This should satisfy for a leap year too. Can you help me out with that? For example if I select month May in a list box I need starting date that is 1 and end date that is 31. A: There you go: public Pair<Date, Date> getDateRange() { Date begining, end; { Calendar calendar = getCalendarForNow(); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH)); setTimeToBeginningOfDay(calendar); begining = calendar.getTime(); } { Calendar calendar = getCalendarForNow(); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); setTimeToEndofDay(calendar); end = calendar.getTime(); } return Pair.of(begining, end); } private static Calendar getCalendarForNow() { Calendar calendar = GregorianCalendar.getInstance(); calendar.setTime(new Date()); return calendar; } private static void setTimeToBeginningOfDay(Calendar calendar) { calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); } private static void setTimeToEndofDay(Calendar calendar) { calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 59); calendar.set(Calendar.MILLISECOND, 999); } PS: Pair class is simply a pair of two values. A: If you have the option, you'd better avoid the horrid Java Date API, and use instead Jodatime. Here is an example: LocalDate monthBegin = new LocalDate().withDayOfMonth(1); LocalDate monthEnd = new LocalDate().plusMonths(1).withDayOfMonth(1).minusDays(1); A: Try LocalDate from Java 8: LocalDate today = LocalDate.now(); System.out.println("First day: " + today.withDayOfMonth(1)); System.out.println("Last day: " + today.withDayOfMonth(today.lengthOfMonth()));
{ "pile_set_name": "StackExchange" }
Q: Conditional agent in Jenkins I'm trying to set a conditional agent in Jenkins defined through the branch such as: cloud = myconditional() pipeline { agent { kubernetes { cloud cloud } } and, the function myconditional is defined in a library /vars/myconditional.groovy def call() { def cloud = "clusterB" echo "Branch ${env.GIT_BRANCH}" if ("${env.GIT_BRANCH}" != "master") { echo "use clusterA" cloud = "clusterA" }else{ echo "use clusterB" } return cloud ... But I get Branch null. Other way using scm def getGitBranchName() { return scm.branches[0].name } def call() { def cloud = "clusterB" def branch = getGitBranchName() echo "Branch ${branch}" if (branch != "master") { echo "use clusterA" cloud = "clusterA" }else{ echo "use clusterB" } return cloud But I get: org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use method hudson.plugins.git.BranchSpec getName and i don't have permissions to change the Jenkins configuration. I try to print the environment vars but I get this: def call() { sh 'env > env.txt' sh 'cat env.txt' .... I have got: org.jenkinsci.plugins.workflow.steps.MissingContextVariableException: Required context class hudson.FilePath is missing My question is, how can i get the actual branch out of the pipeline{}? Thanks a lot A: If you are using Jenkins Multibranch Pipeline, you can obtain the branch name by using the following variable. env.BRANCH_NAME You can use the following conditional: if ("${BRANCH_NAME}" != "master" ) { ... } else { ... }
{ "pile_set_name": "StackExchange" }
Q: Search a file in sub folders When i try to search the zip file in sub-folders of "Input_Files", the command is not running after "\172.24.191.117\data1\NEW-ENDORSEMENTS\Backlog_checked\%J%\CLIENT-SUPPLIED\Backlog". I think the space is problem to get the path. Kindly check and clear. @echo off echo. set /p J=Enter Journal ID : set /p A=Enter Article ID : set "BaseDir=\\172.24.191.117\data1\NEW-ENDORSEMENTS\Backlog_checked\%J%\CLIENT-SUPPLIED\Backlog Transfer\Non EV articles\%J%%A%" For /f "delims=" %%A in (' Dir /B/S/A-D "%BaseDir%\*.zip" ^| Findstr /I "\\Input_Files\\[^\\]*\.zip$" ') Do start %%A pause A: Replace start %%A by start "" "%%A". DIR outputs the found file matching the pattern with full qualified file name (file path + file name + file extension) never enclosed in double quotes. So it is necessary to reference the file with embedding it in double quotes as done here with "%%A". The first double quoted string is interpreted by command START as optional title. For that reason a title must be explicitly specified to avoid interpreting the full qualified file name in " as title string. As the started application for opening the *.zip file is most likely a GUI application, an empty title string can be used with "" because no command process with a console window is opened in this case.
{ "pile_set_name": "StackExchange" }
Q: Controller is not detecting Model Here in my Project Controller is not detecting Model.Am using ASP.net MVC3 ,Visual Studio 2010 But my other projects are working as well.How can i rectify this. I have re-installed VS2010 2 times but its working for this project. Here is my Controller Code using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace OfficeAuto.Controllers { public class LoginController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(LoginModel model) { if (ModelState.IsValid) { if (DataAccess.DAL.UserIsValid(model.UserName, model.Password)) { FormsAuthentication.SetAuthCookie(model.UserName, false); return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError("", "Invalid Username or Password"); } } return View(); } public ActionResult FranchIndex() { return View(); } } } A: It's a simple mistake; not a big problem You didn't add your Model reference: using OfficeAuto.Models;
{ "pile_set_name": "StackExchange" }
Q: Javascript date time comparison returns false but branch stmt still executed I am confused with this Javascript behaviour. Check this code. var NoOfMonthsElapsed = 6; //Should be >= 1 and <= 12 var MsgURL = "about:blank"; var PopupTitle = "ContactInfoUpdate"; var OptionString = "height=165,width=400,menubar=0,toolbar=0,location=1,status=0,resizable=0,status=0,HAlign=center,top=300"; var lastUpdatedDate = crmForm.all.dxb_lastcontactinfoupdatedon.DataValue; //Reads a field with date value = 01 Jan 2010 if (lastUpdatedDate) { var month = lastUpdatedDate.getMonth(); var year = lastUpdatedDate.getYear(); var date = lastUpdatedDate.getDate(); month = month + NoOfMonthsElapsed; year = year + parseInt(month / 11); month = (month % 11); var today = new Date(); var showPopupAfterDate = new Date(); showPopupAfterDate.setYear(year); showPopupAfterDate.setMonth(month); var alertMsg = "LastUpdatedDate = "+ lastUpdatedDate + "\n" var alertMsg += "Today = "+ today + "\n" var alertMsg += "PopupAfterDate = "+ showPopupAfterDate + "\n" var alertMsg += "Today>showPopupAfterDate = "+ (today>showPopupAfterDate) + "\n" alert(alertMsg); if (today>showPopupAfterDate); { window.open(MsgURL, PopupTitle, OptionString); } } else { window.open(MsgURL, PopupTitle, OptionString); } // // It displays the following output // LastUpdatedDate = Wed May 18 20:56:00 UTC+0400 2011 Today = Fri May 18 20:23:49 UTC+0400 2011 PopupAfterDate = Fri Nov 18 20:23:49 UTC+0400 2011 Today>showPopupAfterDate = false Why today is shown as Fri May 18 2011... though May 18 2011 is Wed Why PopupAfterDate is shown as Fri Nov 18 2011... And Even though the dates comparission returns false; The window.open still get executed. A: Found the issue: if (today>showPopupAfterDate) //<-- remove the `;` { window.open(MsgURL, PopupTitle, OptionString); } Your code is running the if, stopping, then doing the next statement which is the window.open
{ "pile_set_name": "StackExchange" }
Q: WPF - Treeview selected item index I have a treeview panel. In the panel, there are several child nodes. Some of them are only a header. The way I create the treeview: treeviewpaneL.Items.Add(art); art.Items.Add(prt); some if statement.... TreeViewItem cldhdr = new TreeViewItem() { Header = "ChildNodes:" }; prt.Items.Add(cldhdr); TreeViewItem cld = new TreeViewItem() ....... ........ ..... cldhdr.Items.Add(cld); Treeview: Node1 ChildNodes: (This is header only. It appears if child node exists) Childnode1 Childnode2 childnode3 Node2 Node3 ChildNodes: Childnode1 Childnode2 childnode3 Node4 Node5 In my treeview there are also images in front of all nodes. It's a code driven treeview. In the xaml part i have only: <TreeView x:Name="treeviewpaneL" SelectedItemChanged="treeviewpaneL_SelectedItemChanged" > </TreeView> What I want to do is when I click on any of the treeview items, I need to get its index number. My code is: private void treeviewpaneL_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { int index = 0; ItemsControl parent = ItemsControl.ItemsControlFromItemContainer(prt); foreach (var _item in parent.Items) { if (_item == treeviewpaneL.SelectedItem) { selectedNodeIndex = index; MessageBox.Show(selectedNodeIndex.ToString()); break; } index++; } } With the code above, I can get the index of Node1,Node2,Node3, Node4 and Node5 as 0,1,2,3,4 What I want is to get the index numbers as: Node1 = 0 Childnode1 = 1 (Skipping the header) Childnode2 = 2 Childnode3 = 3 Node2 = 4 .... .... .... What am I missing? A: Here is the solution, first of all your "MyTreeViewItem" public class MyTreeViewItem :TreeViewItem { private int _index; public int Index { get { return _index; } set { _index = value; } } public MyTreeViewItem() : base() { } } and usage; MyTreeViewItem art = new MyTreeViewItem(); art.Header = "Node1"; art.Index = 1; MyTreeViewItem prt = new MyTreeViewItem(); prt.Header = "Child1"; prt.Index = 2; art.Items.Add(prt); treeviewpaneL.Items.Add(art); and event; private void treeviewpaneL_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { MyTreeViewItem selectedItem = e.NewValue as MyTreeViewItem; if (selectedItem != null) { MessageBox.Show("" + selectedItem.Index); } }
{ "pile_set_name": "StackExchange" }
Q: Return value from Oracle function using Mybatis I have looked at a number of StackOverflow questions on this issue but can't find one that makes any sense. This one comes closest but doesn't show how to get the return value from the function. Here's my mapper call: public Long callMyFunction(@Param("recordId") Long recordId, @Param("otherId") Long otherId, @Param("date") Date date, @Param("comments") String comments); Here's the mapper XML: <select id="callMyFunction" parameterType="map" statementType="CALLABLE" resultType="java.lang.Long"> { #{resultId,javaType=java.lang.Long,jdbcType=NUMERIC,mode=OUT} = call MYSCHEMA.MYPACKAGE.my_function( #{recordId,jdbcType=NUMERIC,mode=IN}, #{otherId,jdbcType=NUMERIC,mode=IN}, #{date,jdbcType=DATE,mode=IN}, #{comments,jdbcType=VARCHAR,mode=IN})} </select> The call works, but the return value (resultId) is always null. Can anybody spot the problem? A: If you want to return directly the result, then the SQL call must be: SELECT MYSCHEMA.MYPACKAGE.my_function(...) FROM DUAL If you want to keep with calling the function in the procedure call style, that means the result is an OUT parameter (you env declared it OUT). The minimum change would consist in adding a parameter to the mapper method signature: public Long callMyFunction(@Param("recordId") Long recordId, @Param("otherId") Long otherId, @Param("date") Date date, @Param("comments") String comments, @Param("resultIdContainer") Map<String, Long> resultIdContainer); In the XML: forget the resultType, this is for selects. And the call: { #{resultIdContainer.resultId, javaType=java.lang.Long,jdbcType=NUMERIC,mode=OUT} = call ... Not that I use here a map to contain the resutlId: an indirection is required: the function will write the parameter 'result' value somewhere you can read later (after your mapper call), you can also use a class with a resultId property.
{ "pile_set_name": "StackExchange" }
Q: VBA 2010 Add Query Table: Application-defined or Object-Defined Error If it were functioning properly, the following code would grab the name of a table from a textbox, concatenate it with 'describe ' and then put the results in a query table. As it stands, the code fails with 'Run Time Error 1004: Application-Defined or Object-Defined error' Private Sub cmdNew_Click() Dim TableName As String Dim NewSheet As Excel.Worksheet Dim ConnString As String Dim SQLStatement As String ConnString = ConnString = "DSN=REMOVED;UID=REMOVED;;DBQ= REMOVED;DBA=W;APA=T;EXC=F;FEN=T;QTO=T;FRC=10;FDL=10;LOB=T;RST=T;BTD=F;BNF=F;BAM=IfAllSuccessful;NUM=NLS;DPM=F;MTS=T;MDI=F;CSR=F;FWC=F;FBS=64000;TLO=O;MLD=0;ODA=F;" TableName = ActiveSheet.txtTableName.Text SQLStatement = "desc " & TableName Set NewSheet = Sheets.Add NewSheet.Name = TableName Set qry = NewSheet.QueryTables.Add(ConnString, NewSheet.Range("A1"), SQLStatement) qry.Refresh End Sub A: Assuming you are querying an Oracle DB, the DESC keyword is for sorting a column in descending order, try using the keyword DESCRIBE in full. If that doesn't work then run your query against the DB server outside of Excel, and see if it gives you a more helpful message?
{ "pile_set_name": "StackExchange" }
Q: How do you compare using .NET types in an NHibernate ICriteria query for an ICompositeUserType? I have an answered StackOverflow question about how to combine to legacy CHAR database date and time fields into one .NET DateTime property in my POCO here (thanks much Berryl!). Now i am trying to get a custom ICritera query to work against that very DateTime property to no avail. here's my query: ICriteria criteria = Session.CreateCriteria<InputFileLog>() .Add(Expression.Gt(MembersOf<InputFileLog>.GetName(x => x.FileCreationDateTime), DateTime.Now.AddDays(-14))) .AddOrder(Order.Desc(Projections.Id())) .CreateCriteria(typeof(InputFile).Name) .Add(Expression.Eq(MembersOf<InputFile>.GetName(x => x.Id), inputFileName)); IList<InputFileLog> list = criteria.List<InputFileLog>(); And here's the query it's generating: SELECT this_.input_file_token as input1_9_2_, this_.file_creation_date as file2_9_2_, this_.file_creation_time as file3_9_2_, this_.approval_ind as approval4_9_2_, this_.file_id as file5_9_2_, this_.process_name as process6_9_2_, this_.process_status as process7_9_2_, this_.input_file_name as input8_9_2_, gonogo3_.input_file_token as input1_6_0_, gonogo3_.go_nogo_ind as go2_6_0_, inputfile1_.input_file_name as input1_3_1_, inputfile1_.src_code as src2_3_1_, inputfile1_.process_cat_code as process3_3_1_ FROM input_file_log this_ left outer join go_nogo gonogo3_ on this_.input_file_token=gonogo3_.input_file_token inner join input_file inputfile1_ on this_.input_file_name=inputfile1_.input_file_name WHERE this_.file_creation_date > :p0 and this_.file_creation_time > :p1 and inputfile1_.input_file_name = :p2 ORDER BY this_.input_file_token desc; :p0 = '20100401', :p1 = '15:15:27', :p2 = 'LMCONV_JR' The query is exactly what i would expect, actually, except it doesn't actually give me what i want (all the rows in the last 2 weeks) because in the DB it's doing a greater than comparison using CHARs instead of DATEs. I have no idea how to get the query to convert the CHAR values into a DATE in the query without doing a CreateSQLQuery(), which I would like to avoid. Anyone know how to do this? UPDATE: I've been looking into trying to use Projections.SqlFunction() or formulas to accomplish this, but to no avail so far. Here's the code i have using SqlFunction(), but i get an NHibernate.QueryException : property does not map to a single column: FileCreationDateTime error: DateTime twoWeeksAgo = DateTime.Now.AddDays(-14); ICriteria criteria = Session.CreateCriteria<InputFileLog>() .Add(Restrictions.Gt(Projections.SqlFunction("to_date", NHibernateUtil.DateTime, Projections.Property(MembersOf<InputFileLog>.GetName(x => x.FileCreationDateTime))), twoWeeksAgo)) //.Add(Expression.Gt(MembersOf<InputFileLog>.GetName(x => x.FileCreationDateTime), DateTime.Now.AddDays(-14))) .AddOrder(Order.Desc(Projections.Id())) .CreateCriteria(typeof(InputFile).Name) .Add(Expression.Eq(MembersOf<InputFile>.GetName(x => x.Id), inputFileName)); I'm sure i'm doing something wrong here and it doesn't like it still anyway because FileCreationDateTime uses a custom ICompositeUserType which splits the .NET DateTime property into two Oracle SQL CHAR columns (see this StackOverflow question for details). A: I finally figure this out! here's the code (for some reason StackOverflow is making some of the methods names in the this first code snippet the syntax color of a type): IList<InputFileLog> list = null; DateTime twoWeeksAgo = DateTime.Now.AddDays(-14); IProjection datePropProj = DefaultStringFileCreationDateTimeType.GetFileCreationDateToDateSQLProjection(); IProjection timePropProj = DefaultStringFileCreationDateTimeType.GetFileCreationTimeToDateSQLProjection(); IProjection dateConstProj = DefaultStringFileCreationDateTimeType.GetFileCreationDateToDateSQLFunction(twoWeeksAgo); IProjection timeConstProj = DefaultStringFileCreationDateTimeType.GetFileCreationTimeToDateSQLFunction(twoWeeksAgo); ICriteria criteria = Session.CreateCriteria<InputFileLog>() .Add(Restrictions.Or(Restrictions.GtProperty(datePropProj, dateConstProj), Restrictions.And(Restrictions.EqProperty(datePropProj, dateConstProj), Restrictions.GeProperty(timePropProj, timeConstProj)))) .AddOrder(Order.Desc(Projections.Id())) .CreateCriteria(typeof(InputFile).Name) .Add(Expression.Eq(MembersOf<InputFile>.GetName(x => x.Id), inputFileName)); list = criteria.List<InputFileLog>(); And here's the methods i used to create the SQLProjections and SQLFunctions. i put them in my ICompositeUserType (DefaultStringFileCreationDateTime) that i used for the custom type mapping on the FileCreationDateTime property. public class DefaultStringFileCreationDateTime : ICompositeUserType { . . . public const string DotNetDateFormat = "yyyyMMdd"; public const string DotNetTimeFormat = "HH:mm:ss"; public const string DbDateFormat = "YYYYMMDD"; public const string DbTimeFormat = "HH24:MI:SS"; private const string _nullDateRepresentationInDb = "00000000"; public struct DatabaseFieldNames { /// <summary> /// File creation date column name. /// </summary> public const string FileCreationDate = "file_creation_date"; /// <summary> /// File creation time column name. /// </summary> public const string FileCreationTime = "file_creation_time"; } public static IProjection GetFileCreationDateToDateSQLProjection() { return ProjectionUtil.GetToDateSQLProjection(DatabaseFieldNames.FileCreationDate, DbDateFormat, NHibernateUtil.DateTime); } public static IProjection GetFileCreationTimeToDateSQLProjection() { return ProjectionUtil.GetToDateSQLProjection(DatabaseFieldNames.FileCreationTime, DbTimeFormat, NHibernateUtil.DateTime); } public static IProjection GetFileCreationDateToDateSQLFunction(DateTime dt) { return ProjectionUtil.GetToDateSQLFunction(dt, DotNetDateFormat, DbDateFormat); } public static IProjection GetFileCreationTimeToDateSQLFunction(DateTime dt) { return ProjectionUtil.GetToDateSQLFunction(dt, DotNetTimeFormat, DbTimeFormat); } } I was already using the consts DatabaseFieldNames struct for the PropertyNames member implementation, so I was able to reuse these hard-coded column names for the Projections i needed as well. Here's the Projection utility class where the generic to_date methods live: public class ProjectionUtil { public static IProjection GetToDateSQLProjection( string columnName, string dbToDateFormat, IType returnType) { return Projections.SqlProjection( string.Format("to_date({0}, '{1}') as {0}", columnName, dbToDateFormat), new string[] { columnName }, new IType[] { returnType }); } public static IProjection GetToDateSQLFunction( DateTime dt, string dotNetFormatString, string dbFormatString) { return Projections.SqlFunction( "to_date", NHibernateUtil.DateTime, Projections.Constant(dt.ToString(dotNetFormatString)), Projections.Constant(dbFormatString)); } } Finally, here's the Oracle SQL that NHibernate generates: SELECT this_.input_file_token as input1_9_2_, this_.file_creation_date as file2_9_2_, this_.file_creation_time as file3_9_2_, this_.approval_ind as approval4_9_2_, this_.file_id as file5_9_2_, this_.process_name as process6_9_2_, this_.process_status as process7_9_2_, this_.input_file_name as input8_9_2_, gonogo3_.input_file_token as input1_6_0_, gonogo3_.go_nogo_ind as go2_6_0_, inputfile1_.input_file_name as input1_3_1_, inputfile1_.src_code as src2_3_1_, inputfile1_.process_cat_code as process3_3_1_ FROM input_file_log this_ left outer join go_nogo gonogo3_ on this_.input_file_token=gonogo3_.input_file_token inner join input_file inputfile1_ on this_.input_file_name=inputfile1_.input_file_name WHERE ( to_date(file_creation_date, 'YYYYMMDD') > to_date(:p0, :p1) or ( to_date(file_creation_date, 'YYYYMMDD') = to_date(:p2, :p3) and to_date(file_creation_time, 'HH24:MI:SS') >= to_date(:p4, :p5) ) ) and inputfile1_.input_file_name = :p6 ORDER BY this_.input_file_token desc; :p0 = '20100415', :p1 = 'YYYYMMDD', :p2 = '20100415', :p3 = 'YYYYMMDD', :p4 = '18:48:48', :p5 = 'HH24:MI:SS', :p6 = 'LMCONV_JR' can't believe i got this one! i thought i was going to have to resort to an ISQLQuery for sure!
{ "pile_set_name": "StackExchange" }
Q: #define negative numbers? Simple question, but I cannot seem to find the answer. Is it okay to use #define to define a negative number, as in: #define kGravity -9.8 XCode is changing the 9.8 to the color of my numbers I have set (purple), but the - is being shown as the same color as the define statement (orange). Is this legal? Will it compile? A: Did you try it? It should work fine. However, I would encourage you to not use pre-processor macros, but instead use real constants. static const float kGravity = -9.8f; Preprocessor directives are a bit frowned upon, in general. Here's some more info on the subject: #define vs const in Objective-C A: It is absolutely legal to define negative constants with #define. What you discovered is most likely a bug in Xcode's code coloring, which will probably be fixed in one of the future revisions.
{ "pile_set_name": "StackExchange" }
Q: C libcurl force "Content-Type" I have the follwing C code with libcurl to upload a file to my webserver, almost ok the only problem I need the upload to be "Content-Type: application/vnd.ms-excel" but it gets "Content-Type: application/octet-stream", tried with headers but now luck. In PHP with curl is easy, I just do curl_setopt($ch, CURLOPT_POSTFIELDS, array("importfile" => "@".$file_path . ";type=application/vnd.ms-excel" and works ok. Any help? Ideas? #include <stdio.h> #include <string.h> #include <curl/curl.h> int main(int argc, char *argv[]) { CURL *curl; CURLcode res; struct curl_httppost *formpost=NULL; struct curl_httppost *lastptr=NULL; struct curl_slist *headerlist=NULL; static const char buf[] = "Expect:"; curl_global_init(CURL_GLOBAL_ALL); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "importfile", CURLFORM_FILE, "document.csv", CURLFORM_END); curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "action", CURLFORM_COPYCONTENTS, "upload", CURLFORM_END); curl = curl_easy_init(); headerlist = curl_slist_append(headerlist, buf); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://www.myhost.com/upload/upload.php"); if ( (argc == 2) && (!strcmp(argv[1], "noexpectheader")) ) curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headerlist); curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost); res = curl_easy_perform(curl); if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); curl_easy_cleanup(curl); curl_formfree(formpost); curl_slist_free_all (headerlist); } return 0; } Tried to add in the HEADER as "Content-Type: application/vnd.ms-excel" but is not right, I get: Content-Type: application/vnd.ms-excel in the headers but I need to have: ------WebbbbFormBoundaryXaI1UTNwqAyKWvLT Content-Disposition: form-data; name="importfile"; filename="document.csv" Content-Type: application/vnd.ms-excel instead I get: ------WebbbbFormBoundaryXaI1UTNwqAyKWvLT Content-Disposition: form-data; name="importfile"; filename="document.csv" Content-Type: application/octet-stream Thanks for help guys, answer is: curl_formadd(&formpost, &lastptr, CURLFORM_COPYNAME, "importfile", CURLFORM_FILE, "document.csv", CURLFORM_CONTENTTYPE, "application/vnd.ms-excel", CURLFORM_END); A: You're looking for curl_formadd's option CURLFORM_CONTENTTYPE.
{ "pile_set_name": "StackExchange" }
Q: To find out if a div has a scrollbar If a div is set as overflow:auto, how can I find out (using plain JS) if a scrollbar (Vertical / Horizontal) has been rendered? A: Check if clientHeight is smaller than scrollHeight.
{ "pile_set_name": "StackExchange" }
Q: Initialize 64 by 64 numpy of (0,0) tuples in python? Is it possible to create a numpy of any arbitrary data structure, for example tuples? If yes, how do I initialize it without writing it out? (Obviously, I don't want to write out 64 by 64 array) A: Another way: value = np.empty((), dtype=object) value[()] = (0, 0) a = np.full((64, 64), value, dtype=object) Some trickery is required here to ensure that numpy does not try to iterate the tuple, hence the initial wrapping in an object array
{ "pile_set_name": "StackExchange" }
Q: Configuration и xml Помогите, не могу разобраться. Я начал изучать Spring (IoC Concept), разобрал как можно конфигурировать бины через xml и отдельно через аннотации, но не пойму возможно ли создать бин в java-классе с аннотацией @Configuration и заполнить его поля, например, через сеттеры() в xml конфигурации? A: Пример конфигурирования самого бина непосредственно при его инициализации в контексте, и да - нет, Вы не сможете через сеттеры с помощью хмл конфигурировать бин @Bean @ServiceActivator(inputChannel = "tcpOutChannel") public TcpSendingMessageHandler tcpOut(AbstractServerConnectionFactory connectionFactory) { TcpSendingMessageHandler gateway = new TcpSendingMessageHandler(); gateway.setConnectionFactory(connectionFactory); return gateway; }
{ "pile_set_name": "StackExchange" }
Q: How to add onClick event to an a tag with class Here's what I have on a page <a class="download-link" href="http://www.test.com/pages-">Pages 1</a> Below is the Result I want to achieve with jQuery. <a class="download-link" href="http://www.test.com/pages-1.asp" onclick="_sz.push(['event', 'PDF', 'download', ('report') ])">Pages 1</a> jQuery <script type="text/javascript">/ $('.download-link').each(function(){ this.href += '-1.asp'; this.attr('onclick', '_sz.push(['event', 'PDF', 'download-request', ('report') ])'); }) </script> A: try this one. $('.download-link').bind('click', function (event) { _sz.push(['event', 'PDF', 'download', ('report')]) }); I hope. It helps you.
{ "pile_set_name": "StackExchange" }
Q: Where to store error/info messages for the user in PHP? I was wondering, what's the best way to store messages for the user in PHP. With messages i mean something like Authentication successful or Please enter a valid e-mail address Currently I'm working on a project where they are stored in the $_SESSION variable, but I don't think this is a good solution. Short explanation how I do it at the moment (The class Message was created by me) $_SESSION["msg"][] = new Message("..."); and foreach ( $_SESSION ["msg"] as $msg ) : echo $msg->getText(); endforeach; unset ( $_SESSION ["msg"] ); This is just a simplified version of the complete code, but you should get the idea. EDIT: Forgot to say, that I'm working with an MVC framework and want to speperate the logic from the output. A: One can only speculate on the nature/contents of your Message Class. However, here; attempt was made to simulate a mock-up of a class called Message; also the Usage in your View Script was shown below the Class. Be sure that $_SESSION is active on both Scripts.... Perhaps, this may shed some new light on how to go about your unique case: <?php //FIRST CHECK IF SESSION EXIST BEFORE STARTING IT: if (session_status() == PHP_SESSION_NONE || session_id() == '') { session_start(); } class Message { protected $msg; public function __construct() { if(!isset($_SESSION['msg'])){ $_SESSION['msg'] = array(); } } public function setText($message){ if(!in_array($message, $_SESSION['msg'])){ $_SESSION['msg'][] = $message; } } public function getText(){ return "Some Logic for getting Message"; } } ?> <?php // INSIDE OF YOUR VIEW SCRIPT; AT THE VERY TOP, ENABLE SESSION AS WELL: //FIRST CHECK IF SESSION EXIST BEFORE STARTING IT: if (session_status() == PHP_SESSION_NONE || session_id() == '') { session_start(); } // THEN LOOP THROUGH THE SESSION DATA FOR MESSAGES TO BE DISPLAYED $msg = new Message(); if(isset($_SESSION['msg'])) { foreach ($_SESSION ["msg"] as $msg) : echo $msg->getText(); endforeach; unset ($_SESSION ["msg"]); }
{ "pile_set_name": "StackExchange" }
Q: PRNG bad seeding and von Neumann unbiasing Large period PRNGs such as Mersenne Twister require good seeding otherwise the initial output in the sequence may not seem to be high-quality, at least for the first few words (and in the way that is useful in production). For example, Marsaglia talked about seeding methods in his May 2003 Communications of the ACM article [1]. It feels like a chicken/egg situation. You need a source of high-quality random bits in order to seed your generator, so you can create a source of high-quality random bits. I was wondering: Is von Neumann unbiasing a legitimate way to defend against poor seeding of large-period PRNGs? In other words, if I apply von Neumann unbiasing to the bitstream output of Mersenne Twister, does the quality of the stream still depend on how I seeded it? [1] George Marsaglia, "Seeds for random number generators." Communications of the ACM, 46(5):90–93, 2003 (ACM page.) A: Von Neumann unbiasing only works if the random source consists of independent samples. Otherwise it is not guaranteed to produce random bits. More generally, in theoretical computer science there exist objects called (randomness) extractors whose job is to extract random bits out of imperfect random sources. Usually they need access to a small number of "high quality" random bits. In practice, seeding a PRNG is not difficult. There are many legitimate sources of randomness, and using an extractor such as a hash function, you can take a decently sized sample and extract a decently random seed. Once you have a handful of high quality random bits, you can use a PRNG to quickly extract many more seemingly random bits.
{ "pile_set_name": "StackExchange" }
Q: Siunitx Won't Display Reciprocal Powers I have several SI units in my document which I would like to typeset using the siunitx package. According to the documentation the default mode for the \per command is 'reciprocal' meaning \si{m\per s} should produce output akin to ms$^{-1}$ but on my system it is producing m/s. I have tried setting \sisetup{per=reciprocal} and \sisetup{per-mode=reciprocal} but it seems to ignore this and continues to use '/'. Specifying the mode for individual units works but I don't want to have to type [per-mode=reciprocal] every time I want to typeset a unit. Am I missing something or is there a way to fix this (preferably without \newcommand)? A: The 'unit parser' in siunitx only operates on 'symbolic' units such as \si{\m\per\s} \si{\metre\per\second} where the behaviour of \per is selectable. For the 'literal' input \si{m\per s} parsing is not possible ('literal' input could be anything), and instead \per switches to simply inserting a /. Thus while the 'interpreted' mode requires slightly more typing, as it is more 'programmable' it's the recommended approach.
{ "pile_set_name": "StackExchange" }
Q: EXCEL VBA: Web Page Button Click I have tried numerous variations of codes on this site to get my VBA to click on a button on a webpage and with the exception of one time have not been able to get any code to work. The one time was either a fluke or in an attempt to add the next step of the code I somehow inadvertently changed what was happening previously. Below is both the source code of the website and the code I'm using currently. Right now I do not get any errors, but instead of loading the next page when I include the button click code if just clears the form and stays on the present web page. CODE: Public Sub TestIE() Dim IE As Object Dim aNodeList As Object, i As Long Dim bNodeList As Object, p As Long ' Create InternetExplorer Object Set IE = CreateObject("InternetExplorer.Application") ' You can uncoment Next line To see form results IE.Visible = False ' Send the form data To URL As POST binary request IE.Navigate "https://pe.fanniemae.com/pe/pricing/search" ' Statusbar Application.StatusBar = "Page is loading. Please wait..." ' Wait while IE loading... Do While IE.Busy Application.Wait DateAdd("s", 1, Now) Loop IE.Visible = True Set aNodeList = IE.document.querySelectorAll("input[type=checkbox]") If aNodeList Is Nothing Then Exit Sub For i = 0 To 18 aNodeList.Item(i).Checked = True Next i 'IE.document.querySelector("button[type=submit]").Click Set bNodeList = IE.document.querySelectorAll("button[type=submit]") If bNodeList Is Nothing Then Exit Sub For p = 1 To 1 bNodeList.Item(p).Click Next p End Sub Page Source: <div class="row submit"> <button id="get-price" tabindex="3" type="submit" class="cell-right- 2">Get Prices</button> <div class="pricing-error-message"></div> When I inspect element on the button it does appear there is a clear form part of the code, which I would expect, but for whatever reason it is clearing the form instead of loading the new page. When I click on the button manually in IE it loads as expected. Script that I believe is running: <script type="text/javascript"> define('pageConf', function() { return null || JSON.parse('{\"lastPricingFactors\": {\"priceIncrement\":\"18\",\"priceView\":\"total\",\"executionType\ ":\"Mandatory\",\"levelType\":\"Product\",\"remittanceType\":\"ActualActual \",\"products\":\"160958\",\"1036FR\",\"102422\",\"163053\",\"160639\",\" 160058\",\"155509\",\"154232\",\"143846\",\"0005FR\",\"125331\",\"102301\", \"114921\",\"115446\",\"144854\"],\"underwrittenWithDu\":false,\" servicingReleased\":false,\"displayMarketFrozenMessage\":false,\"windows\": [10,30,60,90],\"requestTimeMs\":1531424470700}}') }); </script> A: I was able to utilize a Select Case that inserted the criteria I wanted selected in the URL that was generated by the button vs. having to actually press the button which seems to be a working work around. Thanks for taking a look at this.
{ "pile_set_name": "StackExchange" }
Q: OpenCV - Using SVM and HOG for person detection I'm aware of the steps needed to accomplish this task: Collect the training sets (positive and negative sets). Extract the hog descriptor for each image to be used for training the SVM (currently '1' class label for positive and '-1' class label for negative). Set the trained SVM to the HOGDescriptor and use detect/detectMultiscale. I have done all of the steps above. I'm just confused, which class does the HOGDescriptor.detect/detectMultiscale detect? Does it detect only the positive class label (1)? A: In computer vision, visual descriptors or image descriptors (i.e. HoG) are descriptions of the visual features of the contents in images. They describe elementary characteristics such as the shape, the color, the texture or the motion, among others. So HoG descriptors only characterize the scene - shown in the image, i.e. a pedestrian who is walking on the street, you can see an example HoG descriptor below (HoG just counts occurrences of gradient orientation in localized portions of an image): SVMs are a set of supervised learning methods used for classification, regression and outliers detection. But originally, SVM was a technique for building an optimal binary (2-class) classifier, so SVMs make decision about what the descriptors mean. So what is to say, the output of HoG is the input of SVMs and the output of the latter is +1 or -1. OpenCV provides an interface which hides this operation and the full object detection can be done by a function call. This is what HOGDescriptor::detectMultiScale() does, it performs object detection with a multi-scale window. Once a cv::HOGDescriptor hog instance would be declared, then the coefficients of an SVM classifier should be also done by: hog.setSVMDetector(cv::HOGDescriptor::getDefaultPeopleDetector()); And then detectMultiScale() performs the full object detection (descriptor extraction and binary classification together) and returns the bounding boxes of each candidates: std::vector<cv::Rect> found; hog.detectMultiScale(frame, found, 0, cv::Size(8,8), cv::Size(32,32), 1.05, 2);
{ "pile_set_name": "StackExchange" }
Q: Excel VBA: unable to disable DisplayAlert during drag+drop? I'm trying to capture a specific drag and drop event in VBA, and would like to disable the popup "There's already data here. Do you want to replace it?" during this event. I have the basic event of a drag+drop from cell [D1] to cell [E1] captured, but for some reason I'm unable to disable the popup. Does anyone know why? Thanks so much. Option Explicit Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Not Intersect(Target(1, 1), [D1]) Is Nothing Then MsgBox "selected " & Target.Address & " - " & Target(1, 1).Value Application.DisplayAlerts = False End If End Sub Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target(1, 1), [E1]) Is Nothing Then MsgBox "changed " & Target.Address & " - " & Target(1, 1).Value End If End Sub A: Try this - it works on my 2013 Excel: Option Explicit Private Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target(1, 1), [E1]) Is Nothing Then MsgBox "changed " & Target.Address & " - " & Target(1, 1).Value End If End Sub Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Not Intersect(Target(1, 1), [D1]) Is Nothing Then MsgBox "selected " & Target.Address & " - " & Target(1, 1).Value Application.AlertBeforeOverwriting = False Else Application.AlertBeforeOverwriting = True End If End Sub This uses the SelectionChange event to catch the user selecting D1 and disables the alert using Application.AlertBeforeOverwriting. Any other selection ensures it's enabled. Dragging the value causes another SelectionChange which now re-enables the alert for any other overwriting. Also, you ought to use events to trap user clicking in D1 and then changing to another sheet or closing this one as the alerts could remain disabled.
{ "pile_set_name": "StackExchange" }
Q: AWS ALB + Django + Gunicorn +- Nginx? I am building an environment in AWS to host a django application. I am trying to figure out if I should be using nginx as part of the build. I am listing a few different environments below for example/comparison purposes. All environments make use of an AWS ALB. ENV 1 ALB -> dockercontainer running django +uses inbuilt django webserver, static files working -inbuilt django webserver not made for production use ENV 2 ALB -> dockercontainer running django/gunicorn +uses gunicorn (not django webserver) -static files NOT working ENV 3 ALB -> dockercontainer running django/gunicorn + nginx note: I have not tested this configuration yet. +uses gunicorn (not django webserver) +uses nginx static files should work I read this stackoverflow post and understand the differing roles of gunicorn vs nginx. I am being advised by a colleague that ENV 2 is all I need, that I should be able to serve static files with it, that the ALB provides similar functionality to NGINX. Is this correct? A: Just to clarify - "ALB" stands for Application Load Balancer, which is differentiated from the older Elastic Load Balancer in that traffic can be routed based on URI. However, whichever load balancer you're referring to, I believe you'll need nginx in the mix, as AWS load balancers don't offer any file serving capability. If your static files have a consistent URI pattern, you might be able to use an ALB to serve static files from S3 or CloudFront.
{ "pile_set_name": "StackExchange" }
Q: Casablanca - REST C++ SDK, used in Embarcadero RAD Studio XE5 I need to do a http get in RAD Studio XE5 C++. The tutorials on the RAD Studio site discuss a RESTCLient that is not included with the version I have. I found the Casablanca project, which is specifically for Visual Studio, and I made a small program in VS that does the simple http get and handles response in the way I need. What do I need to do to successfully use Casablanca from within RAD Studio? There are the steps I have taken so far. Compiled Casablanca in Visual Studio 2013 Copied the .lib and .dll over to a folder in the RAD Studio project added that folder to the link path in the RAD Studio project added the .lib to the project added dll imports to classes that should be in the .lib to the .cpp I want to use the function in. class __declspec(dllimport) http_client; class __declspec(dllimport) filestream; class __declspec(dllimport) producerconsumerstream; class __declspec(dllimport) rawptrstream; There was a OMF error, and I used a tool that came with RAD Studio to convert the .lib, that got past the error. I don't know how to declare the dll prototype's of the functions, because the returns types are from a namespace in the library itself so they aren't recognized. http_client is an unrecognized structure. I tried this as well without the class keyword. A: DLLs that export classes are not portable across compilers. So you will not be able to use a Visual Studio compiled DLL in C++Builder if it exports classes. Either flatten the DLL interface to export plain C-style functions instead (and then use C++Builder's command-line IMPLIB tool to create an import .lib file for the DLL, do not use the .lib file created by Visual Studio), or else find another solution. For instance, C++Builder (and Delphi) ships with Indy 10, which has a TIdHTTP component. You can use its TIdHTTP::Get() method to perform an HTTP GET request. But if you need to actually use REST, you might be better off simply upgrading your XE5 to a version that has TRESTClient available (BTW, Embarcadero's REST classes use Indy internally).
{ "pile_set_name": "StackExchange" }
Q: Type parameter 'T' must be a class type I am writing a small helper class for REST operations. One of my main goals is to provide automatic casting from the body response in JSON to a specific object using generics. This is how one of the functions look in the helper class: function RESTServiceCallHelper.ExecuteAsObject<TObj>(resource: string): TObj; var RestRequest: TRESTRequest; obj: TObj; begin PrepareRequest(RestRequest, resource); RestRequest.Execute; obj := TJson.JsonToObject<TObj>(RestRequest.Response.Content); result:=obj; end; And here is how I am trying to use it: type TPartnerCreditInfo = class FlCreditClassDesc: string; FCppID: string; FCreditClass: string; FCreditClassDesc: string; FCreditLimit_CurrencyCode: string; FCreditLimit: double; FAmountBalance: double; FAmountBalance_CurrencyCode: string; FAmountBalanceLast: double; FAmountBalanceLast_CurrencyCode: string; end; procedure TModuleX.CallAPIS; var lRESTHelper : TrpRESTServiceCallHelper; pc: TPartnerCreditInfo; begin lRESTHelper:= TrpRESTServiceCallHelper.Create('https://mydomain/api'); lRESTHelper.AddQueryStringParam('param1','paramvalue'); pc:=lRESTHelper.ExecuteAsObject<TPartnerCreditInfo>('resource'); showmessage(pc.FCppID); end; The issue I am facing is this at compilation time: obj := TJson.JsonToObject<TObj>(RestRequest.Response.Content); [dcc32 Error] RESTServiceCallObj.pas(99): E2511 Type parameter 'T' must be a class type According to the documentation the T parameter for JsonToObject function must be a class and TPartnerCreditInfo is a class too. Why is TPartnerCreditInfo not being recognized? A: The T Generic parameter of TJson.JsonToObject() has been marked with the class and constructor constraints. As such, the TObj Generic parameter of your ExecuteAsObject() function needs to be marked with the same constraints: function ExecuteAsObject<TObj: class, constructor>(resource: string): TObj; Those constraints inform the compiler that T/TObj are required to be a class type that has a parameterless Create() constructor, which is what allows JsonToObject() to create a new object instance of the type passed to T/TObj.
{ "pile_set_name": "StackExchange" }
Q: One-off job with hangfire How can I run a one-off job with hangfire? It doesn't look that CRON syntax supports "run at startup and never again" type of thing. I don't want to come up with a fixed CRON date (like 2019-02-28T15:12), because that wouldn't work across several environments. Any ideas how to do it? A: What we ended up with is a job that never runs, but can be triggered via Hangfire UI. So something like this: RecurringJob.AddOrUpdate<SomeType>("name", service => service.Run(), NEVER);
{ "pile_set_name": "StackExchange" }
Q: Bootstrap Sticky navbar is causing vertical scrolling in collapsed mode I am building a navbar that is supposed to stick to the top of the page. I used .navbar-fixed-top class to accomplish that and gave the body element, a padding of 70px. Now in the collapsed mode (mobile resolution), when toggled, it gives a vertical navigation. Not sure where this scrolling is coming from. Here's the code: <header class=" container-fluid navbar-fixed-top"> <!-- header navbar --> <nav class="navbar navbar-default"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="market.html"><img src="images/logo-inner.jpg" / alt="B-Hive: Expand your business"></a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <!-- Form search start --> <form class="navbar-form navbar-left" role="search" class="top-search-padding"> <div class="form-group"> <div class="search-div ui-widget"> <input id="tags" type="text" class="txt-search" placeholder="Search people, products and services"> <button type="submit" class="btn-search"><img src="images/search-icon.png" /></button> </div> </div> </form> <!-- Form search end --> <ul class="nav navbar-nav navbar-right"> <li class="top-menu-links-active"><a href="#">MARKET</a></li> <li><a class="top-menu-links" href="#">EXHIBITIONS</a></li> <li><a class="top-menu-links" href="#">MESSAGES</a></li> <li><a class="top-menu-links" href="#">DASHBOARD</a></li> <li><a class="top-menu-links" href="#">CART</a></li> <li class="profile-pic-padding"></li> <li class="dropdown"> <a href="#" class="dropdown-toggle custom-dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><img class="" src="images/profile-pic.fw.png" /> <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">Account</a></li> <li><a href="#">Privacy</a></li> <li role="separator" class="divider"></li> <li><a href="#">Switch Accounts</a></li> <li role="separator" class="divider"></li> <li><a href="#">Language <span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="#">EN</a></li> <li><a href="#">ع</a></li> </ul> </li> </ul> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <!-- /header navbar --> </header> A: Bootstrap's .navbar-collapse has a default max-height: 340px; which causes scrollbars to appear when the links inside the navigation exceed this height. You can simply remove this property to avoid the scrollbars from appearing in mobile view.
{ "pile_set_name": "StackExchange" }
Q: R select subset of data I have a dataset with three columns. ## generate sample data set.seed(1) x<-sample(1:3,50,replace = T ) y<-sample(1:3,50,replace = T ) z<-sample(1:3,50,replace = T ) data<-as.data.frame(cbind(x,y,z)) What I am trying to do is: Select those rows where all the three columns have 1 Select those rows where only two columns have 1 (could be any column) Select only those rows where only column has 1 (could be any column) Basically I want any two columns (for 2nd case) to fulfill the conditions and not any specific column. I am aware of rows selection using subset<-data[c(data$x==1,data$y==1,data$z==1),] But this only selects those rows based on conditions for specific columns whereas I want any of the three/two columns to fullfill me criteria Thanks A: n = 1 # or 2 or 3 data[rowSums(data == 1) == n,] A: Here is another method: rowCounts <- table(c(which(data$x==1), which(data$y==1), which(data$z==1))) # this is the long way df.oneOne <- data[as.integer(names(rowCounts)[rowCounts == 1]),] df.oneTwo <- data[as.integer(names(rowCounts)[rowCounts == 2]),] df.oneThree <- data[as.integer(names(rowCounts)[rowCounts == 3]),] It is better to save multiple data.frames in a list especially when there is some structure that guides this storage as is the case here. Following @richard-scriven 's suggestion, you can do this easily with lapply: df.oneCountList <- lapply(1:3, function(i) data[as.integer(names(rowCounts)[rowCounts == i]),] names(df.oneCountList) <- c("df.oneOne", "df.oneTwo", df.oneThree) You can then pull out the data.frames using either their index, df.oneCountList[[1]] or their name df.oneCountList[["df.oneOne"]]. @eddi below suggests a nice shortcut to my method of pulling out the table names using tabulate and the arr.ind argument of which. When which is applied on a multipdimensional object such as an array or a data.frame, setting arr.ind==TRUE produces indices of the rows and the columns where the logical expression evaluates to TRUE. His suggestion exploits this to pull out the row vector where a 1 is found across all variables. The tabulate function is then applied to these row values and tabulate returns a sorted vector that where each element represents a row and rows without a 1 are filled in with a 0. Under this method, rowCounts <- tabulate(which(data == 1, arr.ind = TRUE)[,1]) returns a vector from which you might immediately pull the values. You can include the above lapply to get a list of data.frames: df.oneCountList <- lapply(1:3, function(i) data[rowCounts == i,]) names(df.oneCountList) <- c("df.oneOne", "df.oneTwo", df.oneThree)
{ "pile_set_name": "StackExchange" }
Q: Using Beaker with Falcon, Python I'm using the Python WSGI framework Falcon to make an app backend, and using Beaker to handle session management. In production, we're going to using Gunicorn in AWS. There's something I've been unable to understand: Gunicorn will run several workers, so does that mean the environment variables persist for different clients that have made requests? To put it another way, is a beaker session for one client only, or will it be available to several clients making requests in the same Gunicorn worker instance? This is how I understand sessions to work from my reading: A person logs into my app, and the user_id is added to the session with Beaker. Future requests from the same client will have this user_id stored in the session dict. Now, any future requests from that client will be able to access the variables stored in the session. Each client has its own session data. Have I understood this properly? The current method is to return an id to the client (on successful login) to pass to the backend when more user information is required. A: Have I understood this properly? yes, you do, for most part. Gunicorn will run several workers, so does that mean the environment variables persist for different clients that have made requests? To put it another way, is a beaker session for one client only, or will it be available to several clients making requests in the same Gunicorn worker instance? beaker save session data on server side, in a dedicated datastore identified by a unique session id, client side would send back session id via cookie, then server (gunicorn worker) could retrieve session data. I recommend read a more detailed explanation on how session works, like this one: http://machinesaredigging.com/2013/10/29/how-does-a-web-session-work/
{ "pile_set_name": "StackExchange" }
Q: Player Movement I started developing games recently, teaching myself using a german book about C++ and Direct3D 9. The author states, player movement should be implemented using a time delta, like this player.position.x += time.delta * movementFactor as opposed to an implementation without incorporating the time passed since last frame; i.e like this player.position.x += movementFactor Latter solution would cause other players to move faster, since the expression above would be executed more often on faster CPUs. (More explanation on Tayacan's answer below) Is there any other solution to this problem? Old, poorly phrased question I wrote when I was young: I'm reading on a Book that's about Gamedevelopment with C++ and DirectX 9. There is something that interrests me: It says that playermovements are increasing with the power of the CPU. Becouse a faster CPU will move the player with every frame ( better CPU = better FPS ) To bypass it, it says you have just to multiplicate time*movementfactor . I'd like to know is there an another way to bypass it ? A: Why do you want another way? The one you describe is what you'd use in any kind of game development, whether or not you use DirectX. The problem is this: In (most) games you have a main loop. This loop runs as fast as the hardware allows. However, people use different hardware, so on some computers, this will be faster than on others. So in order to make an object in a game move with the same speed on any hardware, you multiply the movement vector with the time, in seconds, since last time the loop was run. This also has the benefit that if you're moving the object, say, 5 * time units in some direction, that's the same as saying "move it 5 units/seconds".
{ "pile_set_name": "StackExchange" }
Q: Dictionary (ObservableCollection) binding to ListView in Windows Phone 8.1 I am trying to bind a dictionary to two textblocks in a listview. The listview ItemsSource binding is defined in the code behind and the text blocks content is in the XAML. I am able to display the items but they are displayed with square brackets around each row like [stringA, stringB]. However, this format will not work. The latest code that I tried was by setting the Key and Value which did not work was: XAML: <ListView Name="lvListLogs" Margin="0,10,0,0"> <ListView.ItemTemplate> <DataTemplate x:Name="ListItemTemplate"> <Grid Margin="5,0,0,0"> <Grid.ColumnDefinitions> <ColumnDefinition Width="122"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition MaxHeight="104"></RowDefinition> </Grid.RowDefinitions> <TextBlock x:Name="tb_PointName" Grid.Column="1" Text="{Binding Key}" Margin="10,0,0,0" FontSize="40" TextWrapping="Wrap" MaxHeight="72" Foreground="#FFFE5815" /> <TextBlock x:Name="tb_PointValue" Grid.Column="1" Text="{Binding Value}" Margin="10,0,0,0" FontSize="40" TextWrapping="Wrap" MaxHeight="72" Foreground="#FFFE5815" /> </Grid> </DataTemplate> </ListView.ItemTemplate> </ListView> C# (abridged for clarity): public Dictionary<string, string> mydict2 { get; set; } mydict2 = new Dictionary<string, string>(); if (item != null) { var props = item.GetType().GetRuntimeProperties(); foreach (var prop in props) { foreach (var itm in group1.Items.Where(x => x.UniqueId == prop.Name)) { var _Title = prop.Name; var _Value = prop.GetValue(item, null); string propertyValue; string propertyName; propertyValue = Convert.ToString(_Value); propertyName = _Title; mydict2.Add(_Title, propertyValue); } } //binding here lvListLogs.ItemsSource = mydict2; } Any assistance would be appreciated. A: To achieve the required binding, instead of the Dictionary I used an ObservableCollection with the class and constructor. To databind the listview (xaml) to ObservableCollection: Create the Class with Constructor public class PointInfoClass { public string PointName { get; set; } public string PointValue { get; set; } public PointInfoClass(string pointname, string pointvalue) { PointName = pointname; PointValue = pointvalue; } } Create collection of the PointInfoClass public ObservableCollection<PointInfoClass> PointInfo { get { return returnPointInfo; } } Instantiate the collection ObservableCollection<PointInfoClass> returnPointInfo = new ObservableCollection<PointInfoClass>(); Add item to collection returnPointInfo.Add(new PointInfoClass(string1, string2)); Databind to the ObservableCollection name. The xaml code: <ListView Grid.Row="1" ItemsSource="{Binding PointInfo}" IsItemClickEnabled="True" ItemClick="ItemView_ItemClick" Margin="19,0.5,22,-0.333" x:Name="lvPointInfo" Background="White"> <ListView.ItemTemplate> <DataTemplate > <Grid Margin="0,0,0,20"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="270"/> <ColumnDefinition Width="60"/> </Grid.ColumnDefinitions> <StackPanel Orientation="Vertical" Grid.Column="1" VerticalAlignment="Top"> <TextBlock x:Name="tb_PointSubTitle" Grid.Column="1" Text="{Binding PointName}" Margin="10,0,0,0" FontSize="20" TextWrapping="Wrap" MaxHeight="72" Foreground="#FF5B5B5B" /> </StackPanel> <StackPanel Orientation="Vertical" Grid.Column="2" VerticalAlignment="Top" HorizontalAlignment="Right"> <TextBlock x:Name="tb_PointValue" Grid.Column="1" Text="{Binding PointValue}" Margin="0,5,0,0" FontSize="20" HorizontalAlignment="Right" TextWrapping="Wrap" FontWeight="Normal" Foreground="Black" /> </StackPanel> </Grid> </DataTemplate> </ListView.ItemTemplate> </ListView> Set the DataContext of the ListView lvPointInfo.DataContext = this; This code is edited for clarity.
{ "pile_set_name": "StackExchange" }
Q: jquery date picker get date string in dd/mm/yy I have the string 'Thu Oct 20 2011 00:00:00 GMT-0400 (Eastern Daylight Time)' and would like to get date in format dd/mm/yyyy out of this. How can I do this using jquery date picker library? A: This is a dupe question asked here before: jQuery UI DatePicker - Change Date Format You can do this: $( ".selector" ).datepicker({ dateFormat: 'yy-mm-dd' }).val(); Just to note though, the JqueryUIDatePicker has a formatdate and parseDate function too. A: You can use the javascript Date() method var dateTime = new Date($("#yourSelector").datepicker("getDate")); var strDateTime = dateTime.getDate() + "/" + (dateTime.getMonth()+1) + "/" + dateTime.getFullYear(); console.log(strDateTime); A: If you already set dateFormat parameter in datepicker initiation, you may use only $( ".selector" ).val(); Because, else, using : $( ".selector" ).datepicker({ dateFormat: 'yy-mm-dd' }).val(); is causing datepicker's onSelect event not to be triggered (don't know why, just observed).
{ "pile_set_name": "StackExchange" }
Q: Why does first version document show as minor version? When I allow SharePoint 2013 to create major and minor versions, the first document uploaded shows up as a minor version. It has a decimal number instead of a whole number. Shouldn't it show up as a major version with a whole number? However, when I only allow Major Versions, the document is uploaded as a Major Version. Thanks for your help. A: No. When minor versioning is used, the initial upload will be .1 and will continue to increment upward until the file is Published as a major version. At that point, it will be 1.0. This is the draft versioning and publishing type scenario where you work on a document and publish it when it is finished. Major versioning only does just that, increments major version numbers on every change of the document, no matter how small or insignificant. The notion of going from a 1.0 to a 2.0 usually implies some significant change. In this case, you can quickly go from 1.0 to 7.0, by rephrasing something, then fixing a typo, then later altering metadata.
{ "pile_set_name": "StackExchange" }
Q: Seeing all store categories under my Appixia BasicCategoryListActivity instead of only primary categories I added the BasicCategoryListActivity module to my mobile app in order to show my store categories. I'm trying to create a tab for category navigation through my store: show primary categories and only when they are tapped on, show the subcategories. Instead, what I got is a very long list of the categories in my store - both primary, subcategories, everything... How do I hide all the categories I don't want from the list? A: By default, the categories that are displayed in the list are unfiltered. This means that every category in the store should show up - so this is behaving as it should. What you probably want to add is a filter to the category list. Add a filter using the Filter property of the category list. If you only want the root categories (your primary store categories), a filter on the category ParentId is probably the most appropriate. Use the root category id as the value for this filter. If you're unsure what your root category id is, just leave it empty.
{ "pile_set_name": "StackExchange" }
Q: SQL query to return a grouped result as a single row If I have a jobs table like: |id|created_at |status | ---------------------------- |1 |01-01-2015 |error | |2 |01-01-2015 |complete | |3 |01-01-2015 |error | |4 |01-02-2015 |complete | |5 |01-02-2015 |complete | |6 |01-03-2015 |error | |7 |01-03-2015 |on hold | |8 |01-03-2015 |complete | I want a query that will group them by date and count the occurrence of each status and the total status for that date. SELECT created_at status, count(status), created_at FROM jobs GROUP BY created_at, status; Which gives me |created_at |status |count| ------------------------------- |01-01-2015 |error |2 |01-01-2015 |complete |1 |01-02-2015 |complete |2 |01-03-2015 |error |1 |01-03-2015 |on hold |1 |01-03-2015 |complete |1 I would like to now condense this down to a single row per created_at unique date with some sort of multi column layout for each status. One constraint is that status is any one of 5 possible words but each date might not have one of every status. Also I would like a total of all statuses for each day. So desired results would look like: |date |total |errors|completed|on_hold| ---------------------------------------------- |01-01-2015 |3 |2 |1 |null |01-02-2015 |2 |null |2 |null |01-03-2015 |3 |1 |1 |1 the columns could be built dynamically from something like SELECT DISTINCT status FROM jobs; with a null result for any day that doesn't contain any of that type of status. I am no SQL expert but am trying to do this in a DB view so that I don't have to bog down doing multiple queries in Rails. I am using Postresql but would like to try to keep it straight SQL. I have tried to understand aggregate function enough to use some other tools but not succeeding. A: The following should work in any RDBMS: SELECT created_at, count(status) AS total, sum(case when status = 'error' then 1 end) as errors, sum(case when status = 'complete' then 1 end) as completed, sum(case when status = 'on hold' then 1 end) as on_hold FROM jobs GROUP BY created_at; The query uses conditional aggregation so as to pivot grouped data. It assumes that status values are known before-hand. If you have additional cases of status values, just add the corresponding sum(case ... expression. Demo here
{ "pile_set_name": "StackExchange" }
Q: Can't find where form is processed? I'm using a wordpress theme that i want to customize and i cannot find where the custom post type Services form $_POST values are processed. The form action returns to the same page but when looking at the page and the wrapper page, i cannot see any functions that process $_POST values? Here is the form action <form id="edit-service" class="edit-service" enctype="multipart/form-data" method="post" action="http://example.com/add-service/?step=edit-info&amp;hash=427d72b2fe6d0e70a9cb" novalidate="novalidate"></form> How do i debug this to find where $_POST values are being processed? A: In the add-service (controller?) you can either do the following: echo "<pre>"; var_dump($_POST); echo "</pre>"; exit; If you are using firefox you could also use the Tamper Data extension, which let's you view and edit all POST data.
{ "pile_set_name": "StackExchange" }
Q: How can I automate the process of copying files from one folder to another in Centos I have a statistical application which runs every minute and creates charts accordingly. In order to make these charts available to other users, I need to copy the whole folder containing the charts and paste it to a shared folder where other users can see the contents. How can I automate this process so that e.g each 5 minutes the files and folders are updated? A: This sounds like something which could perhaps be perfectly solved with rsync. In its simplest form it can be called like this rsync sourceFolder destinationFolder Called in a crontab every 5 minute: */5 * * * * /usr/bin/rsync sourceFolder destinationFolder For options, permissions, exlude of special files or directories see man rsync.
{ "pile_set_name": "StackExchange" }
Q: If $-1$is a root for $ax^2+bx−3$, find $a^2+b^2$ Given: -1 is a root for $ax^2+bx-3$, with $a,b$ being positive primes, $x\in \Bbb R$. Find: the numeric value for $a^2+b^2$. Background: question asked in an entrance exam (Colégio Militar 2005). My attempt: the other root is $3/a$ and by substitution we can easily find that $$a-b=3\ \ \text{or}\ \ a^2+b^2-2ab=9.$$ I got stuck at this point... how to get the value for $ab$? Hints please. A: Starting from $a-b=3$, which is odd, this implies the positive primes cannot be both odd. So one of them is $2$, the other is an odd prime. As $a-b>0$, it's $b$ which is equal to $2$, so $a=3+b=5$, and $a^2+b^2=29$. A: Pure obfuscation. Nothing about roots or algebra or the sum of $a^2 + b^2$ are relevant. That $-1$ is a root simply means $a(-1)^2 + b(-1)-3 = 0$ or in other words $a - b =3$ or $a = b+3$. What does matter is that $a,b$ are positive primes and all primes except $2$ are odd. If they were both odd primes then $a -b$ would be an even number. So one of them is even so one of them is $2$. So the other is $2+3 = 5$. So $a^2 + b^2 = 29$.
{ "pile_set_name": "StackExchange" }
Q: rel and href match http://jsfiddle.net/aprWP/ <a href="#numtag-1">One</a> <a href="#numtag-2">Two</a> <a href="#numtag-3">Three</a> <div class="numtag-1">One</div> <div class="numtag-2">Two</div> <div class="numtag-3">Three</div> .. on hover the appropriate div should toggle class 'active'. Tried a lot of things but can't get it to work. Thanks A: Using a combination of hover event and toggleClass: $('a').hover(function() { $('div.' + $(this).attr('href').substring(1)).toggleClass('active'); }); http://jsfiddle.net/aprWP/7/ Changed to use substring as I think that's a better way of doing it.
{ "pile_set_name": "StackExchange" }
Q: (L'Étranger de Camus) The usage of "se" with "laisser + faire" This question is on "se" in the last sentence of the following quote from L'Étranger by Camus. Nous nous sommes mis en marche. C’est à ce moment que je me suis aperçu que Pérez claudiquait légèrement. La voiture, peu à peu, prenait de la vitesse et le vieillard perdait du terrain. L’un des hommes qui entouraient la voiture s’était laissé dépasser aussi et marchait maintenant à mon niveau. From English translations, I understood that one of the men had fallen behind and got level with the narrator. Questions (1) Should I understand that "se" refers to the man who fell behind. That is, should I understand the sentence to mean that he "had allowed the passing of himself"? (2) Should I understand that the implicit subject (agent) of "dépasser" is the car (la voiture) and anything else in the procession between the car and the narrator (moi)? (3) If we replace "se" with "le," would that be ungrammatical? My motivation for question (3) comes from considering English sentences like, "He let himself be passed" but "He let her pass him." I think my (English-speaking) mind wants to assimilate "se dépasser" in the quote to "her passing him" because "se" occupies a position like "him" (in being the object of "dépasser") even though "se dépasser" does not have an explicit agent (like "her" in "her passing him"). A: You are perfectly right about (1) and (2). To write a similar sentence in active voice you'd use: Il les avait laissé le dépasser. (He let them pass him.) “Les” stands for “them” (alternatively you could use “la” for “la voiture”). Le stands for “him” but since “he” and “him” are now respectively the subject of “laisser” and the object of “dépasser” there is no need for a reflexive pronoun. French and English constructions are very similar in this respect. Note: if you omit the le in the active statement, as your replacement suggested, the reader would be lost as it strongly suggests that the passing/overtaking applies to a third party. In French, the le that stands for the previous subject is generally made explicit. It could be omitted, but only if the situation is very clear to the reader already and the act of passing/overtaking itself is significantly more important than to whom it applies. Also, in any case, if you don't use a reflexive pronoun the auxiliary should be avoir.
{ "pile_set_name": "StackExchange" }
Q: Android ime actionGo doesn't work on certain devices ime actionGo simply won't work on certain devices, like the HTC Evo 4G. It works on Motorola Atrix and Droid X. Here is the code: <EditText android:id="@+id/password" android:layout_width="fill_parent" android:layout_height="40dp" android:layout_centerHorizontal="true" android:hint="@string/password_hint" android:password="true" android:inputType="textPassword" android:autoText="false" android:imeOptions="actionGo"/> TextView.OnEditorActionListener listener = new TextView.OnEditorActionListener() { public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) { if(actionId == EditorInfo.IME_ACTION_GO) { loginValidation(); } return true; }}; password.setOnEditorActionListener(listener); A: This seems to be a bug. Different manufacturers make a customized keyboard for their phone which may not completely behave as the android standard keyboard. This issue has been raised before. Most people overcome this issue by either overiding the onKey event or using a TextWatcher class. A bug has been filed about this http://code.google.com/p/android/issues/detail?id=2882
{ "pile_set_name": "StackExchange" }
Q: Changing font name in vb.net ,I have a rich text box for write text and a combo box for font names. i added fonts to combo box with this code: Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ff As FontFamily For Each ff In System.Drawing.FontFamily.Families FontName.Items.Add(ff.Name) Next End Sub But i don't know, how to change the font name of the rich text box. A: You have to use the code below: RichTextBox1.Font = New Font("Font Name", size) Adapt it to your specific conditions: replace RichTextBox1 with your RichTextBox, "Font Name" with the given item of your ComboBox FontName, size with the size you want (it might be the current one, that is, RichTextBox1.Font.Size). A: RichTextBox.Font = New Font(FontName.Text, 10, FontStyle.Regular)
{ "pile_set_name": "StackExchange" }
Q: How to get a picture drawn in canvas using drawImage ()? I'm trying to write a function that lets a user download an image drawn in a canvas. Here's the code: canvas.html: <html lang="en"> <head> <meta charset="utf-8" /> <script type="text/javascript" src="canvas.js"> </script> </head> <body onload="="draw()"> <button type="button" onClick="saveImage()"> save image</button> <canvas width="1600" height="1440" id="canvas"></canvas> </body> </html> canvas.js function draw() { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); ctx.fillRect(550, 150, 300, 300); ctx.fill(); ctx.moveTo(722, 380); ctx.arc(380,380,350,0,2*Math.PI); ctx.lineWidth=15; ctx.strokeStyle="blue"; ctx.stroke(); } function download_image() { var _image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); window.location.href = _image; alert("start") } The code works - provided the image is drawn "normally" / as above - and not loaded with the drawImage() function. As soon as I change the canvas.js file to: function draw() { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var img2= new Image(); img2.onload=function() { ctx.drawImage(img2, 0, 50); } img2.src="./smile.png"; } function saveImage() { var _image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // tu sobie pobieramy adres URL i konwertuje na 'octet-stream' window.location.href = _image; alert("start"); } Unfortunately, nothing happens. No alert pops up. The console shows the following error: "Uncaught TypeError: Can not read property 'toDataURL' of undefined      at saveImage (canvas.js: 17)      at HTMLButtonElement.onclick " How to fix it? Can I download a picture drawn with drawImage()? How? A: /** * Ken Fyrstenberg Nilsen * Abidas Software */ var canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'); /** * Demonstrates how to download a canvas an image with a single * direct click on a link. */ function doCanvas() { /* draw something */ ctx.fillStyle = '#f90'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = '#fff'; ctx.font = '60px sans-serif'; ctx.fillText('Code Project', 10, canvas.height / 2 - 15); ctx.font = '26px sans-serif'; ctx.fillText('Click link below to save this as image', 15, canvas.height / 2 + 35); } /** * This is the function that will take care of image extracting and * setting proper filename for the download. * IMPORTANT: Call it from within a onclick event. */ function downloadCanvas(link, canvasId, filename) { link.href = document.getElementById(canvasId).toDataURL(); link.download = filename; } /** * The event handler for the link's onclick event. We give THIS as a * parameter (=the link element), ID of the canvas and a filename. */ document.getElementById('download').addEventListener('click', function() { downloadCanvas(this, 'canvas', 'test.png'); }, false); /** * Draw something to canvas */ doCanvas(); body { background-color:#555557; padding:0; margin:0; overflow:hidden; font-family:sans-serif; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } canvas { border:1px solid #000; float:left; clear:both; } #download { float:left; cursor:pointer; color:#ccc; padding:3px; } #download:hover { color:#fff; } /* div, input { font-size:16px; font-family:sans-serif; border:1px solid #000; border-radius: 5px; float:left; padding:5px; width:50px; margin:1px 1px; background-color:#bbb; } input[type='text'] { font-size:16px; font-weight:bold; width:70px; text-align:center; background-color:#fff; padding-bottom:4px; } input[type='button'] { font-size:16px; font-weight:bold; width:110px; text-align:center; background-color:#333; color:#eee; padding-bottom:4px; } input[type='button']:hover { background-color:#fff463; color:#000; } input[type='range'] { width:100px; margin:0 0 0 10px; } */ <canvas width="500" height="300" id="canvas">Sorry, no canvas available</canvas> <a id="download">Download as image</a> found a solution here: http://jsfiddle.net/wboykinm/fL0q2uce/ function downloadCanvas(link, canvasId, filename) { link.href = document.getElementById(canvasId).toDataURL(); link.download = filename; }
{ "pile_set_name": "StackExchange" }
Q: Using Scala 2.10 `to` to convert a List to a SortedMap I am trying to convert a scala.collection.immutable.List of pairs to a scala.collection.immutable.SortedMap using the new to method from Scala 2.10, but I get a compile-time error: scala> List((1, "Fred"), (2, "Barney")).to[scala.collection.immutable.SortedMap] <console>:10: error: scala.collection.immutable.SortedMap takes two type parameters, expected: one List((1, "Fred"), (2, "Barney")).to[SortedMap] ^ Can this be done using the to method? Am I missing an intermediate method call? A: I had a similar question some time ago and came up with this: SortedMap( list: _*) So you can do it like : val map = SortedMap( List((1, "Fred"), (2, "Barney")): _*) The _* means you take the Seqs elements instead of the Seq itself as parameter. A: @gourlaysama already explained why it does not compile, and @Chirlo provided the simplest (and recommended) work around: SortedMap( list: _*). I'd like to propose an alternative: import collection.Traversable import collection.generic.CanBuildFrom implicit class RichPairTraversable[A,B]( t: Traversable[(A,B)] ) { def toPairCol[Col[A,B]](implicit cbf: CanBuildFrom[Nothing, (A,B), Col[A, B]]): Col[A, B] = { val b = cbf() b.sizeHint(t) b ++= t b.result } } Some test in the REPL: scala> List((1, "Fred"), (2, "Barney")).toPairCol[scala.collection.immutable.SortedMap] res0: scala.collection.immutable.SortedMap[Int,String] = Map(1 -> Fred, 2 -> Barney) scala> List((1, "Fred"), (2, "Barney")).toPairCol[scala.collection.immutable.HashMap] res1: scala.collection.immutable.HashMap[Int,String] = Map(1 -> Fred, 2 -> Barney) Now, I will probably not use it in production, given that doing SortedMap( list: _* ) is not that hard and requires no magic.
{ "pile_set_name": "StackExchange" }
Q: AC power adapter wattage and type cannot be determined - battery won't charge I am currently living in Japan but using a Dell XPS 13 bought in the U.S but with a Swedish charger, I thus have to use a power converter in order to fit my charger into the Japanese plugs. In the beginning I had no problems with this at all, but then suddenly this message was displayed when I turned on the laptop(which got Ubuntu 16.04 installed): Warning Message I was not allowed to post images so I'll write down the text here instead: "Alert! The AC power adapter wattage and type cannot be determined. The battery may not charge. The system will adjust the performance to match the power available." I can hit F1 and start the laptop anyway and it runs fine as long as the power plug is connected, but the battery won't charge at all. The strange thing is that this happened the first time a couple of weeks ago but then suddenly it disappeared for a while and the battery would charge just fine. Then it returned and now it's been like this for over a week. I haven't been able to find any information regarding this online and I have tried two different power converters with the same result. Any ideas how this can be fixed? A: The warning signal was from BIOS and had nothing to do with Ubuntu. Turns out there was something wrong with my charger making it unable to charge the battery. Replacing the charger with a new one fixed the problem and the battery now charges as it should.
{ "pile_set_name": "StackExchange" }
Q: Adding a Javascript Array To a Numbered List I have a predefined array list that I need to be formatted into a numbered list in HTML. I'm very new to html with javascript and am having a hard time with dom manipulation here is my js code var fruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos']; here is my html <div id="fruits"> </div> <h3>Fruits</h3> ` its very bare bones and that's simply because I have no idea where to start. A: You can use DOM like below. This code loops through your array, and adds each element to an ordered list. var fruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos']; var listOfFruits = []; var list = document.getElementById("list"); fruits.forEach(function(element) { listOfFruits.push("<li>" + element + "</li>"); }); list.innerHTML = listOfFruits.join(''); <ol id="list"></ol> Or you can use jQuery like below. This code loops through your array and appends a <li> to your html. var fruits = ['Apples', 'Oranges', 'Pears', 'Grapes', 'Pineapples', 'Mangos']; var listOfFruits = []; fruits.forEach(function(element) { listOfFruits.push("<li>" + element + "</li>"); }); $("#list").html(listOfFruits.join('')); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ol id="list"></ol>
{ "pile_set_name": "StackExchange" }
Q: Search recursively for all files with a .sql extension and pass them to mysql as argument Given: Directory tree that contains files with .sql extension. Requred Find them all recursively and pass found files one by one to mysql client as: mysql < ./dir/subdir/subsubdir/schema.sql My feeble attempt find . -name '*.sql' | xargs mysql Results in: ERROR 1049 (42000): Unknown database './dir/subdir/subsubdir/schema.sql' Question How to do it right? Thanks! A: I believe this will work find . -type f -name '*.sql' -exec bash -c 'cat '{}' | mysql' \; Basically the above finds all files ending in .sql (I put the -type f in there just in case there are any directories that end in .sql). For each file found, find runs the exec command. The exec runs a bash sub-shell that cats the file and pipes that to the mysql program. Hope this helps.
{ "pile_set_name": "StackExchange" }
Q: Using loops within CSV export - Ruby I'm trying to DRY up my code and wondering if many people have experience with CSV's and ruby. My code is below. It works just... Its awful. I'm wondering if anyone has any ideas on how I could do the following: 1 - How could I use a loop rather than explicit 1..10 that I've done. I did try a few ways but couldn't get them to work with CSV. 2 - Is there a nicer way to do headers in CSV? 3 - Any other ideas on how to make CSV code nicer? I initially went with this (1..10).each do |number| end However the csv system didn't like that one! It was thinking my end statements were incorrect however, I don't think this was the case. Here's my code. If you have any bright ideas you're awesome! Yes I know it's awful, just wondering how I could do it better! require 'csv' class CampagignsCsv class << self HEADERS = [ 'Job Title', 'Business Name', 'Business Contact Name', 'Location', 'Job Status', 'Created date', 'Last Modified date', '# Positions', 'Description', 'Std/Prem', 'Referral code (To discuss)', 'Coupon code (To discuss)', 'Question1', 'Knockout?1', 'Correct Answer1', 'Question2', 'Knockout?2', 'Correct Answer2', 'Question3', 'Knockout?3', 'Correct Answer3', 'Question4', 'Knockout?4', 'Correct Answer4', 'Question5', 'Knockout?5', 'Correct Answer5', 'Question6', 'Knockout?6', 'Correct Answer6', 'Question7', 'Knockout?7', 'Correct Answer7', 'Question8', 'Knockout?8', 'Correct Answer8', 'Question9', 'Knockout?9', 'Correct Answer9', 'Question10', 'Knockout?10', 'Correct Answer10' ].freeze def report puts 'campaigns_report.csv created in reporting_output folder' CSV.open("reporting_output/campagins_report.csv", "wb") do |csv| csv << HEADERS Paddl::Models::Job.all.each do |job| csv << [ job.title, job.employer.business_name, job.employer.profile.full_name, job.address, job.status, job.created_at, job.updated_at, job.num_of_positions, job.description, job.employer.account_type, 'null', 'null', job.job_questions.map { |item| item[:question] }[1], job.job_questions.map { |item| item[:knockout] }[1], job.job_questions.map { |item| item[:correct_answer] }[1], job.job_questions.map { |item| item[:question] }[2], job.job_questions.map { |item| item[:knockout] }[2], job.job_questions.map { |item| item[:correct_answer] }[2], job.job_questions.map { |item| item[:question] }[3], job.job_questions.map { |item| item[:knockout] }[3], job.job_questions.map { |item| item[:correct_answer] }[3], job.job_questions.map { |item| item[:question] }[4], job.job_questions.map { |item| item[:knockout] }[4], job.job_questions.map { |item| item[:correct_answer] }[4], job.job_questions.map { |item| item[:question] }[5], job.job_questions.map { |item| item[:knockout] }[5], job.job_questions.map { |item| item[:correct_answer] }[5], job.job_questions.map { |item| item[:question] }[6], job.job_questions.map { |item| item[:knockout] }[6], job.job_questions.map { |item| item[:correct_answer] }[6], job.job_questions.map { |item| item[:question] }[7], job.job_questions.map { |item| item[:knockout] }[7], job.job_questions.map { |item| item[:correct_answer] }[7], job.job_questions.map { |item| item[:question] }[8], job.job_questions.map { |item| item[:knockout] }[8], job.job_questions.map { |item| item[:correct_answer] }[8], job.job_questions.map { |item| item[:question] }[9], job.job_questions.map { |item| item[:knockout] }[9], job.job_questions.map { |item| item[:correct_answer] }[9], job.job_questions.map { |item| item[:question] }[10], job.job_questions.map { |item| item[:knockout] }[10], job.job_questions.map { |item| item[:correct_answer] }[10] ] end end end end end A: How's this? ... job.employer.account_type, 'null', 'null', *1.upto(10).flat_map {|i| jq = job.job_questions[i] [jq[:question], jq[:knockout], jq[:correct_answer]] } ...
{ "pile_set_name": "StackExchange" }
Q: Why do we feel gravity on a plane? How come a plane flying at constant velocity experiences gravity? If you were in a space capsule flying (not accelerating) you would feel weightless until you hit the ground. Why not a plane? A: This is the difference between flying and in orbit. In orbit, you are indeed falling toward the earth, but the spacecraft is too, and you're going fast enough that you keep missing the earth. In an aircraft, because it's staying aloft due to lift, it is not falling. This is why you experience the pull of gravity on a plane. Some aircraft are designed to feel weightlessness, see Vomit comet. A: Why do we feel gravity on a plane? Exactly for the reasons we feel gravity when traveling on a train: We're not free falling (the cabin floor prevents this to happen). We're not at orbital speed which is about 28,460 km/h. We're not flying very tight curves that could create a free fall (but only for a few seconds anyway). Gravity and weight Everything is weighty everywhere in the cosmos as soon as it is subject to some acceleration (e.g. gravity acceleration, but not limited to it) and it tries to oppose this acceleration. So there are only two means to escape gravity acceleration effects: Remove gravity with another exactly opposite acceleration. This is "the satellite way". The satellite own speed and its circular trajectory create (as viewed from the satellite) a centrifugal acceleration exactly opposite to gravity acceleration. Effects of both accelerations disappear. Remove everything preventing gravity to fully act, this is "the free fall way". Gravity wants us to fall, then we just remove everything preventing us to fall, starting with the floor and/or the ground. When we jump from some height we're in micro-gravity for a short time, and then at the hospital if we underestimated the time. This is also what some aircraft do for 30s to train astronauts ("0G flight"). While the gravity still exists, its effects are cancelled by accelerating with the "gravity flow". In both cases, the aircraft and the satellite experiences "micro-gravity" (which means a residual gravity in the order of some $\small \mu g$). Any mass subject to micro-gravity is (nearly) weightless. For the physicists here, there is actually a single case, as a satellite in orbit is also in free fall and there is no centrifugal force, provided we select the appropriate frame of reference for the observer (an inertial frame). If we wanted to be even more rigorous, Einstein also intuited gravity is actually fictitious (if I may say) itself, an idea which led him to the discovery of the general relativity and the space-time curvature Constant velocity vs constant speed How come a plane flying at constant velocity experiences gravity? Micro-gravity never happens in a trajectory at constant velocity. The reason is because constant velocity is constant speed and also constant direction: Constant speed means we are not free falling, else we would accelerate towards Earth. Constant direction means we are not creating any centrifugal acceleration either, because it requires changing direction. When satellites are in circular orbit, they are not at constant velocity, they are at constant speed. Following their orbit, the direction of their displacement is constantly adjusted, hence velocity constantly varies, which allows them to create a centrifugal acceleration exactly opposite to gravity. Can we create micro-gravity on a plane (or on a train) moving horizontally? Horizontal doesn't mean "in straight line". It means at right angle from the direction of gravity (the local vertical), so when moving horizontally on large distances, we are actually following Earth curvature. If the plane/train follows Earth curvature (hence changes direction constantly), we could in theory achieve micro-gravity, but at the condition we travel very fast, a bit faster than the ISS (27,560 km/h at the current time), about 28,460 km/h. In such case we are in orbit at altitude zero (orbital trajectory doesn't depends on altitude). This is not possible in practical, an enormous amount of power would be required and everything would melt due to friction. Micro-gravity in a plane flying a specific curve But as explained in Can one fly up side down while a glass of water keeps full due to g-forces?, we can create micro-gravity by flying a specific trajectory. In that case, the speed we are missing is replaced by constant changes in direction along the curve. This gives nice videos, like the funny weightless dog with the two unperturbed guys: Source To sum up Weightlessness is the consequence of being subject to micro-gravity which can be obtained: At constant speed we need to follow a curve which creates an acceleration exactly opposite to gravity. This either requires moving at a large and specific speed (orbital speed) or doing relatively tight turns at limited speed. In free fall we must follow the downwards trajectory and permanent acceleration dictated by gravity, which means, e.g. in 35 seconds, and 6 km lower, we are already moving hypersonic! Not so comfortable, and that's only for the first 35 seconds! For feasible and durable micro-gravity at low altitude, the two techniques must be combined. A: You never actually “feel gravity” at all†, not in orbit, not on a plane and not on solid ground either. What you do feel on ground is the earth pushing against your feet, with a force that exactly cancels out the gravitational acceleration. As soon as you stop that force, e.g. by cutting the ropes in an elevator, the gravitational acceleration would very quickly change your velocity, downwards, which of course inevitably brings you back to the ground (where it will hurtfully reaffirm its upward force...) in situations like an elevator. We're completely used to that upwards force as the normal state, so much that we don't even notice it as a force and instead talk about the “gravitational down force”, but physically that's not really the force that's there. In a plane, the situation is much the same: the force you're feeling is the force of air flowing around the wings, pushing the entire plane upwards. Without that force, the plane quickly stops travelling at constant velocity and instead travels ever faster towards the ground. Now, for a space capsule in orbit, this actually happens as well: here, there isn't any force counteracting the gravitational acceleration, so it is in free fall. But because it has a blisteringly fast horizontal velocity, there's not enough time for it to fall down onto the ground – it “misses the Earth” instead, and thus continues its orbit. †The only place where you could actually feel gravity itself is close to a black hole, where your body would be getting stretched out by the tidal forces... but that never happens in homogeneous gravity field, and any sufficiently large/distant field is approximately homogeneous.
{ "pile_set_name": "StackExchange" }
Q: Different twist on "public" is or are? I just read this sentence: "Note that 'public' have also other usages:" Since in this use of "public," we're talking about the word itself & not the group it's referring to, shouldn't the verb be "has"? (Is "the general public" redundant?) A: You are quite right -- the verb must be "has". (Perhaps the writer meant to say "can have".) But "has also" is wrong too; it should be "also has".
{ "pile_set_name": "StackExchange" }
Q: Coldfusion/Oracle - Inserted BLOB Value is Returning an Empty String Using coldfusion 8, blob values selected from a table are appearing as "[empty string]". Is there a mistake in my cfml or is there another issue? I appreciate the help! ColdFusion Server - 8,0,1,195765 Oracle Database 11g - 11.2.0.3.0 - 64bit BLOB test - <cfset idval="1"> <cfset val="hello world"> <cfset encoding="utf-8"> <!---STRING CONVERSION TO BINARY DATA---> <cfset form.binVal = CharsetDecode(val,encoding)> <cfdump var="#form.binVal#"> <!---CLEAR TABLE---> <cfquery name="delete" datasource="DATA1"> DELETE FROM DATA1.TEST_BLOB </cfquery> <!---INSERT---> <cfquery name="insert" datasource="DATA1"> INSERT INTO DATA1.TEST_BLOB VALUES(<cfqueryparam value="#idval#">, <cfqueryparam cfsqltype="CF_SQL_BLOB" value="#form.binVal#"> ) </cfquery> <!---SELECT AND DISPLAY DATA---> <cfquery name="select" datasource="DATA1"> SELECT * FROM DATA1.TEST_BLOB </cfquery> <cfdump var="#select#"> A: A utl_raw.cast_to_Varchar2() is needed to get results: <cfquery name="select" datasource="DATA1"> SELECT UTL_RAW.CAST_TO_VARCHAR2(DBMS_LOB.SUBSTR(*name_of_field*)) FROM DATA1.TEST_BLOB </cfquery> OR To return the data without casting Go to the CF admin setting for the DSN, there are advanced setting that enable BLOB data
{ "pile_set_name": "StackExchange" }
Q: Stop-loss Order, Market Price, and Volume How does volume affect when a stop-loss order is triggered? Assume a stock is trading at 100$ per share. Person A places a stop-loss order at 90$ for 1000 shares. Can Person B sell a single share for say 1$ and trigger A's stop-loss order which would create a market order to sell all 1000 shares? If not, what prevents it? Is the sale of a single share for 1$ not the market price? If so, how should stop-loss orders be used to prevent this? A: Ultimately you should not trust any answer we can give, but you should ask your broker. They will tell you what they are legally obligated to follow. Whereas the answers we give might not apply to your broker. Generally, volume affects it in two ways: If it is very low, it won't trigger the stop, or the results might be unexpected based on conventional purpose of a stop. This is a consequence of extremely low liquidity, and shouldn't be an issue unless you're trading some crazy penny stocks. My broker usually says that only transactions of 100 shares will trigger stops, but I trade mostly NYSE and NASDAQ stocks and never had a problem due to this. If it is too low in relation to the size of your order, the price you get might not be very good. There's nothing mysterious here if you recall that a stop loss is just a market order placed once some condition is met. You may do a market sell at $100, but if it's for 1,000,000 shares, maybe the (average) price goes up to $123.45 for the whole order because the order book is shallow. In your example, nothing would happen because B sold only 1 share, which is too small to trigger the stop. But let's say he bought, 100 shares or whatever the threshold is. The price would drop suddenly to $1. B's stop would be triggered, because it is a stop loss it would become a market sell for 1000 shares. Market sell means best price on the market, there's two ways that can turn out: When the market participants see A drop 99%, a lot of them will suspect that the drop is a fluke rather than genuine loss of value, and regard it as a discount buying opportunity. They will quickly buy up shares and drive the price back up. Nowadays with algos this can even happen in nanoseconds. By the time the broker gets around to filling B's small fry 1000 share market sell, the best price will be a lot closer to $100 than to B's $1. A might make or lose some money from the volatility. He will have to deal with the hassle of rebuying the stock, repaying the commission, and re-issuing the stop. He will then consider trading a less crappy stock. When looking at the graph, it will look like a sharp spike down, and immediate recovery back up. If the market "believes" A's tiny $1 sale, then the new normal becomes that the stock is suddenly worth a lot less than it used to be. This can actually happen if A is the first person reacting to a bankruptcy for instance. So B's stop will trigger and probably go for $1 a share. B has 99% loss because his stock suddenly crashed. He will have to deal with the hassle of his wife asking for a divorce, selling his car and using public transit, and become the laughing stock of his social circle. He will consider a different hobby. When looking at the graph, it will look like a sharp step down (sometimes called a "gap down"). However, there is one more thing to add. For us small retail traders, "trading" may seem like everyone just trades with this guy: In reality it really is like a literal marketplace, with everyone constantly hawking out buy/sell offers: Except it's not done by yelling, but electronically and by big brokers. The broker does the hawking so you don't have to, which is why you pay them a commission. The point is, when the broker sees that A wants to sell for $1 but the stock goes for $100, they will sell it for (eg.) $99.5 and give the $98.5 to A, because brokers are nice like that. If so, how should stop-loss orders be used to prevent this? Well, ultimately you can't. Anything can happen, nobody can predict the future. Welcome to the markets! :) But generally: Don't trade stocks with low liquidity. Look at the chart and note any major gap up/downs. Ask your broker how they handle stops and act accordingly. Set a stop-limit order. This is just like a stop-loss but converts to a limit order instead of market. So it's like saying "sell this sucker if it falls below X, but don't take less than Y". Of course, if the price legitimately breaks below Y, the limit won't execute, and then you're stuck holding a bag of worthless X. Welcome to the markets! :)
{ "pile_set_name": "StackExchange" }
Q: How to print array in format [1, 2, 3, 4 ,5] with string.Join in C#? i have an array 1 2 3 4 5 in C#. I just want to print in format with: [] ; Ex. [1, 2, 3, 4, 5] A: You can use string.Format and string.Join combined var output = string.Format("[{0}]", string.Join(",", yourArray)); and then you just need to print output string anywhere you want. String.Format will provide you with possibility to wrap joined string with [ and ] without concatenating string manually.
{ "pile_set_name": "StackExchange" }
Q: Windows Explorer Stuck on Cancelling Does this ever happen to you? When try to copy a file and suddenly you want to cancel it or in my case I was try to write it over a network drive and I lost the connection. But regardless what's the reason this annoying box just doesn't go away. Anyone know why this is happening? or How I can prevent such happen over and over again? A: Not sure why it happens, but I get it too. To get rid of this annoying dialog you need to kill explorer and restart it: from Task Manager, Processes tab, find explorer.exe and choose "End Process" still in Task Manager, select File → New Task → type explorer → OK A: Try a copy program that handles exceptions better like TeraCopy or Unstoppable Copier. Both free, fast, and far more reliable than Windows' native copy. http://teracopy-portable.en.softonic.com/ http://www.roadkil.net/program.php?ProgramID=29
{ "pile_set_name": "StackExchange" }
Q: Django: resetting password without a CSRF token I have a Django website that manages Users. Using the built-in functionality, users can request a password reset from the website and that works great. I have implemented it according to this tutorial so I am using the built-in password reset functionality. I have an Android app from which users should also be able to request a password reset. The problem is that I do not have a CSRF token in the application, and the the built-in password_reset method has the @csrf_protect decorator. This means that I cannot access it without a CSRF token and I also can't modify it with the @csrf_exempt decorator. So the next idea is to create a function, which generates a CSRF token, stores it in the request and redirects to the correct URL which sends the reset email. The problem is that according to this, django does not allow to pass POST parameters further in a redirect. Therefore my question is how can I request a password reset in Django without a CSRF token? Alternatively, what is the correct way to request this from an application? A: I found a solution myself. Please feel free to post any alternative solutions. One that doesn't require two separate requests would be particularly great. If you look at the password_reset method, you can see that it only tries to process the request as a reset request if the request method is POST. Otherwise it just returns a TemplateResponse containing a form. This also contains the CSRF token as a cookie. So first, I send a GET request to http://myaddress.com/user/password/reset/ and extract the CSRF cookie from the response. Then I send a POST request containing the cookie, the email address and 2 headers (see below). This is the code I've implemented to achieve this from Android (trimmed): String url = "http://myaddress.com/user/password/reset/"; GET Request: HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); CookieStore cookieStore = new BasicCookieStore(); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpResponse httpResponse = httpClient.execute(httpGet, localContext); Cookie csrfCookie = null; for (Cookie cookie : cookieStore.getCookies()) { if (cookie.getName() == "csrftoken") { csrfCookie = cookie; break; } } if (csrfCookie == null) { throw new NullPointerException("CSRF cookie not found!"); } return csrfCookie; Note that you want the CookieStore from org.apache.http.client. POST Request: HttpClient httpClient = new DefaultHttpClient(); HttpContext localContext = new BasicHttpContext(); HttpPost httpPost = new HttpPost(url); // Prepare the cookie store to receive cookies. CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(csrfCookie); httpPost.setHeader("Referer", url); httpPost.setHeader("X-CSRFToken", csrfCookie.getValue()); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); builder.addTextBody("email", emailAddressToReset); httpPost.setEntity(builder.build()); HttpResponse httpResponse = httpClient.execute(httpPost, localContext); if (httpResponse.getStatusLine().getStatusCode() != 200) { throw new Exception("Could not reset password!"); } Toast.makeText(context, "Password reset requested! Please check your email inbox!", Toast.LENGTH_LONG).show();
{ "pile_set_name": "StackExchange" }
Q: How to prepare warmup request file for tensorflow serving? Current version of tensorflow-serving try to load warmup request from assets.extra/tf_serving_warmup_requests file. 2018-08-16 16:05:28.513085: I tensorflow_serving/servables/tensorflow/saved_model_warmup.cc:83] No warmup data file found at /tmp/faster_rcnn_inception_v2_coco_2018_01_28_string_input_version-export/1/assets.extra/tf_serving_warmup_requests I wonder if tensorflow provides common api to export request to the location or not? Or should we write request to the location manually? A: At this point there is no common API for exporting the warmup data into the assets.extra. It's relatively simple to write a script (similar to below): import tensorflow as tf from tensorflow_serving.apis import model_pb2 from tensorflow_serving.apis import predict_pb2 from tensorflow_serving.apis import prediction_log_pb2 def main(): with tf.python_io.TFRecordWriter("tf_serving_warmup_requests") as writer: request = predict_pb2.PredictRequest( model_spec=model_pb2.ModelSpec(name="<add here>"), inputs={"examples": tf.make_tensor_proto([<add here>])} ) log = prediction_log_pb2.PredictionLog( predict_log=prediction_log_pb2.PredictLog(request=request)) writer.write(log.SerializeToString()) if __name__ == "__main__": main()
{ "pile_set_name": "StackExchange" }
Q: How do I access Postgres when I get an error about "/var/run/postgresql/.s.PGSQL.5432"? I am running Ubuntu 16. I have installed Postgresql. Postgresql used to work, but then I rebooted. nmap commands show port 5432 is open. Postgres seems to be working correctly: service postgresql status postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled) Active: active (exited) since Sat 2017-07-29 18:42:59 EDT; 1min 4s ago Process: 201 ExecStart=/bin/true (code=exited, status=0/SUCCESS) Main PID: 201 (code=exited, status=0/SUCCESS) Memory: 0B CGroup: /system.slice/postgresql.service I ran this: psql But I got this: psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? The file listed above does not seem to exist. How do I get into Postgresql? Normally I'd run psql or sudo -i -u postgres then psql. But these commands are not working. I keep getting an error about "could not connect to server." Several reboots have not helped. Update: I ran this command: dpkg -l | grep postgres rc postgresql-9.5 9.5.6-0ubuntu0.16.04 amd64 object-relational SQL database, version 9.5 server ii postgresql-client 9.5+173 all front-end programs for PostgreSQL (supported version) ii postgresql-client-9.5 9.5.7-0ubuntu0.16.04 amd64 front-end programs for PostgreSQL 9.5 ii postgresql-client-common 173 all manager for multiple PostgreSQL client versions ii postgresql-common 173 all PostgreSQL database-cluster manager A: You probably have multiple PostgreSQL versions installed. If so, the other version probably defaults to unix_socket_directories = '/tmp/' but the libpq your psql is linked to probably defaults to /var/run/postgresql/. Try psql -h /tmp If that works, the above is the problem. You can add export PGHOST=/tmp to your .bashrc to change the default locally for your user. If that doesn't work, make sure PostgreSQL is actually running ps aux |grep postgres and if not, start it. How depends on how you installed it, but it'll be via the service or systemctl command(s) if you installed using packages. A: If your Postgres service is up and running without any error or there is no error in starting the Postgres service and still you are getting the mentioned error, follow these steps Step1: Running pg_lsclusters will list all the postgres clusters running on your device eg: Ver Cluster Port Status Owner Data directory Log file 9.6 main 5432 online postgres /var/lib/postgresql/9.6/main /var/log/postgresql/postgresql-9.6-main.log most probably the status will be down in your case . Try restarting Postgres clusters and service Step 2: Restart the pg_ctlcluster #format is pg_ctlcluster <version> <cluster> <action> sudo pg_ctlcluster 9.6 main start #restart postgresql service sudo service postgresql restart Step 3: Step 2 failed and threw an error If this process is not successfull it will throw the error. My error was(You can see the error log on /var/log/postgresql/postgresql-9.6-main.log) FATAL: could not access private key file "/etc/ssl/private/ssl-cert-snakeoil.key": Permission denied Try adding `postgres` user to the group `ssl-cert` Step 4: check ownership of postgres Make sure that postgres is the owner of /var/lib/postgresql/version_no/main eg: sudo chown postgres -R /var/lib/postgresql/9.6/main/ Step 5: Check Postgres user belongs to ssl-cert user group It happened to me and it turned out that I removed erroneously the Postgres user from "ssl-cert" group. Run the below code to fix the user group issue and fixing the permissions #set user to group back with sudo gpasswd -a postgres ssl-cert # Fixed ownership and mode sudo chown root:ssl-cert /etc/ssl/private/ssl-cert-snakeoil.key sudo chmod 740 /etc/ssl/private/ssl-cert-snakeoil.key sudo service postgresql restart A: psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? This error generally means that the server is not running. Based on dpkg -l output and the thread of comments, it was due to the postgresql-9.5 main package being somehow uninstalled. Since the uninstall hasn't been called with the --purge option to dpkg, the data and configuration files are still there, so apt-get install postgresql-9.5 can fix the problem.
{ "pile_set_name": "StackExchange" }
Q: Ruby on Rails - Referencing Image in Javascript I'm using jquery.infinitescroll.js in my Rails 5.0 app. I have the script in my Vendor directory, and I'm trying to customize the JS to use a different image. I can do it, if I set this property: img: "/img/loading.gif", I tried adding the image in a directory called img in the Vendor directory, but that didn't work. I also tried setting the property to "/image/loading.gif" and the image still couldn't be found. What's the best way to handle this? A: One approach is to append .erb extension to your jquery.infinitescroll.js. And, in jquery.infinitescroll.js.erb, you can use the asset_path method: { /* ... */ img: '<%= asset_path('loading.gif') %>' /* ... */ } You must move your image to the app/assets/images folder. Or, if you want to use it in a custom folder, add this path to the assets search path with config.assets.paths << Rails.root.join("vendor", "images") in config/application.rb. By the way, that's the way recommended by the docs: 2.3.3 JavaScript/CoffeeScript and ERB If you add an erb extension to a JavaScript asset, making it something such as application.js.erb, you can then use the asset_path helper in your JavaScript code: $('#logo').attr({ src: "<%= asset_path('logo.png') %>" }); This writes the path to the particular asset being referenced.
{ "pile_set_name": "StackExchange" }
Q: Conditional probability given two events Is the following probability correct given that $W$ and $H$ depend on $G$? $$P(G\mid w,h) = \frac{P(w\mid G)\cdot P(h\mid G)\cdot P(G)}{\left(P(w\mid G) P(G)+P(w\mid \overline{G}) P(\overline{G})\right) \cdot \left(P(h\mid G) P(G)+P(h\mid \overline{G}) P(\overline{G})\right)} $$ A: More information on the dependancies of W and H is needed. Generally: $$\mathsf P(G\mid W,H) ~=~ \dfrac{\mathsf P(W, H\mid G)~\mathsf P(G)}{\mathsf P(W, H)}$$ Now, if events $W$ and $H$ depend on event $G$ but are conditionally independent given $G$, then the numerator you want occurs: $$\mathsf P(G\mid W,H) ~=~ \dfrac{\color{navy}{\mathsf P(W\mid G)~\mathsf P(H\mid G)~\mathsf P(G)}}{\mathsf P(W\mid G)~\mathsf P(H\mid G)~\mathsf P(G)+\mathsf P(W\mid\overline G)~\mathsf P(H\mid\overline G)~\mathsf P(\overline G)}$$ On the other hand if events $W$ and $H$ depend on event $G$ but are pairwise independent, then the denominator you want occurs: $$\begin{align} \mathsf P(G\mid W,H) ~=~& \dfrac{\mathsf P(W, H\mid G)~\mathsf P(G)}{\mathsf P(W)~\mathsf P(H)} \\ = ~& \dfrac{\mathsf P(W, H\mid G)~\mathsf P(G)}{\color{navy}{\Big(\mathsf P(W\mid G)~\mathsf P(G)+\mathsf P(W\mid\overline G)~\mathsf P(\overline G)\Big)~\Big(\mathsf P(H\mid G)~\mathsf P(G)+\mathsf P(H\mid\overline G)~\mathsf P(\overline G)\Big)}} \end{align}$$ To mix and match, both scenarios would need to be so.
{ "pile_set_name": "StackExchange" }
Q: Introduce syntax highlighting for fixed font messages in chat For a chat that's supposedly catering for developers, it lacks developer specific features. Reading code fragments in messages is annoying because there is no syntax highlighting. The existing solution is already used on the SO proper: deduce the language from the list of the tags on the chatroom (just like SO does with the tags on the question) A: This would work well, if the algorithm that detects what programming language a code block is based on its contents and the tags was perfect. But it's not. In many cases, it does identify the language correctly; in cases where it doesn't, the lang-default scheme works well enough. But in certain cases, the lang-default scheme completely screws up the highlighting, in such a way that the code is better off not highlighted at all. If the feature, as implemented, is going to force automatic language detection on every code block without a way to specify a hint when needed, I'd rather none be highlighted at all. I've never had any issues with reading code on chat as it is, and I've never heard any chat user complain about the lack of syntax highlighting, even in code that I share. On the other hand, I've heard many chat users complain about people dumping entire class definitions into chat and failing to explain their problem, as often seen on SO proper. If the feature, as implemented, is going to allow hinting individual code blocks per message (as well as the choice of opting out entirely with lang-none), I could see that getting somewhere. It depends on how exactly this hinting feature would be implemented (add Markdown hints to the chat message parser? Have a separate dialog for it?). But this is chat we're talking about, not Q&A. Plus, only a fraction of the sites on the network will benefit from this feature. I reckon the developers will prioritize based on that.
{ "pile_set_name": "StackExchange" }
Q: how to get current device on Mac Is there any way to get the device info that user is using? I just want to know the device is MacBookPro or iMac. [[NSHost currentHost] localizedName] is used to get info from web. A: You can use int sysctlbyname(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen); Take a look at documentation. size_t size; sysctlbyname("hw.model", NULL, &size, NULL, 0); char *model = malloc(size); sysctlbyname("hw.model", model, &size, NULL, 0); NSLog(@"%s", model);
{ "pile_set_name": "StackExchange" }
Q: Contacts Matching I have the below Models: class UserModel(User): mobile_number = StringField common_name = StringField class Contacts(models.Model): user = ForeignKey(UserModel) mobile_number = StringField name = StringField and I created a new UserModel of non repeated mobile number and most commonly used name from Contacts Model. I implemented it by using: from collections import Counter Any professional suggestions ? to get the common name from Contacts Model of each mobile_number of Contacts Model A: contact_list = Contacts.objects.all().order_by('name') name = None for contact in contact_list: if contact.name != name: print '-- New Name --' print 'name: %s' % contact.name name = contact.name print 'phone number: %s' % contact.phone It's one of millions solutions.. above you have contact_list ordered by names. Counter from collections is also a good approach.. even better then this.
{ "pile_set_name": "StackExchange" }
Q: How can I import my excel file to php myadmin without converting it to csv format How can I import my excel file to php myadmin without converting it to csv format, considering the excel file is too large. A: got my answer...and it worked perfectly. answer- http://itsolutionstuff.com/post/php-import-excel-file-into-mysql-database-tutorialexample.html
{ "pile_set_name": "StackExchange" }
Q: Mesh intersection in three.js after modifying vertices/position I have a mesh inited with plane geometry with placeholder parameters (like xyz 0, wh 100). Later I set actual position for the mesh and 4 vertices for the geometry, and it renders fine. However when I try to intersect the mesh with raycaster, I get intersections only where it was inited, not where it's rendered after parameters were set. What should I call after vertices/position update for the mesh to be intersectable? A: You need to recompute the geometries boundingBox and/or boundingSphere using computeBoundingBox() and/or computeBoundingSphere() method. This should do the trick
{ "pile_set_name": "StackExchange" }
Q: Android Intent Clear Top not working I want to hit an intent to my HomeScreenActivity and clear all the activity that are alive in the Stack, below is the intent code: Intent intent = new Intent(activity, HomeScreenActivity.class); if (Build.VERSION.SDK_INT >= 11) { intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); } intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(intent); finish(); The stack is not getting cleared and when i press the back key, all the previous activity are shown, which is not the expected result. Please help! Thanks in advance. A: Use both flags at the same time: intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); First flag creates new activity when it isn't available in the current task (stack of activities) or reuses existing one. Second flag clears a task associated with requested activity.
{ "pile_set_name": "StackExchange" }
Q: Macro to Copy/Paste Data Here is the code I have. I am trying to find the last populated row in a range. Then copy that data as formulas to the next blank row in the range. Finally copy the last populated row again and paste it to the second to last populated row as values. In a nutshell, move the formulas in the last row/cells down one row and retain that data where it was copied as numbers. So when new data is brought into the file, the formulas recalculate and I do not lose the previous calculated data. Hopefully that makes sense. The below code runs but does not appear to do anything other than to paste the data as values in the existing rows. What am I doing wrong? Sub Data Copy() Dim myLastCell As Range Set myLastCell = LastCell(Worksheets("YTD Metric Calculator").Range("E7:J76")) Sheets("YTD Metric Calculator").Range("E7:J" & myLastCell.Row).Copy Sheets("YTD Metric Calculator").Range("E7:J" & myLastCell.Row + 1).PasteSpecial Paste:=xlPasteFormulas Sheets("YTD Metric Calculator").Range("E7:J" & myLastCell.Row).Copy Sheets("YTD Metric Calculator").Range("E7:J" & myLastCell.Row + 1).PasteSpecial Paste:=xlPasteValues 'Retain Yesterday's YTD Metric Data Function LastCell(r As Range) As Range Dim LastRow&, lastCol% On Error Resume Next With r LastRow& = .Cells.Find(What:="*", _ SearchDirection:=xlPrevious, _ SearchOrder:=xlByRows).Row lastCol% = .Cells.Find(What:="*", _ SearchDirection:=xlPrevious, _ SearchOrder:=xlByColumns).Column End With Set LastCell = r.Cells(LastRow&, lastCol%) End Function VBA Goal A: Your LastCell function isn't doing what you think it is doing, because it is determining the row and column within the worksheet of the last used cell in the range, and then using that as an offset from the start of the range. So if the last used row in E7:J76 was row 10, and the last used column was column I, the cell being returned from your function is cell M16 (i.e. 9 rows below E7, and 8 columns to the right). Change Set LastCell = r.Cells(LastRow&, lastCol%) to be Set LastCell = r.Cells(LastRow& - r.Row + 1, lastCol% - r.Column + 1) or to Set LastCell = r.Worksheet.Cells(LastRow&, lastCol%) The parts where you are copying the formulas, and then replacing with values, should be something like: Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row).Resize(1, 6).Copy Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row + 1).Resize(1, 6).PasteSpecial Paste:=xlPasteFormulas Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row).Resize(1, 6).Value = _ Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row).Resize(1, 6).Value That can be rewritten using a With block to save a few keystrokes: With Sheets("YTD Metric Calculator").Range("E" & myLastCell.Row).Resize(1, 6) .Copy .Offset(1, 0).PasteSpecial Paste:=xlPasteFormulas .Value = .Value End With
{ "pile_set_name": "StackExchange" }
Q: After each push to Heroku I get 404 errors on images I am having issues with my Rails App on Heroku. code-dojo.herokuapp.com After every push to heroku any images I uploaded with Carrierwave Gem return a 404 error message. Do I need to precompile this folder or point to it ? Does Heroku replace this folder with a blank one? Should I create my app with all the images on locathost and then push the database? A: Heroku is Read-only Filesystem The following types of behaviors are not supported: Caching pages in the public directory Saving uploaded assets to local disk (e.g. with attachment_fu or paperclip) Writing full-text indexes with Ferret Writing to a filesystem database like SQLite or GDBM Accessing a git repo for an app like git-wiki
{ "pile_set_name": "StackExchange" }
Q: Losing php empty post entries I have a strange situation in one of my servers. Whenever I post a form that contains an empty value for a given post key, when I try to read that key from the $_POST array it is not set as expected. I expect: isset($_POST[$k]) == true But I get: isset($_POST[$k]) == false I have not been able to find evidence of this problem anywhere else in the web. I have two servers and in one of them it happens and in the other one it does not. I have no idea if it could related to my version of PHP, or Apache, or some configuration file. Test scenario: <?php print_r($_POST['param']); ?> <form action="posttest.php" method="post"> <input type="text" name="param[text1]" value="1"><br> <input type="text" name="param[text2]" value=""><br> <input type="text" name="param[text3]" value="3"><br> <input type="text" name="param[text4]" value=""><br> <input type="text" name="param[text5]" value="4"><br> <button type="submit">Send</button> </form> Server A (the good one) Data: PHP Version 5.4.45 Echoes this: [param] => Array ( [text1] => 1 [text2] => [text3] => 3 [text4] => [text5] => 4 ) Server B (the faulty one) Data: PHP Version 5.6.20 Echoes this: [param] => Array ( [text1] => 1 [text3] => 3 [text5] => 4 ) I don't know what more info to add to the question, so if you have a clue and need more information please let me know and I will update the question A: The problem has disappeared and it was after running an EasyApache on my WHM console. Maybe it was a misconfiguration or a bug in the php binary I was using, who knows.
{ "pile_set_name": "StackExchange" }
Q: What does this error in Sass mean? "Illegal nesting: Only properties may be nested beneath properties." This is my code html, body { width: 100%; height: 100%; padding: 0; margin: 0; } body { font-family: 'Open Sans'; } .navigation { padding: 0; margin: 0; background: #333; position: fixed; top: 0; z-index: 999; width: 100% li { display: inline; padding: 5px 10px; a { color: #e1e1e1; text-decoration: none; a:hover{color: lighten(#e1e1e1, 20%);} } } } But whenever I build it and refresh the webpage I get this error: Syntax error: Illegal nesting: Only properties may be nested beneath properties. on line 23 of style.scss here is the my css code with line numbers 18: z-index: 999; 19: width: 100% 20: li { 21: display: inline; 22: padding: 5px 10px; 23: a { 24: color: #e1e1e1; 25: text-decoration: none; 26: a:hover{color: lighten(#e1e1e1, 20%);} 27: } 28: } I guess it's the anchor tag that's creating the problem but I don't understand why. Theoretically it should work. A: You're missing a semicolon: .navigation { padding: 0; margin: 0; background: #333; position: fixed; top: 0; z-index: 999; width: 100%; <=== right here A: Although this isn't the correct answer for this specific question, others who stumble upon this article because they encounter the same error message ("Illegal nesting: Only properties may be nested beneath properties.") may find the cause to be related to using the scss_lint gem. In particular, if you've upgraded from scss-lint to scss_lint, you may need to add require: false to your Gemfile to get things working again. Reference: https://github.com/brigade/scss-lint/issues/496 Docs: https://github.com/brigade/scss-lint#installation
{ "pile_set_name": "StackExchange" }
Q: ICommand vs IValueConverter I am new to WPF. I am currently developing an application in WPF where I had to enable/disable a button based on a value from database. I found solutions on the net to do so using Command as well as Converters. So which one is a better solution and why? A: When working with buttons it would be best to use the command implementation , since it is built in and you can provide a command parameter for predicate , the converter is something you would need to write , instance and place in each place you would wan't to use it . To summarize a command with CanExecute would be more reusable and maintainable .
{ "pile_set_name": "StackExchange" }
Q: Why are browsers not caching these static files? Here's an example JavaScript file request/response: Request URL:http://local/index.js?time=1367958844038 Request Method:GET Status Code:200 OK Request Headers Accept:*/* Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 Connection:keep-alive DNT:1 User-Agent:Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31 Response Headers cache-control:max-age=31536000 content-encoding:gzip content-type:application/javascript expires:Wed, 07 May 2014 20:34:04 GMT last-modified:Tue, 07 May 2013 20:34:04 GMT transfer-encoding:chunked As you can see, the server responds with cache control, expires and even last modified, but everytime I reload with either F5 or clicking enter in location bar the request looks the same (I'd expect browser to send if-modified-since, etc.) This happens in Chrome and Firefox at least. A: Probably because the URL's time parameter changes with every request. Since the URL is different, the browser can't use the previously cached response.
{ "pile_set_name": "StackExchange" }
Q: Android- Create tabs inside fragment without v4 support library I am trying to create a 'tabs' w/o using support library for my application, but I didn't find even a simple working example/tutorial anywhere. Since my entire application is using android.app.fragment, so I cannot change all of the existing fragments to android.support.v4.app.Fragment. Creating a tab within fragment using support library is a piece of cake, but I am wondering whether we can create one w/o android.support.v4.app.Fragment. A: This can be achieved, it's easily, follow my step: 1.Copy the offical source code of FragmentTabHost to your project, and change following 3 class refrence: android.support.v4.app.Fragment to android.app.Fragment android.support.v4.app.FragmentManager to android.app.FragmentManager android.support.v4.app.FragmentTransaction to android.app.FragmentTransaction 2.Use the modify version of your FragmentTabHost in project, and forget the android.support.v4 library. My edited version: FragmentTabHost Sample code: (Show the first tab, after 5 sec delay, you will see the second tab, I run on my Android Studio successfully!) MainActivity.java public class MainActivity extends Activity { FragmentTabHost mTabHost; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTabHost = (FragmentTabHost) findViewById(R.id.tabhost); mTabHost.setup(this, getFragmentManager(), R.id.container); // Add each tab mTabHost.addTab(mTabHost.newTabSpec("first").setIndicator("first"), BlankFragment1.class, null); mTabHost.addTab(mTabHost.newTabSpec("second").setIndicator("second"), BlankFragment2.class, null); mTabHost.postDelayed(new Runnable() { @Override public void run() { mTabHost.setCurrentTabByTag("second"); } }, 5000); } } activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <com.example.bill.myapplication.FragmentTabHost android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/tabhost"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TabWidget android:id="@android:id/tabs" android:orientation="horizontal" android:layout_width="0dp" android:layout_height="0dp"/> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="0dp" android:layout_height="0dp"/> <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"/> </LinearLayout> </com.example.bill.myapplication.FragmentTabHost> </RelativeLayout>
{ "pile_set_name": "StackExchange" }
Q: Finding a closed form expression for the following recurrence relation. Given that: $S_0 = 0$ $S_1 = 3$ $S_n = S_{n-1} + 6S_{n-2}$ for $n ≥ 2$ What are the steps I would take to find the closed form expression for the following recurrence relation? A: What you are being asked for is an equation that has $x_n$ on the left side and a formula in $n$ on the right side containing just familiar functions like polynomials and exponentials and only finitely many of them. First, write it like this for simplicity: $S_0=0$, $S_1=3$, $S_n=S_{n-1}+6S_{n-2}$. Now, let's suppose there is a solution of the form $S_n=x^n$ for some $x$. Then the equation says $x^n=x^{n-1}+6x^{n-2}$, simplifies to $x^2-x-6=0$, which undoubtedly you would be able to solve. You'll get two values of $x$ that work, let's call them $x_1$ and $x_2$, and then anything of the form $$\alpha x_1^n+\beta x_2^n$$ will work also, for any numbers $\alpha$ and $\beta$.
{ "pile_set_name": "StackExchange" }
Q: Bash Functions - Create a variable with parameter's label I'm trying to create a function which will create a variable with the tag $1 (first param) and with the value $3 (third param). Here is my code: function var { if [ "$2" = "=" ]; then $1 = $3 fi } Now, I believe the reason this doesn't work is because the way I wrote this function makes bash try to overwrite the value of $1 with that of $3. Is there a work-around for this? This is what I'm aiming to do: var i = 1 var greeting = "hello" and both of these variables would be assigned their value. A: Don't use eval, use declare with the -g flag (create global variables) function var { if [ "$2" = "=" ]; then declare -g "$1=$3" fi } var foo = bar echo $foo bar
{ "pile_set_name": "StackExchange" }
Q: How can you restore health in Sword & Sworcery? Playing through Sword and Sworcery on the iPad - I've reached the point where I'm battling the first trigon. It defeated me - so I was down to 1 star health. How can I regain some health? I've gone through my stash of mushrooms and can't leave the current screen. A: Method 1 : during a fight hold up the shield for a while and you'll see a circle closing in on you - when it gets close in you gain an extra star. A: You can restore health between battles by sitting down (such as in Logfella's cabin) or by eating a mushroom.
{ "pile_set_name": "StackExchange" }
Q: How Class/Static Methods get invoked While reading The Ruby Programming Language I came to know that, class methods are invoked on an object which got the same name as class. I found objective-c also does a similar thing from a blog. Here Classes happens to be instances of meta-classes. As another major Object Oriented language i would love to know how Java implements/achieve this. Edit I appreciate the answers from everyone. But my question wasn't about how to invoke a class method. As many answers were answering that. Apologies if my question was not well framed or it gave you a wrong idea. A: In the Java language, static methods are invoked on the class instead of an object e.g. System.currentTimeMillis. So conceptually this is very similar to Ruby, ObjC, Smalltalk, etc. Unlike Ruby and Objective C, there is no object instance that those methods get invoked upon: The Java bytecode has a special bytecode instruction that invokes the static method; this bytecode instruction does not use an object pointer from the stack: INVOKESTATIC "java/lang/System" "currentTimeMillis" "()J" When using reflection, this special handling of static methods is represented by the fact that you don't need to specify an object that the method is called upon. Instead, you can supply null as the target of the call.
{ "pile_set_name": "StackExchange" }
Q: Qt5, set text size in lineEdit Is it possible to change text size (and font too) in Qt5 QLineEdit class? I looked in the official documentation but found no solution. //the font I want to use to display a message QFont littleFont("Courier New", 10); //my message QString strS = "hi all" // setting the message in my lineEdit object ui.lineEdit->setText(strS); A: As the others said in the comments: You can set the font to the line edit using this line: ui.lineEdit->setFont(littleFont); This member function can be found in the Documentation by clicking on > List of all members, including inherited members If you do not set all attributes of the Font be aware that the documentation states: When you assign a new font to a widget, the properties from this font are combined with the widget's default font to form the widget's final font. You can call fontInfo() to get a copy of the widget's final font. The final font is also used to initialize QPainter's font.
{ "pile_set_name": "StackExchange" }
Q: Query for distinct instance of model + one other field I have a model called Evaluation. When an evaluation is created, an eval_number is created with it. There are many evaluations with the same eval_number. Here's an example: - !ruby/object:Evaluation attributes: id: 2023 score: 3 created_at: 2013-09-08 13:10:53.000000000 Z updated_at: 2013-09-08 13:10:53.000000000 Z student_id: 26 goal_id: 50 eval_number: 33 - !ruby/object:Evaluation attributes: id: 2099 score: 4 created_at: 2013-09-08 13:19:12.000000000 Z updated_at: 2013-09-08 13:19:12.000000000 Z student_id: 26 goal_id: 36 eval_number: 34 - !ruby/object:Evaluation attributes: id: 2100 score: 3 created_at: 2013-09-08 13:19:12.000000000 Z updated_at: 2013-09-08 13:19:12.000000000 Z student_id: 26 goal_id: 37 eval_number: 34 - !ruby/object:Evaluation attributes: id: 2101 score: 4 created_at: 2013-09-08 13:19:12.000000000 Z updated_at: 2013-09-08 13:19:12.000000000 Z student_id: 26 goal_id: 38 eval_number: 34 In a view, I want to show the date that a given evaluation was created in a table header. It should look like this: date_1 | date_2 | date_3 | date_4 | etc.. To do this, I need to get distinct evaluation_numbers + the created_at dates that go with them. I thought that this would help, but it's returning more than one record per eval_number with this code: def eval_date(i) evals = self.goals.first.evaluations eval = evals.select("distinct(eval_number), created_at").all[i] eval.created_at.to_date end It seems like distinct eval_numbers are being selected, but also distinct created_at columns (which of course are all different). This makes the .all[i] basically useless as it's finding the [0], [1], [2], etc element correctly - but there are far more than whatever the given number of i is in the returned array. I want to find a distinct eval_number and load only the created_date that goes with it. I think I could load the whole record with all attributes, but I don't need them, so I'd rather not. A: Try this: def eval_date(i) evals = self.goals.first.evaluations eval = evals.order("eval_number").group(:eval_number).all[i] eval.created_at.to_date end PS: if you are calling eval_date repeatedly then cache the evaluations like so def eval_date(i) @evals ||= self.goals.first.evaluations.order("eval_number").group("eval_number").all eval = @evals[i] eval.created_at.to_date end
{ "pile_set_name": "StackExchange" }
Q: Flutter: multiple firebase projects in one app but showing incorrect data The last few days I spend a lot of time to read through several SO-questions and tutorials. What I'm trying to achieve is, that a user of my flutter app can choose a firebase project and log in with email/password. After the login, obviously, the correct data of the corresponding database should be shown. And that is where I fail. After a while of reading some sites and questions from SO, I went with the following site to get the first part of the login. https://firebase.googleblog.com/2016/12/working-with-multiple-firebase-projects-in-an-android-app.html After working through this article, I was able to successfully log in to my defined firebase projects. How did I know that the login was successful? I compared the user-uids from the projects with the print statement from my app in the console. That was the prove my configuration for the non-default project is correct. But now the main problem which I can't solve. After the login, the data is always of the default firebase project from the google-service.json. For state management, I choose the provider package, as they mentioned in the I/O '19. So inside my main.dart, I wrap the whole application with MultipleProvider: Widget build(BuildContext context) { return MultiProvider( providers: [ ChangeNotifierProvider<LoginModel>( builder: (_) => LoginModel(), ), ChangeNotifierProvider<Auth>( builder: (_) => Auth(), ), ], child: MaterialApp( title: 'Breaking News Tool', theme: ThemeData( primarySwatch: Colors.blue, ), home: RootPage(), ), ); } The provided Auth class is a service that connects to firebase sdk and also configure non-default apps to create the needed firebase auth abstract class BaseAuth { getDefaultAuth(); getAbnAuth(); ... } class Auth with ChangeNotifier implements BaseAuth { ... Auth() { _configureAbnApp(); _configureProdApp(); } getDefaultAuth() { _firebaseAuth = FirebaseAuth.instance; } getAbnAuth() { _firebaseAuth = FirebaseAuth.fromApp(_abnApp); } _configureAbnApp() { FirebaseOptions abnOptions = FirebaseOptions( databaseURL: 'https://[project-id].firebaseio.com', apiKey: 'AIzaSxxxxxxxxxxxxxxxx, googleAppID: '1:10591xxxxxxxxxxxxxxxxxxx'); FirebaseApp.configure(name: 'abn_database', options: abnOptions) .then((result) { _abnApp = result; }); } ... } After a log in the app redirects the user to the home_page (StatefulWidget). Here I use a snapshot of the database to show data. _stream = Firestore.instance.collection(collection).snapshots(); ... Center( child: Container( padding: const EdgeInsets.all(10.0), child: StreamBuilder<QuerySnapshot>( stream: _stream, builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.hasError) return Text('Error: ${snapshot.error}'); switch (snapshot.connectionState) { case ConnectionState.waiting: return Text('Loading...'); default: return ListView( children: snapshot.data.documents .map((DocumentSnapshot document) { return CustomCard( docID: document.documentID, title: document[title], message: document[message], fromDate: document[fromDate], endDate: document[endDate], disableApp: document[disableApp], ); }).toList(), ); } }, ), ), ), In the beginning, I only had one project to connect to and the data was correct. But now I successfully connect to another project with the correct user-uid, but the data is always from the default project which is defined by the google-service.json. And at this point, I have no clue why this happens. Did anyone have an advice or idea? A: You create your _stream based on Firestore.instance, which will give you the default firebase app, as documented in the docs: /// Gets the instance of Firestore for the default Firebase app. static Firestore get instance => Firestore(); Therefore you always get the data from the default project. To fix this you need to create your firestore using the app created by FirebaseApp.configure(). So replace: _stream = Firestore.instance.collection(collection).snapshots(); with _stream = Firestore(app: _abnApp).collection(collection).snapshots();
{ "pile_set_name": "StackExchange" }
Q: Chaining multiple ajax requests with promises I'm looking to chain multiple ajax requests, something along the lines of: get first JSON, if successful move on and get second JSON, if successful make a new object consisting of both JSON data. // get first json $.getJSON('http://www.json1.com').then(function(json1){ return json1 }).then(function(json1){ // get second json $.getJSON('http://www.json2.com').then(function(json2){ var both = {} both.one = json1 both.two = json2 return both }) }) Should I be nesting .then statements in each other? I'm not completely sure how to get the both variable. A: .then(function(json1){ return json1 }) That's an unnecessary, (nearly) identity call. .then(function(json1){ …; You should always return from a then callback, so that the new promise gets a value. You can even return promises, which will be "unwrapped"! Should I be nesting .then statements in each other? It doesn't really matter whether you nest them or chain them, that's the great thing about promises. Chaining them reduces the height of your "pyramid", so it is considered cleaner, however you cannot access the variables from higher scopes. In your case, you need to access json1, so you have to nest them. I'm not completely sure how to get the both variable. When you do return from the callbacks, you can get it as the resolution value of the promise that you get back from the then call. $.getJSON('http://www.json1.com').then(function(json1){ return $.getJSON('http://www.json2.com').then(function(json2){ return {one: json1, two: json2}; }) }).then(function(both) { // do something with both! });
{ "pile_set_name": "StackExchange" }
Q: Email Works fine but got two emails at same time? I try to send email, below code works fine but email sends twice at a time. I tried a lot but I don't know where I made a mistake. RTElapsedTime.cs: public void Elapsed() { T1.Elapsed += new ElapsedEventHandler(T1_Elapsed); T1.Interval = 60000; T1.Enabled = true; } public void T1_Elapsed(object source, ElapsedEventArgs e) { try { MatchingTime = DateTime.Now.ToString("HH:mm"); EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString); DataTable dt = EmailMgr.EmailServiceScheduleTimeIntervalRunTime(MatchingTime.ToString()); TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "report schedule count : " + dt.Rows.Count); foreach (DataRow r in dt.Rows) { T1.Enabled = false; RTEmailManagement(r); T1.Enabled = true; } TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "Tasks are completed."); } catch (Exception ex) { TraceImplogs.TraceLTService(ex.Message); } } DataTable dataRPT1 = new DataTable(); public DataTable ReportGeneration2(EmailDTO EETO) { EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString); dataRPT1 = EmailMgr.EmailLatearrivalReport(EETO.Departments, "0", EETO.ReportType); return dataRPT1; } public void RTEmailManagement(DataRow dr) { EDTO = null; EDTO = new EmailDTO(); MatchingTime = DateTime.Now.ToString("HH:mm"); EDTO.SecondTime = MatchingTime; EDTO.ScheduleTime = dr["rshtime"].ToString(); EDTO.ToEmails = dr["rsh_altrntmail"].ToString(); EDTO.CcEmails = dr["rsh_ccmail"].ToString().Split(';'); EDTO.Subject = dr["rsh_subjct"].ToString(); EDTO.ReportID = dr["reportid"].ToString(); EDTO.Departments = dr["rsh_dept"].ToString(); EDTO.ReportType = Convert.ToInt32(dr["rsh_typly"].ToString()); EDTO.weekly = dr["rsh_day"].ToString(); EDTO.Monthly = dr["rsh_dayofmnth"].ToString(); EDTO.Day = dr["xday"].ToString(); EDTO.Body = dr["rsh_body"].ToString(); EDTO.langcode = Convert.ToInt32(dr["langcode"].ToString()); CompanyID = Int32.Parse(dr["Company_id"].ToString()); dataRPT1 = ReportGeneration2(EDTO); TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "report schedule count---- : " + dataRPT1.Rows.Count); foreach (DataRow r in dataRPT1.Rows) { EDTO.CcEmails = new List<string>(EDTO.CcEmails) { r["Manager"].ToString() }.ToArray(); EDTO.CcEmails = EDTO.CcEmails.Distinct().ToArray(); //EDTO.CcEmails[EDTO.CcEmails.Length-1] = dataRPT1.Rows[k]["Manager"].ToString(); EDTO.ToEmails1 = r["email_addr"].ToString(); EDTO.LateArrival = r["LateArrivals"].ToString(); if (EDTO.ScheduleTime == EDTO.SecondTime) { TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "time matched"); switch (Convert.ToInt32(EDTO.ReportType)) { case 0: case 1: EmailConfiguration(CompanyID, EDTO); break; case 2: //TraceImplogs.TraceLTService("tyoe 2 new"); EmailConfiguration(CompanyID, EDTO); break; case 3: // TraceImplogs.TraceLTService("tyoe 3 new"); EmailConfiguration(CompanyID, EDTO); break; default: break; } } } // else TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "not matching"); } public void EmailConfiguration(int compid, EmailDTO EDTO) { try { ConfigDTO mlDTO = new ConfigDTO(); EmailMgr = new MachineBL(RTSqlConnection.Provider, RTSqlConnection.ConnectionString); DataTable EmailConfigDT = EmailMgr.SelectAllCompanyEmailConfiguration(compid); RTMailProcessing Mprocess = new RTMailProcessing(); mlDTO.ConfigMail = EmailConfigDT.Rows[0]["comp_email"].ToString(); mlDTO.ConfigPwd = EmailConfigDT.Rows[0]["comp_pwd"].ToString(); mlDTO.ConfigHost = EmailConfigDT.Rows[0]["host_name"].ToString(); mlDTO.ConfigPort = Convert.ToInt32(EmailConfigDT.Rows[0]["host_port"].ToString()); Mprocess.EmailProcessing(mlDTO, EDTO); } catch (Exception ex) { TraceImplogs.TraceLTService(ex.Message + " Email Error"); } } Email processing cs code. RtMailprocessing.cs: public void EmailProcessing(ConfigDTO conDTO, EmailDTO EDTO) { RTMsg.language(EDTO.langcode); conDTO.ConfigPwd = utility.Decrypt_Secure_Keylock(conDTO.ConfigPwd); // TraceImplogs.TraceLTService("Entered Config file" + conDTO.ConfigPwd); SmtpClient smtp = new SmtpClient { Host = conDTO.ConfigHost, Port = conDTO.ConfigPort, EnableSsl = true, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new System.Net.NetworkCredential(conDTO.ConfigMail, conDTO.ConfigPwd) // Timeout = 30000, }; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); // TraceImplogs.TraceLTService("Entered inside"); if (EDTO.ToEmails != "") { using (System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage(conDTO.ConfigMail, EDTO.ToEmails1, EDTO.Subject, EDTO.Body)) { for (int k = 0; k < EDTO.CcEmails.Length; k++) { if (EDTO.CcEmails[k] != "") { message.CC.Add(EDTO.CcEmails[k].TrimEnd(';')); } else { TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + "Ccmails are empty"); } } message.CC.Add(EDTO.ToEmails); message.Subject = ""; message.Body = ""; message.Subject = EDTO.Subject; message.SubjectEncoding = System.Text.Encoding.UTF8; // ReportGeneration(EDTO); string EmailBody = ""; if (attach != null) { message.Attachments.Add(attach); string[] RepBody = EDTO.Body.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); /*****with attachment***/ foreach (string lines in RepBody) { EmailBody += "<p style='font-family: Arial, Helvetica, sans-serif; font-size: 12px; color: #333333; margin-left: 10px'>" + lines + "</p>"; } message.Body = "Email Testing"; message.BodyEncoding = System.Text.Encoding.UTF8; //message.Attachments.Dispose(); //message.Dispose(); } if (dataRPT.Rows.Count < 1) { message.Body ="Test Email"; message.BodyEncoding = System.Text.Encoding.UTF8; message.Attachments.Clear(); } message.IsBodyHtml = true; //Send this as plain-text smtp.Send(message); TraceImplogs.TraceLTService(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt") + " " + NameRPT + " sent successfully."); message.CC.Clear(); //((IDisposable)smtp).Dispose(); //message.Attachments.Dispose(); //message.Dispose(); } } } When I debug with breakpoint loop run single time only but I got two email. I don't know where I made exactly mistake. Thanks in advance. A: I'm going to take a guess, you're not unsubscribing the event: T1.Elapsed += new ElapsedEventHandler(T1_Elapsed); You need to unsubscribe it: T1.Elapsed -= new ElapsedEventHandler(T1_Elapsed); The email server processed both messages and delivered them at the same time.
{ "pile_set_name": "StackExchange" }
Q: Android AES issue I need to implement AES algorithm with my Android application, and I created this code below and it works prefectly as Java application, but it seems that Android doesnt recognize JAXB. Because as you can see i use import javax.xml.bind.DatatypeConverter, because I use Datatype converter to convert from byte[] to string... I tried to import jaxb jar, but it fails again with this error: Conversion to Dalvik format failed with error 1. How I can fix this? Here is the code: public class AESCrypt { private final Cipher cipher; private final SecretKeySpec key; private AlgorithmParameterSpec spec; private String encryptedText, decryptedText; ByteArrayOutputStream baos; public AESCrypt(String password) throws Exception { // hash password with SHA-256 and crop the output to 128-bit for key MessageDigest digest = MessageDigest.getInstance("SHA-256"); digest.update(password.getBytes("UTF-8")); byte[] keyBytes = new byte[16]; System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length); cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); key = new SecretKeySpec(keyBytes, "AES"); spec = getIV(); } public AlgorithmParameterSpec getIV() { AlgorithmParameterSpec ivspec; byte[] iv = new byte[cipher.getBlockSize()]; new SecureRandom().nextBytes(iv); ivspec = new IvParameterSpec(iv); return ivspec; } public String encrypt(String plainText) throws Exception { cipher.init(Cipher.ENCRYPT_MODE, key, spec); byte[] encrypted = cipher.doFinal(plainText.getBytes()); encryptedText = DatatypeConverter.printBase64Binary(encrypted); return encryptedText; } public String decrypt(String cryptedText) throws Exception { cipher.init(Cipher.DECRYPT_MODE, key, spec); byte[] bytes = DatatypeConverter.parseBase64Binary(cryptedText); byte[] decrypted = cipher.doFinal(bytes); decryptedText = new String(decrypted, "UTF-8"); return decryptedText; } } A: The Android library has the class Base64 (android.util.Base64) that is very convenient to convert base64 string to data.
{ "pile_set_name": "StackExchange" }
Q: How to display several values filtered from two columns I have homework where I have to select data from two tables (book and author). Books has two authors and i need to display result with book title and authors separated by comma. I tried by myself but I got errors. Schema SQL: CREATE TABLE IF NOT EXISTS `author` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(128), `surname` VARCHAR(128), PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8mb4 ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS `book` ( `id` INT NOT NULL AUTO_INCREMENT, `title` VARCHAR(128), `author_id` INT NOT NULL, `author_id_2` INT NOT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8mb4 ENGINE=InnoDB; Query SQL: INSERT INTO `author` (`name`, `surname`) VALUES ("William", "Shakespeare"); INSERT INTO `author` (`name`, `surname`) VALUES ("Agatha", "Christie"); INSERT INTO `author` (`name`, `surname`) VALUES ("J. K", "Rowling"); INSERT INTO `author` (`name`, `surname`) VALUES ("George", "Orwell"); INSERT INTO `book` (`title`, `author_id`, `author_id_2`) VALUES ("Hamlet", 1, 2); INSERT INTO `book` (`title`, `author_id`, `author_id_2`) VALUES ("Macbeth", 1, 3); INSERT INTO `book` (`title`, `author_id`, `author_id_2`) VALUES ("Murder on the Orient Express", 2, 3); INSERT INTO `book` (`title`, `author_id`, `author_id_2`) VALUES ("The Secret of Chimneys", 2, 1); INSERT INTO `book` (`title`, `author_id`, `author_id_2`) VALUES ("1984", 3, 1); INSERT INTO `book` (`title`, `author_id`, `author_id_2`) VALUES ("Animal Farm", 3, 2); Query: SELECT b.title Pavadinimas, concat(concat(a1.name, ' ', a1.surname), ', ', concat(a2.name, ' ', a2.surname) Autoriai FROM book b INNER JOIN author a1 WHERE book.author_id=a1.id INNER JOIN author a2 WHERE book.author_id_2=a2.id; The result should be: Hamlet | William Shakespeare, Agatha Christie A: You would need to join twice the book table with the author table, like: SELECT b.title, CONCAT(a1.name, ' ', a1.surname, ', ', a2.name, ' ', a2.surname) authors FROM book b INNER JOIN author a1 ON b.author_id = a1.id INNER JOIN author a2 ON b.author_id_2 = a2.id This demo on DB Fiddle with your sample data returns: | title | authors | | ---------------------------- | ------------------------------------ | | Hamlet | William Shakespeare, Agatha Christie | | Macbeth | William Shakespeare, J. K Rowling | | Murder on the Orient Express | Agatha Christie, J. K Rowling | | The Secret of Chimneys | Agatha Christie, William Shakespeare | | 1984 | J. K Rowling, William Shakespeare | | Animal Farm | J. K Rowling, Agatha Christie | NB: if you have books with just one author, you can use LEFT JOIN instead of INNER JOIN.
{ "pile_set_name": "StackExchange" }
Q: Generating function for the partition function Could someone explain what is the reasoning behind the following equality? Or maybe direct me to a proof of the following equality? $$\sum_{n=0}^{\infty}p(n)x^n = \prod_{k=1}^{\infty}(1-x^k)^{-1}$$ where $\sum_{n=0}^{\infty}p(n)x^n$ is the generating function for the partition function. A: For the basic generating functions in term of $(1 - x^k) ^ {-1}$, we can write them out as a infinite sum. $(1 - x) ^ {-1}$ = $1 + x + x^2 + x^3 + ....$ $(1 - x^2) ^ {-1}$ = $1 + x^2 + x^4 + x^6....$ $(1 - x^3) ^ {-1}$ = $1 + x^3 + x^6 + x^9....$ and so on. So $\prod(1 - x^k) ^ {-1}$ is just an infinite product of ($1 + x + x^2 + x^3 + ....$)( $1 + x^2 + x^4 + x^6....$)($1 + x^3 + x^6 + x^9....$).... The for each power term $x^n$, there is a corresponding coefficient p(n). And we need to sum up all these power terms.
{ "pile_set_name": "StackExchange" }
Q: Swap two characters in the cell array of strings I have a cell array of string and I want to swap A and B in a percentage of the cell array , like 20%, 30% of the total number of strings in the cell array For example : A_in={ 'ABCDE' 'ACD' 'ABCDE' 'ABCD' 'CDE' }; Now, we need to swap A and B in 40% of the sequences in A (2/5 sequences ). There are some sequences which do not contain A and B so we just skip them, and we will swap the sequences which contain AB . The pickup sequences in A are chosen randomly. I appropriate someone can tell me how to do this . The expected output is: A_out={ 'ABCDE' 'ACD' 'BACDE' 'BACD' 'CDE' } A: Get the random precent index with randsample and swap with strrep % Input swapStr = 'AB'; swapPerc = 0.4; % 40% % Get index to swap hasPair = find(~cellfun('isempty', regexp(A_in, swapStr))); swapIdx = randsample(hasPair, ceil(numel(hasPair) * swapPerc)); % Swap char pair A_out = A_in; A_out(swapIdx) = strrep(A_out(swapIdx), swapStr, fliplr(swapStr));
{ "pile_set_name": "StackExchange" }
Q: System boots to a black screen after upgrade to 11.04 I was a similar situation to this user: Dual Boot 10.10 and 11.04 can't boot into 10.10 after an update Only many more GRUB entres. Natty still worked - and I could still access the natty partition, until I ran sudo apt-get dist-upgrade to install a kernel update. Now trying to boot natty gives me a black screen. Booting into the same kernel in 'recovery mode' gets me a little further: Plymouth appears and pressing any key shows me that it's stuck at 'CUPS printing... OK'. A: For Maverick users who have NVIDIA and/or ATI graphics together with activation of graphics drivers in the Additional Hardware Window are likely to suffer from the issue as described in the question. These drivers (especially nvidia) create a file called /etc/X11/xorg.conf. This file gives details about resolutions and describes the actual driver in use. However, during the upgrade to Natty, the file remains in place - but the proprietary driver from NVIDIA is replaced by an open-source driver called nouveau. Since the file is still in place, the underlying graphics system called "X" still tries to invoke the old NVIDIA driver because its relying on the instructions in the xorg.conf file - the NVIDIA driver is not there resulting in black-screens etc. For these users, the suggested route is to remove this file BEFORE upgrading. However, this can be overcome by booting from a Live CD - the desktop CD. Start a terminal and type gksudo nautilus then navigate to the folder /etc/X11/xorg.conf on your local hard-drive and either rename it or remove it.
{ "pile_set_name": "StackExchange" }
Q: Column is NULL when printed as individual field or column, filled when whole data frame is printed When I create a column of counts using dplyr, it appears to be filled correctly, until I try to use the counts column on its own. Example: I create this dataframe: V1 <- c("TEST", "test", "tEsT", "tesT", "TesTing", "testing","ME-TESTED", "re tested", "RE testing") V2 <- c("othertest", "anothertest", "testing", "123", "random stuff", "irrelevant", "tested", "re-test", "tests") V3 <- c("type1", "type2", "type1", "type2", "type3", "type2", "type2", "type2", "type1") df <- data.frame(V1, V2, V3) Then, I use dplyr to create a column of counts: df$counts <- df %>% group_by(V3) %>% mutate(count = n()) This gives the expected result: > df V1 V2 V3 counts.V1 counts.V2 counts.V3 counts.count 1 TEST othertest type1 TEST othertest type1 3 2 test anothertest type2 test anothertest type2 5 3 tEsT testing type1 tEsT testing type1 3 4 tesT 123 type2 tesT 123 type2 5 5 TesTing random stuff type3 TesTing random stuff type3 1 6 testing irrelevant type2 testing irrelevant type2 5 7 ME-TESTED tested type2 ME-TESTED tested type2 5 8 re tested re-test type2 re tested re-test type2 5 9 RE testing tests type1 RE testing tests type1 3 But, when I try to use the counts.count column in any way, the result is null: > df$counts.count NULL Same result for the other columns created by dplyr. But the rest of the data frame seems normal: > df$V1 [1] TEST test tEsT tesT TesTing testing ME-TESTED re tested RE testing Levels: ME-TESTED re tested RE testing test tesT tEsT TEST testing TesTing I am totally confused about why printing the whole df gives me a different output than printing just the column of interest. What am I missing here? A: If you rewind and recreate the dataframe and then don't do an assignment but just print the result to the screen you see this: df %>% group_by(V3) %>% mutate(count = n()) Source: local data frame [9 x 4] Groups: V3 [3] V1 V2 V3 count <fctr> <fctr> <fctr> <int> 1 TEST othertest type1 3 2 test anothertest type2 5 3 tEsT testing type1 3 4 tesT 123 type2 5 5 TesTing random stuff type3 1 6 testing irrelevant type2 5 7 ME-TESTED tested type2 5 8 re tested re-test type2 5 9 RE testing tests type1 3 If you now do the assgnment the structure is rather confused and I think you might have gotten a more informative error if there had been fewer unique values of V1 or V2: df$counts <- df %>% group_by(V3) %>% mutate(count = n()) # snipped what you already showed str(df) #----- 'data.frame': 9 obs. of 4 variables: $ V1 : Factor w/ 9 levels "ME-TESTED","re tested",..: 7 4 6 5 9 8 1 2 3 $ V2 : Factor w/ 9 levels "123","anothertest",..: 4 2 8 1 5 3 7 6 9 $ V3 : Factor w/ 3 levels "type1","type2",..: 1 2 1 2 3 2 2 2 1 $ counts:Classes ‘grouped_df’, ‘tbl_df’, ‘tbl’ and 'data.frame': 9 obs. of 4 variables: ..$ V1 : Factor w/ 9 levels "ME-TESTED","re tested",..: 7 4 6 5 9 8 1 2 3 ..$ V2 : Factor w/ 9 levels "123","anothertest",..: 4 2 8 1 5 3 7 6 9 ..$ V3 : Factor w/ 3 levels "type1","type2",..: 1 2 1 2 3 2 2 2 1 ..$ count: int 3 5 3 5 1 5 5 5 3 ..- attr(*, "vars")=List of 1 .. ..$ : symbol V3 ..- attr(*, "labels")='data.frame': 3 obs. of 1 variable: .. ..$ V3: Factor w/ 3 levels "type1","type2",..: 1 2 3 .. ..- attr(*, "vars")=List of 1 .. .. ..$ : symbol V3 .. ..- attr(*, "drop")= logi TRUE ..- attr(*, "indices")=List of 3 .. ..$ : int 0 2 8 .. ..$ : int 1 3 5 6 7 .. ..$ : int 4 ..- attr(*, "drop")= logi TRUE ..- attr(*, "group_sizes")= int 3 5 1 ..- attr(*, "biggest_group_size")= int 5 The format you are seeing is how R displays a matrix that is embedded in a dataframe. Objects of class table (and perhaps tbl?) inherit from the matrix-class.
{ "pile_set_name": "StackExchange" }
Q: How can I restrict gameobject from moving beyond line in unity I have this red apple that needs to move only inside the green apple line. If it tries to move beyond line it will be stopped at the green line and can' move beyond. How can I do that? This is the code I use to move a red apple. Camera mainCamera; float zAxis = 0; Vector3 clickOffset = Vector3.zero; // Use this for initialization void Start() { mainCamera = Camera.main; mainCamera.gameObject.AddComponent<Physics2DRaycaster>(); zAxis = transform.position.z; } public void OnBeginDrag(PointerEventData eventData) { clickOffset = transform.position - mainCamera.ScreenToWorldPoint(new Vector3(eventData.position.x, eventData.position.y, zAxis)); } public void OnDrag(PointerEventData eventData) { //Use Offset To Prevent Sprite from Jumping to where the finger is Vector3 tempVec = mainCamera.ScreenToWorldPoint(eventData.position) + clickOffset; tempVec.z = zAxis; //Make sure that the z zxis never change /* Debug.Log(tempVec.x); if (tempVec.x < 90) { tempVec.x = 90; } if (tempVec.x > 310) { tempVec.x = 310; } */ transform.position = tempVec; } public void OnEndDrag(PointerEventData eventData) { } A: Don't use code for this use colliders on both sides.
{ "pile_set_name": "StackExchange" }
Q: Using quotes in Twig ternary operators How does one prevent quotes from being escaped when used in a twig ternary operator? My desire is <div id="my_id">my div11</div> (or <div id='my_id'>my div11</div>), however, as seen my results are different. {% set id="my_id" %} <div{{ id?" id='"~id~"'" }}>my div1</div> <div{{ id?' id="'~id~'"' }}>my div2</div> <div{{ id?" id='#{id}'" }}>my div3</div> <div{{ id?" id=/'#{id}/'" }}>my div4</div> <div{{ id?' id='~"'"|raw~id~"'"|raw }}>my div5</div> <div{{ id?' id='~'"'|raw~id~"'"|raw }}>my div6</div> <div{{ id?" id="~id }}>my div7</div> <div{{ id?' id='~id }}>my div8</div> <div{{ id?" id=#{id}" }}>my div9</div> {% set id="" %} <div{{ id?" id='"~id~"'" }}>my div1</div> <div{{ id?' id="'~id~'"' }}>my div2</div> <div{{ id?" id='#{id}'" }}>my div3</div> <div{{ id?" id=/'#{id}/'" }}>my div4</div> <div{{ id?' id='~"'"|raw~id~"'"|raw }}>my div5</div> <div{{ id?' id='~'"'|raw~id~"'"|raw }}>my div6</div> <div{{ id?" id="~id }}>my div7</div> <div{{ id?' id='~id }}>my div8</div> <div{{ id?" id=#{id}" }}>my div9</div> Output: <div id=&#039;my_id&#039;>my div1</div> <div id=&quot;my_id&quot;>my div2</div> <div id=&#039;my_id&#039;>my div3</div> <div id=/&#039;my_id/&#039;>my div4</div> <div id=&#039;my_id&#039;>my div5</div> <div id=&quot;my_id&#039;>my div6</div> <div id=my_id>my div7</div> <div id=my_id>my div8</div> <div id=my_id>my div9</div> <div>my div1</div> <div>my div2</div> <div>my div3</div> <div>my div4</div> <div>my div5</div> <div>my div6</div> <div>my div7</div> <div>my div8</div> <div>my div9</div> A: try this <div{{ (id?' id="'~id~'"')|raw }}>my div1</div>
{ "pile_set_name": "StackExchange" }
Q: Are 'climb via a SID' instructions actually used in the US? In the USA, a departing aircraft is instructed to climb: to flight level and maintain, or via standard instrument departure (SID) That's according to US Aeronautical Information Publication (AIP). But pilots say they never hear climb via SID. Can anybody clarify if climb via SID instruction is really used by ATC? A: In my experience, I've received a climb via SID many times at airports like Las Vegas and Teterboro. This is common at certain airports, but a lot of airports don't use it because the procedures aren't designed that way. I think that a lot of pilots, especially those flying smaller non-turbine powered aircraft, don't receive this type of clearance because: They are flying at smaller airports that don't have a SID which uses it, or They are not assigned the SID's which do have it because the SID is only assigned to turbine-powered aircraft or aircraft capable of flight above a certain speed or altitude. It is also a relatively new procedure in the US. They were originally going to start using it in 2014, but it got delayed and was finally implemented a year or two ago (I don't remember exactly when). For a while, the US was only using "descend via" clearances, and not "climb via" clearances. Here are a couple of resources about this: NBAA PBN site FAA Climb Via/Descend Via Speed Clearances Frequently Asked Questions FAA “Climb Via” and “Descend Via” Procedures and Phraseology Air Traffic Policy Notice
{ "pile_set_name": "StackExchange" }
Q: Usando function dentro de Select Tenho um select, dentro dele tenho uma função : SELECT VAL1, VAL2, ".funcao('VAL1', 'VAL2')." AS soma FROM Conta WHERE soma < 100 Estrutura da tabela CONTA -------------------- | ID | VAL1 | VAL2 | -------------------- | 1 | 10 | 50 | -------------------- | 2 | 50 | 80 | -------------------- | 3 | 30 | 70 | -------------------- Se eu usar a seguinte estrutura na função : function funcao($valor1, $valor2) { $retorno = $valor1 + $valor2; return $retorno; }; Consigo retornar o valor de cada coluna numa boa, e ainda obtenho o resultado! Dai tentei trabalhar mais a função e aplicar o valor dentro de uma string. Ex: function funcao($valor1, $valor2) { $res = "Os números a ser somados são ".$valor1." e ".$valor2.""; echo $res ; //Esse echo serve apenas de exemplo, pra mostrar o retorno da variável }; Só que isso eu não conseguir fazer! Quando apliquei a variável $valor1 ou $valor2, em vez de mostrar o valor referente a coluna, ele mostrou o próprio nome da coluna, ou seja, VAL1 e VAL2 Minha dúvida é É possível trabalhar com essas variáveis em uma função mais complexa de acordo com o exemplo citado, sem que se perca o valor da coluna? Já que quando eu tento fazer isso o valor fica como "VAL1" em vez de 10 ou 50. Em modo mais simples! Mesmo que eu queira simplesmente fazer um "echo $valor1" dentro da função, o resultado é "VAL1" em vez de "10" A: Veja a aplicação do seu código: query( "SELECT VAL1, VAL2, ".funcao('VAL1', 'VAL2')." AS soma FROM Conta WHERE soma < 100" ); Neste caso, o PHP vai juntar estas três coisas, pois você usou o operador de concatenação (.): "SELECT VAL1, VAL2, " funcao('VAL1', 'VAL2') " AS soma FROM Conta WHERE soma < 100" A primeira e a última são strings. A do meio, é uma chamada de função. Então, o PHP vai obter seu valor antes de concatenar, chamando sua função com duas strings, que são 'VAL1' e 'VAL2', resultando em zero, que é a soma das duas strings que você passou no seu exemplo, que não tem relação nenhuma com os valores do SELECT (que sequer aconteceu ainda). Então o resultado será esse: query( "SELECT VAL1, VAL2, 0 AS soma FROM Conta WHERE soma < 100" ); Só depois de concatenada a string no PHP, ela será enviada para o MySQL. No segundo exemplo a coisa fica mais evidente: function funcao($valor1, $valor2) { $res = "Os números a ser somados são ".$valor1." e ".$valor2.""; echo $res ; }; Cpomo não tem return na função, só echo, fica mais fácil de perceber que 'VAR1' e 'VAR2' são somente strings para o PHP, portanto saem na tela como foram enviadas. E mesmo que pusesse um return, a string final não seria um SQL válido. Solução Se você quer usar funções no lado do DB, precisa que as funções sejam as do SQL, e não do PHP. Exemplo: query( "SELECT VAL1, VAL2, VAL1+VAL2 AS soma FROM Conta WHERE soma < 100" ); Outro exemplo, com strings do lado do SQL: query( "SELECT VAL1, VAL2, CONCAT( "Resultado:", VAL1+VAL2, "rea ) AS soma FROM Conta" ); Outra possibilidade seria pegar todo o resultado em um array, e depois fazer um loop no PHP chamando sua função (desta vez em PHP). Isto poderia ser feito na hora de mostrar os valores na tela. Exemplo: while ($row = $result->fetch_row()) { echo $row['VAL1'].' somado com '.$row['VAL2'].' resulta em '.($row['VAL1']+$row['VAL2']); }
{ "pile_set_name": "StackExchange" }
Q: Spring 4 @Transactional doesn't work I have a Spring 4.3 Application with simple configuration and I expect my methods from service classes to be transactional so I enable transaction management in my configuration and then annotate my service methods with @Transactional. I call service methods from my controlles but they don't behave as expected. When some part of a method throws exception rollback is never called AppInitializer.class: @EnableTransactionManagement public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[]{WebConfig.class}; } @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[]{RootConfig.class, SecurityConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } } RootConfig.class: @Configuration @EnableJpaRepositories(basePackages"package.repository"}) public class RootConfig { @Bean public DataSource dataSource() { ... return dataSource; } @Bean public JpaVendorAdapter jpaVendorAdapter() { ... return hibernateJpaVendorAdapter; } @Bean public EntityManagerFactory entityManagerFactory() { LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); ... return factory.getObject(); } @Bean public JpaTransactionManager transactionManager() { return new JpaTransactionManager(entityManagerFactory()); } } Does anybody have idea what is wrong here GitHub link https://github.com/VadOs1/TRANSACTIONAL-ISSUE/ Thanks A: can you remove the @EnableTransactionManagement annotation from the AppInitializer class and enable it in RootConfig class and let me know if this worked for you ie @Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages"package.repository"}) public class RootConfig { @Bean public DataSource dataSource() { ... return dataSource; } @Bean public JpaVendorAdapter jpaVendorAdapter() { ... return hibernateJpaVendorAdapter; } @Bean public EntityManagerFactory entityManagerFactory() { LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); ... return factory.getObject(); } @Bean public JpaTransactionManager transactionManager() { return new JpaTransactionManager(entityManagerFactory()); } }
{ "pile_set_name": "StackExchange" }
Q: PHP what does it mean when using this '$$var'? I am trying to learn php, and I saw this in a foreach loop what does it mean? I understand &$var which its a direct reference to the memory address of the object. But what does $$var means? what is it exactly? This is the example. foreach($this->vars as $key => $value) { $$key = $value; echo "$$Key: " . $$key; echo "Key: " . $key; echo "<br/>"; echo "Value: " . $value; } A: You're looking at a variable variable. e.g. // original variable named 'foo' $foo = "bar"; // reference $foo dynamically by evaluating $x $x = "foo"; echo $$x; // "bar"; echo ${$x}; // "bar" as well but the {} allows you to perform concatenation // different version of {} to show a more "complex" operation $y = "fo"; $z = "o"; echo ${$y . $z}; // "bar" also ("fo" . "o" = "foo") To show an example more closely matching your question: $foo = "foo"; $bar = "bar"; $baz = "baz"; $ary = array('foo' => 'FOO','bar' => 'BAR','baz' => 'BAZ'); foreach ($ary as $key => $value){ $$key = $value; } // end result is: // $foo = "FOO"; // $bar = "BAR"; // $baz = "BAZ";
{ "pile_set_name": "StackExchange" }