text
stringlengths
64
89.7k
meta
dict
Q: Input text showing on next row On http://www.bigbasket.com, the Input for "Qty" is coming on the next row in case of IE9. Its fine on IE7/8, FF and Chrome. But for some reason it is breaking on IE9. A: The issue might be the fact that you are not using the label correctly. The Label should contain the text "qty", and the input should not be inside the label. E.g. <label for="p10000159_qty">Qty:</label> <input id="p10000159_qty" class="qtyTxtField" name="pqty" maxLength="2" value="1" type="text"> EDIT it works if you either reduce the width of .qtyTextField by 3px, or take off margin-left:3px. It is shifting onto the next row because there's not enough room on that row for IE.
{ "pile_set_name": "StackExchange" }
Q: Running an API Request Every 15 Seconds I use an API that has been recently rate limited and requests have to be run every 15 seconds as that is the wait time otherwise a status code of 429 rate limit exceeded is returned. I often have more than one email address that needs to be run against this API and the email addresses are contained within an array. How would I go about running the request every say 15.5 seconds but move onto each email address until the end of the array? It's a very tricky one for sure. I've tried: setInterval(checkEmail(email), 15500); No joy, for some reason that just doesn't seem to work. Btw should point out that I'm using a JQuery $.ajax() within that checkEmail(email) function. Any ideas anybody? Thanks in advance. A: You could do the following: var emails = []; var interval_id; function _start() { interval_id = window.setInterval(function() { var email = emails.shift(); if (email) { var r=checkEmail(email.address); if (email.callback) email.callback(r); } else { window.clearInterval(interval_id); } }, 15500); } function add_email(email, callback) { emails.push({address:email, callback:callback}); if (!interval_id) _start(); } Whenever you have a new email address to check, just run add_email(email). This will add it to the queue and start the interval timer if necessary. Additionally, you can say add_email(email,function(result) {....}) if you want to get notified when the check is completed.
{ "pile_set_name": "StackExchange" }
Q: Umbraco 7 hide navigation nodes user has no access to I've seen some examples in previous versions of Umbraco (namely 5) where this seemed to be relatively straightforward. See this stackoverflow question for example. The theory is that I can use a property HasAccess or IsProtected on a node, or the method WhereHasAccess when selecting which nodes to use. The code I have so far is: var nodes = @CurrentPage.AncestorsOrSelf(1).First().Children; This gets me the list of pages, no problem. However, I am struggling to filter the list of pages so that a logged in user only sees what they have access to and a public visitor sees no protected pages. The V5 code suggests this is possible: var nodes = @CurrentPage.AncestorsOrSelf(1).First().Children.WhereCanAccess(); But this results in the error: 'Umbraco.Web.Models.DynamicPublishedContentList' does not contain a definition for 'WhereCanAccess' The latest published version of the Razor cheatsheet for Umbraco indicates that HasAccess() and IsProtected() are two methods that are both available, but when using either of these I get null values, e.g.: @foreach(var node in nodes.WhereCanAccess()) { <li>@node.Name / @node.IsProtected / @node.IsProtected() / @node.HasAccess() / @node.HasAccess </li> } Returns null for all the test values (e.g. @node.IsProtected). It seems that what I am trying to achieve is simple, but I am approaching it the wrong way. Someone please point out the error of my ways! A: I check user access to pages like this: var node = [the page you want to verify access to ie. "CurrentPage"]; var isProtected = umbraco.library.IsProtected(node.id, node.path); var hasAccess = umbraco.library.HasAccess(item.id, item.path); My top menu code: var homePage = CurrentPage.AncestorsOrSelf(1).First(); var menuItems = homePage.Children.Where("UmbracoNaviHide == false"); @foreach (var item in menuItems) { var loginAcces = umbraco.library.IsProtected(item.id, item.path) && umbraco.library.HasAccess(item.id, item.path); var cssClass = loginAcces ? "loginAcces ":""; cssClass += CurrentPage.IsDescendantOrSelf(item) ? "current_page_item" :""; if(!umbraco.library.IsProtected(item.id, item.path) || loginAcces){ [render your item here] } } This will hide items that are protected, unless user is logged in and has access.
{ "pile_set_name": "StackExchange" }
Q: Email Masking FreeFrom pro I am using Freeform pro with a EE site that sells classified goods. I have a form where the customer can email another customer/member. But id like to mask the email with sender and receiver something like gumtree or craigslist. Can someone suggest a method for this if its possible. Thank, Mario A: You'd need to run some custom software that integrated with a local mail server to do this - beyond the scope of even an EE add-on I'd say, because your mail server would need to know how to map the incoming email aliases to your site members. Maybe there's a third-party service that lets you create forwarding addresses programmatically via an API? That would be your best bet, if it exists - then you'd just need to store that anonymous email address as a custom member field for each member.
{ "pile_set_name": "StackExchange" }
Q: How do I read in a text file from the command line I created a scanner to read in a text file from the first element in the command line, but it results in a FileNotFoundException. How do I format it to where it accepts this file? Here is my code: Scanner scanner = new Scanner(new File(args[0])); For example, if the file name is Hello.txt, I put Hello.txt as the first element in the command line. A: Works for me. "build.xml" is a file I happen to know exists in my project's folder. Try printing the "absolute path" of the file, it'll show you where Java is looking, which might be different than what you are expecting. public class ScratchPad { public static void main( String[] args ) throws Exception { System.out.println( new File("build.xml").exists() ); System.out.println( new File("build.xml").getAbsoluteFile() ); } } Output: run: true C:\Users\Brenden\Google Drive\proj\tempj8\build.xml BUILD SUCCESSFUL (total time: 0 seconds)
{ "pile_set_name": "StackExchange" }
Q: Demystifying CSRF? I've read through a lot of long explanations of CSRF and IIUC the core thing that enables the attack is cookie based identification of server sessions. So in other words if the browser (And note I'm specifically narrowing the scope to web browsers here) does not use a cookie based session key to identify the session on the server, then a CSRF attack cannot happen. Did I understand this correctly? So for example suppose someone creates a link like: href="http://notsosecurebank.com/transfer.do?acct=AttackerA&amount;=$100">Read more! You are tricked into clicking on this link while logged into http://notsosecurebank.com, however http://notsosecurebank.com does not use cookies to track your login session, and therefore the link does not do any harm since the request cannot be authenticated and just gets thrown in the garbage? Assumptions The OpenID Connect Server / OAuth Authorization server has been implemented correctly and will not send authentication redirects to any URL that you ask it to. The attacker does not know the client id and client secret Footnotes The scenario I'm targeting in this question is the CSRF scenario most commonly talked about. There are other scenarios that fit the CSRF tag. These scenarios are highly unlikely, yet good to be aware of, and prepared for. One of them has the following components: 1) The attacker is able to direct you to a bad client 2) The attacker owns that client 3) The attacker has the secret for that client registered with the OAuth Authorization Server 4) The attacker is able to tell the Authorization Server that authenticates you to redirect back to the bad client after you have been authenticated with the proper server. So setting this up is a little bit like breaking into Fort Knox, but certainly good to be aware of. For example OpenID Connect or OAuth Authorization Providers should most likely flag clients that register redirect URLs pointing to redirect URLs that other clients have also registered. A: The most common / usually discussed CSRF Cross Site Request Forgery scenario can only happen when the browser stores credentials (as a cookie or as basic authentication credentials). OAuth2 implementations (client and authorization server) must be careful about CSRF attacks. CSRF attacks can happens on the client's redirection URI and on the authorization server. According to the specification (RFC 6749): A CSRF attack against the client's redirection URI allows an attacker to inject its own authorization code or access token, which can result in the client using an access token associated with the attacker's protected resources rather than the victim's (e.g., save the victim's bank account information to a protected resource controlled by the attacker). The client MUST implement CSRF protection for its redirection URI. This is typically accomplished by requiring any request sent to the redirection URI endpoint to include a value that binds the request to the user-agent's authenticated state (e.g., a hash of the session cookie used to authenticate the user-agent). The client SHOULD utilize the "state" request parameter to deliver this value to the authorization server when making an authorization request. [...] A CSRF attack against the authorization server's authorization endpoint can result in an attacker obtaining end-user authorization for a malicious client without involving or alerting the end-user. The authorization server MUST implement CSRF protection for its authorization endpoint and ensure that a malicious client cannot obtain authorization without the awareness and explicit consent of the resource owner
{ "pile_set_name": "StackExchange" }
Q: how to get the parent element id in JQuery or Javascript i have un ordered list of html elements from the list on clicking any of the list i want to get the parent ul tag id. <ul id="123"> <li> <li>test1</li> <a href="#" onclick="validate()"/> </li> </li> ........ ........ </ul> function validate(){ var test=$(this).parent().parent().attr('id'); alert(test); } above validate function test variable result should ul tag id that is 123. A: First problem is that your function validate() dont know what this refers to, so you need to add it like validate(this); Then we can do it like this. function validate(obj) { var test = $(obj).closest("ul").attr('id'); alert(test); } Also, you should not really have <li> as a child of another <li> use something like this structure. <ul id="123"> <li> <a href="#" onclick="validate(this)">test1</a> <ul id="456"> <li> <a href="#" onclick="validate(this)">test2</a> </li> </ul> </li> </ul> function validate(obj) { var test = $(obj).closest("ul").attr('id'); alert(test); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul id="123"> <li> <a href="#" onclick="validate(this)">test1</a> <ul id="456"> <li> <a href="#" onclick="validate(this)">test2</a> </li> </ul> </li> </ul>
{ "pile_set_name": "StackExchange" }
Q: Button Click event not firing for dynamically created button I have created dynamic controls on DropdownList's SelectedIndexChanged event. Button is one of those controls. I have also assigned event to that button but debugger is not coming on that click event. Following is my code. protected void Page_Load(object sender, EventArgs e) { try { token = Session["LoginToken"].ToString(); if (!IsPostBack) { BindData(); fsSearch.Visible = false; btnDownload.Visible = false; } else { foreach (HtmlTableRow row in (HtmlTableRowCollection)Session["dynamicControls"]) { tblSearch.Rows.Add(row); } } } catch { } } private void BindData() { ddlReportName.DataSource = svcCommon.GetReports(token, out message); ddlReportName.DataValueField = "Key"; ddlReportName.DataTextField = "Value"; ddlReportName.DataBind(); ddlReportName.Items.Insert(0, "--Select--"); } protected void ddlReportName_SelectedIndexChanged(object sender, EventArgs e) { try { string[] reportInfo = ddlReportName.SelectedValue.Split('|'); Session["dynamicControls"] = null; tblSearch.Rows.Clear(); HtmlTableRow row = new HtmlTableRow(); HtmlTableCell cellFieldNameLbl = new HtmlTableCell(); HtmlTableCell cellFieldNameDdl = new HtmlTableCell(); HtmlTableCell cellOperatorLbl = new HtmlTableCell(); HtmlTableCell cellOperatorDdl = new HtmlTableCell(); HtmlTableCell cellValueLbl = new HtmlTableCell(); HtmlTableCell cellValueTxt = new HtmlTableCell(); HtmlTableCell cellOperatorRbtn = new HtmlTableCell(); HtmlTableCell cellAddMoreFilter = new HtmlTableCell(); Button btnAddMore = new Button(); DropDownList ddlColumn = new DropDownList(); DropDownList ddlOperator = new DropDownList(); TextBox txtValue = new TextBox(); RadioButtonList rbtnOperator = new RadioButtonList(); List<string> filterValues = svcCommon.GetSearchColumns(Convert.ToInt64(reportInfo[0]), token, out message); fsSearch.Visible = btnDownload.Visible = filterValues.Count > 0 ? true : false; ddlColumn.ID = "_ddlColumn0"; ddlOperator.ID = "_ddlOperator0"; txtValue.ID = "_txtValue0"; rbtnOperator.ID = "_rbtnOperator0"; btnAddMore.ID = "_btnAddMore0"; rbtnOperator.Items.Add("AND"); rbtnOperator.Items.Add("OR"); rbtnOperator.RepeatDirection = RepeatDirection.Horizontal; btnAddMore.Text = "Add More"; btnAddMore.Click +=btnAddMore_Click; ddlColumn.DataSource = filterValues; ddlColumn.DataBind(); ddlOperator.DataSource = new List<string>() { "Equal", "Not Equal", "Less Than", "Less Than Or Equal", "Greater Than", "Greater Than Or Equal", "Start With", "Not Start With", "End With", "Not End With", "Contains", "Not Contains", "Between", "Not Between", "In", "Not In" }; ddlOperator.DataBind(); cellFieldNameLbl.InnerText = "Field Name:"; cellFieldNameDdl.Controls.Add(ddlColumn); cellOperatorLbl.InnerText = "Operator"; cellOperatorDdl.Controls.Add(ddlOperator); cellValueLbl.InnerText = "Value"; cellValueTxt.Controls.Add(txtValue); cellOperatorRbtn.Controls.Add(rbtnOperator); cellAddMoreFilter.Controls.Add(btnAddMore); row.Cells.Add(cellFieldNameLbl); row.Cells.Add(cellFieldNameDdl); row.Cells.Add(cellOperatorLbl); row.Cells.Add(cellOperatorDdl); row.Cells.Add(cellValueLbl); row.Cells.Add(cellValueTxt); row.Cells.Add(cellOperatorRbtn); row.Cells.Add(cellAddMoreFilter); tblSearch.Rows.Add(row); Session["dynamicControls"] = tblSearch.Rows; } catch (Exception ex) { } } protected void btnAddMore_Click(object sender, EventArgs e) { try { } catch { } } A: The problem with dynamically created controls in asp.net webforms is that they aren't automatically added to the viewstate, so the postback event won't happen. This should help you to understand adding controls dynamically, and managing them via the viewstate http://forums.asp.net/t/1900207.aspx?Creating+buttons+dynamically Alternatively, a much easier way to manage this is to have the buttons on the page but not visible, then in the selected_index_changed event, just switch the visibility to true. A: I hadn't enough time to try so many thing. The thing I did is stored the container on which dynamic controls are added into Session and on Page_Init event I have bound event and it is working fine now. :)
{ "pile_set_name": "StackExchange" }
Q: find the particular solution of the semi linear equation given the data u(1,y)= ln(y^(-1/2)) semi linear equation the general solution to that equation (general solution) Given the data that u(1,y)=ln(y^(-1/2)) what would the right method be to go from the general solution to the particular solution given the data? particular solution A: This is the continuation of Find the general solution of $x^3u_x-u_y=e^{2u}$ to which a boundary condition is now added. The general solution is $$y-\frac12 e^{-2u}=f(y-\frac{1}{2x^2}) \tag 1$$ and the condition is : $$u(1,y)=\ln(y^{-1/2})=-\frac12\ln(y)$$ $e^{-2u}=e^{\ln(y)}=y\quad$ that we put into $(1)$ with $x=1$ : $$y-\frac12 y=f(y-\frac{1}{2}) $$ $$\frac12 y=f(y-\frac{1}{2})$$ Let $\quad X=y-\frac{1}{2} \quad\implies\quad y=X+\frac12$ $$\frac12 (X+\frac12)=f(X)$$ Now the function $f$ is determined : $$f(X)=\frac12X +\frac14$$ We put it into $(1)$ where $X=y-\frac{1}{2x^2}$ $$y-\frac12 e^{-2u}= \frac12(y-\frac{1}{2x^2}) +\frac14$$ $$e^{-2u}= y+\frac{1}{2x^2} -\frac12$$ $$-2u= \ln\left(y+\frac{1}{2x^2} -\frac12\right)$$ The particular solution satisfying the specified condition is : $$u=-\frac12\ln\left(y+\frac{1}{2x^2} -\frac12\right)$$
{ "pile_set_name": "StackExchange" }
Q: Prestashop - Layered Navigation is Empty I'm working on a prestashop site and facing some problem with the layered navigation. It appears for the top level categories but when I click on any of the sub categories, it goes to blank. There is nothing to filter on. It should atleast display a Price filter. And yes I do have products in the category with different prices so a price filter should appear. In my header.tpl file I have {if isset($left_column_size) && !empty($left_column_size)} <div id="left_column" class="column col-xs-12 col-sm-{$left_column_size|intval}">{$HOOK_LEFT_COLUMN}</div> {/if} Which hides the left column when I don't have anything in my layered navigation. I want to diagnose why I don't have anything in my layered navigation. A: To display the filter(s) in all categories you have to configure a blocklayered 'template' with all categories of your shop. I'll post a screenshot to better understating :) Enter in the module configuration, then click on "Add new template" Then on 'check all' After that configure your filters (in the bottom of page) as you wish. Save, now the filters will display in all categories. ;)
{ "pile_set_name": "StackExchange" }
Q: How to send WM_ENTERSIZEMOVE? I have the following code called on WM_MOVE procedure TForm15.WMMove(var Message: TMessage); begin if( (((TWMMove(Message).XPos + Self.Width >= Form14.Left) and (TWMMove(Message).XPos <= Form14.Left)) or ((TWMMove(Message).XPos <= Form14.Left + Form14.Width) and (TWMMove(Message).XPos >= Form14.Left))) and (((TWMMove(Message).YPos + Self.Height >= Form14.Top) and (TWMMove(Message).YPos <= Form14.Top)) or ((TWMMove(Message).YPos <= Form14.Top + Form14.Height) and (TWMMove(Message).YPos >= Form14.Top)))) then begin Self.DragKind := dkDock; end else Self.DragKind := dkDrag; end; It's probably the ugliest if statement you've seen in your life,but that's not the question. :) It's supposed to change DragKind if the current form(Self) is somewhere inside the mainForm(Form14). However,When It sets DragKind to dkDock ,it doesn't make the currentForm(Self) dockable unless the user stops moving the form and start moving it again,so I'm trying to do the following: If the result from the statement above is non zero and dkDock is set then Send the following messages to the form: WM_EXITSIZEMOVE //stop moving the form WM_ENTERSIZEMOVE //start movement again However,I don't know how to do it: SendMessage(Self.Handle,WM_EXITSIZEMOVE,?,?); I tried using random parameters(1,1) ,but no effect.Maybe that's not the right way? A: It looks like those two messages are notifications - directly sending them probably doesn't do anything. As Raymond Chen once said (horribly paraphrased), directly sending these messages and expecting action is like trying to refill your gas tank by moving the needle in the gauge. WM_SIZING and WM_MOVING are messages that you can use to monitor a user changing a window's size and position, and block further changes. From MSDN: lParam Pointer to a RECT structure with the current position of the window, in screen coordinates. To change the position of the drag rectangle, an application must change the members of this structure. So you can change the members to force the window to remain in a single position.
{ "pile_set_name": "StackExchange" }
Q: Progression bar sync javascript to server time? I have an object which contains some data about progression of a bar but it keeps stopping at 99% and won't continue, i believe its because client time is not going to be the same as server time accurately enough to do it. So i don't know how to solve it. These 2 timers are created server side and sent to the client. myOjb[i].end: 1374805587 //seconds since epoch for when 100% is made myObj[i].strt: 1374805527 //seconds since epoch when it started The function that is calculating the percentage : function clocker() { var now = new Date().getTime() / 1000; for (var i in myObj) { if (myObj[i].end > now) { var remain = myObj[i].end - now; var per = (now - myObj[i].strt) / (myObj[i].end - myBuildings[i].strt) * 100; var per = fix_percentage(per); // stops > 100 and < 0 returns int if true myObj[i].percentage = Math.ceil(per); console.log(myObj[i].percentage); //reaches 99 max if (myObj[i].percentage > 99) { console.log('test'); //never occurs return false; } break; } else { continue; } } setTimeout(clocker, 1000); } function fix_percentage(per){ if(per>100)per=100; if(per<0)per = 0; return Math.round(per); } How could i sync the two together so the timing is more accurate ? A: Edit: Original answer was based on a bad assumption. I think what is happening is that essentially your block setting the percent to 100 might be getting skipped. This would happen if on one iteration, the value of per was < 99.5 but > 88.5. In this case, the rounded per would have a value of 99. Then, one second later when the function gets called again, the outer if block would not be entered due to myObj[i].end > now being false. The following code will make sure that if time expires and the myObj[i].percentage is < 100 because of the above scenario, it will be set to 100 and return like the other if block does. if (myObj[i].end > now) { var remain = myObj[i].end - now; var per = (now - myObj[i].strt) / (myObj[i].end - myBuildings[i].strt) * 100; var per = fix_percentage(per); // stops > 100 and < 0 returns int if true myObj[i].percentage = Math.ceil(per); console.log(myObj[i].percentage); //reaches 99 max if (myObj[i].percentage > 99) { console.log('test'); //never occurs return false; } break; } else if ( (now >= myObj[i].end) && (myObj[i].percentage < 100) ) { console.log('Time expired, but percentage not set to 100') myObj[i].percentage = 100; return false; } else { continue; }
{ "pile_set_name": "StackExchange" }
Q: Rails 4 .where nested model search Hi, I have a Model of Users and a Model of Products. My Model Products belongs_to my Model User and a User has_many Products. My question is how can i search 1 or multiple products matching a user attribute? exemple: Product.where(price: 10) for user.where(id: 2) What is the solution for nested model search, i'm a bit lost. Many Thanks A: Since products belongs to user (and user has_many products), you can query off of the relation: user = User.find(2) products = user.products.where(price: 10)
{ "pile_set_name": "StackExchange" }
Q: Python not finding file in the same directory I am writing a simple script that attaches file to a mail, but it is not finding the file. This is my one block: # KML attachment filename='20140210204804.kml' fp = open(filename, "rb") att = email.mime.application.MIMEApplication(fp.read(),_subtype="kml") fp.close() att.add_header('Content-Disposition','attachment',filename=filename) msg.attach(att) The file 20140210204804.kml is present in the same folder as the script. I am getting below error: IOError: [Errno 2] No such file or directory: '20140210204804.kml' Any help is appreciated. A: The working directory is not set to the directory of the script, but to the current directory where you started the script. Use __file__ to determine the file location and use that as a starting point to make filename an absolute path: import os here = os.path.dirname(os.path.abspath(__file__)) filename = os.path.join(here, '20140210204804.kml')
{ "pile_set_name": "StackExchange" }
Q: Replacing text globally with line break in React Native/Javascript I want to replace an xml tag <Add with \n<Add so that it open a new line for every <Add. However I tried .replace(/\<Add/g, '\n') It shows a blank screen. I also tried replace it once .replace('\<Add', '\n') It works with the first <Add replaced by line break. But I need to reaplce all <Add with a line break... Why I can't replace text with "\n" globally? How can I do it in react native? A: Considering: .replace('\<Add', '\n') Works for the first, but not others, do the replacement using the global flag: .replace(/(<Add)/g, '\n$1')
{ "pile_set_name": "StackExchange" }
Q: How to get konsole work on gns3 i am interested in making my devices display in tabs when working on GN3. i made some research and found out that konsole can do that. i installed it. i have gone to preferences => edit => set KDE konsole amazingly when i open the console of a device it i need it to display the router or device i intend working with normally. how do i fix this A: it is simple, just to preferences => edit => general, on the tab for console change the command there to console application commands: konsole --new-tab -p tabtitle=%d -e telnet %h %p then {the second console application commands: Local serial connections (remember to install socat) konsole --new-tab -p tabtitle=%d -e socat UNIX-CONNECT:"%s" stdio,raw,echo=0
{ "pile_set_name": "StackExchange" }
Q: strace: order of and <... resumed> I'm writing a script that analyzes file access traced with strace. The trace contains some calls which have been interrupted by another process. strace shows them with <unfinished ...> and <... close resumed> (in case of an interrupted close call) markers. [pid 26817] 12:48:22.972737 close(449 <unfinished ...> [pid 28708] 12:48:22.972797 fcntl(451, F_SETFD, FD_CLOEXEC <unfinished ...> [pid 26817] 12:48:22.972808 <... close resumed> ) = 0 The process and all its threads have been traced with strace -f -tt -p <pid> The man page is uncertain about when the call has been finished. If a system call is being executed and meanwhile another one is being called from a different thread/process then strace will try to preserve the order of those events and mark the ongoing call as being unfinished. When the call returns it will be marked as resumed. While I'd assume that, natually the resumed marker will indicate that the call is now finished. I'd like to ask if it is so. Can the above trace excerpt be reconstructed to A [pid 28708] 12:48:22.972797 fcntl(451, F_SETFD, FD_CLOEXEC <unfinished ...> [pid 26817] 12:48:22.972808 close(449) = 0 or should it be reconstructed to B [pid 26817] 12:48:22.972737 close(449) = 0 [pid 28708] 12:48:22.972797 fcntl(451, F_SETFD, FD_CLOEXEC <unfinished ...> The order is crucial here since there may be multiple calls between the unfinished and resumed and one of them might do something with the file that is about to be closed at the moment. A: The system call begins when strace writes the line close(449 <unfinished ...>, and ends when it outputs <... close resumed>. The close is not interrupted by any other call or signal: the other call is executed by another process, while the kernel is closing your file descriptor. There is no way to know which is the exact point when the file descriptor is closed; the only thing you know is that it is not closed until the syscall is executed, and that it is closed when the syscall finishes.
{ "pile_set_name": "StackExchange" }
Q: вопрос о списке в Android Studio Хочу осуществить переход на новую Activity после нажатия на первый элемент списка, но выдает ошибку в последней строке с getApplicationContex, с чем это может быть связано? final String[] Spisok = new String[]{ "Что", "Как", "Для кого"}; private ArrayAdapter<String> mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, Spisok); setListAdapter(mAdapter);; } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); if(position==0) { Intent intent = new Intent(getApplicationContext(), MainActivity.class); getApplicationContex.startActivity(intent); } A: Потому что это метод. Вы не поставили скобки. Исправьте на: getApplicationContext().startActivity(intent);
{ "pile_set_name": "StackExchange" }
Q: jQuery next DIV with Specific Class that resides in another DIV To make the question short, here is the HTML code that I have: <div class="step1 main-step"> <div class="step1a tooltip" step-name="step1a" title="Step 1a" style="width: 25.000%;"></div> <div class="step1b tooltip" step-name="step1b" title="Step 1b" style="width: 25.000%;"></div> <div class="step1c tooltip" step-name="step1c" title="Step 1c" style="width: 25.000%;"></div> <div class="step1d tooltip" step-name="step1d" title="Step 1d" style="width: 25.000%;"></div> </div> <!-- End of Step 1 --> <div class="step2 main-step"> <div class="step2a tooltip" step-name="step2a" title="Step 2a" style="width: 25.000%;"></div> <div class="step2b tooltip" step-name="step2b" title="Step 2b" style="width: 25.000%;"></div> <div class="step2c tooltip" step-name="step2c" title="Step 2c" style="width: 25.000%;"></div> <div class="step2d tooltip" step-name="step2d" title="Step 2d" style="width: 25.000%;"></div> </div> <!-- End of Step 2 --> <a href="#" current-step="step1a" next-step="step1b" class="button" id="continue-button">Continue</a> Now, my problem is when I use this jQuery code: $nextStep = $('#continue-button').attr('next-step'); $('#continue-button').attr('current-step', $nextStep); $nextTemp = $('div.' + $nextStep).next('.tooltip').attr('step-name'); $('#continue-button').attr('next-step', $nextTemp); $nextTemp stops at step1d. What can I do so $nextTemp will read the next div.tooltip from the other divs (step2, step3, step4, etc.) ? A: External Fiddle DEMO Well I have made some changes to your html to use a valid html data-* attributes which will be as follows and also check for inline comments: $(".button").on('click',function(){ var currentStep=$(this).data('current-step'); //get the current-step var $nextStep=$('.'+currentStep).next('.tooltip').length?$('.'+currentStep).next('.tooltip').data('step-name'):$('.'+currentStep).closest('.main-step').next('.main-step').find('div:first').data('step-name'); //ternary operator if there is nextstep in current main-step then take it otherwise //go to its parent and get next main-step first div's step-name data attribute if(typeof $nextStep != 'undefined') //check if it is undefined { $(this).data('current-step', $nextStep); $nextTemp = $('div.' + $nextStep).next().length?$('div.' + $nextStep).next().data('step-name'):$('.'+$nextStep).closest('.main-step').next().find('div:first').data('step-name'); typeof $nextTemp!='undefined'?$(this).data('next-step', $nextTemp):$(this).data('next-step', 'No more steps'); //ternary operators again } $('.result').append("Current Step : " +$(this).data('current-step')+ " " + "Next Step :" +$(this).data('next-step') +"<br/>"); //just to show what the results will be after each click. }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="step1 main-step"> <div class="step1a tooltip" data-step-name="step1a" title="Step 1a" style="width: 25.000%;"></div> <div class="step1b tooltip" data-step-name="step1b" title="Step 1b" style="width: 25.000%;"></div> <div class="step1c tooltip" data-step-name="step1c" title="Step 1c" style="width: 25.000%;"></div> <div class="step1d tooltip" data-step-name="step1d" title="Step 1d" style="width: 25.000%;"></div> </div> <!-- End of Step 1 --> <div class="step2 main-step"> <div class="step2a tooltip" data-step-name="step2a" title="Step 2a" style="width: 25.000%;"></div> <div class="step2b tooltip" data-step-name="step2b" title="Step 2b" style="width: 25.000%;"></div> <div class="step2c tooltip" data-step-name="step2c" title="Step 2c" style="width: 25.000%;"></div> <div class="step2d tooltip" data-step-name="step2d" title="Step 2d" style="width: 25.000%;"></div> </div> <!-- End of Step 2 --> <a href="#" data-current-step="step1a" data-next-step="step1b" class="button" id="continue-button">Continue</a> <div class='result'></div>
{ "pile_set_name": "StackExchange" }
Q: How can I make a Triple boot Currently I am using a dual boot with Windows7 and Ubuntu 12.04LTS. I would like to try Windows8. Not because I like it, but more and more people are using it. I have created a partition where I would like to install it. I have only one physical drive. What should I do to create a triple-boot and don't mess up my Ubuntu? This is my primary OS. But occasionally I need my Windows7. A: Install Windows 8 on a separate partition, then boot to Linux and update grub. You'll then have Windows 8 added to the boot option. $ update-grub Updating grub will add all OS installations to the list. Update: I thought this was kind of elementary because this pop up all the time: RecoveringUbuntuAfterInstallingWindows: Boot to your Live Ubuntu CD Install and run Boot-Repair Click "Recommended Repair" Now reboot your system. I was initially more focus on the part where it's standard to have multiple boots. If you have 10 partitions you can actually have an OS on each and updating grub will automatically add each to the boot menu. YOu can even include USB drives or pen drives as some of those partitions.
{ "pile_set_name": "StackExchange" }
Q: Ошибка вызова presentviewcontroller Господа прошу помощи, сам не могу разобраться...пока Есть FVC и SVC. В FVC есть кнопка связанная с SVC по modal, при нажатии SVC открывается все норм. Но в процессе работы FVC есть необходимость показать SVC без нажатия на кнопку и вернуться обратно. Я делаю так: в .h файле: import "SVC.h" в .m if (условие) { SVC *secondViewController = [[SVC alloc] initWithNibName:@"SVC" bundle:nil]; [self presentViewController:secondViewController animated:YES completion:nil]; } Но при выполнении и срабатывании условия, исполнение прерывается с ошибкой: Could not load NIB in bundle: 'NSBundle ........ (loaded)' with name 'SVC'' Может я не правильно пытаюсь отобразить SVC? A: если они описаны в сториборде, зачем вы делаете [[SVC alloc] initWithNibName:@"SVC" bundle:nil];? либо в том же сториборде опишите segue, назовите как-нибудь типа "SVC", а затем [self performSegueWithIdentifier:@"SVC" sender:self]; или если по каким-то причинам segue использовать не хочется, то задайте своему презентуемому UIVIewController storyboard ID = @"SVC" далее [self presentViewController:[self.storyboard instantiateViewControllerWithIdentifier:@"SVC"] animated:YES completion:nil];
{ "pile_set_name": "StackExchange" }
Q: How to remove an added value by uncheck box? Hi I have check box to add a value on click. However, It also adds even if I unchecked the box. How can I remove the added value when I uncheck the box? Thank you! $('.addCheckBox').click( function( event ){ var btn = $(event.currentTarget); var Data = btn.data(); var addList = $('#ListBtn'); var Obj = { aID: Data.id, aName: Data.name }; addList.push( Obj ); addListBtn[0].innerHTML = "(" + addList.length + ") in List"; }); A: $('.addCheckBox').click(function (event) { if ($('.addCheckBox').is(':checked')) { var btn = $(event.currentTarget); var Data = btn.data(); var addList = $('#ListBtn'); var Obj = { aID: Data.id, aName: Data.name }; addList.push({"myData":Obj}); console.log(addList); }else{ var addList = $('#ListBtn'); addList.remove("myData"); console.log(addList); } });
{ "pile_set_name": "StackExchange" }
Q: Rails/Passenger/Apache: Simple one-off URL redirect to catch stale DNS after server move One of my rails apps (using passenger and apache) is changing server hosts. I've got the app running on both servers (the new one in testing) and the DNS TTL to 5 minutes. I've been told (and experienced something like this myself) by a colleague that sometimes DNS resolvers slightly ignore the TTL and may have the old IP cached for some time after I update DNS to the new server. So, after I've thrown the switch on DNS, what I'd like to do is hack the old server to issue a forced redirect to the IP address of the new server for all visitors. Obviously I can do a number of redirects (301, 302) in either Apache or the app itself. I'd like to avoid the app method since I don't want to do a checkin and deploy of code just for this one instance so I was thinking a basic http url redirect would work. Buuttt, there are SEO implications should google visit the old site etc. etc. How best to achieve the re-direct whilst maintaining search engine niceness? A: I guess the question is - where would you redirect to? If you are redirecting to the domain name, the browser (or bot) would just get the same old IP address and end up in a redirect loop. If you redirect to an IP address.. well, that's not going to look very user friendly in someone's browser. Personally, I wouldn't do anything. There may be some short period where bots get errors trying to access your site, but it should all work itself out in a couple days without any "SEO damage"
{ "pile_set_name": "StackExchange" }
Q: Improving the performance of a webscraper I have here a modified version of a web scraping code I wrote some weeks back. With some help from this forum, this modified version is faster (at 4secs per iteration) than the earlier version. However, I need to run many iterations (over 1million) which is so much time. Is there any way to further enhance its performance? Thank you. sample data (data.csv) Code Origin 1 Eisenstadt 2 Tirana 3 St Pölten Hbf 6 Wien Westbahnhof 7 Wien Hauptbahnhof 8 Klagenfurt Hbf 9 Villach Hbf 11 Graz Hbf 12 Liezen Code: import csv from functools import wraps from datetime import datetime, time import urllib2 from mechanize import Browser from bs4 import BeautifulSoup, SoupStrainer # function to group elements of a list def group(lst, n): return zip(*[lst[i::n] for i in range(n)]) # function to convert time string to minutes def get_min(time_str): h, m = time_str.split(':') return int(h) * 60 + int(m) # Delay function incase of network disconnection def retry(ExceptionToCheck, tries=1000, delay=3, backoff=2, logger=None): def deco_retry(f): @wraps(f) def f_retry(*args, **kwargs): mtries, mdelay = tries, delay while mtries > 1: try: return f(*args, **kwargs) except ExceptionToCheck, e: msg = "%s, Retrying in %d seconds..." % (str(e), mdelay) if logger: logger.warning(msg) else: print msg time.sleep(mdelay) mtries -= 1 mdelay *= backoff return f(*args, **kwargs) return f_retry # true decorator return deco_retry def datareader(datafile): """ This function reads the cities data from csv file and processes them into an O-D for input into the web scrapper """ # Read the csv with open(datafile, 'r') as f: reader = csv.reader(f) next(reader, None) ListOfCities = [lines for lines in reader] temp = ListOfCities[:] city_num = [] city_orig_dest = [] for i in ListOfCities: for j in temp: ans1 = i[0], j[0] if ans1[0] != ans1[1]: city_num.append(ans1) ans = (unicode(i[1], 'iso-8859-1'), unicode(j[1], 'iso-8859-1'), i[0], j[0]) if ans[0] != ans[1] and ans[2] != ans[3]: city_orig_dest.append(ans) yield city_orig_dest input_data = datareader('data.csv') def webscrapper(x): """ This function scraped the required website and extracts the quickest connection time within given time durations """ #Create a browser object br = Browser() # Ignore robots.txt br.set_handle_robots(False) # Google demands a user-agent that isn't a robot br.addheaders = [('User-agent', 'Chrome')] @retry(urllib2.URLError, tries=1000, delay=3, backoff=2) def urlopen_with_retry(): try: # Retrieve the website, return br.open('http://fahrplan.sbb.ch/bin/query.exe/en') except urllib2.HTTPError, e: print e.code except urllib2.URLError, e: print e.args # call the retry function urlopen_with_retry() # Select the 6th form on the webpage br.select_form(nr=6) # Assign origin and destination to the o d variables o = i[0].encode('iso-8859-1') d = i[1].encode('iso-8859-1') print 'o-d:', i[0], i[1] # Enter the text input (This section should be automated to read multiple text input as shown in the question) br.form["REQ0JourneyStopsS0G"] = o # Origin train station (From) br.form["REQ0JourneyStopsZ0G"] = d # Destination train station (To) br.form["REQ0JourneyTime"] = x # Search Time br.form["date"] = '10.05.17' # Search Date # Get the search results br.submit() connections_times = [] ListOfSearchTimes = [] #Click the LATER link a given number of times times to get MORE trip times for _ in xrange(3): # Read the result of each click and convert to response for beautiful soup formatting for l in br.links(text='Later'): response = br.follow_link(l) # get the response from mechanize Browser parse_only = SoupStrainer("table", class_="hfs_overview") soup = BeautifulSoup(br.response(), 'lxml', from_encoding="utf-8", parse_only=parse_only) trs = soup.select('tr') # Scrape the search results from the resulting table for tr in trs: locations = tr.select('td.location') if locations: time = tr.select('td.time')[0].contents[0].strip() ListOfSearchTimes.append(time.encode('latin-1')) durations = tr.select('td.duration') # Check that the duration cell is not empty if not durations: duration = '' else: duration = durations[0].contents[0].strip() # Convert duration time string to minutes connections_times.append(get_min(duration)) arrivals_and_departure_pair = group(ListOfSearchTimes, 2) #Check that the selected departures for one interval occurs before the departure of the next interval fmt = '%H:%M' finalDepartureList = [] for idx, res in arrivals_and_departure_pair: t1 = datetime.strptime(idx, fmt) if x == '05:30': control = datetime.strptime('09:00', fmt) elif x == '09:00': control = datetime.strptime('12:00', fmt) elif x == '12:00': control = datetime.strptime('15:00', fmt) elif x == '15:00': control = datetime.strptime('18:00', fmt) elif x == '18:00': control = datetime.strptime('21:00', fmt) else: x == '21:00' control = datetime.strptime('05:30', fmt) if t1 < control: finalDepartureList.append(idx) # Get the the list of connection times for the departures above fastest_connect = connections_times[:len(finalDepartureList)] # Return the result of the search if not fastest_connect: return [i[2], i[3], NO_CONNECTION] else: return [i[2], i[3], str(min(fastest_connect))] NO_CONNECTION = '999999' # List of time intervals times = ['05:30', '09:00', '12:00', '15:00', '18:00', '21:00'] # Write the heading of the output text file headings = ["from_BAKCode", "to_BAKCode", "interval", "duration"] with open("output.txt", "w+") as f: f.write(','.join(headings)) f.write('\n') if __name__ == "__main__": for ind, i in enumerate(input_data.next()): print 'index', ind for ind, t in enumerate(times): result = webscrapper(t) result.insert(2, str(ind + 1)) print 'result:', result print with open("output.txt", "a") as f: f.write(','.join(result[0:4])) f.write('\n') A: There is a major limitation. Your code is of a blocking nature - you process timetable searches sequentially - one at a time. I really think you should switch to Scrapy web-scraping framework - it is fast, pluggable and entirely asynchronous. As a bonus point, you will be able to scale your spider to multiple instances or multiple machines. For example, you may divide your input data evenly into N parts and run a spider instance for every part (check out scrapyd). Here is a sample spider that works for a single timetable search: import scrapy TIMES = ['05:30', '09:00', '12:00', '15:00', '18:00', '21:00'] DEFAULT_PARAMS = { "changeQueryInputData=yes&start": "Search connection", "REQ0Total_KissRideMotorClass": "404", "REQ0Total_KissRideCarClass": "5", "REQ0Total_KissRide_maxDist": "10000000", "REQ0Total_KissRide_minDist": "0", "REQComparisonCarload": "0", "REQ0JourneyStopsS0A": "255", "REQ0JourneyStopsZ0A": "255", "REQ0JourneyStops1.0G": "", "REQ0JourneyStops1.0A": "1", "REQ0JourneyStopover1": "" } def merge_two_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" z = x.copy() z.update(y) return z class FahrplanSpider(scrapy.Spider): name = "fahrplan" allowed_domains = ["fahrplan.sbb.ch"] def start_requests(self): params = { "REQ0JourneyStopsS0G": "Eisenstadt", "REQ0JourneyStopsZ0G": "Tirano, Stazione", "date": "27.02.17", "REQ0JourneyTime": "17:00" } formdata = merge_two_dicts(DEFAULT_PARAMS, params) yield scrapy.FormRequest("http://fahrplan.sbb.ch/bin/query.exe/en", method="POST", formdata=formdata) def parse(self, response): for trip_time in response.css("table.hfs_overview tr td.time::text").extract(): print(trip_time.strip()) If you want to take it further, you should do the following: use the datareader() results in the start_requests() method and start a form request for every input item define an Item class and yield/return it in the parse() callback use an "Item Pipeline" to "pipe" your items into the output file I understand that there is a lot of new information for you, but doing web-scraping for a long time, I can say that's really worth it, especially performance-wise.
{ "pile_set_name": "StackExchange" }
Q: C++ add new code during runtime I am using C++ (in xcode and code::blocks), I don't know much. I want to make something compilable during runtime. for eg: char prog []={"cout<<"helloworld " ;} It should compile the contents of prog. I read a bit about quines , but it didn't help me . A: It's sort of possible, but not portably, and not simply. Basically, you have to write the code out to a file, then compile it to a dll (invoking the compiler with system), and then load the dll. The first is simple, the last isn't too difficult (but will require implementation specific code), but the middle step can be challenging: obviously, it only works if the compiler is installed on the system, but you have to find where it is installed, verify that it is the same version (or at least a version which generates binary compatible code), invoke it with the same options that were used when your code was compiled, and process any errors. C++ wasn't designed for this. (Compiled languages generally aren't.)
{ "pile_set_name": "StackExchange" }
Q: Error when data contract member refer each other i have a simple data contract which is have a data member that refer to each other, here are the data member: [DataContract(Namespace = "", Name = "ScaleTransactionHeaderMessage")] public class ScaleTransactionHeaderMessage { [DataMember] public int ScaleTransactionHeaderMessageId { get; set; } [DataMember] public string OperatorName { get; set; } [DataMember] public string Shift { get; set; } [DataMember] public string Source { get; set; } [DataMember] public string Destination { get; set; } **[DataMember] public List<ScaleTransactionDetailMessage> ScaleTransactionDetailMessages { get; set; }** } [DataContract(Namespace = "", Name = "ScaleTransactionDetailMessage")] public class ScaleTransactionDetailMessage { [DataMember] public int ScaleTransactionDetailMessageId { get; set; } [DataMember] public double Tonnage { get; set; } [DataMember] public DateTime TransactionDetailDate { get; set; } **[DataMember] public ScaleTransactionHeaderMessage scaleTransactionHeaderMessage { get; set; }** } Here is the operation causing the problem private static ScaleTransactionDetailMessage ConvertTransactionDetail(ScaleTransactionHeaderMessage headerMessage, ScaleTransactionDetail transactionDetail) { ScaleTransactionDetailMessage detailMessage = new ScaleTransactionDetailMessage { Tonnage = transactionDetail.Tonnage, TransactionDetailDate = transactionDetail.TransactionDetailDate, ScaleTransactionDetailMessageId = transactionDetail.TransactionDetailId, //TODO: Check why this is not working **scaleTransactionHeaderMessage = headerMessage** }; return detailMessage; } The problem is every time i add ScaleTransactionHeaderMessage in the ScaleTransactionDetailMessage data contract i always got an error mentioning connection timeout, i'm sure this is not configuration issue since if i did not add the value to the ScaleTransactionHeaderMessage in the operation contract the service can running properly. i have unit test the operation and it is working properly, the problem only appear when invoking the service. Is there any mistakes in the data contract design ? A: You need to add IsReference = true to the DataContract: [DataContract(IsReference=true] Take a look here.
{ "pile_set_name": "StackExchange" }
Q: sync option in /etc/fstab From the man pages of mount command sync All I/O to the filesystem should be done synchronously. In the case of media with a limited number of write cycles (e.g. some flash drives), sync may cause life-cycle shortening. Does this mean that when providing this option in /etc/fstab (given the following definition of sync command) $ sync --help Usage: sync [OPTION] [FILE]... Synchronize cached writes to persistent storage ...caching of contents (i.e. of memory pages created from the contents of the particular device) is prohibited? A: Read caching is not prohibited. Write caching is prohibited. In other words, writes to the device have to be done immediately, so there is no risk of data loss.
{ "pile_set_name": "StackExchange" }
Q: Consume API with basic authentication using Javascript without exposing key pair I have a private API, where I'm using basic authentication as my security layer. Right now the API is consumed by my iOS app, so no one is able to see the key pair. I'm creating the same app for the web now, using React and Javascript and need to consume the same API using basic authentication. How can I use my API key pair in Javascript without exposing that key pair to the public? Is such a thing even possible? A: As @Andrew mentioned, that is not possible, you can just make it harder to get, but it'll be there somewhere on the client code, and that's enough to say you're exposing it. If you're open to alternatives, I suggest you to use a per user authentication for the first request, and then a token based authentication for further requests. That token can be a JSON Web Token and it's the flow I'm talking about: This is the way it works, taken from JWT's official documentation: In authentication, when the user successfully logs in using their credentials, a JSON Web Token will be returned and must be saved locally (typically in local storage, but cookies can be also used), instead of the traditional approach of creating a session in the server and returning a cookie. Whenever the user wants to access a protected route or resource, the user agent should send the JWT, typically in the Authorization header using the Bearer schema. The content of the header should look like the following: Authorization: Bearer <token>
{ "pile_set_name": "StackExchange" }
Q: use data attribute in animate function I want to use the data attribute value in the jquery animate function in order to set speed of the animation depending on the data attribute value. html <li class="layer" data-depth="2"><img src="imgs/logo/zaincorp logo.png"></li> <li class="layer" data-depth="4"><img src="imgs/logo/creative hands logo.png"></li> <li class="layer" data-depth="6"><img src="imgs/logo/la logo.png"></li> jquery function slide(){ layer.animate({ 'left': '+='+data('depth')*20+'px' },100, 'linear',function(){ slide(); }); } slide(); A: You'll need to iterate the elements: function slide() { var $this = $(this); $this.animate({ 'left': '+=' + $this.data('depth') * 20 + 'px' }, 100, 'linear', slide); } $('.layer').each(slide);
{ "pile_set_name": "StackExchange" }
Q: Temporary managed objects are not properly merged from child context to main context I have a multi-threaded application where I need to merge a private context to the main context which in turn is connected to the persistent storage controller. I also have the need to create temporary objects that are NOT managed (until I later on decide to manage them). First, I tried to create my temporary objects as follows; NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:myMainQueueContext]; User* user = (User *)[[User alloc] initWithEntity:entity insertIntoManagedObjectContext:nil]; After deciding to keep the object or not, I then simply; [privateContext insertObject:user]; Before I made the application multi-threaded, this worked great, but now after having torn things apart slightly and added the multi-thread concurrency by child/parent contexts, the result is NOT as expected. By looking at the context's "registeredObjects", I can see that my created, and now inserted, user is managed in the privateContext. After saving it, the mainContext changes accordingly and I can see that it hasChanges and that there are now one object in the registeredObjects. But looking closer at THAT registeredObject in the mainContext, reveal that it's emptied. No contents. All attributes are nil or 0 depending on type. Hence, one would expect that this might be because of the objectId is not the same... but it is ;( It's the same object. But without contents. I tried to get some input on this concern in a different post here, but without success. Child context objects become empty after merge to parent/main context Anyhow, I finally got things to work by changing how I create my objects; User* user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:privateContext]; Suddenly my child objects are merged to the mainContext without loosing their contents, for reasons to me unknown, but unfortunately this has also lead to the fact that I cannot any longer create temporary unmanaged objects... ;( I read that Marcus Zarra backed my first approach when it comes to creating unmanaged objects, but that does not work with merging contexts in my multi-threaded app... Looking forward to any thoughts and ideas -- am I the only one trying to create temporary objects in an async worker-thread, where I only want to manage/merge a subset of them up to the mainContext? EDIT Concrete code showing what's working, and more importantly what's NOT working; //Creatre private context and lnk to main context.. NSManagedObjectContext* privateManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; //Link private context to main context... privateManagedObjectContext.parentContext = self.modelManager.mainManagedObjectContext; [privateManagedObjectContext performBlock:^() { //Create user NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:self.modelManager.mainManagedObjectContext]; User* user = (User *)[[User alloc] initWithEntity:entity insertIntoManagedObjectContext:nil]; [user setGuid:@"123123"]; [user setFirstName:@"Markus"]; [user setLastName:@"Millfjord"]; [privateManagedObjectContext insertObject:user]; //Debug before we start to merge... NSLog(@"Before private save; private context has changes: %d", [privateManagedObjectContext hasChanges]); NSLog(@"Before private save; main context has changes: %d", [self.modelManager.mainManagedObjectContext hasChanges]); for (NSManagedObject* object in [privateManagedObjectContext registeredObjects]) NSLog(@"Registered private context object; %@", object); //Save private context! NSError* error = nil; if (![privateManagedObjectContext save:&error]) { //Oppps abort(); } NSLog(@"After private save; private context has changes: %d", [privateManagedObjectContext hasChanges]); NSLog(@"After private save; main context has changes: %d", [self.modelManager.mainManagedObjectContext hasChanges]); for (NSManagedObject* object in [privateManagedObjectContext registeredObjects]) NSLog(@"Registered private context object; %@", object); for (NSManagedObject* object in [self.modelManager.mainManagedObjectContext registeredObjects]) NSLog(@"Registered main context object; %@", object); //Save main context! [self.modelManager.mainManagedObjectContext performBlock:^() { //Save main context! NSError* mainError = nil; if (![self.modelManager.mainManagedObjectContext save:&mainError]) { //Opps again NSLog(@"WARN; Failed saving main context changes: %@", mainError.description); abort(); } }]; }]; The above does NOT work, since it create a temporary object and then insert it into context. However, this slight mod make things work, but prevent me from having temporary objects...; NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:self.modelManager.mainManagedObjectContext]; User* user = (User *)[[User alloc] initWithEntity:entity insertIntoManagedObjectContext:privateManagedObjectContext]; Hence, I'm wondering; what's the difference? There must be some difference, obviously, but I don't get it. A: As far as I can tell, this is another CoreData bug. I can somewhat understand the "how" but not the "why" of it. As you know, CoreData rely heavily on KVO. A managed context observe changes to its objects like a hawk. Since your "Temporary" objects have no context, the context cannot track their changes until they are attached to it, so it does not report changes to the parent context correctly (or at all). So, the parent context will get the "committed value" of the inserted object which turns to nil as soon as you insert your object to the context using insertObject: (this is the bug I guess). So I have devised a cunning plan :D We will swizzle our way out of this! introducing NSManagedObjectContext+fix.m: //Tested only for simple use-cases (no relationship tested) + (void) load { Method original = class_getInstanceMethod(self, @selector(insertObject:)); Method swizzled = class_getInstanceMethod(self, @selector(__insertObject__fix:)); method_exchangeImplementations(original, swizzled); } - (void) __insertObject__fix:(NSManagedObject*)object { if (self.parentContext && object.managedObjectContext == nil) { NSDictionary* propsByName = [object.entity propertiesByName]; NSArray* properties = [propsByName allKeys]; NSDictionary* d = [object committedValuesForKeys:properties]; [propsByName enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSPropertyDescription* prop, BOOL *stop) { if ([prop isKindOfClass:[NSAttributeDescription class]]) { [object setValue:[(NSAttributeDescription*)prop defaultValue] forKey:key]; } else if ([prop isKindOfClass:[NSRelationshipDescription class]]) { [object setValue:nil forKey:key]; } }]; [self __insertObject__fix:object]; [object setValuesForKeysWithDictionary:d]; } else { [self __insertObject__fix:object]; } } This might help you keep your code a bit more sain. However, I would probably try to avoid this type of insertion altogether. I don't really understand your need for inserting an object to a specific context and leaving it hanging until you decide if it is needed or not. Wouldn't it be easier to ALWAYS insert your objects into the context (keeping the values in a dictionary if needed for extended period of time). but when you decide the object should not "hit the store", simply delete it? (this is called weeding BTW)
{ "pile_set_name": "StackExchange" }
Q: can't convert Array into String - add tag I have the following controller code: class NodesController < ApplicationController def index @nodes = Node.com_name_scope("27").find(:all, :conditions => ['COMPONENT_NAME LIKE ?', "#{params[:search]}%"]) respond_to do |format| format.js {render :js => @nodes.map { |node| "<li>#{node.COMPONENT_NAME}</li>"}} end end When I do: http://localhost/myproject/nodes.js I get the following list: <li>Value A</li> <li>Value B</li> <li>Value C</li> <li>Value D</li> I would like to insert a <ul> tag at the start and end of the list so that it look as follows: <ul> <li>Value A</li> <li>Value B</li> <li>Value C</li> <li>Value D</li> </ul> But when I do: format.js {render :js => "ul" + @nodes.map { |node| "<li>#{node.COMPONENT_NAME}</li>"}+ "</ul>" } It is giving me the following error message: TypeError in NodesController#index can't convert Array into String My question is how do I include the <ul> tag in front and at the end of the list. Thanks a lot for your help A: @nodes.map { |node| "<li>#{node.COMPONENT_NAME}</li>"} returns an array of strings, you need to join them in some way before merging them with the string. format.js { render :js => "<ul>#{@nodes.map { |node| "<li>#{node.COMPONENT_NAME}</li>"}.join}</ul>" }
{ "pile_set_name": "StackExchange" }
Q: Implement SOAP 1.2 service in asp.net core I'm trying to implement OCPP 1.5 under ASP.Net Core 2.2. The standard makes use of SOAP 1.2. The issue comes from poor interpretation of the MessageHeader attribute. Properties with MessageHeader should be in header, but they are not. Source code: https://github.com/delianenchev/OcppDemo I use SoapCore under ASP.Net Core. My initialization looks like this: var transportBinding = new HttpTransportBindingElement(); var textEncodingBinding = new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressingAugust2004, System.Text.Encoding.UTF8); var customBinding = new CustomBinding(transportBinding, textEncodingBinding); app.UseSoapEndpoint<ISampleService>("/SOAP/service.wsdl", customBinding, SoapSerializer.DataContractSerializer); My demo model with the MessageHeader and MessageBodyMember attributes. [MessageContract] public class MessageModelRequest { [MessageHeader] public string Id { get; set; } [MessageBodyMember] public string Name { get; set; } [MessageBodyMember] public string Email { get; set; } } I test API with SoapUI. This is my API under ASP.NET core with SoapCore. <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:tem="http://tempuri.org/" xmlns:mod="http://schemas.datacontract.org/2004/07/Models"> <soap:Header/> <soap:Body> <tem:TestMessageModel> <!--Optional:--> <tem:inputModel> <!--Optional:--> <mod:Email>?</mod:Email> <!--Optional:--> <mod:Id>1</mod:Id> <!--Optional:--> <mod:Name>?</mod:Name> </tem:inputModel> </tem:TestMessageModel> </soap:Body> </soap:Envelope> Correct API from WCF project for IIS. <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/"> <soapenv:Header> <tem:Id>34</tem:Id> </soapenv:Header> <soapenv:Body> <tem:MessageModelRequest> <!--Optional:--> <tem:Email>3</tem:Email> <!--Optional:--> <tem:Name>4</tem:Name> </tem:MessageModelRequest> </soapenv:Body> </soapenv:Envelope> A: Well, judging by the source code of SoapCore it seems to support message headers for reading the SOAP message as it uses MessageEncoder for that purpose which knows exactly how to read a SOAP message, but when it comes to serializing a response in your case it uses a native DataContractSerializer for writing the body that ignores any message contract attributes you have on your class and furthermore it doesn't have any part for writing header, just the message body. So I guess you need to implement the header support in response messages by yourself. First of all, add IgnoreMemberAttribute (or XmlIgnoreAttribute if you switch to SoapSerializer.XmlSerializer) on the properties you intend to add to your response message header so that data contract serializer doesn't add them to the body of the message. Finally, you will need to locate the properties decorated with MessageHeader attribute manually and add them to your header. Luckily SoapCore has multiple options for doing that as suggested here. As alternative if you plan to include the source of SoapCore in your solution, you could easily achieve the goal somewhere along these lines. It's easy to do so because at this place you have the full control of the message and the response you got from your service method. With the aid of reflection, you can easily find the properties of responseObject which need to be moved to the header and just forward them to responseMessage.Headers. I know it's a bit nasty, but well... this is the price of using SOAP in .NET Core.
{ "pile_set_name": "StackExchange" }
Q: Examining Binary File for Information using Bit Masks I have been given the following programming task (edited to obscure mission-specifics): The raw (binary) file (needed for Phase II implementation) can be interrogated to detect if pods are present. Format is dependent on the source of the file – FormatX vs. FormatY. Using a wordsize of 16 bits, the following bit masks can be used to determine presence of pods from the file: Word # Mask Value Indicates 1 0xFF00 0x8700 Little Endian (Format X) 1 0x00FF 0x0087 Big Endian (Format Y) 13 0x0200 0x0200 right pod installed (Format X) 13 0x0002 0x0002 right pod installed (Format Y) 13 0x0100 0x0100 left pod installed (Format X) 13 0x0001 0x0001 left pod installed (Format Y) How I have approached this problem so far: I have the file on my local file system, so I use System.IO.File.OpenRead to get it into a Stream object. I want to read through the stream 16 bits/2 bytes at a time. For the first "word" of this size, I try applying bitmasks to detect what format I am dealing with. Then I skip forward to the 13th "word" and based on that format, detect right/left pods. Here's some preliminary code I have written that is not working. I know the file I am reading should be Format Y but my check is not working. int chunksRead = 0; int readByte; while ((readByte = stream.ReadByte()) >= 0) { chunksRead++; if (chunksRead == 1) { // Get format bool isFormatY = (readByte & 0x00FF) == 0x0087; } else if (chunksRead == 13) { // Check pods } else if (chunksRead > 13) { break; } } Can anyone see what's wrong with my implementation? How should I account for the 2 byte wordsize? Edit based on response from @Daniel Hilgarth Thanks for the quick reply, Daniel. I made a change and it's working for the first word, now: byte[] rawBytes = new byte[stream.Length]; stream.Read(rawBytes, 0, rawBytes.Length); ushort formatWord = Convert.ToUInt16(rawBytes[0] << 8 | rawBytes[1]); bool formatCheck = (formatWord & 0x00FF) == 0x0087; I just need to find an example file that should return a positive result for right/left pod installed to complete this task. A: You are mixing bytes and words. The word at position 13 is about whether the left or the right pod is installed. You are reading 12 bytes to get to that position and you are checking the 13th byte. That is only half way. The same problem is with your format check. You should read the first word (=2 bytes) and check whether it is one of the desired values. To get a word from two bytes you read, you could use the bit shift operator <<: ushort yourWord = firstByte << 8 | secondByte;
{ "pile_set_name": "StackExchange" }
Q: how generate chart from Views Aggretation Plus I created a table from webform submission data (group and compress) using Views Aggregator Plus I would like to generate a pie chart from this table (industry as the label and turnover as the values). Any hints to generate the pie chart would be appreciated. A: Now I can do that, (a) Exclude the Company field (b) In the VAP setting, disable the summary sum in the footer (b) Then use highcharttable module to create the pie chart.
{ "pile_set_name": "StackExchange" }
Q: Opto-isolation amplifier giving no output First of all, thanks to the community for having such helpful answers here - don't post very often but here's one I could really do some help with. I want to measure a voltage range of 0-100V DC in an isolated manner and using an Arduino Uno. I've got a HCPL 7520 (datasheet) and created an initial test circuit with just 5V input but I'm getting no output. I've got a voltage divider to bring the 5V down to the +/- 200mV range and chosen resistors to bring the current to ~10mA (which is less than the 20mA max). But whenever I measure voltage between VOut and Vdd2_Gnd, I get 0V. I'm no expert so any advice would be much, much appreciated ! A: You've got \$V_{REF}\$ tied to 0 volts - the recommended value is between 4 volts and \$V_{DD2}\$: - The whole premise for this device amplifying is that it has a gain determined by: - $$\boxed{\dfrac{V_{REF}}{0.512}}$$
{ "pile_set_name": "StackExchange" }
Q: How do I set the background color/pattern in a Nautilus window? In Previous versions of Ubuntu, I used to go under the edit menu to set the background color of a Nautilus window. I have no idea how to do this in Ubuntu. A: My problem with this new ubuntu 11.10 was the fact that i was not able to change the background color of the windows, that white color just drove me crazy; as you noticed 'appearance preferences' from the old ubuntu does not exit any more here; there is a way though (or maybe more): Here's what you have to do to change colors in ubuntu 11.10: Open the terminal, paste sudo apt-get install dconf-tools then dconf-editor Browse to org.gnome.desktop.interface. Locate gtk-color-scheme, don't click on it, click on the empty space on the right side to get a small box where you will paste the following: bg_color:#ebe0be;selected_bg_color:#737370;base_color:#9d906a Press enter, nothing else! The colors will change right away (this is just an example with my favourite colors). If you wanna find your own colors, install gnome color chooser and play with the colors (the color palette will look the same as it did in 'appearance preferences in the old ubuntu) to find out the right codes (six digit hexadecimal numbers) for the ones that you like. Once you find yours, paste the six digit code number into the right place in gtk-color-scheme and then enter again it is done.
{ "pile_set_name": "StackExchange" }
Q: How to get Last Access Time of any file in Android Without Using BasicFileAttribute Class I want a class which would be a part of an Android application that can directly provide me the last open status or last access status of any file like images, videos. The BasicFileAttribute.class seems not to work for me. The solution need to use JDK 8. I don't want to use JDK 7. A: You can use Os.stat - since api 21, it returns StructStat which contains field st_atime with Time of last access (in seconds). example: if (Build.VERSION.SDK_INT >= 21) { try { StructStat stat = Os.stat("/path/to/my/file"); if (stat.st_atime != 0) { // stat.st_atime contains last access time, seconds since epoch } } catch (Exception e) { // deal with exception } } Other solution is to execute shell command stat : Process p = Runtime.getRuntime().exec("stat -c \"%X\" /path/to/file"); p.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader( p.getInputStream())); String line = reader.readLine(); long time_sec = 0; if (!TextUtils.isEmpty()) time_sec = Long.parseLong(line); I have not tested above code - but it looks like it should work. Third aproach would be to use NDK and call stat function from C or C++.
{ "pile_set_name": "StackExchange" }
Q: wmi accelerator and authentication It seems I can not find clearly written somewhere that when using WMI accelerator in a PowerShell script, you can not pass on authentication. A little background ... I am writing PowerShell scripts for SCCM 2012 and found, for instance, the following quite using : PS R:\> ([wmi]((gwmi -namespace root\sms\site_AAA -class SMS_Application -filter "LocalizedDisplayName LIKE '%Winzip_Tartempion%'") .__PATH)).SDMPackageXML When executed locally (on the SCCM primary server, it works fine and swiftly. However, the following ends up in error when executed from my desktop computer running W7 : PS R:\> ([wmi]((gwmi -namespace root\sms\site_AAA -credential $cred -ComputerName CEMTECH -class SMS_Application -filter "LocalizedDisplayName LIKE '%Winzip_Tartempion%'") .__PATH)).SDMPackageXML For the time being, using a PSSession is out of the question. With the current infrastructure I have to deal with, using SCCM commandlet is out of the question. My only question here is : can you confirm that we can not pass any authentication with a WMI accelerator ? At that point, I am searching for that answer mainly for my curiosity. I found a way to manage with my current constraints. It is just that I find the accelerators so "elegant". Now why do I need it ? I need to access "lazy properties" without using SCCM cmdlets, from a desktop computer to which the user is logged on with an account which will not be the same as the name authorized to connect/access the SCCM primary server. What I still did not find is how to use "*.__PATH" with the Get-WMIObject cmdlet. A: The WMI-accelerator [wmi] doesn't support alternate credentials. Why do you need it? You could just run: $obj = Get-WmiObject -namespace root\sms\site_P41 -credential $cred -ComputerName qs07352 -class SMS_Application -filter "LocalizedDisplayName LIKE '%Winzip_Tartempion%'" $obj.Get() $obj.SDMPackageXML
{ "pile_set_name": "StackExchange" }
Q: Visual C++ values differ while printing and debugging? I am checking a piece of code. Everything is correct but concept I am not able to understand. double a = 0.001; double b = 0.001; double c = a * b; printf ("%lf", c); While debugging in visual c++ when i am pointing mouse over c after 3rd line it is displaying 9.999999999999995e-007 but while printing it is showing correct result i.e. 0.000001. I want to know actually what value it displays in debug tooltip and how it represents and converts. A: This is the result of rounding performed by printf. The printf format %lf rounds to a default precision. From the top of my head, I think the default is 6, that is why you get 0.000001. The debugger shows the actual content of the double. Due to the nature of floating point arithmetic, the result of 0.001 * 0.001 is not actually 0.000001, but an approximation although with very small difference. By using other formats, you can see the difference. E.g. try printf("%.15e", c);
{ "pile_set_name": "StackExchange" }
Q: Ought you study Complex Analysis and/or Variables in university? I deliberately haven't stipulated the kind of Quant job, as I'm asking in general. This r/quant comment answers "what is complex analysis used for in quant finance?": Some pricing models, and some analysis of distributions. E.g. Option valuation using the fast Fourier transform by Peter Carr and Dilip B. Madan has 2207 citations according to Google. But can you learn Complex Analysis and/or Variables on your own? Or ought you study them in university? I'm assuming Complex Analysis and Variables differ like how regular and honors multivariable calculus. Physics Forums: The impression I have is that the Complex Variables class is more concerned with computation and calculus using complex numbers (something that as a physicist you may have to do a lot). And the Complex Analysis class will be more about developing the theory of complex numbers and their use in calculus and whatnot. A complex analysis course will mostly be concerned with proving things, while I imagine the complex variables class will be all about using complex numbers to help with computation. In my grad complex analysis class, we reviewed the entire complex variables course in a day and a half. In other words, the variables course is sort of a prereq for the analysis course. Depending on your familiarity with the complex plane, some topology, and calculus, you could probably go into the analysis class directly. It's certainly more enjoyable. Dr Transport wrote Unless you do a PhD in Mathematical Physics, a theorem-proof class in my opinion would not be that helpful. I'm a theoretician and have not had a need for that level of mathematical rigor. Mathwonk wrote I am not a physicist, I am a mathematician, but I have taught both those courses. I would imagine that for you the applied course is more useful. I.e. you would probably rather understand how to use complex analysis than how to prove the theorems. Andy Nguyen discourages it: Complex analysis has little to no use in FE program. You would better off spend the summer working on your C++. Vic_Siqiao: complex analysis has no direct use in FE, but it helps sometimes do calculations invloving complex variables. and i think some topics such as residual theorem are important, which i was asked in a fin math program interview. macroeconomicus: I think stochastic calculus will give you better benefit/cost at this stage. Stochastic calculus is used a lot in asset pricing and mathematical finance, and I assume in some other subjects in economics (macro perhaps?). Complex analysis is used a little in advanced probability to work with characteristic functions and such, and also for some things in time series, but you probably don't need to take a whole analysis course to follow. I heard you can just pick it up along the way. A: In the context of mathematical finance and financial economics, complex analysis naturally arise in derivative pricing. Specifically, some models impose that the conditional characteristic function of the underlying will be affine in all state variables. In those cases, you can generally obtain a quasi-analytical formula for pricing European options where you evaluate an integral whose integrand is a function of the conditional characteristic function of the underlying. It looks something like this: \begin{equation} \int_0^\infty \text{Imag}\left( g \circ \psi(\phi - i) \right) d\phi \end{equation} Because of the conditional characteristic function $\psi(.)$, $g \circ \psi(\phi - i)$ is going to be complex-valued, so it spits out numbers of the form $a+bi$ where $i^2 = -1$. You're really just working with a grid of $\phi'$s and a corresponding grid of $b'$s when you seek to numerically approximate this integral... So, you don't need a whole course in complex analysis to understand this. Another place where you will find complex analysis is in time series econometrics. The reason is that you can think of a time series in the time space, just as in the frequency space. I have seen a lot of people trying to get papers on this subject off the ground, but it's the sort of paper almost no one reads -- and even less uses in practice. My advice: if you're going to put time on something, put time on stochastic calculus and computer programming. Why? Stochastic calculus is the lingua franca of deritative pricing, so almost no matter what you do, it will be useful. As for computer programming, you need to be able to solve problems numerically, as well as to implement analytical solutions. There's nothing like getting your hands dirty, trying to do everything from the theory to the calibration to the data to understand how models work (and sometimes don't work).
{ "pile_set_name": "StackExchange" }
Q: jQuery .find() in server response I am trying to get the text inside a specific div in a server response. I used Firebug to see what the response was, and I can see my element in the returned code, but for some reason I can get jQuery to capture it. Here is what I am using: var response = $('<div />').html(serverData); $('#uploadedFiles').html($(response).find("#created").text()); alert($(response).find("#created").text()); Trying that just returns nothing, not text or anything. Am I doing this correctly? Note: The server response is not from a jQuery ajax function, rather from the jQuery SWFUpload plugin, would this matter though? A: When are you running the code? If you run it before the uploadedFile element is created, the code will not find it. I tested this, and it works just fine, it alerts "asdf" and then replaces "test" with "asdf" in the div element: <script type="text/javascript"> $(function(){ var response = $('<div />').html('<div id="created">asdf</div>'); alert(response.find("#created").text()); $('#uploadedFiles').html(response.find("#created").text()); }); </script> <div id="uploadedFiles">test</div> Note that response is alread a jQuery object, so $(response) is redundant.
{ "pile_set_name": "StackExchange" }
Q: Memory leak for javascript setInterval Is there any difference between these 2 statements setInterval(animateImage, 1000); or setInterval('animateImage()', 1000); Will the second statement be interpreted by the browser js engine is any different way that could cause memory leak or performance issues. Same is the case with the setTimeout() call. The application makes use of 4 timer calls with 1-2 sec intervals. A: The biggest difference is that the second statement will cause animateImage() to be evaluated in global scope. This can lead to problems if animateImage is not in global scope animateImage has to access variables that are not in global scope E.g. the following will not work: function foo() { var answer = 42; function bar() { alert(answer); } setTimeout('bar()', 1000); } foo(); Actually there is never a reason to use the second statement, so the question about memory leaks is not relevant anymore ;) And obviously, passing a direct reference to a function will be 'faster' than evaluating a string. A: Use the first one. It makes debugging nicer since there's no eval'd code involved, it is faster and cleaner. Eval is evil and it's good to avoid it whenever possible. In case you ever need to pass an argument, use the following code: setInterval(function() { animateImage(...); }, 1000);
{ "pile_set_name": "StackExchange" }
Q: WCF XML Serialization & Overloading In my WCF service I only want 1 endpoint (1 URI), however, I want this URI to be able to handle multiple types of requests. 5 different request types can be sent to this service from another company. Each request has a unique XML schemas. I created classes for each XML request to be serialized. Normally I would just overload a function when the parameter is different.... however I cannot do this in this instance because the UriTemplate of my WCF functions are the same, and throws errors when I try to run the app (saying the UriTemplate must be unique). In each XML request is a node named "requestType". I'm trying to get a feel for what others would do... should I serialize on my own and ignore the built in serialization from the DataContract? What type of parameter should I set my function to accept... an XMLDocument then based on the requestType branch out to the request specific logic? The returned XML from this function is also unique based on the request type.... however I cannot return an XMLDocument from an OperationContract... more errors are thrown (I think because it said it cannot be serialized). I've tried creating a class that can get serialized from all request types by setting IsRequired = false, EmitDefaultValue = false ...on the DataMembers for objects that are not shared amongst the different request types. I'm now running into a problem where the Order has to be properly set for each DataMember otherwise it doesn't get serialized at all into my class object.... I would have thought the Order wouldn't have to be set :/ Edit: This is what I'm using now... the XML is POSTed to my service. [WebHelp(Comment = "comment")] [WebInvoke(UriTemplate = "foobar", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Xml)] [OperationContract] public ResponseType foobar(ReqeustType request) ... When testing I would post XML to http://localhost:4011/XMLWCF/Service.svc/foobar A: I would have one service endpoint, e.g. one URL, but I would clearly define five separate, unique service methods in your service contract, and implement those separately. THat's by far the easiest and cleanest solution, in my opinion. [ServiceContract(Namespace=".......")] interface IYourService { [OperationContract] ReturnValue1 YourMethodNo1(int a, int b); [OperationContract] ReturnValue2 YourMethodNo2(........); [OperationContract] ReturnValue3 YourMethodNo3(..........); [OperationContract] ReturnValue4 YourMethodNo4(...........); [OperationContract] ReturnValue5 YourMethodNo5(........); } You can't really have just a single service method which gets five different types of parameters. Also, WCF doesn't support method overloading - since WSDL doesn't support it. All your methods have to have a unique name and have to have defined and clear parameters types. You could use a general parameter of type Message - but that does get pretty hairy, in my opinion. This MSDN page or this blog post shed some light on how to do that - if you really want to... UPDATE: in this scenario I described, you'd have ONE service URL - http://site.com/service.svc. From that service URL, you'd create a client proxy at your client end, which would have five methods to call: (pseudo-code): class ClientProxy { ReturnValue1 YourMethodNo1(int a, int b); ReturnValue2 YourMethodNo2(........); ReturnValue3 YourMethodNo3(..........); ReturnValue4 YourMethodNo4(...........); ReturnValue5 YourMethodNo5(........); } From your client code, you would then call either of those five methods: ReturnValue1 result = ClientProxy.YourMethodNo1(5, 7); but all would go to the single service URL.
{ "pile_set_name": "StackExchange" }
Q: "every prime number $p$ $(p>3)$ can be expressed sum of consecutive numbers " is it true? I'm finding some necessary and sufficient conditions for a integer $n$ to be a prime number. But I'm not sure if "every prime number $p \, ,(p>3)$ can be expressed sum of consecutive number" is true. If it is right, I hope you help me prove that. Thank you very much. A: Every prime greater than or equal to $3$ is odd, and every odd is of the form $2k+1$ that is, $$\exists \,k \in \mathbb N \, : \,p=2k+1=\underbrace{(k)+(k+1)}_{\text{Sum of two consecutive integers}}$$
{ "pile_set_name": "StackExchange" }
Q: Example of logical order and total order in distributed system Total order: Lamport timestamps can be used to create a total ordering of events in a distributed system by using some arbitrary mechanism to break ties (e.g. the ID of the process). Logical order: When two entities communicate by message passing, then the send event is said to 'happen before' the receive event, and the logical order can be established among the events enter link description here Can anyone give me an example where I can see the differences of logical order and total order? What is the difference of both orders? A: Since you are looking for an example about differences between Logical order and Total order, here is a little story my old distributed algorithm teacher told us when he wanted to explain that specific topic. Let's say that A owes B some money. A tells B on the phone, that A is going to credit B's account in A's local branch at 6 p.m. So anytime after 6 p.m., B can withdraw money from A's bank. Let's say B is nice and tells A's branch that at 8 p.m. they can debit A's account the money that A owes B. So B's branch is going to basically do a debit call to the central bank server asking for the money that is owed by A to be transferred to B's account and that's what is going to happen. B has been given A enough time to make sure that A have indicated to B bank, that A have enough money, so that A's debit transaction can go through. B would think it should go through, right? But it turns out, that B's branch's local time is far ahead of real time. The branch thought it was 8 p.m., it was not quite 8 p.m., yet. A is keeping his word, exactly at 6 p.m., A's branch happens to be good with the time. (synced with the real time) So at 6 p.m., A has done the credit of the amount that A owes B to A's central bank server. Unfortunately, the central bank server, in real time, got B's message much earlier than the time at which A sent his message. The central bank server isn't looking at any logical time. It is looking at real time when there's a debit transaction coming in. Is there money in the bank for paying those debit transactions? No, there isn't. So B's request is declined. This is the result of the fact that in real world scenarios, logical clocks are not good enough. So what caused the problem here? It is the fact that B's branch's notion of real time is completely at odds with real time. The computer at B's local bank might have a clock that is drawing near with the respect to real time.It's either going faster than real time or it is going slower than the real time. It so happens that A's, A's branch's time is is perfectly in sync with the real time, but that doesn't help A. This example seems a little complex to understand straightaway. This is know as the clock synchronization problem. I invite you strongly to read Lamport's paper concerning Time, Clocks, and the Ordering of Events in a Distributed System as he presents a different way to explain the differences. You might also find these references quite handy : A lecture about Clock Synchronization by Paul Krzyzanowski An intersting blogpost about Synchronization in a Distributed System I found while trying to formulate the answer. I hope this helps.
{ "pile_set_name": "StackExchange" }
Q: textfile to an array...any ideas? I am needing to turn a textfile into an array...I am not sure how to go about this because the other features ive seen for php take an entire file and put it into an array but not quite how I want it to be so I am looking for advice here.. The following is written in a textfile: "jim kroi,richard wuu,yan kebler,justin persaud" How can I use php to make an array where automatically a loop puts each name as an item of the array until all the names run out? so the end result of what I am trying to do is: $array= array("jim kroi","richard wuu","Yan kebler","justin persaud"); So a loop of some sort would basically search upto each comma and extract the name before it until all of the names run out.... There are some php substr and such functions but I cant quite think of how to do this.. Yes, I do have code, here it is: <?php error_reporting(-1); $fp = fopen('numbers.csv', 'w'); fputcsv($fp, $_POST['names']); fputcsv($fp, $_POST['numbers']); fclose($fp); ?> i put them all in a csv but now how can I make 2 arrays, one with name the other with numbers? http://imageshack.us/photo/my-images/215/csv.png/ using implode I get the error: Warning: implode() [function.implode]: Bad arguments. in C:\Program Files\xampp\htdocs\xampp\something.php on line 14 <?php error_reporting(-1); $myFile = "testFile.txt"; $fh = fopen($myFile, 'r'); // open file $theData = fread($fh, 5); // read file and store in var $array = explode("\n", $theData); // explode string by lines using \n echo implode("<br/>", $theData); // put the array back together and show each item as a line fclose($fh); ?> A: Something like: $names = array_map('trim', explode(',', file_get_contents('%yourFileHere')));
{ "pile_set_name": "StackExchange" }
Q: ADT-PLUGIN ISSUE I installed the adt-plugin for eclipse. I'm using Ubuntu 10.4 and have been stuck on this issue for 2 days now. Select Window > Preferences... to open the Preferences panel (Mac OS X: Eclipse > Preferences). Select Android from the left panel. For the SDK Location in the main panel, click Browse... and locate your downloaded SDK directory. I cant find the location of the downloaded plugin and have looked in /usr /etc /home everywhere possible, I still can't believe im stuck on something so simple. Anyone who could point me into the right direction, would help me sooo much. thnx hi.im.new A: The Android SDK is a different component from the plugin. You need the SDK to do any Android development at all. The plugin is just a helper for Eclipse. It sound like you haven't got the Android SDK on your system. You can get it from: link text Pick the starter package first of all then once you have that, you can add more components using the SDK Manager which will come with the starter package.
{ "pile_set_name": "StackExchange" }
Q: Python - Using pytest to skip test unless specified Background I have am using pytest to test a web scraper that pushes the data to a database. The class only pulls the html and pushes the html to a database to be parsed later. Most of my tests use dummy data to represent the html. Question I want to do a test where a webpage from the website is scraped but I want the test to be automatically turned off unless specified. A similar scenario could be if you have an expensive or time consuming test that you do not want to always run. Expected Solution I am expecting some kind of marker that suppresses a test unless I give pytest to run all suppressed tests, but I do not see that in the documentation. What I have done I am currently using the skip marker and comment it out. Tried to use the skipif marker and and give arguments to python script using this command from command prompt pytest test_file.py 1 and the following code below in the test file. The problem is that when I try to provide an argument to my test_file, pytest is expecting that to be another file name so I get an error "no tests run in 0.00 seconds, ERROR: file not found: 1" if len(sys.argv) == 1: RUN_ALL_TESTS = False else: RUN_ALL_TESTS = True ... # other tests ... @pytest.mark.skipif(RUN_ALL_TESTS) def test_scrape_website(): ... I might be able to treat the test as a fixture and use @pytest.fixture(autouse=False), not sure how to override the autouse variable though A similar solution was stated in How to skip a pytest using an external fixture? but this solutions seems more complicated than what I need. A: The docs describe exactly your problem: https://docs.pytest.org/en/latest/example/simple.html#control-skipping-of-tests-according-to-command-line-option. Copying from there: Here is a conftest.py file adding a --runslow command line option to control skipping of pytest.mark.slow marked tests: # content of conftest.py import pytest def pytest_addoption(parser): parser.addoption( "--runslow", action="store_true", default=False, help="run slow tests" ) def pytest_collection_modifyitems(config, items): if config.getoption("--runslow"): # --runslow given in cli: do not skip slow tests return skip_slow = pytest.mark.skip(reason="need --runslow option to run") for item in items: if "slow" in item.keywords: item.add_marker(skip_slow) We can now write a test module like this: # content of test_module.py import pytest def test_func_fast(): pass @pytest.mark.slow def test_func_slow(): pass A: There's a couple ways to handle this, but I'll go over two common approaches I've seen in Python baselines. 1) Separate your tests by putting the "optional" tests in another directory. Not sure what your project layout looks like, but you can do something like this (only the test directory is important, the rest is just a toy example layout): README.md setup.py requirements.txt test/ unit/ test_something.py test_something_else.py integration/ test_optional.py application/ __init__.py some_module.py Then, when you invoke pytest, you invoke it by doing pytest test/unit if you want to run just the unit tests (i.e. only test_something*.py files), or pytest test/integration if you want to run just the integration tests (i.e. only test_optional.py), or pytest test if you want to run all the tests. So, by default, you can just run pytest test/unit. I recommend wrapping these calls in some sort of script. I prefer make since it is powerful for this type of wrapping. Then you can say make test and it just runs your default (fast) test suite, or make test_all, and it'll run all the tests (which may or may not be slow). Example Makefile you could wrap with: .PHONY: all clean install test test_int test_all uninstall all: install clean: rm -rf build rm -rf dist rm -rf *.egg-info install: python setup.py install test: install pytest -v -s test/unit test_int: install pytest -v -s test/integration test_all: install pytest -v -s test uninstall: pip uninstall app_name 2) Mark your tests judiciously with the @pytest.mark.skipif decorator, but use an environment variable as the trigger I don't like this solution as much, it feels a bit haphazard to me (it's hard to tell which set of tests are being run on any give pytest run). However, what you can do is define an environment variable and then rope that environment variable into the module to detect if you want to run all your tests. Environment variables are shell dependent, but I'll pretend you have a bash environment since that's a popular shell. You could do export TEST_LEVEL="unit" for just fast unit tests (so this would be your default), or export TEST_LEVEL="all" for all your tests. Then in your test files, you can do what you were originally trying to do like this: import os ... @pytest.mark.skipif(os.environ["TEST_LEVEL"] == "unit") def test_scrape_website(): ... Note: Naming the test levels "unit" and "integration" is irrelevant. You can name them whatever you want. You can also have many many levels (like maybe nightly tests or performance tests). Also, I think option 1 is the best way to go, since it not only clearly allows separation of testing, but it can also add semantics and clarity to what the tests mean and represent. But there is no "one size fits all" in software, you'll have to decide what approach you like based on your particular circumstances. HTH! A: A very simply solution is to use the -k argument. You can use the -k parameter to deselect certain tests. -k tries to match its argument to any part of the tests name or markers You can invert the match by using not (you can also use the boolean operators and and or). Thus -k 'not slow' skips tests which have "slow" in the name, has a marker with "slow" in the name, or whose class/module name contains "slow". For example, given this file: import pytest def test_true(): assert True @pytest.mark.slow def test_long(): assert False def test_slow(): assert False When you run: pytest -k 'not slow' It outputs something like: (note that both failing tests were skipped as they matched the filter) ============================= test session starts ============================= platform win32 -- Python 3.5.1, pytest-3.4.0, py-1.5.2, pluggy-0.6.0 rootdir: c:\Users\User\Documents\python, inifile: collected 3 items test_thing.py . [100%] ============================= 2 tests deselected ============================== =================== 1 passed, 2 deselected in 0.02 seconds ==================== Because of the eager matching you might want to do something like putting all your unittests in a directory called unittest and then marking the slow ones as slow_unittest (so as to to accidentally match a test that just so happens to have slow in the name). You could then use -k 'unittest and not slow_unittest' to match all your quick unit tests. More pytest example marker usage
{ "pile_set_name": "StackExchange" }
Q: Sonar Maven plugin finds more bugs than Sonar Jenkins or Sonar CLI Scanner on multi-module Maven project Given the same code and the same SonarQube server with the same rules I get vastly different number of bugs and vulnerabilities found when scanning with mvn sonar:sonar vs the sonar-scanner CLI and a sonar-project.properties file or the Sonar Jenkins plugin. Like, more than twice as many. I have the modules setup in the properties file and on the server I can see the count of lines of code is the same between the two scanners. I can see tests in one report but not the other but the tests aren't being counted for the lines of code or any bugs. An example of something Maven is finding that Jenkins is not is squid:S2160 where the parent class is part of the same module as the child class. My main concern is whether the additional errors Maven is finding are legit, especially given that Sonar has deprecated the "SonarQube analysis with Maven" post-build action and the recommended Jenkins scanner ISN'T finding the same problems when looking at the same code. Which scanner is right, and if it's Maven is it still OK to use the deprecated step in Jenkins? I've anonymized the properties file with the modules, but it looks like this: # Required metadata sonar.projectKey=groupId:artifactID sonar.projectName=My Project name sonar.projectVersion=0.0.4-SNAPSHOT # Comma-separated paths to directories with sources (required) sonar.sources=coreModule/src/main/java,appModule/src/main/java sonar.tests=coreModule/src/test/java,appModule/src/test/java sonar.modules=core,app core.sonar.projectBaseDir=coreModule core.sonar.sources=src/main/java core.sonar.projectName=My Core Module Name app.sonar.projectBaseDir=appModule app.sonar.sources=src/main/java app.sonar.projectName=My App Module Name # Language sonar.language=java sonar.java.source=8 # Encoding of the source files sonar.sourceEncoding=UTF-8 A: The SonarQube Scanner for Jenkins is essentially a wrapper around the other scanners to make them available to you conveniently in Jenkins. From the rest of your question, I'll guess that you're using the SonarQube Scanner analysis Build Step in Jenkins. From the properties you've posted, you don't appear to be providing byte code to SonarQube Scanner analysis. If you were, there would be a sonar.java.binaries property. The reason the SonarQube Scanner for Maven is finding more issues is that it automatically provides that value to the analysis. And if you're able to analyze with SonarQube Scanner for Maven, you should. As you've already discovered it "just handles" most of the details for you. You accomplish this in Jenkins not with a SonarQube Scanner for Maven-specific build step, but with a normal Maven build step. As described in the docs you will have first enabled "Prepare SonarQube Scanner environment" in the Build Environment section. Then you can analyze with $SONAR_MAVEN_GOAL -Dsonar.host.url=$SONAR_HOST_URL. (Note that you may also need to pass an analysis token via -Dsonar.login depending on your project permissions.) To answer your question, the "extra" issues found by the Maven analysis are legitimate. They are not found by the other analyses because they are raised by rules that work against byte code.
{ "pile_set_name": "StackExchange" }
Q: Setting Isolation level in ruby v 2.1.3 I have been struggling with putting a record level lock on my table, to avoid any dirty reads and race condition while updating the record. I am using ruby 2.1.3 and rails version 3.2.13. I tried using the command: Account.connection.execute("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE") and tested by putting sleep, but 2 processes trying to update the same record read the old value and the final data is wrong. For example: if my old value is 100, both processes read 100 and then update, 100+x and 100+y and thus,the data is getting corrupted. I am using mySQL database. Any help is appreciated. A: The following solution worked for me (slight modification of dimakura's answer): When I used find() for active record query: acc = Account.lock.find(id) acc.balance += 100 acc.save! When I used where() for active record query: acc = Account.where(:acc_code => acc_code).first acc.with_lock do acc.balance += 100 acc.save! end
{ "pile_set_name": "StackExchange" }
Q: Why do these values change like the objects were passed by reference if I set the properties? Program: class Program { class class1 { public string Name { get; set; } public int Value { get; set; } } class class2 { public string Name { get; set; } public int Value { get; set; } } static void Main(string[] args) { var Source = new class1() { Name = "Source", Value = 1 }; var Target = new class2() { Name = "Target", Value = 2 }; setValue(Source, Target); Console.WriteLine(string.Format("Source - Name:{0} Value:{1}", Source.Name,Source.Value)); Console.WriteLine(string.Format("Target - Name:{0} Value:{1}",Target.Name, Target.Value)); } private static void setValue(object Source, object Target) { Target = Source; } } When this runs I get(which I expected): Source - Name:Source Value:1 Target - Name:Target Value:2 But when I change the setValue method to: private static void setValue(object Source, object Target) { var source = Source as class1; var target = Target as class2; target.Name = source.Name; target.Value = source.Value; } I get: Source - Name:Source Value:1 Target - Name:Source Value:1 A: This line: Target = Source; Is just copying the value of Source into the variable Target. That value is just a reference - and Target is effectively just a local variable, as it's a normal parameter. In your other code: var source = Source as class1; var target = Target as class2; target.Name = source.Name; target.Value = source.Value; That's setting the data within the objects which are referred to by the parameters. Think about it like this. Imagine you give someone a piece of paper with an address on, and they go to that address and painting the house red. Later you visit the house yourself, and you see that it's red. Now compare that with your first example - that's like giving someone a piece of paper, and them crossing out the address and writing the address of a red house onto it. You don't see this - you just gave them the piece of paper and let them get on with it. So when you go to the original address, you don't see a red house, because it hasn't changed. I have two articles which may help you to understand the concepts involved: Parameter passing Reference types and value types
{ "pile_set_name": "StackExchange" }
Q: Getting Array value in a dictionary swift I am trying to get key and value in a Dictionary while I am able to the key and map it to a dictionary, I am unable to get the value which is an array. var dict = [String: [String]] I was able to get the key as an array which is what I want like: var keyArray = self.dict.map { $0.key } How can I get the value which is already an array A: Use flatMap if you want to flatten the result you get when you use map which is of type [[String]]. let valueArray = dict.flatMap { $0.value } // gives `[String]` mapping all the values
{ "pile_set_name": "StackExchange" }
Q: Как открыть порт в Ubuntu? Я новичок в ubuntu, поэтому никак не могу понять, почему порт не открывается и как это всё-таки сделать. Подскажите, пожалуйста!Я пробовал открыть порт в iptables, но, как я понял, iptables служат для управления файерволлом ufw, а при вводе команды sudo ufw status получаю ответ:sudo: ufw: command not foundКак в таком случае открыть порт? Гугление мне посоветовало лишь iptables.На всякий случай приведу выход команды netstat -an | grep LISTENtcp 0 0 127.0.0.1:25 0.0.0.0:* LISTENtcp 0 0 127.0.0.1:953 0.0.0.0:* LISTENtcp 0 0 127.0.0.1:587 0.0.0.0:* LISTENtcp 0 0 0.0.0.0:80 0.0.0.0:* LISTENtcp 0 0 5.231.61.235:53 0.0.0.0:* LISTENtcp 0 0 127.0.0.2:53 0.0.0.0:* LISTENtcp 0 0 127.0.0.1:53 0.0.0.0:* LISTENtcp 0 0 0.0.0.0:22 0.0.0.0:* LISTENtcp 0 0 127.0.0.1:631 0.0.0.0:* LISTENtcp6 0 0 ::1:953 :::* LISTENtcp6 0 0 :::53 :::* LISTENtcp6 0 0 :::22 :::* LISTENtcp6 0 0 ::1:631 :::* LISTENunix 2 [ ACC ] STREAM LISTENING 3215411995 /var/run/cups/cups.sockunix 2 [ ACC ] STREAM LISTENING 3215409707 /var/run/avahi-daemon/socketunix 2 [ ACC ] STREAM LISTENING 3215403381 @/com/ubuntu/upstartunix 2 [ ACC ] STREAM LISTENING 3215406175 /var/run/dbus/system_bus_socketunix 2 [ ACC ] STREAM LISTENING 3215553140 /var/run/sendmail/mta/smcontrolunix 2 [ ACC ] STREAM LISTENING 3215421071 /var/run/acpid.socketunix 2 [ ACC ] SEQPACKET LISTENING 3215405745 /run/udev/controlunix 2 [ ACC ] STREAM LISTENING 3215427067 /var/run/saslauthd/muxТо есть вроде как 53-й порт открыт... Как бы ещё портов открыть? A: Ваш листинг это не открытые порты, а вывод того кто какие порты слушает. Если вы хотите например открыть порт 53 по tcp, используя утилиту iptables : iptables -I INPUT -p tcp -m tcp --dport 53 -j ACCEPT
{ "pile_set_name": "StackExchange" }
Q: Conditionally closing a tag in HAML I'm iterating through a set of items and displaying them in lists nested in divs. The goal is to have a div for each day and within each div show the items for that day. How do I do this in HAML? I don't think I can (or should) conditionally close and create a new tag like I could in erb. I tried: - @items.each do |item| - if item date is diff from previous make a new container .container %h2 #{item.date} = yield_content :display_item item - else = yield_content :display_item item But this creates the following: <div class="container"> <h2>01/28/2012</h2> <ul> <li> ... item </li> </ul> </div> <li> ...item </li> But I want the other item in the same div. I'm using ruby, sinatra (including the content_for helper) A: The answer is to use more and better Ruby :) - @items.group_by(&:date).each do |date,items| .container %h2= date - items.each do |item| = yield_content :display_item item See Enumerable#group_by docs for more details. You could close and re-open the containers and headers as you were thinking, but this is a horrible, hard-to-maintain hack that I would suggest against. Embrace the elegance of Ruby and Haml; don't write Haml like it was ERB.
{ "pile_set_name": "StackExchange" }
Q: Why does the Ebay application automatically startup at boot? I can't find a good reason that this application must always be running on my phone. However, it starts at boot and I'm constantly getting error traces in Logcat about the Ebay application. Why does this application start at boot? A: Well it starts because that's how dev coded it. You can try programs like startup manager that will kill the program once it starts.
{ "pile_set_name": "StackExchange" }
Q: Using XPath Contains against HTML in Java I'm scraping values from HTML pages using XPath inside of a java program to get to a specific tag and occasionally using regular expressions to clean up the data I receive. After some research, I landed on HTML Cleaner ( http://htmlcleaner.sourceforge.net/ ) as the most reliable way to parse raw HTML into a good XML format. HTML Cleaner, however, only supports XPath 1.0 and I find myself needing functions like 'contains'. for instance, in this piece of XML: <div> <td id='1234 foo 5678'>Hello</td> </div> I would like to be able to get the text 'Hello' with the following XPath: //div/td[contains(@id, 'foo')]/text() Is there any way to get this functionality? I have several ideas, but would prefer not to reinvent the wheel if I don't need to: If there is a way to call HTML Cleaner's evaluateXPath and return a TagNode (which I have not found), I can use an XML serializer on the returned TagNode and chain together XPaths to achieve the desired functionality. I could use HTML Cleaner to clean to XML, serialize it back to a string, and use that with another XPath library, but I can't find a good java XPath evaluator that works on a string. Using TagNode functions like getElementsByAttValue, I could essentially recreate XPath evaluation and insert in the contains functionality using String.contains Short question: Is there any way to use XPath contains on HTML inside an existing Java Library? A: Regarding this: I could use HTML Cleaner to clean to XML, serialize it back to a string, and use that with another XPath library, but I can't find a good java XPath evaluator that works on a string. This is exactly what I would do (except you don't need to operate on a string (see below)). A lot of HTML parsers try to do too much. HTMLCleaner, for example, does not properly/completely implement the XPath 1.0 spec (contains (for example) is an XPath 1.0 function). The good news is that you don't need it to. All you need from HTMLCleaner is for it to parse the malformed input. Once you've done that, it's better to use the standard XML interfaces to deal with the resulting (now well-formed) document. First convert the document into a standard org.w3c.dom.Document like this: TagNode tagNode = new HtmlCleaner().clean( "<div><table><td id='1234 foo 5678'>Hello</td>"); org.w3c.dom.Document doc = new DomSerializer( new CleanerProperties()).createDOM(tagNode); And then use the standard JAXP interfaces to query it: XPath xpath = XPathFactory.newInstance().newXPath(); String str = (String) xpath.evaluate("//div//td[contains(@id, 'foo')]/text()", doc, XPathConstants.STRING); System.out.println(str); Output: Hello
{ "pile_set_name": "StackExchange" }
Q: When are the carry flags set? What is meant by "Applying the NEG instruction to a nonzero operand always sets the Carry flag." Why does substracting 2 from 1 set the carry flag? 00000001 (1) + 11111110 (-2) [in 2-complement form] --------------------- CF:1 11111111 (-1) [ why is the carry flag set here???] A: You could view NEG a as equivalent to SUB 0, a. If a is non-zero, then this will set the carry flag (as this will always result in an unsigned overflow).
{ "pile_set_name": "StackExchange" }
Q: Correct sorting after text to columns in EXCEL I have some data in which one column represents the Days of Operations, as below: ------- Days ------- 15 7 1234567 etc. I want to "break" the column (via text to columns option in the Data tab of Excel) and create the following columns: -------------------- D1|D2|D3|D4|D5|D6|D7 -------------------- 1| | | | 5| | | | | | | | | 7| 1| 2| 3| 4| 5| 6| 7| However, the data is being messed up and I get different days in different columns... How I can overpass this? Is there a way to assign the values accordingly? A: I want to "break" the column (via text to columns option in the Data tab of Excel) As per your question, you want to do this with Text-to-Columns. Well, that's a no go. Text-to-columns works either on a character delimiter or a fixed width. Your data has neither. You apparently want to distribute the data based on its values. That cannot be done with Text-to-Columns. You will need a code or a formula solution for that. If you import your source data into a spreadsheet, with all the imported data sitting in column A, you can use a formula like this: =IF(ISERROR(FIND(COLUMN(A1),$A4)),"",COLUMN(A1)) If the data as posted above starts in A1, then the formula will be in cell B4 and can be copied across and down. You can hide column A do display just the results of the formula.
{ "pile_set_name": "StackExchange" }
Q: Odoo: how to show fields of a many2one fields which is inside a one2many field I don't know how to put it but here's what i want, i want to show the fields of a custom.product model in the tree view of a one2many field my code is as follows class CustomSale(models.Model): _name = 'custom.sale' _description = 'Sale Record' name = fields.Char(string='Order Reference', required=True, copy=False, readonly=True, default=lambda self: _('New')) order_line = fields.One2many('custom.sale.line', 'order_id', string='Order Lines', copy=True, auto_join=True) class CustomSaleLine(models.Model): _name = 'custom.sale.line' _description = 'Sales Line' order_id = fields.Many2one('custom.sale', string='Order Reference', required=True,) product_id = fields.Many2one('custom.product', string='Product', change_default=True, ondelete='restrict') product_uom_qty = fields.Integer(string='Ordered Quantity', required=True, ) <record id="form_custom_sale" model="ir.ui.view"> <field name="name">custom.sale.form</field> <field name="model">custom.sale</field> <field name="arch" type="xml"> <form string="Sales"> <sheet> <group> <group> <field name="name"/> </group> </group> <notebook> <page string="Order Lines" name="order_lines"> <field name="order_line" widget="section_and_note_one2many" mode="tree"> <tree editable="bottom"> <control> <create string="Add a product"/> </control> <field name="product_id"> <tree> <field name="brand_id"/> <field name="country_id"/> <field name="sell_price"/> </tree> </field> <field name="product_uom_qty" string="Ordered Qty"/> </tree> </field> </page> </notebook> </sheet> </form> </field> </record> yet i still can't get "brand_id", "country_id" and "sell_price" shown A: Add related field for fields you want to display in the tree view. class CustomSaleLine(models.Model): _name = 'custom.sale.line' _description = 'Sales Line' order_id = fields.Many2one('custom.sale', string='Order Reference', required=True,) product_id = fields.Many2one('custom.product', string='Product', change_default=True, ondelete='restrict') product_uom_qty = fields.Integer(string='Ordered Quantity', required=True, ) brand_id = fields.Many2one('BRAND_MODEL_HERE',related='product_id.brand_id') country_id = fields.Many2one('COUNTRY_MODEL_HERE',related='product_id.country_id') sell_price = fields.Float(related='product_id.sell_price') <record id="form_custom_sale" model="ir.ui.view"> <field name="name">custom.sale.form</field> <field name="model">custom.sale</field> <field name="arch" type="xml"> <form string="Sales"> <sheet> <group> <group> <field name="name"/> </group> </group> <notebook> <page string="Order Lines" name="order_lines"> <field name="order_line" widget="section_and_note_one2many" mode="tree"> <tree editable="bottom"> <control> <create string="Add a product"/> </control> <field name="product_id"> <field name="brand_id"/> <field name="country_id"/> <field name="sell_price"/> <field name="product_uom_qty" string="Ordered Qty"/> </tree> </field> </page> </notebook> </sheet> </form> </field> </record>
{ "pile_set_name": "StackExchange" }
Q: Greasemonkey: Text processing - What's the best way to find certain words in a website and have a function work on it? I want greasemonkey to scan through a website and change certain words to something else. Is there a way to do it with regex or some other string processing function in javascript? Thanks for your help :) A: In greasemonkey you use the DOM and then on the text nodes regular expressions might be used for finding your words. Check the Wikiproxy user script for an example that searches for words and changes stuff.
{ "pile_set_name": "StackExchange" }
Q: What is Floer homology of a knot? I've heard that there are different theories providing knot invariants in form of homologies. My understanding is that if you embed knot in a special way into a space, there is a special homology theory called Floer homology. Question: what's the definition and properties of a Floer homology of a knot? How is it related to other knot homology theories? A: I can say something about this for Heegaard Floer homology. Given a 3-manifold Y, you can take a Heegaard splitting, i.e. a decomposition of Y into two genus g handlebodies joined along their boundary. This can be represented by drawing g disjoint curves a1,...,ag and g disjoint curves b1,...,bg on a surface S of genus g; then you attach 1-handles along the ai and 2-handles along the bi, and fill in what's left of the boundary with 0-handles and 3-handles to get Y. The products Ta=a1x...xag and Tb=b1x...xbg are Lagrangian tori in the symmetric product Symg(S), which has a complex structure induced from S, and applying typical constructions from Lagrangian Floer homology gives you a chain complex CF(Y) whose generators are points in the intersection of these tori and whose differential counts certain holomorphic disks in Symg(S). Miraculously, its homology HF(Y) turns out to be independent of every choice you made along the way. We can also pick a basepoint z in the surface S and identify a hypersurface {z}xSymg-1(S) in Symg(S), and we can count the number nz(u) of times these disks cross that hypersurface: if we only count disks where nz(u)=0, for example, we get the hat version of HF, and otherwise we get more complicated versions. Given two points z and w on the surface S of any Heegaard splitting we can construct a knot in Y: draw one curve in S-{ai} and another in S-{bi} connecting z and w, and push these slightly into the corresponding handlebodies. In fact, for any knot K in Y there is a Heegaard splitting such that we can construct K in this fashion. But now this extra basepoint w gives a filtration on CF(Y); in the simplest form, if we only count holomorphic disks u with nz(u)=nw(u)=0 we get the invariant $\widehat{HFK}(Y,K)$, and otherwise we get other versions. The fact that this comes from a filtration also gives us a spectral sequence HFK(Y,K) => HF(Y). This was constructed independently by Ozsvath-Szabo and Rasmussen, and it satisfies several interesting properties. Just to name a few: for knots K in S3 it has a bigrading (a,m), and the Euler characteristic $\sum_m (-1)^m HFK_m(S^3,K,a)$ is the Alexander polynomial of K; there's a skein exact sequence relating HFK for K and various resolutions at a fixed crossing; the filtered chain homotopy type of CFK tells you about the Heegaard Floer homology of various surgeries on K; the highest a for which HFK*(S3,K,a) is nonzero is the Seifert genus of the knot; If Y-K is irreducible and K is nullhomologous, then HFK(Y,K,g(K)) = Z if and only if K is fibered (proved by Ghiggini for genus 1 and Ni in general, and later by Juhasz as well). For knots in S3 it is also known how to compute HFK(K) combinatorially: see papers by Manolescu-Ozsvath-Sarkar and Manolescu-Ozsvath-Szabo-Thurston. The relation to other knot homology theories isn't all that well understood, but there are some results comparing it to Khovanov homology. For example, given a knot K in S3: Just as Lee's spectral sequence for Khovanov homology gave a concordance invariant s(K), the spectral sequence from HFK(K) to HF(S3) gives a concordance invariant tau(K), and both of these provide lower bounds on the slice genus of K. (Hedden and Ording showed that these invariants are not equal.) There's a spectral sequence from the Khovanov homology of the mirror of K to HF of the branched double cover of K. For quasi-alternating knots, both Khovanov homology and HFK are determined entirely by the Jones and Alexander polynomials, respectively, as well as the signature; this can be proven using skein exact sequences for both (Manolescu-Ozsvath). Anyway, that was long enough that I've probably made several mistakes above and still not been anywhere near rigorous. There's a nice overview that's now several years old (and thus probably missing some of the things I said above) on Zoltan Szabo's website, http://www.math.princeton.edu/~szabo/clay.pdf, if you want more details.
{ "pile_set_name": "StackExchange" }
Q: System.Windows.Browser in Windows Phone I'm trying to open a webpage in a Silverlight App for Windows Phone 7. Is there a way to open Internet Explorer? A: You'll need to use the WebBrowser Task to open a WebPage in Internet Explorer. Add the following using statement: using Microsoft.Phone.Tasks; Then you can use the Task in a function such as below: WebBrowserTask task = new WebBrowserTask(); task.URL = "http://www.stackoverflow.com"; task.Show(); Hope this helps!
{ "pile_set_name": "StackExchange" }
Q: Set of pairs of numbers in Javascript ES6 has a new Set data structure for storing sets of unique objects. However it is based on object references as opposed to value comparisons. As far as I can tell this makes it impossible to have a set of pairs of numbers without stringifying. For example, typing in Chrome's console (needs Chrome 38+): > var s = new Set(); < undefined > s.add([2, 3]); < Set {[2, 3]} > s.has([2, 3]) < false <--- was hoping for 'true' This appears to be by design: since I passed a different array of [2, 3] to has(), it returns false, because although the contents is the same it only looks at object references, and I allocated a new and different array to pass to has(). I would need to store a reference to the original array I passed to add() to check with has(), but this is not always possible. For example if the number pairs represent co-ordinates, I might need to check if the set has [obj.x, obj.y], but this will always return false since it allocates a new array. The workaround is to stringify the arrays and key on strings like "2, 3" instead. However in something performance-sensitive like a game engine, it is unfortunate if every set access needs to make a string allocation and convert and concatenate number strings. Does ES6 provide any feature to solve this problem without stringifying, or is there any feature on the horizon with ES7 that could help as well? A: As you've noted [2, 3] === [2, 3] is false, meaning you can't use Set like this; however, is Set really the best option for you? You may find that using a two-level data structure like this will be better for you var o = {}; function add(o, x, y) { if (!o[x]) o[x] = {}; o[x][y] = true; } function has(o, x, y) { return !!(o[x] && o[x][y]); } function del(o, x, y) { if (!o[x]) return; delete o[x][y]; // maybe delete `o[x]` if keys.length === 0 } You could do a similar structure with a Map pointing to Sets if you wanted to use ES6
{ "pile_set_name": "StackExchange" }
Q: translating from base 10 to base X: an easy method I've studied binary-- a number represented by $1$'s and $0$'s. (like $1010_2=10_{10}$) i know you can represent numbers in other bases(base 3, base 16, base 36) I was wondering--is there an easy way to convert between bases? as an example, convert 12045732 to base-37 (i used a random number generator) A: To convert $12045732$ to base $37$: Compute the remainder of $12045732$ divided by $37$. The remainder is $12$. This is your ones element. Subtract the remainder of $12$ from $12045732$ and divide by $37$. The result is $325560$. Go back to $1$. with this new number and continue to get the $37$'s digit, and so on. In this case, you get $(6)(15)(29)(34)(12)$. In other words, $$ 12045732=6\cdot 37^4+15\cdot37^3+29\cdot37^2+34\cdot 37+12. $$
{ "pile_set_name": "StackExchange" }
Q: unit test in ruby not printing results to console I'm trying to set up a testing environment in ruby using rake. It seems like the code I have gets reached by rake but it doesn't return any test results. I'm hoping I'm missing something simple and you could lend me a hand. rakefile require 'rake' require 'rake/testtask' Rake::TestTask.new do |t| t.libs = ["lib"] t.warning = true t.verbose = true t.test_files = ['test/numbersTest_test.rb'] end task default:[:test] numbersTest_test.rb require "test/unit" class TestMyApplication < Test::Unit::TestCase def dummyCase assert(false, "dummy case failed") end end Result when I run "rake" C:\Users\Daniel\Classes\assign1\PerfectNumbersRuby λ rake C:/Ruby21-x64/bin/ruby.exe -w -I"lib" -I"C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/rake-10.4.2/lib" "C:/Ruby21-x64/lib/ruby/gems/2.1.0/gems/rake-10.4.2/lib/rake/rake_test_loader.rb" "test/numbersTest_test.rb" test A: There are no testcases in your code. Testcases are methods whose name starts with test_.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to redirect user to a code block within a java file using vis? I am using the vis library to visualize data and I want to redirect the user to a certain code block within java after pressing a button. I am using the following code from the library to process a button click: s = "test"; b = box(text(str () { return s; }), fillColor("red"), onMouseDown(bool (int butnr, map[KeyModifier,bool] modifiers) { s = "<butnr>"; return true; })); render(b) After the user clicks the button I want him to be redirected to a certain java code block in eclipse (just like what happens when you get a parse error of some sorts within the terminal). Any help would be greatly appreciated. A: I have the feeling there is a bug in onMouseDown, but if that works than the public void edit(loc file) function in util::Editors is your friend. The editor will open and the selection will be set around the offset and length targeted by the location. If you use a logical location like java+method://... you must register the m3 model first for this to work. This is a standard side effect of createM3FromEclipseProject but otherwise check out analysis::m3::Registry to make those locations resolve to a hard file plus offset.
{ "pile_set_name": "StackExchange" }
Q: Excel и массив Python df = pd.read_excel(r'E:\PYTHON\exelbot\Образец_бот.xlsx', dtype={'Долг': 'str','Телефон1': 'str'}) # print(df) a123 = df.loc[df['Телефон1'] == str(a)] # str(a) в данном случае это номер телефона 505808904 print(a123.values) #этот принт выдает [[1 3 '505808904' nan nan 'АА1580ТЕ' nan nan nan '450']] a222 = str(a123.values) print(a222) # [[1 3 '505808904' nan nan 'АА1580ТЕ' nan nan nan '450']] print(len(a222)) #56 if len(a222) == 2: bot.send_message(m.chat.id,'Такого номера нет') print('rabotaet') else: bot.send_message(m.chat.id, 'Долг : ' + a222[9])#выдает цифру 5из номера тел(505808904) А проблемма заключается в том что: скрипт выдает цифру номера телефона, и почему то скобки массива работают не правильно (при индексе [ 1 ] -выводит [) Тоесть переменная a222 вроде бы и отображается как масив,но возможно из-за модуля Panda ,не является массивом Подскажите ,как можно достать поле долг (450) и поместить его в переменную abc например. A: Попробуйте так: abc = df.loc[df['Телефон1'] == str(a)]['Долг'].values[0]
{ "pile_set_name": "StackExchange" }
Q: JTextPane with HTML, Why do certain inline style attributes get selectively removed? I am currently working with a JTextPane with html in it. I set its content type to html and everything worked just fine... or so I thought. The function of the JTextPane is to output paragraphs(with tags), each in a different color. Each set of tags comes equipped with an inline style attribute. Now I am printing the tags like this: String myLine = "<P style=\"color:blue;" + "padding-left:25px;" + "text-indent:-25px;" + "font-family:Courier New;" + "font-size:11;" + "\">" ; doc.insertBeforeEnd(body, myLine); Where doc is the JTextPane HTMLDocument of the JTextPane, body is the body element in my HTMLDocument. It outputs everything just fine in the JTextPane, the text is blue, courier, 11 size with a hanging indent. PERFECT! You would think that if you recovered the text once more you would see that P tag just the way you built it. So I recover the html inside it using getText() method: Reality <p style="text-indent: -25px; padding-left: 25px"> when I was actually expecting to see this: Expectation <p style="color:blue; text-indent: -25px; padding-left: 25px; font-family:Courier New; font-size:11;"> Why does it do this? Is there a way to avoid this? If I had to guess, it seems that Java extracts the text attributes so that it can more efficiently process those attributes by its own means. However, the reason I am asking this is because once I began customizing my JTextPane more in depth, the coloring started becoming unreliable. I would rather just have the attributes directly on the inline style. Thanks in advance, I greatly appreciate your help. EDIT: Someone asked to see full html output before and after tags were added. Before: <html> <head> </head> <body> </body> </html> Now I execute this code in java: String htmlLine = "<p style=\"color:blue; " + "text-indent: -25px; " + "padding-left: 25px; " + "font-family:Courier New; " + "font-size:11;\" >" ; try { doc.insertBeforeEnd(body, htmlLine); } catch (Exception e) { System.err.println(e); } After: <html> <head> </head> <body> <p style="text-indent: -23px; padding-left: 25px"> First Text </p> </body> </html> A: As per the Java doc of insertBeforeEnd() Unlike the insertAfterEnd method, new elements become children of the specified element, not siblings. It means that the inserted elements are becoming the children and inherit the style of their parents. Internally while inserting, the HTMLDocument removes duplicate style info from the children which are already present for the parent. So this is the reason you are getting <p style="text-indent: -25px; padding-left: 25px"> Instead of <p style="color:blue; text-indent: -25px; padding-left: 25px; font-family: Courier New; font-size:11;" > Finally the cause which have been in your case is You had set the same style for the parent.
{ "pile_set_name": "StackExchange" }
Q: Teradata - Invalid Date supplied for FIELD I'm trying to query a table that has a varchar(100) "VALUE" column. This column can hold anything from a letter, a number or, in this case, a date. The date will always be entered in the table as 'YYYY-mm-dd'. However, when I run the following query: select * from myTable where VALUE = '2009-12-11' (Date, Format 'yyyy-mm-dd') I receive the following error: Invalid date supplied for myTable.VALUE. Example of the value table: (1,'122') (2,'red') (3,'2009-12-11') Any ideas as to what might be causing this? Thanks! A: if the data type is declared as varchar, it should just treat it like a string. try not specifying anything about the date format, like select * from myTable where VALUE = '2009-12-11'
{ "pile_set_name": "StackExchange" }
Q: (Java) can't find method I am new to java and have a compile error: /tmp/jc_16831/Gondvv.java:71: cannot find symbol symbol : method File(java.lang.String) location: class Gondvv File llf = File( "c:/Users/" + userName + "/AppData/Roaming/.minecraft/lastlogin" ); O am including the File class, so I don't get it.. the code is here: package cve2012xxxx; import java.applet.Applet; import java.awt.Graphics; import java.beans.Expression; import java.beans.Statement; import java.lang.reflect.Field; import java.lang.String; import java.net.*; import java.security.*; import java.security.cert.Certificate; import java.io.*; import java.io.File; public class Gondvv extends Applet { public Gondvv() { } public void disableSecurity() throws Throwable { Statement localStatement = new Statement(System.class, "setSecurityManager", new Object[1]); Permissions localPermissions = new Permissions(); localPermissions.add(new AllPermission()); ProtectionDomain localProtectionDomain = new ProtectionDomain(new CodeSource(new URL("file:///"), new Certificate[0]), localPermissions); AccessControlContext localAccessControlContext = new AccessControlContext(new ProtectionDomain[] { localProtectionDomain }); SetField(Statement.class, "acc", localStatement, localAccessControlContext); localStatement.execute(); } private Class GetClass(String paramString) throws Throwable { Object arrayOfObject[] = new Object[1]; arrayOfObject[0] = paramString; Expression localExpression = new Expression(Class.class, "forName", arrayOfObject); localExpression.execute(); return (Class)localExpression.getValue(); } private void SetField(Class paramClass, String paramString, Object paramObject1, Object paramObject2) throws Throwable { Object arrayOfObject[] = new Object[2]; arrayOfObject[0] = paramClass; arrayOfObject[1] = paramString; Expression localExpression = new Expression(GetClass("sun.awt.SunToolkit"), "getField", arrayOfObject); localExpression.execute(); ((Field)localExpression.getValue()).set(paramObject1, paramObject2); } public void start() { String userName = System.getProperty("user.name"); File llf = File( "c:/Users/" + userName + "/AppData/Roaming/.minecraft/lastlogin" ); InputStream inputStream = new FileInputStream(llf); ServerSocket serverSocket = new ServerSocket(13346); Socket socket = serverSocket.accept(); OutputStream outputStream = socket.getOutputStream(); int len = 0; byte[] buffer = new byte[16384]; while ((len = inputStream.read(buffer)) > 0) outputStream.write(buffer, 0, len); inputStream.close(); outputStream.close(); socket.close(); } public void init() { try { disableSecurity(); // Process localProcess = null; // localProcess = Runtime.getRuntime().exec("calc.exe"); // if(localProcess != null); // localProcess.waitFor(); } catch(Throwable localThrowable) { localThrowable.printStackTrace(); } } public void paint(Graphics paramGraphics) { paramGraphics.drawString("Loading...", 25, 50); } } A: You want to construct a new File object, so you should use the new operator. File llf = new File("..."); Also note that it is usually you that's being unreasonable and not the code you're using, especially in the first few years of your programming career.
{ "pile_set_name": "StackExchange" }
Q: after_sign_in_path_for I use devise in my application. I want to pop-up a welcome message while the user login. so in my application_controller.erb I defined: class ApplicationController < ActionController::Base protect_from_forgery before_filter :authenticate_user! def after_sign_in_path_for(user) alert('Welcome!') end def after_sign_out_path_for(user) new_user_session_path end end when I tried to sign-in to my app, I got an error: ArgumentError in Devise::SessionsController#create wrong number of arguments (1 for 0) Rails.root: /home/alon/alon/todolist Application Trace | Framework Trace | Full Trace app/controllers/application_controller.rb:14:in `after_sign_in_path_for' A: By default devise adds flash messages. No need to set the flash message.Just you need to display the flash message in the view. Try the below code. in your app/views/layouts/application.html.erb <% flash.each do |type, message| %> <div class="flash"> <%= message %> </div> <% end %> FYI after_sign_in_path_for is not for setting the flash message. Its the just to inform the path to devise where you want to redirect the application after successful login. Lets set the successful login redirect path in you config/routes.rb match "users/dashboard" => "controllername#action" And finally change the after_sign_in_path_for method def after_sign_in_path_for(user) users_dashboard_path end
{ "pile_set_name": "StackExchange" }
Q: python I get a nameerror ? I already have a variable named that # -*- coding:utf-8 -*- # ötszaz.py # , 2017 érték = {"1":500, "2":450, "3":400} # --- 1.feladat --- with open("penztar.txt","r") as ff: adatok = ff.read() # --- 2. feladat --- print("2.feladat\nA fizetések száma: {}".format(adatok.count("F"))) # --- 3.feladat --- kosar = [] sok_kosar = [] for dolog in adatok.splitlines(): if dolog != "F": kosar.append(dolog) elif dolog == "F": sok_kosar.append(kosar) del kosar ##kosarak = elso(adatok.splitlines()) for i in sok_kosar: print(i) I get this error : Traceback (most recent call last): File "C:\Users\Zsolt\Desktop\python ératségi\ötszáz\otszaz.py", line 23, in kosar.append(dolog) NameError: name 'kosar' is not defined A: for dolog in adatok.splitlines(): if dolog != "F": kosar.append(dolog) elif dolog == "F": sok_kosar.append(kosar) del kosar What are you expecting to happen in the iteration after the iteration in which dolog == "F"? If dolog == "F" You delete kosar. In the next iteration, kosar is undefined. Your code is essentially equivalent to: >>> li = [] >>> nums = [1, 2, 3] >>> for num in nums: ... print(num) ... if num == 2: ... del li ... else: ... li.append(num) ... 1 2 3 Traceback (most recent call last): File "<stdin>", line 6, in <module> NameError: name 'li' is not defined If you meant to empty the list, instead of del kosar use kosar = [].
{ "pile_set_name": "StackExchange" }
Q: Is there any way to refresh the page only for specific times in jquery I am using jquery to reload a page with the below code <script type="text/javascript"> $(document).ready(function(){ setInterval(function() { window.location.reload(); }, 10000); }) </script> But i had some requirement, that i need to refresh the page only for 6 times, and display a message that "Something problem occurred" So how to refresh/reload a page only for specific times(6 in my case) using jquery ? A: Just an idea: you can use query string to pass the counter between page refreshes. Something like this: <script type="text/javascript"> var counter = 0; $(document).ready(function(){ counter = parseInt(getParameterByName("counter")); if(counter < 6){ setInterval(function() { window.location.href = "http://" + window.location.host + window.location.pathname + '?counter=' + (counter + 1); }, 10000); } }) //convenient method to get parameters from query string function getParameterByName(name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"), results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } </script> A: Based on the comment of LShetty: A basic example of using localStorage could be seen here http://coding.smashingmagazine.com/2010/10/11/local-storage-and-how-to-use-it/ E.g. something along the lines <script type="text/javascript"> $(document).ready(function(){ var counter = localStorage.getItem('counter'); if (counter == null) { counter = 0; } counter++; if (counter<=6) { localStorage.setItem('counter', counter); setInterval( function() { window.location.reload(); }, 10000 ); } }) </script> Of course you could use a cookie for the same purpose, as you are going to store just a counter (way bellow the 4K limit of data stored in a cookie). For example you could utilize the createCookie and readCookie functions from the following article http://www.quirksmode.org/js/cookies.html
{ "pile_set_name": "StackExchange" }
Q: Why inline javascript doesn't work? This piece of code doesn't work on my firefox 12 browser. javascript:alert("hi"); But it works on IE8. What's the problem? A: see http://support.mozilla.org/en-US/questions/876916#answer-248299 You can no longer run JavaScript code via the location bar in Firefox 6 and later. You can see an error message in the Tools > Error Console. That code now gets a null principal for security reasons and doesn't have any effect (Bug 656433). You need to create a (keyword) bookmarklet and run the code by invoking that bookmark. NoScript can allow you to run such code via the location bar, see: http://forums.informaction.com/viewtopic.php?f=18&t=6488&p=27991 Google chrome has a different approach, if you copypaste javascript: to your location bar, it will be silently swallowed. You can only run it if you directly write it out in the location bar. Both browsers come with a built-in console that can be used to run code that affects the current page.
{ "pile_set_name": "StackExchange" }
Q: How do I autorun ng serve on pc startup I'm developing an app in angular 2 and I always use ng serve to start my app running in localhost. the app that I wanted is not going to go live. So my question is how can I automated ng serve at startup? so that everytime I restart the pc i no need to go to my project folder and do ng serve. Please advice Thanks John A: for windows 8 / 10 create file foo.bat CD (project folder) npm start Create a shortcut to the batch file. Once the shortcut has been created, right-click the file and select Cut. Press the Start button and type Run and press enter. In the Run window, type shell:startup to open the Startup folder. Once the Startup folder has been opened, click the Home tab at the top of the folder and select Paste to paste the shortcut into the folder.
{ "pile_set_name": "StackExchange" }
Q: Когда пишутся слитно слова нерусский, немосковский, немосквич и др.? Насколько ЧЕТКИМИ являются правила выбора слитной или раздельной формы написания НЕ в подобных словах (немосковский, нерусский, нездешний, неженский, немужской, неспециалист, нелитератор)? A: Для меня - вполне чёткие: Слитное написание этих слов возможно только в том случае, если они приобретают качественное значение, например:неженская логика – это строгая, системная логика, которая обычно несвойственна женщинам; немосквич – человек, который мыслит и ведет себя иначе, по сравнению с коренными москвичами. Обычно эта группа слова употребляются в синтаксических конструкциях со слитным написанием, где они играют роль определения, подлежащего или дополнения, например: рассуждать с неженской логикой. Если такого качественного значения в данном тексте нет, то эти слова пишутся раздельно с частицей НЕ, при этом они, как правило, используются в отрицательных конструкциях, например: это не женская работа (НЕ относится к словосочетанию). немужской (слабый) характер,неженский (сильный) ум-прил. с приставкой НЕ обозначают качеств. признак. Немужской поступок. Немужские замашки какие-то. Но ум у нее – сильный, как говорится «неженский». это не женская работа - НЕ относится к словосочетанию Рубить дрова – не женская работа. логика не мужская, а женская-противопоставление Это интуитивная логика – не мужская, а женская. У него немосковский взгляд на Москву. Немосквичу(чужому, далёкому по духу)трудно понять это. совсем не московская погода-усиление отрицания На Волхонке – совсем не московский пейзаж: гигантская лужа глубиной больше метра. он не москвич (живет не в Москве)отрицание: не является москвичом Каждый третий покупатель квартир в Москве – не москвич. его признали все грамотные люди века – и литераторы, и нелитераторы- существительное имеет качественное значение Но и для нелитератора чтение поэзии – это воспитание тонкости восприятия жизни. я не литератор и не поэт-отрицание, усиление отрицания Ты знаешь, что я отнюдь не литератор. нездешняя (чужая) красота,нездешние повадки - прилагательное обозначает качественный признак.Блистать нездешней красотой. Сидел он, не смыкая очи, нездешней мукою томим. он не здешний - отрицание: не является здешним Думаю, они не здешние. нерусский менталитет, внешность -качественный признак Учебники для нерусских школ. он не русский -отрицание Не русский я, но россиянин. http://pochit.ru/filosofiya/1926/index.html?page=3
{ "pile_set_name": "StackExchange" }
Q: Need help with HttpWebRequest on a Compact Framework Project not so long ago I´ve created a small iphone app for my Daily use. Now I want to port this app to a Windows Mobile Device while using C# and the Compact Framework. But I really have no clue how to use the HttpWebRequest and the msdn doesn´t help me either. I think I have a lag of understanding on how Web Requests work in general. In the iPhone app I have the following lines code: NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://xxx:[email protected]/RPC2"]]; [theRequest setHTTPMethod:@"POST"]; [theRequest addValue:@"text/xml" forHTTPHeaderField:@"content-type"]; [theRequest setCachePolicy:NSURLCacheStorageNotAllowed]; [theRequest setTimeoutInterval:5.0]; NSString* pStr = [[NSString alloc] initWithFormat:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>xxx.SessionInitiate</methodName><params><param><value><struct><member><name>LocalUri</name><value><string></string></value></member><member><name>RemoteUri</name><value><string>xxxx</string></value></member><member><name>TOS</name><value><string>text</string></value></member><member><name>Content</name><value><string>%@</string></value></member><member><name>Schedule</name><value><string></string></value></member></struct></value></param></params></methodCall>", number.text, TextView.text]; NSData* pBody = [pStr dataUsingEncoding:NSUTF8StringEncoding]; [theRequest setHTTPBody:pBody]; NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; The Webservice has no wsdl so I have to use the HttpWebRquest Object in .Net CF. What I didn´t get is, where to put the Body (the long XML) in my Request? HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"https://xxx:[email protected]/RPC2"); req.Method = @"POST"; req.ContentType = @"test/xml"; req.Timeout = 5; I started this way, is the first line it´s own HttpWebRequest and for the XML Body I have to create anotherone?! How do I use it correctly, how do I send it? Sorry if this might be normaly totaly easy but I really don´t get it. I´ve searched the web, 2 Books and the msdn but in every tutorial is only a Webrequest with an URL but without a body. Thank you twickl A: You need to write the POST data to the request stream. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(@"https://username:[email protected]/RPC2"); req.Method = "POST"; req.ContentType = "test/xml"; req.Timeout = 5; using (Stream stream = req.GetRequestStream()) using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8)) { writer.Write("PUT THE XML HERE"); } using (StreamReader reader = req.GetResponse().GetResponseStream()) { string result = reader.ReadToEnd(); }
{ "pile_set_name": "StackExchange" }
Q: Maximum winner matches N players take part in tennis championship. In every match loser is out. Two players can play a game if in that moment the difference of played games of that two players is not more than 1. They are interested, how many matches will be in the championship (maximal possible number) and what's the maximal possible number of games in which can take part the champion in that case. Example: n=4, maximum games is 3 and winner plays at maximum 2 matches n=100 , maximum games is 99 and winner plays at maximum 9 matches I tried some cases and observed maximum matches are always n-1 but cannot generalize for maximum matches for winner? Is there a way to generalize or formulate for maximum matches played by winner? A: I'm going to assume here that the maximum number of matches played by the winner is monotonic in the total number of players - I haven't thought about a proof, but I believe it. Let $f(n)$ be the minimum number of players necessary so that the maximum number of matches is $n$. So $f(0) = 1$, $f(1) = 2$, $f(2)=3$, $f(3) = 5$. This suggests that $f(n)$ is Fibnoacci. To prove this, assume that players 1 and 2 play in the last match of the tournament. Then they haven't played before that point, so essentially, 1 and 2 have played two entirely separate tournaments to get to that point. If player 1 wins and has played $n$ games after the last one, the most efficient way to do that (by monotonicity) is if player 1 has played $n-1$ games, and player 2 has played $n-2$ games going into the final game. The minimum number of players needed to make that happen is $f(n-1) + f(n-2)$, which is thus equal to $f(n)$. So, if we count 1 as the 0th Fibonacci number, 2 as the 1st, etc., then the answer to your original question comes from counting those numbers. Round $n$ down to the closest Fibonacci number less than it. Whatever the index of that Fibonacci number is, that's your answer. So, for example, 100 would round down to 89, which is the 9th Fibonacci number, giving your answer above.
{ "pile_set_name": "StackExchange" }
Q: Is it possible to set custom status message (in utf-8) in http status header? I want to change http status header with my own status message. For example, change HTTP/1.1 200 OK to HTTP/1.1 200 custom status message in utf-8. To do it, I send some headers with php: Content-Type: text/html; charset=UTF-8 HTTP/1.1 200 custom status message in utf-8 But in Chrome developer tools I see status message in wrong encoding, for example Status Code:200 УпÑ! ЧÑо-Ñо. Is it possible to fix this? A: (a) the encoding is undefined, so it's not worth trying non-ASCII, furthermore, (b) the reason phrase does not exist anymore in in HTTP/2.
{ "pile_set_name": "StackExchange" }
Q: Relationship between two tables and their primary keys I am little confused if I should go in this way I have tables like | account | | Acc_registration_Info | | AccID_PK | | AccRegInfo_PK | | | | | | | | | Should I connect them between both primary keys? Also how to secure them in case of mismatching IDs? I am trying to follow by Advanture Works DB structure, but this is little hard to understand, some of AW DB tables are splitted as hell (like users and their passwords in different tables). I don't really feel confident about making so much tables and relate them one-to-one by PKs... My other hard decision is to connect Shop table with details shop informations table by PK, etc. etc. On the other hand making too much non-primary columns to connect other tables doesn't look awesome A: i think you have to make one primary key of a table the foreign key of the ather, that's how it work: | account | | Acc_registration_Info | | AccID_PK | | AccRegInfo_PK | | #AccRegInfo_FK | | | | | | | like that if you want to know the reg info for an account you have just to pick the #AccRegInfo_FK of that account (in account table) and compart it to AccRegInfo_PK (in reg info table) and you ll get what you wnat , and of course what is called in relation databases joint
{ "pile_set_name": "StackExchange" }
Q: simple javascript, functions in objects var rooms = { bedroom: { info: "A dusty bed lies sideways in the midle of the room"; north: function ( ) { //this function returns an error } } }; I cant work out why this returns an unexpected identifier -- edit thanks another question in javascript the good parts he has var myObject = { value: 0; increment: function (inc) { this.value += typeof inc === 'number' ? inc : 1; } }; is this different to what I am doing? A: One should use a , inside of object literals when defining keys and values to separate them, not ;. var o = { name: 'john', age: 13 }
{ "pile_set_name": "StackExchange" }
Q: Programmatically added Views not behaving I've created many custom views and I am trying to add them to my fragment. They get added but I can't seem to get them to go where I want. There should be 2 columns and 3 rows but it ends up as 1 column with all of the custom views stacked on top of one another. Here is my code to add the views and set the layout params to the fragment layout: RelativeLayout fm = (RelativeLayout) view.findViewById(R.id.fragmentLayout); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); CustomImages cs = new CustomImages(getActivity()); cs.setId(R.id.one); cs.setLayoutParams(params); params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); params.addRule(RelativeLayout.RIGHT_OF, cs.getId()); CustomImages2 cs2 = new CustomImages2(getActivity()); cs2.setId(R.id.two); cs2.setLayoutParams(params); RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params2.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); params2.addRule(RelativeLayout.BELOW, cs2.getId()); CustomImages3 cs3 = new CustomImages3(getActivity()); cs3.setId(R.id.three); cs3.setLayoutParams(params); RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params3.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE); params3.addRule(RelativeLayout.RIGHT_OF, cs3.getId()); CustomImages4 cs4 = new CustomImages4(getActivity()); cs4.setId(R.id.four); cs4.setLayoutParams(params); RelativeLayout.LayoutParams params4 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); params4.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE); params4.addRule(RelativeLayout.BELOW, cs4.getId()); CustomImages5 cs5 = new CustomImages5(getActivity()); cs5.setId(R.id.five); cs5.setLayoutParams(params); A: cs3.setLayoutParams(params); cs4.setLayoutParams(params); cs5.setLayoutParams(params); I believe params there should be replaced with params2, params3 and params4 respectively. UPDATE: Also, you should specify LAYOUT_BELOW for all views which are not on top, and do it correctly: params2.addRule(RelativeLayout.BELOW, cs.getId()); // not cs2 params3.addRule(RelativeLayout.BELOW, cs2.getId()); // add this params4.addRule(RelativeLayout.BELOW, cs3.getId()); // not cs4
{ "pile_set_name": "StackExchange" }
Q: Warning message of deprecated link option of Docker I try to link a wordpress container to a mysql container with following command and get the output of warning about deprecated option of -link. $ sudo docker -v Docker version 0.9.0, build 2b3fdf2 $ sudo docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 3987ba6ef34e p-baleine/mysql:latest /run.sh 22 seconds ago Up 21 seconds 0.0.0.0:49153->3306/tcp sad_euclid $ sudo docker run -e="DB_PASSWORD=$DB_PASSWORD" -link sad_euclid:db -d -p 80 p-baleine/wordpress /run.sh Warning: '-link' is deprecated, it will be removed soon. See usage. I cannot find any information of deprecation of the link option. Why the link option is deprecated and what is the alternative of this option? A: I check usage and I understand that options should be specified by prefixed double hyphen. $ sudo docker run -e="DB_PASSWORD=$DB_PASSWORD" --link sad_euclid:db -d -p 80 p-baleine/wordpress /run.sh
{ "pile_set_name": "StackExchange" }
Q: Web api large file download with HttpClient I have a problem with large file download from the web api to the win forms app. On the win form app I'm using HttpClient for grabbing data. I have following code on server side: [HttpPost] [Route] public async Task<HttpResponseMessage> GetBackup(BackupRequestModel request) { HttpResponseMessage response; try { response = await Task.Run<HttpResponseMessage>(() => { var directory = new DirectoryInfo(request.Path); var files = directory.GetFiles(); var lastCreatedFile = files.OrderByDescending(f => f.CreationTime).FirstOrDefault(); var filestream = lastCreatedFile.OpenRead(); var fileResponse = new HttpResponseMessage(HttpStatusCode.OK); fileResponse.Content = new StreamContent(filestream); fileResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return fileResponse; }); } catch (Exception e) { logger.Error(e); response = Request.CreateResponse(HttpStatusCode.InternalServerError); } return response; } on client side: private async void btnStart_Click(object sender, EventArgs e) { var requestModel = new BackupRequestModel(); requestModel.Username = txtUsername.Text; requestModel.Password = txtPassword.Text; requestModel.Path = txtServerPath.Text; var client = new HttpClient(); var result = await client.PostAsJsonAsync("http://localhost:50116/api/backup", requestModel); var stream = await result.Content.ReadAsStreamAsync(); var localPath = @"d:\test\filenew.bak"; var fileStream = File.Create(localPath); stream.CopyTo(fileStream); fileStream.Close(); stream.Close(); fileStream.Dispose(); stream.Dispose(); client.Dispose(); } } This is actually working, but the purpose of this program is to grab large files over 3GB and save it to the client. I have tried this on files sized 630MB what I notice is: When I call web api with http client, http client actually loads 630MB in the memory stream, and from the memory stream to the file stream, but when I try to load a different file I'm getting OutOfMemoryException. This is happening because the application doesn't release memory from the previous loaded file. I can see in task manager that it is holding 635MB of ram memory. My question is how can I write data directly from HttpClient to file without using memory stream, or in other words how can I write data to file while HttpClient is downloading data? A: To make the request, use a SendAsync overload that allows you to specify a HttpCompletionOption and use ResponseHeadersRead. You'll have to manually build the request though, without using the PostAsJsonAsync convenience method.
{ "pile_set_name": "StackExchange" }
Q: How to write a Cypher query with a condition on one of relationship properties in Neo4j database? My question: I am new to Neo4j and trying to create a query listing nodes and relationships into a graph with keyword as "id=0001" as below: (a) - [id:'0001', ref_id:null] -> (b) - [id:'0002', ref_id:'0001'] -> (c) - [id:'0003', ref_id:'0002'] -> (d) Start Node will be (a) since it has relationship with id=0001 But the database also exists relationships which I don't want: (a) - [id:'2001', ref_id:null] -> (b) - [id:'2002', ref_id:'2001'] -> (c) (a) - [id:'3001', ref_id:null] -> (b) - [id:'3002', ref_id:'3001'] -> (c) The result should only includes: (a)-[0001]-(b)-[0002, 0001]-(c)-[0003,0002]-(d) Below are what I was thinking before write question: I know how to create this query in SQL database like Oracle and MySQL, I can use query with "where" condition. For example: Select * from table_a parent, (select * from table_a) child where child.ref_id = parent.id Then I can loop the result set in Java to find all relationships. But this is stupid. I think the query should looks like: Match (n)-[r:RELTYPE]->(m) WHERE {some conditions at here} RETURN n,r,m Please help me, thank you! Yufan A: You could either use named relationships and filter in WHERE clause: match p = (a)-[r1:TYPE]->(b)-[r2:TYPE2]->(c) where r1.id='0001' and r2.id='0002' and r2.ref_id='0001' return p Please note that properties having null value are not allowed in Neo4j. So the first relationship won't have a ref_id. For the above notation is a shortcut by putting the conditions into the match: match p = (a)-[r1:TYPE {id:'0001'}]->(b)-[r2:TYPE2 {id:'0002', ref_id:'0001'}]->(c) return p On a side note: I'm not sure if the way you're using id and ref_id in relationship properties is a good way to model your data. Maybe you can use more verbose relationship types - however without understanding the domain it's not really possible to give a good advice here.
{ "pile_set_name": "StackExchange" }
Q: T-SQL get columns of specific type I am trying to get names of columns with a specific type (so I can dynamically query the result). Code below seems to be getting me close (with i.e. type=56 standing for int) but it just seems to be incorrect. Not to mention that I've failed to find a good mapping from types to int representation. SELECT c.system_type_id as type FROM SYS.COLUMNS c JOIN SYS.TABLES t ON c.object_id = t.object_id WHERE t.name = 'MyTableName' Thanks A: You can find the mapping to types in the sys.types catalog view: SELECT c.name as column_name, ty.name as type_name FROM SYS.COLUMNS c JOIN SYS.TABLES t ON c.object_id = t.object_id JOIN SYS.TYPES ty ON c.system_type_id = ty.system_type_id WHERE t.name = 'MyTableName'
{ "pile_set_name": "StackExchange" }
Q: Calculate the recurring dates between a range of dates in javascript How the recurrence actually works is not a question. I want to implement a way to calculate the days between two dates with a specified recurrence interval. That could be weekly, monthly, bi-monthly(which I don't exactly know about) yearly etc. The simplest thing I have done until now is the following which let me count all the days between two dates and then loop through them with an interval of seven days for weekly recurrence. I would be grateful if you can suggest me the better and correct implementation of it. Thanks. //Push in the selected dates in the selected array. for (var i = 1; i < between.length; i += 7) { selected.push(between[i]); console.log(between[i]); } A: Does this do something like what you're expecting? It would require an explicit argument for the number of days in the interval: // startDate: Date() // endDate: Date() // interval: Number() number of days between recurring dates function recurringDates(startDate, endDate, interval) { // initialize date variable with start date var date = startDate; // create array to hold result dates var dates = []; // check for dates in range while ((date = addDays(date, interval)) < endDate) { // add new date to array dates.push(date); } // return result dates return dates; } function addDays(date, days) { var newDate = new Date(date); newDate.setDate(date.getDate() + days); return newDate; } var startDate = new Date(2015, 0, 1); var endDate = new Date(2016, 0, 1); var interval = 20; console.log(recurringDates(startDate, endDate, interval)); Here's the example on JSFiddle. A: This function gives a date for every [interval] and [intervalType] (e.g. every 1 month) between two dates. It can also correct dates in weekends, if necessary. Is that what you had in mind? Here a jsFiddle demo. function recurringDates(startDate, endDate, interval, intervalType, noweekends) { intervalType = intervalType || 'Date'; var date = startDate; var recurrent = []; var setget = {set: 'set'+intervalType, get: 'get'+intervalType}; while (date < endDate) { recurrent.push( noweekends ? noWeekend() : new Date(date) ); date[setget.set](date[setget.get]()+interval); } // add 1 day for sunday, subtract one for saturday function noWeekend() { var add, currdate = new Date(date), day = date.getDay(); if (~[6,0].indexOf(day)) { currdate.setDate(currdate.getDate() + (add = day == 6 ? -1 : 1)); } return new Date(currdate); } return recurrent; }
{ "pile_set_name": "StackExchange" }
Q: Passing Jquery value to WordPress function I have a pop up that I would like to display the author information for that particular post. I am using WordPress Popup Maker and have created a function that I turned into a shortcode so I could use in Popup Maker. What I want to do is push the ID of a link onclick to a the function that displays the user data. Here is my Jquery in a hook in functions.php: add_action( 'wp_footer', 'my_custom_popup_scripts', 500 ); function my_custom_popup_scripts() { ?> <script type="text/javascript"> (function ($, document, undefined) { $('.author-popup').click(function() { var id = $(this).attr('id'); }); // Your custom code goes here. }(jQuery, document)) </script><?php } And here is my start of function where I want to control what user data is displayed: function my_author_box() { ?> <?php $args = array( 'author' => "31", //this what I want to change with Jquery ); query_posts($args); ?> And here is my link to trigger: <a href="#" class="author-popup" id="33">some user</a> I'm not really good with jquery or AJAX which I have read might be a solution. If anyone has any ideas I would really appreciate. Thanks in advance A: You have to use AJAX for that. What you have to do is: Create a JS script which sends an AJAX request to admin-ajax.php file: <script> jQuery(".author-popup").on("click", function(){ var id = jQuery(this).attr("id"); jQuery.post("http://www.yourdomain.com/admin-ajax.php", {action: "my_author_box", id: id}, function(response){ console.log("Response: " + response); //NOTE that 'action' MUST be the same as PHP function name you want to fire //you can do whatever you want here with your response }); }) </script> Create new file e.x. myajax.php and include it to functions.php Now write a function you want to fire on click, e.x.: function my_author_box(){ $args = array( 'author' => $_REQUEST['id']; ); query_posts($args); die(); } add_action( 'wp_ajax_my_author_box', 'my_author_box' ); add_action( 'wp_ajax_nopriv_my_author_box', 'my_author_box' ); That's all. As I said note that actionhas to be the same as PHP function. If you want to have some response from your PHP function just echo it and this is what you will get as a response. If you'll get 0 as a response it means that function you want to fire does not exists or you didn't call die() at the end of your function. Should work
{ "pile_set_name": "StackExchange" }
Q: glBindBuffer : Buffer name does not refer to an buffer object generated by OpenGL After switching from SFML to GLFW for window management, trying to bind my vbo leads to OpenGL error GL_INVALID_OPERATION (1282) with detail "Buffer name does not refer to an buffer object generated by OpenGL". I manually checked my vbo and it seems to be assign a correct value. Here is the working example I can produce, using glew-2.1.0 and glfw-3.3.0. if (!glfwInit()) { return EXIT_FAILURE; } std::cout << glfwGetVersionString() << std::endl; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); auto window = glfwCreateWindow(g_width, g_height, "An Other Engine", nullptr, nullptr); if (window == nullptr) { return EXIT_FAILURE; } glfwMakeContextCurrent(window); if (glewInit() != GLEW_OK) { return EXIT_FAILURE; } GLint flags; glGetIntegerv(GL_CONTEXT_FLAGS, &flags); if (flags & GL_CONTEXT_FLAG_DEBUG_BIT) { glEnable(GL_DEBUG_OUTPUT); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(glDebugOutput, nullptr); glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); } GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); GLuint vbo; glGenVertexArrays(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); A: In a core profile OpenGL Context, the buffer object (name) value has to be generated (reserved) by glGenBuffers. This is not necessary in a compatibility profile context. You wrongly tried to generate the buffer name by glGenVertexArrays rather than glGenBuffers. glGenVertexArrays(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); That causes an INVALID_OPERATION error when you try to generate the buffer object by glBindBuffer. Use glGenBuffers to solve the issue: glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); Note, you do not specify the profile type (glfwWindowHint(GLFW_OPENGL_PROFILE, ...)), by default the profile type is GLFW_OPENGL_ANY_PROFILE and not specified.
{ "pile_set_name": "StackExchange" }
Q: Is this Possible to retrieve a report names specific to object reference. Ex:Like for account object how many reports/dashboards are associated Requirement:-I want to fetch a report and Dashboard names which using Account ,contact,Opportunity,Lead And some custom object reference(Fields)). Is this Possible to retrieve a report name specific to object reference. Ex:Like for account object how many reports/dashboards are associated. As this is business requirement early response is more appriciated A: As far as I know it can't be done with SOQL. You probably could try with Analytics API but it has some limitations. The "old school" way would be to download all report types and report definitions to Eclipse IDE (or with any other tool of your choice). If you'd have > 5,000 reports the retrieval would have to be split into chunks - for example fetch few folders at a time. Report definitions will be shown as XML files (sample is at the bottom of Metadata API page for Report object). You'll then be able to run text searches on the XML files (Ctrl+H in Eclipse but you could also use Windows "Find in files" or anything really). Search for your custom object's API name (Xyz__ - ideally without the c at the end because you might see Xyz__r sometimes). Personally I like Notepad++ "find in files" - easy to select the search results and paste to text file or Excel... If that's too much work - go to the object's definition, clear the "allow reports" checkbox and soon your users will tell you which reports are related to that object ;) Source : Link
{ "pile_set_name": "StackExchange" }
Q: Is it possible to connect to Node.js's net moudle from browser? i want to make TCP server with Node.js and then connect it from browser without http , express and socket.io moudles. something like what i do in java or c# but this time from browser. A: The browser does not contain the capability for Javascript in a regular web page to make a straight TCP socket connection to some server. Browser Javascript has access to the following network connection features: Make an http/https request to an external server. Make a webSocket connection to an external server. Use webRTC to communicate with other computers In all these cases, you must use the libraries built into the browser in order to initiate connections on these specific protocols. There is no capability built into the browser for a plain TCP socket connection. A webSocket (which can only connect to a webSocket server) is probably the closest you can come.
{ "pile_set_name": "StackExchange" }
Q: Left/Right Mouse Click Function VB.NET I'm trying to make my own auto-clicker (settable to left or right, depending on the radio button selection) and I can't seem to make the mouse click. In order to be able to set the delay wished for the auto-clicker, I've put it within the Timer1 (one for left click, one for right click). My questions are: a) How can I make the mouse click when a certain key is pressed (e.g, F6). b) How can I make it have the delay of Timer1/Timer2 for each click. For the record, I wish for this auto-clicker to work EVERYWHERE, not just within the form. A: You can use user32.dll lib. Private Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Integer, ByVal dx As Integer, ByVal dy As Integer, ByVal cButtons As Integer, ByVal dwExtraInfo As Integer) &H2 means left mouse button down. &H4 means left mouse button up. mouse_event(&H2, 0, 0, 0, 0) mouse_event(&H4, 0, 0, 0, 0)
{ "pile_set_name": "StackExchange" }
Q: What happens when your score reaches 2048? In the new game Flappy 2048 what happens when your score reaches this magic number, and through what colors does your tile change during its journey? A: Everything is essentially the same as the original 2048. Once you have a 2048 tile, the game will give you the option to continue. It is worth noting, however, that the timer will not stop when the overlay is shown, but keyboard input will still be rejected. If you wish to keep playing beyond 2048 points, you had better be quick dismissing the overlay. As for the colours, they are again the same as 2048, but for half the value. So a tile with value 2 will have the 2048 style for a 4 tile, an 8 tile will have the same as a 16, etc. Source: completing the game digging through the code. A: The overlay will not show, as i tested (with barriers removed). The tile's appearance is the same as it is 2048.
{ "pile_set_name": "StackExchange" }
Q: Excel - SUMIFS + INDEX + MATCH with Multiple Criteria In the example below, I'm trying to sum any numbers that fit the criteria: Beverage + RTD Coffee for the month of January from the source. This is the formula that I'm currently trying to use for the above scenario: =SUMIFS(INDEX('Grocery Input'!$D8:$BY66,MATCH(1,('Grocery Input'!$D8:$D66=Summary!$D8)*('Grocery Input'!$E8:$E66=Summary!$E8),0),F$6),'Grocery Input'!$D8:$D66,"="&Summary!$D8,'Grocery Input'!$E8:$E66,"="&Summary!$E8) It needs to check both the 'Family' criteria and "Master Category' criteria A: Can you just eliminate the index match portion of the formulas and use SUMIFS with direct cell references? For example, =SUMIFS('Grocery Input'!$AD$8:$AD$66,'Grocery Input'!$D$8:$D$66,Summary!$D8,'Grocery Input'!$E$8:$E$66,Summary!$E8)
{ "pile_set_name": "StackExchange" }
Q: Nested list to Flat list with depth using jquery I'm trying to translate a nested list like <ul> <li>Coffee</li> <li>Tea <ul> <li>Black tea</li> <li>Green tea</li> </ul> </li> <li>Milk</li> </ul> to <div> <div class="list-depth-1">Coffee</div> <div class="list-depth-1">Tea</div> <div class="list-depth-2">Black tea</div> <div class="list-depth-2">Green tea</div> <div class="list-depth-1">Milk</div> </div> Can you help me? And is this order always the same (from top to bottom)? A: How about this? var parent = $("<div></div>"); $('#top li').each(function(pos,elem){ var child = $("<div></div>").addClass("list-depth-" + $(elem).parents('ul').length).text(elem.childNodes[0].nodeValue); parent.append(child); }); $('body').append(parent);
{ "pile_set_name": "StackExchange" }
Q: Python, trying to parse html to attain email address I am using beautifulsoup to attain an email address, however I am having problems. I do not know where to start to parse through this, to attain the email address. > #input: url > #output: address > > def urlSC(url): > soup = BeautifulSoup(urllib2.urlopen(url).read()) > #word = soup.prettify() > word = soup.find_all('a') > print word > return word OUTPUT: > [<a href="default.aspx"><img alt="·Î°í" border="0" src="image/logo.gif"/></a>, <a href="http://www.ctodayusa.com"><img > border="0" src="image/ctodayusa.jpg"><a></a> > </img></a>, <a></a>, <a href="mailto:[email protected]" id="hlEmail">[email protected]</a>, <a id="hlHomepage"></a>, <a > href="javascript:img_up('','','');"><img border="0" class="img" > src="upload/" vspace="10" width="1"/></a>, <a > href="javascript:img_up('','','');"><img border="0" class="img" > src="upload/" vspace="10" width="1"/></a>, <a > href="javascript:openWin('http://maps.yahoo.com/maps_result?addr=2100 > De armoun Rd.&amp;csz=99515&amp;country=us')" id="hlMap"><img > border='0"' src="images/globe.gif"> 위치</img></a>, <a > href="javascript:print()"><img border="0" src="images/printer.gif"> > 프린트</img></a>, <a href="javascript:mail_go('[email protected]', > '2Y5E9%2bk0h%2b4P%2f0H3jEJTq9VUG%2f0gaj40')" id="hlSendMail"><img > border="0" src="images/mails.gif"> 메일보내기</img></a>, <a > href="javascript:history.go(-1)"><img border="0" > src="images/list.gif"> > </img></a>, <a href="UpdateAddress.aspx?OrgID=4102" id="hlModify"><img alt="" border="0" src="Images/Modify.gif"/></a>] I want this email: [email protected] A: Get the a element by id, extract everything after mailto: from the href attribute value: link = soup.find('a', id='hlEmail') print link['href'][7:] Demo: >>> from bs4 import BeautifulSoup >>> import urllib2 >>> url = "http://www.koreanchurchyp.com/ViewDetail.aspx?OrgID=4102" >>> soup = BeautifulSoup(urllib2.urlopen(url)) >>> link = soup.find('a', id='hlEmail') >>> print link['href'][7:] rev_han seven seven seven at yahoo.com # obfuscated intentionally
{ "pile_set_name": "StackExchange" }
Q: Compiler versus Interpreter So, let me see if I get this clearly or not. When we say the differences between a compiler and an interpreter is that an interpreter translates high-level instructions into an intermediate form, which it then executes. [I think the compiler also translate high-level instructions into an intermediate form but at this moment it generate the object code instead of executing it, right?] An interpreter reads the source code one instruction or line at a time, converts this line into machine code and executes it. [The interpreter itself doesn't convert the code to machine code, it evaluates the instruction (after that had been parsed) using ist own precompiled functons. E.g. Add expression in the high-level language will be evaluated using the interpreter add function which has been previously compiled, right?] A: The key difference is this: An interpreter processes the source code as it runs it. It does not convert the source into machine code, it simply uses its own code to accomplish what the source directs. A compiler converts the source code into machine code that can be run directly. Not all compilers are separate from the execution process. For example, most Java run-times include a "JIT compiler" that compiles Java code while it's running, as needed. You can have things in-between. Essentially, a process similar to compiling can be used first to convert the source code into something smaller and easier to interpret. This compiled output can then be interpreted. (For example, a first pass could convert, say 'if' to 53, 'else' to 54, 'for' to 55, and so on -- this will save the interpreter from having to handle variable-length strings in code that doesn't actually deal with strings.) A: I would agree with the first, although it is not necessarily true that the interpreter is working on one line at a time (it could do optimizations based on knowledge of the whole code). The second I think is slightly off: the compiler does create "machine code" (which could be byte code, for a JVM). The interpreter executes parts of its own program based on the input (so far same as compiler), which executed parts are performing the computation described in the input (as opposed to performing computation to calculate the needed machine code). It is possible to blur the lines between the two as a compiler can generate code that will be interpreted at the time of execution (to provide runtime optimization based on factors that are not available at compile time)
{ "pile_set_name": "StackExchange" }
Q: switch from SSH key-based authentication to normal account login The current login method of the server is SSH key-based authentication, I wish to switch it to normal linux login by key in username and password. i understand this is unnecessary, but i have to switch it over. How to do it? A: Look inside of /etc/ssh/sshd_config change lines PasswordAuthentication PubkeyAuthentication !check other options / lines so you don't lock yourself out. If you want to be sure, post your config file here and ask back beforehand. If the machine is connected to the internet and the ssh port is accessible, you should take this as a warning that you don't fully understand ssh configuration.
{ "pile_set_name": "StackExchange" }
Q: Adding multiple values on list Is it possible to add multiple items into list or adding a list of values into a list. here is my current pseudo code to do it: List<string> myList = new List<string>(); myList.add("a","b","c","d","e","f","g"); myList.add("h","i","j","k","l","m","n"); myList.add("a1","a2","a3"); and my expected result is: [["a","b","c","d","e","f","g"], ["h","i","j","k","l","m","n"], ["a1","a2","a3"]] Any suggestions/comments TIA. A: What you are asking for is a List<List<string>>. There are probably better structures for storing your data but since you haven't given any context, you can do this: var myList = new List<List<string>>(); And add items like this: myList.Add(new List<string> { "a", "b", "c", "d", "e", "f", "g" }); myList.Add(new List<string> { "h", "i", "j", "k", "l", "m", "n" }); myList.Add(new List<string> { "a1", "a2", "a3" }); Or in one piece of code using a collection initialiser: var myList = new List<List<string>> { new List<string> { "a", "b", "c", "d", "e", "f", "g" }, new List<string> { "h", "i", "j", "k", "l", "m", "n" }, new List<string> { "a1", "a2", "a3" } }; A: Should be as easy as var myList = new List<List<string>>() { new List<string> { "a", "b", "c", "d", "e", "f", "g" }, new List<string> { "h", "i", "j", "k", "l", "m", "n" }, new List<string> { "a1", "a2", "a3" }, }; // OR var myarray = new[] { new[] { "a", "b", "c", "d", "e", "f", "g" }, new[] { "h", "i", "j", "k", "l", "m", "n" }, new[] { "a1", "a2", "a3" }, }; Additional Resources Object and Collection Initializers (C# Programming Guide) C# lets you instantiate an object or collection and perform member assignments in a single statement. Collection initializers Collection initializers let you specify one or more element initializers when you initialize a collection type that implements IEnumerable and has Add with the appropriate signature as an instance method or an extension method. The element initializers can be a simple value, an expression, or an object initializer. By using a collection initializer, you do not have to specify multiple calls; the compiler adds the calls automatically.
{ "pile_set_name": "StackExchange" }
Q: Deploy / build application for OSX I have created my first XE2 FM HD application. I have my OSX machine connected and running debug builds on OSX works fine, but I don't have a way to create a release version and copy it to another computer. I tried just copying over the Package made by the debug but that's missing files. Inside XE2 I went to Project -> Deployment. For the OSX Debug deployment I have a green button, but under OSX Release deployment I don't. Clues? A: Here's step-by-step instructions for building the App bundle and putting in the required dynamic link library: Create a folder called MyApp.app Create a subfolder in Myapp.app called Contents Create a subfolder in Contents called MacOS Create a subfolder in Contents called Resources From your build, copy Info.plist into Contents From your build, copy the Mac binary to MacOS From your build, copy the icon to Resources Copy libcgunwind.1.0.dylib to MacOS Copy the .app folder to your Mac and double-click it to run You will find libcunwind.1.0.dylib on your Mac where you installed the platform assistant, most likely: /Users/username/Applications/Embarcadero/PAServer/ Here's a video tutorial on how to create the manual install Disk Image installer on the Mac.
{ "pile_set_name": "StackExchange" }