text
stringlengths
64
81.1k
meta
dict
Q: Java Generics - why doesn't it output the variables? I've searched and searched, and I feel like I'm missing something really minor about the steps of using them. Class file for the generic: public class Point <T> { private T xPos, yPos; public Point(T xPos, T yPos) { this.xPos = xPos; this.yPos = yPos; } public T getXPos() { return xPos; } public void setXPos(T xPos) { this.xPos = xPos; } public T getYPos() { return yPos; } public void setYPos(T yPos) { this.yPos = yPos; } } Demo file: public class PointTester { public static void main(String[] args) { Point<Integer> point1 = new Point<Integer>(10,20); Point<Double> point2 = new Point<Double>(14.5, 15.6); Point<String> point3 = new Point<String>("topleftx", "toplefty"); System.out.println(point1); System.out.println(point2); System.out.println(point3); } } A: To define how a class in printed, you need to override the standard toString() method. In your example, you'd do something like public String toString() { return "(" + xPos + ", " + yPos + ")"; }
{ "pile_set_name": "StackExchange" }
Q: how to interpolate a 2d function with 6 points? I'm implementing an algorithm that uses a so called 6-point interpolation, which I never heard before. In the article I'm reading it's described like this: $\phi(p\Delta x, q\Delta y)=[q(q-1)/2] \phi_{0,-1}+[p(p-1)/2]\phi _{-1,0}$ $+(1-pq-p^2-q^2)\phi_{0,0}+[p(p-2q+1)/2]\phi_{1,0}+[q(q-2p+1)/2]\phi_{0,1}$ $+pq\phi_{1,1}+O(max(\Delta x,\Delta y)^2\phi_{0,0})$ Also, this image should clarify who are $q$ and $p$. http://i.minus.com/ibogDgHRRWKAVc.jpg My implementation is running into some problems and I would like to at least exclude this obscure interpolation algorithm as a source of problems. Does anyone know how to obtain it? A: I noticed a small mistake: the third term on the right hand side should be $+(1+pq-p^2-q^2)\phi_{0,0}$ Notice the sign of $pq$. (If you set $p=q=0$, this term should be $\phi_{0,0}$, for example.)
{ "pile_set_name": "StackExchange" }
Q: How to prove $A$ is generated by $a_0,a_1$? I am doing an exercise in Hatcher an stuck on it for a while. This is: Finding the $A's$ fitting into the exact sequence: $0 \rightarrow \Bbb Z_{p^m} \rightarrow A \rightarrow \Bbb Z_{p^n} \rightarrow 0$. I am understanding the solution here: https://www3.nd.edu/~lnicolae/ProblemsHatcher.pdf And I have trouble understanding this part: I think I need a complete formal proof for $A$ is generated by $a_0$ and $a_1$. To do this, I think I need to show that for all elements in $A$, it can be written as $ta_0+sa_1$ for some $t,s\in\Bbb Z$, conversely, any element of this form is in $A$. How can I prove it? I do notice that there are three posts in this sites discussing this question. But all of them has not solved my problem yet. Could someone give some explaination at this point? Thanks. A: Let $i:\Bbb Z_{p^m}\to A$ and $p:A\to \Bbb Z_{p^n}$ be the maps from the exact sequence. Let $a=i(1)\in A$, and $b$ be any element of $A$ with $p(b)=1$. If $c\in A$ then $p(c)=k\in\Bbb Z_{p^n}$ and let's think of $k$ as an integer. Then $p(c-kb)=0$, so $c-kb\in\ker p$. Thus $c-kp=i(u)$ with $u\in \Bbb Z_{p^m}$, thus $c-kb=la$ for some $l$.
{ "pile_set_name": "StackExchange" }
Q: How to make counter with custom images? I want to make a "tally counter" like application in Xcode with my custom images only numeric digits 0-999 to looks like this: And I don't know from where to start. I know how to do it with UILabel and system fonts, but i want to use my custom photoshop images without fonts or labels. Any help? A: You can do it pretty much as for websites (remembering the old good 90s when every website had a graphical visitor counter...) Create an UIImageView that will be the background (bg.png), and one image for each digits (0.png ... 9.png). Now in interface builder you place four images over the background, initializing them say with 0.png. In your view controller, in turn, you can change the png loaded in the UIImageView, so if the UIImageView of your first digit is called digit1 and you want to set it to 6, you'd use digit1.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d.png", 6]];
{ "pile_set_name": "StackExchange" }
Q: What is that attachment on the telephone? In The Wire, I noticed there was an attachment on the telephone set. What is it? I encircled it with a polygon. A: That is a Shoulder rest. This is to help you hold the phone up to your ear by shrugging your shoulder or tilting your head a bit. It made a lot more sense before cell phones.
{ "pile_set_name": "StackExchange" }
Q: 섭리 pronounced as 섬니? Is this another sound assimilation to make it easier to pronounce? I'm not used to two consonants changing sounds. It's usually just one of them that changes, so just to verify, is what I heard correct? A: This is nasalization applied twice. First, 섭리 > 섭니. Korean Standard Pronunciation, Chapter 5 Assimilation of Sounds, Clause 19, Attachment reads (English translation by myself): 받침 ‘ㄱ, ㅂ’ 뒤에 연결되는 ‘ㄹ’도 [ㄴ]으로 발음한다. 'ㄹ' connected after syllable-final 'ㄱ,ㅂ' is pronounced [ㄴ]. Then, 섭니 > 섬니. Same resource, Clause 18 reads: 받침 ‘ㄱ(ㄲ, ㅋ, ㄳ, ㄺ), ㄷ(ㅅ, ㅆ, ㅈ, ㅊ, ㅌ, ㅎ), ㅂ(ㅍ, ㄼ, ㄿ, ㅄ)’은 ‘ㄴ, ㅁ’ 앞에서 [ㅇ, ㄴ, ㅁ]으로 발음한다. Syllable-final 'ㄱ(ㄲ, ㅋ, ㄳ, ㄺ), ㄷ(ㅅ, ㅆ, ㅈ, ㅊ, ㅌ, ㅎ), ㅂ(ㅍ, ㄼ, ㄿ, ㅄ)' are pronounced [ㅇ, ㄴ, ㅁ] each, in front of 'ㄴ, ㅁ'. So there is nothing irregular about this, and you heard it very correctly. Indeed, it is the standard pronunciation according to the Standard Korean Language Dictionary.
{ "pile_set_name": "StackExchange" }
Q: Package import failure in Python 3.5 I have the following folder structure: /main main.py /io __init__.py foo.py In Python 2.7 I would write the following in main.py: import io.foo or from io.foo import * wheareas in Python 3.5 I get an import error: Traceback (most recent call last): File "./main.py", line 6, in <module> import io.foo ImportError: No module named 'io.foo'; 'io' is not a package I couldn't find any help so far. A: io is a built-in module. Don't name your local packages the same as a built-in module.
{ "pile_set_name": "StackExchange" }
Q: How to change the line between two elements in listview Imagine a basic ListView, like this: Item1 --------- Item2 --------- Item3 --------- Item4 How do I change the color or width of ------ the line that divides each item in a ListView? A: Please try android:divider="#FF0000" android:dividerHeight="4px" and have a look at that question: How to change color of Android ListView separator line?
{ "pile_set_name": "StackExchange" }
Q: Baby Rudin's exercise 2.21 Here's the exercise: Let $A$ and $B$ be separated subsets of some $\mathbb{R}^k$, suppose $a \in A$, $b \in B$, and define: $$p(t) = (1-t)a + tb$$ for $t \in \mathbb{R}^1$. Put $A_0 = p^{-1} (A)$, $B_0 = p^{-1} (B)$ [Thus $t \in A_0 \iff p(t) \in A$] My problem is that I don't get just what is $p(t)$. Is it a mapping? If so, then what is $p(A)$? Is it a set? I'm sorry if it sounds stupid or too elementary but I simply don't understand what is this $p(t)$ Rudin just defined. It resembles a property of convexity - but it accepts any real $t$, not just a real $t$ such that $0<t<1$. I think this has something to do with convexity in finite dimensions, but I'm not sure. A: $p: \mathbb{R} \to \mathbb{R^n}: t \mapsto p(t)$ is a map. Geometrically, the graph of the function is the line between the points a and b. Btw, I dislike Rudin's approach to show that convex sets are connected. It's easier and more general to show that pathconnected sets are connected and then it's trivial to see that convex sets are connected (using the map that Rudin provides).
{ "pile_set_name": "StackExchange" }
Q: Why can't pilots drink alcohol after a flight? Why are pilots told not to drink alcoholic drinks even after landing, even when their next flight is more than 24 hours later? Is this some kind of precautionary rule? A: Commercial pilots (in the United States) are usually not allowed to drink while on duty regardless of their flight status because, among other things, it would be frightening to any prospective passengers who might see them drinking. For example, American Airlines strictly forbids consuming alcohol or any intoxicant publicly while in uniform. Here is the exact text of their company policy: Rule 25 Unauthorized possession or using any intoxicants on Company premises at any time, or drinking intoxicants in public while wearing a uniform with Company emblem or insignia is prohibited. Note that this does not disallow drinking as long as it is (1) not on company premises, and (2) is in private. Obviously, if the person is a US crewmember then they must adhere to FAA rules in addition to company rules (see FAR Section 91.17 for details on those rules). A: Pilots absolutely can drink after a flight once off duty, just not in uniform. Every company I'm aware of prohibits alcohol consumption in uniform while in view of the public. This prohibition is about maintaining an image and to not associate drunk pilots with the airline. The regulations have no verbiage about uniforms but stipulate no one on-duty may consume alcohol. The rules for air carrier pilots is laid out in 14 CFR 120.37 (excerpt): (b) Alcohol concentration. No covered employee shall report for duty or remain on duty requiring the performance of safety-sensitive functions while having an alcohol concentration of 0.04 or greater. No certificate holder having actual knowledge that an employee has an alcohol concentration of 0.04 or greater shall permit the employee to perform or continue to perform safety-sensitive functions. (c) On-duty use. No covered employee shall use alcohol while performing safety-sensitive functions. No certificate holder having actual knowledge that a covered employee is using alcohol while performing safety-sensitive functions shall permit the employee to perform or continue to perform safety-sensitive functions. (d) Pre-duty use. (1) No covered employee shall perform flight crewmember or flight attendant duties within 8 hours after using alcohol. No certificate holder having actual knowledge that such an employee has used alcohol within 8 hours shall permit the employee to perform or continue to perform the specified duties. The rule here is 8 hours "bottle to throttle" and at the end of those 8 hours for BAC must be less than 0.04. 14 CFR part 121 Appendix J further stipulates that pilots may not perform "safety sensitive" functions until BAC is below 0.02. Additionally, many company operating manuals (FAA approved) require 12 hours between alcohol consumption and the beginning of a duty period. For most pilots, the rule is 12 hours "bottle to throttle" and BAC < 0.02. This means a pilot, once off-duty and out of uniform, can enjoy a drink as long as the overnight is longer than 12 hours.
{ "pile_set_name": "StackExchange" }
Q: Closing a CMD Window after launching an application through command line from Delphi I am trying to do the following. It works but the cmd window waits for the acrobat.exe to finish executing before exiting. I have to use this method of launching because I intend to pass certain command line parameters in future. cmdLineString := Format('/c ""%s" "%s""',['C:\Program Files (x86)\Adobe\Acrobat 11.0\Acrobat\Acrobat.exe', 'F:\Android-interview\Packt.Android.3.0.Application.Development.Cookbook.Jul.2011.ISBN.1849512949.pdf']); ShellExecute(Handle, 'open', 'cmd.exe', PChar(CmdLineString), nil, SW_SHOWNORMAL); A: There are a number of ways to improve this: Don't use ShellExecute. It is tempting to do so because it is simple to call. However, it is not very flexible. Use CreateProcess instead. If you must hide a console window, pass the CREATE_NO_WINDOW flag to CreateProcess. That said, there is no point to use cmd here. You don't need to create a process that creates another process. Doing so actually makes it harder to pass on arguments. Create the Acrobat process directly. Cut out the middle man.
{ "pile_set_name": "StackExchange" }
Q: convert aggregate result to list I'm passing a list to a serialize JSON string value back to a Visualforce page. Traditionally I can easily pass back a List to the JSON. However, my SOQL is an aggregate. I need to be able to serialize this aggregate result. That may require converting that SOQL to a List. I'm unsure how to do that. I've tried iterating through but that requires adding "new" objects to and I'm not sure how to construct those new objects with all of the fields I need. public Activity__c[] getActs(){ setVar(); return myActs; } public void setVar(){ string soql = 'select max(Activity_Time_Stamp__c), max(Activity_Date__c), min(id), min(Task_Site__c), min(GeoCode__Latitude__s), min(GeoCode__Longitude__s), workday__r.owner.name' + ' from Activity__c ' + ' where GeoCode__Latitude__s != null ' + ' group by workday__r.owner.name'; for (AggregateResult ar: [select max(Activity_Time_Stamp__c), max(Activity_Date__c), min(id), min(Task_Site__c), min(GeoCode__Latitude__s), min(GeoCode__Longitude__s), workday__r.owner.name from Activity__c where GeoCode__Latitude__s != null group by workday__r.owner.name] ){ myActs.add(new Activity__c('****WHAT DO I PUT HERE**** If this is the correct method')); } myActs = database.query(soql); } A: Just use the AggregateResult directly. If you decide to serialize it, your data would look like this: [    {       "attributes": {          "type": "AggregateResult"       },       "Name": "Account 0"    },    {       "attributes": {          "type": "AggregateResult"       },       "Name": "Account 1"    } ]
{ "pile_set_name": "StackExchange" }
Q: How does BitPay manage to confirm transactions so fast (less than a minute)? I believe it takes about an hour for 6 confirmations. (Edited from David Schwartz's comment) However, when I purchased some stuff from merchants who used BitPay, the payment/orders were confirmed in like 20 seconds or so? Since BitPay is confirming the order before 6 confirmations, how does it protect itself from double spending attacks? A: BitPay takes all the risks of a double-spend and they don't wait for any confirmation to make the user feel good with the purchase. The merchant doesn't care because they'll receive fiat and most of them are not direct access purchases.
{ "pile_set_name": "StackExchange" }
Q: How can I right-align the contents of a ExtJS tbar? I have a tbar inside a grid panel like this: This is the code that produces it: var grid = new Ext.grid.GridPanel({ region: 'center', style: 'margin: 10px', store: new Ext.data.Store({ data: myData, reader: myReader }), title: 'Testing', tbar: ['Filters:', { width: 100, xtype: 'combo', mode: 'local', value: 'en', triggerAction: 'all', forceSelection: true, editable: false, fieldLabel: 'Produkt', name: 'language', hiddenName: 'language', displayField: 'name', valueField: 'value', store: new Ext.data.JsonStore({ fields : ['name', 'value'], data : [ {name : 'German', value: 'de'}, {name : 'English', value: 'en'}, {name : 'French', value: 'fr'} ] }) }], What do I need to change so that the dropbox is right-aligned instead of left-aligned? Addendum thanks @dogbane, that works perfectly, here's how I right aligned both text and dropdown: tbar: [ {xtype: 'tbfill'}, 'Filters:', { width: 100, xtype: 'combo', mode: 'local', ... A: Try: {xtype: 'tbfill'}, // or '->' See the docs for Ext.Toolbar.Fill.
{ "pile_set_name": "StackExchange" }
Q: Spark Plug/Ignition Coil: DC Pulse If you have the following circuit with a step up voltage from L1 to L2, then when do you get a spark across the spark plug? I have three scenarios. Scenario 1. You have the switch open, then you close it right away you get a spark. Scenario 2. You have the switch open, then you close the switch. This allows the magnetic lines of flux to expand. A current then is induced for L2. Once a little time passes you reopen the switch, and then you get a spark. Scenario 3. Neither of these, I am dead wrong. simulate this circuit – Schematic created using CircuitLab A: Scenario #2 is the correct one. Without some type of voltage step up a 12V battery can not create a high enough change in current to create a spark. If instead current is set up through the coil and then the path is broken the change in current is orders of magnitude higher. To make this circuit practical the addition of a capacitor across the switch is needed to make the switch break clean. This would work like a condenser in a point and breaker automotive ignition.
{ "pile_set_name": "StackExchange" }
Q: selenium test on ubuntu 16.04 with chromedriver i'm in UBUNTU 16.04 when i run this test : sudo java -jar SeleniumTest.jar Driver Chrome Import Accounts.xml BaseUrl https://URL output: Dec 15, 2017 3:46:22 AM com.company.vip.core.CoreManager main INFO: Detected OS is : Linux Dec 15, 2017 3:46:22 AM com.company.vip.core.CoreManager main INFO: Loading App Config Data Dec 15, 2017 3:46:22 AM com.company.vip.core.CoreManager main INFO: App Configuration loaded Successfully Dec 15, 2017 3:46:22 AM com.company.vip.core.CoreManager main INFO: Starting Test Automation ... Dec 15, 2017 3:46:22 AM com.company.vip.core.CoreManager main INFO: Running All Tests Dec 15, 2017 3:46:22 AM com.company.vip.core.CoreManager main INFO: Starting Test Cases ... [TestNG] Running: /opt/old/VIP2/testresources/Login.xml Dec 15, 2017 3:46:22 AM com.company.vip.tests.Login.LoginSuite BeforeSuiteMethod SEVERE: Chrome driver path is either unreadable or unassigned. Please configure your AppConfig.xml Dec 15, 2017 3:46:22 AM com.company.vip.tests.Login.Login TestInvalidUserLogin INFO: Starting TestInvalidUserLogin Dec 15, 2017 3:46:22 AM com.company.vip.tests.Login.LoginSuite AfterMethod SEVERE: Test Case : Login.TestInvalidUserLogin()[pri:0, instance:com.company.vip.tests.Login.Login@17579e0f] Failed Dec 15, 2017 3:46:22 AM com.company.vip.tests.Login.Login TestValidUserLogin INFO: Starting TestValidUserLogin Dec 15, 2017 3:46:22 AM com.ilerra.vip.tests.Login.LoginSuite AfterMethod SEVERE: Test Case : Login.TestValidUserLogin()[pri:0, instance:com.company.vip.tests.Login.Login@17579e0f] Failed Dec 15, 2017 3:46:22 AM com.company.vip.tests.Login.LoginSuite AfterMethod SEVERE: Test Case : SignUp.TestUserSignUp()[pri:0, instance:com.company.vip.tests.Login.SignUp@34cd072c] Failed =============================================== LoginSuite Total tests run: 3, Failures: 3, Skips: 0 Configuration Failures: 1, Skips: 0 =============================================== [TestNG] Running: /opt/old/VIP2/TestNG.xml =============================================== allSuites Total tests run: 3, Failures: 3, Skips: 0 Configuration Failures: 1, Skips: 0 =============================================== Xvfb stopping Finished: SUCCESS the content of Appconfig.xml: <?xml version="1.0" encoding="UTF-8"?> <AppConfig> <Environment>Staging</Environment> <ChromePath>/usr/local/bin/chromedriver</ChromePath> <ChromeProfile>/home/usr/.config/google-chrome/Default/</ChromeProfile> <ChromeIsHeadless>1</ChromeIsHeadless> <ImportParamsFrom>App</ImportParamsFrom> </AppConfig> ~ A: After many of times tries and troubleshooting i found that: 1- you should run test with normal user (something related to chrome if you start it with root it will fail) 2- you have to have a x permission on chromedriver 3- you must pass all parameter on Appconfig.xml file like full pass to chromedriver and chrome profile
{ "pile_set_name": "StackExchange" }
Q: seralizing EF entities; disabling Proxy Creation and Lazy Loading? Ive been having some problems regarding circular references when converting EF entities to json objects. I have found a solution that works for me, but i would like to know what is actually happening when im adding context.ContextOptions.ProxyCreationEnabled = false; and/or context.ContextOptions.LazyLoadingEnabled = false; The first one seems to be enough to get a single-dimensional json object. Should i use both? And what does they actually do? Is there a smarter way around this? Thanks A: First line turns off runtime generation of class that inherits from your entity class. This class is really used during runtime. Not your class. This runtime generated class is probably not Serializable and that's why this line (turning off proxy generation) makes serialization work. Second line turns off lazy loading. So let's say you have Parent entity and Child entity. When you ask for Parent you don't load Children when lazy loading is on. When it is off whenever you load Parent you load all of it's children. I think this is something you should familiarize with if you are using EF. Edit: If there is problem with circular reference then you should turn off lazy loading. Then when you serialize Parent you will not try to serialize Children that have reference to Parent (creating circular reference)
{ "pile_set_name": "StackExchange" }
Q: Pass file to asp.net controller using angular i need upload file from <input class="fromFileInput" id="VeryfyFromFileInput" type="file" fileread="fileContent" ng-click=uploadFile /> using angular controller: $scope.fileInformation = []; $scope.uploadFile = function () { $scope.fileModel = $('#VeryfyFromFileInput'); recordsService.passFile($scope.fileModel.context); }; service: this.passFile = function (data) { return $http({ method: 'POST', url: url + "/GetFile", data: data, headers: { 'Content-Type': 'application/json' } }); }; To ASP.NET MVC controller [HttpPost] public void GetFile([FromBody] HttpRequestMessage file) { } But i have always null, so which type of parameters i must use instead of 'HttpRequestMessage '? Or maybe problem in JS side? A: You cannot pass bytedata over the wire as application/json. One solution is to use a Form Data object and make the ajax call as a multipart/formdata. Use the following Ajax call. $.ajax({ url: 'api/controller/action', processData: false, contentType: false, type: 'POST', data: formDataObject, success: function () { alert('yay!'); }, error: function () { alert('nay :c'); } }); I used angular-ui file upload directive. I'm not sure if the way you're accessing it works, if it does then you can simply use the following syntax to add your file to FormData var formDataObject = new FormData(); formDataObject.append('file', $scope.fileModel; On the server use this snippet to access your data var filesReadToProvider = await Request.Content.ReadAsMultipartAsync(); foreach (var stream in filesReadToProvider.Contents) switch (stream.Headers.ContentDisposition.Name) { case "\"file\"": byte[] fileData = await stream.ReadAsByteArrayAsync(); break; default: break; } } For information on how to write a byte array as file to server follow: Write File to server Good luck!
{ "pile_set_name": "StackExchange" }
Q: Opening a new tab, but should function as a back button with saved search I have a page where you can search rates using location and dates. Once you get to the confirmation page I have a link to go back and select a different rate. By using history.go(-2) I can go back to the rates page fine. But I were to right click open or wheel click, it just goes to the home page, because the search criteria is not saved. How do I go about fixing this? <a href="#" onclick="history.go(-2)"><u>select a different rate</u></a> A: Browser history cannot be inherited by a new tab, as far as I know. You can, however, pass the previous page URL to the new page as a URL parameter, for example: domain.com/newPage?oldPage=http%3A%2F%2Foldpage.com You can then modify the browser history when the new page loads, adding the previous page. See Manipulating the browser history
{ "pile_set_name": "StackExchange" }
Q: How to remove all physical bodies from physical I'm working on a corona project and I now want to remove all bodies from the physics. I see it has only a method to remove a body but not all physics.removeBody() I need to remove all, like that physics.removeAllBodies() Who can give me a way to do that. Thank you A: The only way to do that is to add each display body to a physicsBodies table whenever you add to physics: local physicsDisplayObjects = {} ... function scene:createScene(event) ... local displayObject1 = ... -- display object physics.addBody(displayObject1, ...) -- transform it into a physics body table.insert(physicsDisplayObjects, displayObject1) ... end ... function something() ... for i,obj in ipairs(physicsDisplayObjects) do physics.removeBody(obj) -- revert obj into regular display object end physicsDisplayObjects = {} -- clear ... end ...
{ "pile_set_name": "StackExchange" }
Q: variant of pascal's triangle in haskell - problem with lazy evaluation To solve some problem I need to compute a variant of the pascal's triangle which is defined like this: f(1,1) = 1, f(n,k) = f(n-1,k-1) + f(n-1,k) + 1 for 1 <= k < n, f(n,0) = 0, f(n,n) = 2*f(n-1,n-1) + 1. For n given I want to efficiently get the n-th line (f(n,1) .. f(n,n)). One further restriction: f(n,k) should be -1 if it would be >= 2^32. My implementation: next :: [Int64] -> [Int64] next list@(x:_) = x+1 : takeWhile (/= -1) (nextRec list) nextRec (a:rest@(b:_)) = boundAdd a b : nextRec rest nextRec [a] = [boundAdd a a] boundAdd x y | x < 0 || y < 0 = -1 | x + y + 1 >= limit = -1 | otherwise = (x+y+1) -- start shoud be [1] fLine d start = until ((== d) . head) next start The problem: for very large numbers I get a stack overflow. Is there a way to force haskell to evaluate the whole list? It's clear that each line can't contain more elements than an upper bound, because they eventually become -1 and don't get stored and each line only depends on the previous one. Due to the lazy evaluation only the head of each line is computed until the last line needs it's second element and all the trunks along the way are stored... I have a very efficient implementation in c++ but I am really wondering if there is a way to get it done in haskell, too. A: Works for me: What Haskell implementation are you using? A naive program to calculate this triangle works fine for me in GHC 6.10.4. I can print the 1000th row just fine: nextRow :: [Integer] -> [Integer] nextRow row = 0 : [a + b + 1 | (a, b) <- zip row (tail row ++ [last row])] tri = iterate nextRow [0] main = putStrLn $ show $ tri !! 1000 -- print 1000th row I can even print the first 10 numbers in row 100000 without overflowing the stack. I'm not sure what's going wrong for you. The global name tri might be keeping the whole triangle of results alive, but even if it is, that seems relatively harmless. How to force order of evaluation: You can force thunks to be evaluated in a certain order using the Prelude function seq (which is a magic function that can't be implemented in terms of Haskell's other basic features). If you tell Haskell to print a `seq` b, it first evaluates the thunk for a, then evaluates and prints b. Note that seq is shallow: it only does enough evaluation to force a to no longer be a thunk. If a is of a tuple type, the result might still be a tuple of thunks. If it's a list, the result might be a cons cell having thunks for both the head and the tail. It seems like you shouldn't need to do this for such a simple problem; a few thousand thunks shouldn't be too much for any reasonable implementation. But it would go like this: -- Evaluate a whole list of thunks before calculating `result`. -- This returns `result`. seqList :: [b] -> a -> a seqList lst result = foldr seq result lst -- Exactly the same as `nextRow`, but compute every element of `row` -- before calculating any element of the next row. nextRow' :: [Integer] -> [Integer] nextRow' row = row `seqList` nextRow row tri = iterate nextRow' [0] The fold in seqList basically expands to lst!!0 `seq` lst!!1 `seq` lst!!2 `seq` ... `seq` result. This is much slower for me when printing just the first 10 elements of row 100,000. I think that's because it requires computing 99,999 complete rows of the triangle.
{ "pile_set_name": "StackExchange" }
Q: Calculated Field in PowerPivot I have tried researching this question, but have had issues understanding DAX. I am using PowerPivot instead of a normal pivot table so that I can use the distinct count feature. I would like to create what in a classic pivot table would equate to a calculated field. I put together an example in the picture below. In the value section of the pivot table, I have a distinct count of the sales of red hats (column B). To the right also in the value section, I have the count of total hat sales (all colors) (column C). I would like to add another column that displays the red hat sales as a percent of the total hat sales - The solution that I am looking for would divide the 'Distinct Count of Red Hat Sales' over the 'Count of Total Sales' using a field or measure in PowerPivot (Essentially what I have manually entered in column D). I believe that I am doing to have to use DAX to create a measure? I am sure that this has probably been answered before, but I have had trouble finding exactly what I am asking. Any help would be greatly appreciated. A: You need to create a DAX measure with the following formula: = DIVIDE( [Count of Red Hats], [Count of Total Hats]) This function ignores division by zero errors. If such errors happen, the function by default displays blanks, but you can choose to display something else (DIVIDE function has third optional parameter).
{ "pile_set_name": "StackExchange" }
Q: How to determine the current widget's parent container (sidebar widget id) I have several custom widgets that are installed as part of my theme. I'd like to execute conditional code inside each widget's admin panel (not the public side, I'm just interested in the admin panel inside function form($intance)), depending on which sidebar the widget is inserted into. How can I obtain a reference to the current sidebar id which holds the widget, from within the widget's function form($instance) handler? A: If your widgets use the widget API you should have the following method in your widget class... function widget($args, $instance){ //output html here... } $args['id'] will hold the id of the current sidebar.
{ "pile_set_name": "StackExchange" }
Q: Error: incompatible types in assignment I am writing some objective-C code and i can't figure out why this does not work: buttonRect = CGRectMake(0,0,100.0,100.0);//error:incompatible types in assignment CGRect newFrame = CGRectInset(buttonRect, -0.2, -0.2);//error:incompatible type for argument 1 of CGRectInset button.frame = newFrame; buttonRect is a CGRect defined as an instance variable in my class, and button is a UIButton also defined as an instance variable. Why is this not working? My header file: // // MyViewController.h // HelloWorld // // Created by RCIX on 7/10/09. // Copyright 2009 __MyCompanyName__. All rights reserved. // #import <UIKit/UIKit.h> @interface MyViewController : UIViewController { UITextField *textField; UILabel *label; NSString *string; UIButton *button; CGRect *buttonRect; } @property (nonatomic, assign) CGRect *buttonRect; @property (nonatomic, retain) IBOutlet UITextField *textField; @property (nonatomic, retain) IBOutlet UILabel *label; @property (nonatomic, retain) IBOutlet UIButton *button; @property (nonatomic, retain) NSString *string; - (IBAction)helloButtonDown:(id)sender; - (IBAction)helloButtonUp:(id)sender; @end A: buttonRect is declared as a CGRect * — that is, a pointer to a CGRect. Remove the splat and all will be well.
{ "pile_set_name": "StackExchange" }
Q: NameError: name 'Area' is not defined I made area data model in models.py. #coding:utf-8 from django.db import models class User(models.Model): name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) area = models.ForeignKey(Area) class Area(models.Model): name = models.CharField(max_length=20, verbose_name='area') class Prefecture(models.Model): name = models.CharField(max_length=20, verbose_name='city') area = models.ForeignKey(Area) class City(models.Model): name = models.CharField(max_length=20, verbose_name='region') prefecture = models.ForeignKey(Prefecture) class Price(models.Model): name = models.CharField(max_length=20, verbose_name='price') PRICE_RANGE = ( ('a', 'under500'), ('b', '500-1000'), ('c', 'upper1000'), ) price_range = models.CharField(max_length=1, choices=PRICE_RANGE) city = models.ForeignKey(City) When I run migration command,NameError: name 'Area' is not defined area = models.ForeignKey(Area) error happens.However,I defined Area,so I really cannot understand why this error happens.How should I fix this? A: Try to define theArea class before User class. Things should be fine. class Area(models.Model): name = models.CharField(max_length=20, verbose_name='area', null=True) class User(models.Model): name = models.CharField(max_length=200,null=True) age = models.CharField(max_length=200,null=True) area = models.ForeignKey('Area') class Prefecture(models.Model): name = models.CharField(max_length=20, verbose_name='city') area = models.ForeignKey('Area') class City(models.Model): name = models.CharField(max_length=20, verbose_name='region') prefecture = models.ForeignKey('Prefecture') class Price(models.Model): name = models.CharField(max_length=20, verbose_name='price') PRICE_RANGE = ( ('a', 'under500'), ('b', '500-1000'), ('c', 'upper1000'), ) price_range = models.CharField(max_length=1, choices=PRICE_RANGE) city = models.ForeignKey('City')
{ "pile_set_name": "StackExchange" }
Q: Update SharePoint List Item using Microsoft Graph API We are trying to update fields of a ListItem using Microsoft Graph. When we use the PATCH command in the Graph Explorer, everything works. However as soon as we want to try the same using JSON in C#, it throws back a Bad Request at us. Below is the request that I am sending to Graph Explorer for updating the field: PATCH https://graph.microsoft.com/v1.0/sites/mysharepoint:/sites/mySite:/lists/myList/items/1582/fields` Content-type: application/json {"CaseNumber": "13XX17101310238"} The code we are trying to execute is: string addItemJsonString = "{\"CaseNumber\":\"13XX17101310238\"}"; string requestUrl = sharepointURL + "/sites/mySharepointSiteID/lists/myList/items/1315/fields"; HttpClient client = new HttpClient(); HttpRequestMessage message = new HttpRequestMessage(new HttpMethod("PATCH"), requestUrl); message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); message.Content = new StringContent(addItemJsonString); HttpResponseMessage response = await client.SendAsync(message); The request message that gets sent is Method: PATCH, RequestUri: 'https://graph.microsoft.com/v1.0/sites/mySite:/sites/hha:/lists/myList/items/1584/fields', Version: 2.0, Content: System.Net.Http.StringContent, Headers:{ Accept: application/json Authorization: Bearer eyJ0eXAiOiJKV1QiLCJub25jZSI6IkFRQUJBQUFBQUFCSGg0a21TX2FLVDVYcmp6eFJBdEh6Z3M3NHRlVmt2WEZiVF9lS21lR21sbk9jdlV5bnNFdEIwWGc0c2p3TUdNQTQ2NnNGRklUbXFSMjJVYWNRc1NlWVdOX1d0cXo3aFp2ZVd5MkZsZTAyenlBQSIsImFsZyI6IlJTMjU2IiwieDV0IjoiRlNpbXVGckZOb0Mwc0pYR212MTNuTlpjZURjIiwia2lkIjoiRlNpbXVGckZOb0Mwc0pYR212MTNuTlpjZURjIn0.eyJhdWQiOiJodHRwczovL2dyYXBoLm1pY3Jvc29mdC5jb20vIiwiaXNzIjoiaHR0cHM6Ly9zdHMud2luZG93cy5uZXQvMzczZDNkODItMDdiZi00MjZiLWE4ZDItNjdhOWIzZWUwNGE1LyIsImlhdCI6MTUyMjE1MzA5NCwibmJmIjoxNTIyMTUzMDk0LCJleHAiOjE1MjIxNTY5OTQsImFjciI6IjEiLCJhaW8iOiJBVFFBeS84R0FBQUFQK00yQjRhWDNTSE43NlNPNHJUNmdzMFN4TEVTRzI1MlMvVng0eUlZM0tnMXF5UStRQjRSUkUrRzdvZlR5cUd3IiwiYWx0c2VjaWQiOiI1OjoxMDAzM0ZGRkE4NkNGRjg0IiwiYW1yIjpbInB3ZCJdLCJhcHBfZGlzcGxheW5hbWUiOiJQcm9saWZpYyBDYXJlIFNvbHV0aW9ucyIsImFwcGlkIjoiOGM1Yzg5ZDYtMjVmNi00Yjg2LWE2MmYtY2RiNTAxODY1NjFmIiwiYXBwaWRhY3IiOiIwIiwiZV9leHAiOjI2MjgwMCwiZW1haWwiOiJydXNzZWxsLm1hbm5pbmdAY2FyaW5naGVhcnR6LmNvbSIsImlkcCI6Imh0dHBzOi8vc3RzLndpbmRvd3MubmV0LzA1NGU4YjQwLWYxYjUtNDY2YS1hMDg0LTdlNmIwNjg1MDExNi8iLCJpcGFkZHIiOiIzOS41OS4yMTAuMTcxIiwibmFtZSI6IlJ1c3NlbGwgTWFubmluZyIsIm9pZCI6ImY5MjdiOGVlLTU0YWYtNGRiMy1iOWZiLWEzMjgyMmJlZWExMiIsInBsYXRmIjoiMyIsInB1aWQiOiIxMDAzMDAwMEE4QkJERUE2Iiwic2NwIjoiQWxsU2l0ZXMuRnVsbENvbnRyb2wgQWxsU2l0ZXMuTWFuYWdlIEFsbFNpdGVzLlJlYWQgQWxsU2l0ZXMuV3JpdGUgQm9va2luZ3MuTWFuYWdlLkFsbCBCb29raW5ncy5SZWFkLkFsbCBCb29raW5ncy5SZWFkV3JpdGUuQWxsIEJvb2tpbmdzQXBwb2ludG1lbnQuUmVhZFdyaXRlLkFsbCBDYWxlbmRhcnMuUmVhZCBDYWxlbmRhcnMuUmVhZC5TaGFyZWQgQ2FsZW5kYXJzLlJlYWRXcml0ZSBDYWxlbmRhcnMuUmVhZFdyaXRlLlNoYXJlZCBDb250YWN0cy5SZWFkIENvbnRhY3RzLlJlYWQuU2hhcmVkIENvbnRhY3RzLlJlYWRXcml0ZSBDb250YWN0cy5SZWFkV3JpdGUuU2hhcmVkIERldmljZS5Db21tYW5kIERldmljZS5SZWFkIERldmljZU1hbmFnZW1lbnRBcHBzLlJlYWQuQWxsIERldmljZU1hbmFnZW1lbnRBcHBzLlJlYWRXcml0ZS5BbGwgRGV2aWNlTWFuYWdlbWVudENvbmZpZ3VyYXRpb24uUmVhZC5BbGwgRGV2aWNlTWFuYWdlbWVudENvbmZpZ3VyYXRpb24uUmVhZFdyaXRlLkFsbCBEZXZpY2VNYW5hZ2VtZW50TWFuYWdlZERldmljZXMuUHJpdmlsZWdlZE9wZXJhdGlvbnMuQWxsIERldmljZU1hbmFnZW1lbnRNYW5hZ2VkRGV2aWNlcy5SZWFkLkFsbCBEZXZpY2VNYW5hZ2VtZW50TWFuYWdlZERldmljZXMuUmVhZFdyaXRlLkFsbCBEZXZpY2VNYW5hZ2VtZW50UkJBQy5SZWFkLkFsbCBEZXZpY2VNYW5hZ2VtZW50UkJBQy5SZWFkV3JpdGUuQWxsIERldmljZU1hbmFnZW1lbnRTZXJ2aWNlQ29uZmlnLlJlYWQuQWxsIERldmljZU1hbmFnZW1lbnRTZXJ2aWNlQ29uZmlnLlJlYWRXcml0ZS5BbGwgRGlyZWN0b3J5LkFjY2Vzc0FzVXNlci5BbGwgRGlyZWN0b3J5LlJlYWQuQWxsIERpcmVjdG9yeS5SZWFkV3JpdGUuQWxsIEVBUy5BY2Nlc3NBc1VzZXIuQWxsIEVkdUFkbWluaXN0cmF0aW9uLlJlYWQgRWR1QWRtaW5pc3RyYXRpb24uUmVhZFdyaXRlIEVkdUFzc2lnbm1lbnRzLlJlYWQgRWR1QXNzaWdubWVudHMuUmVhZEJhc2ljIEVkdUFzc2lnbm1lbnRzLlJlYWRXcml0ZSBFZHVBc3NpZ25tZW50cy5SZWFkV3JpdGVCYXNpYyBFZHVSb3N0ZXIuUmVhZCBFZHVSb3N0ZXIuUmVhZEJhc2ljIEVkdVJvc3Rlci5SZWFkV3JpdGUgZW1haWwgRmlsZXMuUmVhZCBGaWxlcy5SZWFkLkFsbCBGaWxlcy5SZWFkLlNlbGVjdGVkIEZpbGVzLlJlYWRXcml0ZSBGaWxlcy5SZWFkV3JpdGUuQWxsIEZpbGVzLlJlYWRXcml0ZS5BcHBGb2xkZXIgRmlsZXMuUmVhZFdyaXRlLlNlbGVjdGVkIEZpbmFuY2lhbHMuUmVhZFdyaXRlLkFsbCBHcm91cC5SZWFkLkFsbCBHcm91cC5SZWFkV3JpdGUuQWxsIElkZW50aXR5UHJvdmlkZXIuUmVhZC5BbGwgSWRlbnRpdHlQcm92aWRlci5SZWFkV3JpdGUuQWxsIElkZW50aXR5Umlza0V2ZW50LlJlYWQuQWxsIE1haWwuUmVhZCBNYWlsLlJlYWQuU2hhcmVkIE1haWwuUmVhZFdyaXRlIE1haWwuUmVhZFdyaXRlLlNoYXJlZCBNYWlsLlNlbmQgTWFpbC5TZW5kLlNoYXJlZCBNYWlsYm94U2V0dGluZ3MuUmVhZCBNYWlsYm94U2V0dGluZ3MuUmVhZFdyaXRlIE1lbWJlci5SZWFkLkhpZGRlbiBNeUZpbGVzLlJlYWQgTXlGaWxlcy5Xcml0ZSBOb3Rlcy5DcmVhdGUgTm90ZXMuUmVhZCBOb3Rlcy5SZWFkLkFsbCBOb3Rlcy5SZWFkV3JpdGUgTm90ZXMuUmVhZFdyaXRlLkFsbCBOb3Rlcy5SZWFkV3JpdGUuQ3JlYXRlZEJ5QXBwIG9mZmxpbmVfYWNjZXNzIG9wZW5pZCBQZW9wbGUuUmVhZCBQZW9wbGUuUmVhZC5BbGwgcHJvZmlsZSBSZXBvcnRzLlJlYWQuQWxsIFNpdGVzLkZ1bGxDb250cm9sLkFsbCBTaXRlcy5NYW5hZ2UuQWxsIFNpdGVzLlJlYWQuQWxsIFNpdGVzLlJlYWRXcml0ZS5BbGwgU2l0ZXMuU2VhcmNoLkFsbCBUYXNrcy5SZWFkIFRhc2tzLlJlYWQuU2hhcmVkIFRhc2tzLlJlYWRXcml0ZSBUYXNrcy5SZWFkV3JpdGUuU2hhcmVkIFRlcm1TdG9yZS5SZWFkLkFsbCBUZXJtU3RvcmUuUmVhZFdyaXRlLkFsbCBVc2VyLkludml0ZS5BbGwgVXNlci5SZWFkIFVzZXIuUmVhZC5BbGwgVXNlci5SZWFkQmFzaWMuQWxsIFVzZXIuUmVhZFdyaXRlIFVzZXIuUmVhZFdyaXRlLkFsbCBVc2VyVGltZWxpbmVBY3Rpdml0eS5Xcml0ZS5DcmVhdGVkQnlBcHAiLCJzdWIiOiJFQWlYZnlnSTJNV2tDeVJFTE43WDJJdGJpd0J5YlV2dU1xTWhfMXVESlo4IiwidGlkIjoiMzczZDNkODItMDdiZi00MjZiLWE4ZDItNjdhOWIzZWUwNGE1IiwidW5pcXVlX25hbWUiOiJydXNzZWxsLm1hbm5pbmdAY2FyaW5naGVhcnR6LmNvbSIsInV0aSI6Ii14b29sWW1JUTB5bjZkaXFWWVFMQUEiLCJ2ZXIiOiIxLjAifQ.eUDL7Kn6NwFRk8vOYegoAPT4HSMW2zsjlrxBHGN2o1HUk7GldCbq3ket76eW6LKChNjKgilLktB13pdC-Us5tFrQIBTxbSYnSeKFy2Jtz1aUxMtqAxD2eXcZGjE44KqUf40agD_-eqMTmDy4vSbxUEvsacin8RlSwMd94cOuxrCz3eSpdWfpsJiqsd2tkg7i7EkA9hRE9xHEyVlQR8KLzyt1Zxvoh-RyCfzKqeEfhuBUcRdgdXxx2kgqrJI1Zv7NckslDs2dc4FcZ_JhgCFc0Hzmtqq9FrwQ-1IekMG2T8Gjkb-wzNu0qwKm3ZtMPReMKQkDu61Bx-00OKu02DFO3g Content-Type: text/plain; charset=utf-8 Content-Length: 32} } The response that we get back is StatusCode: 400, ReasonPhrase: 'Bad Request', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:{ client-request-id: c0d1f2c4-e586-4094-9367-ed527dd28896 Strict-Transport-Security: max-age=31536000 request-id: c0d1f2c4-e586-4094-9367-ed527dd28896 Transfer-Encoding: chunked x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"SouthEast Asia","Slice":"SliceA","Ring":"3","ScaleUnit":"002","Host":"AGSFE_IN_10","ADSiteName":"SIN"}} Duration: 2632.4966 Cache-Control: private Date: Tue, 27 Mar 2018 12:23:49 GMT Content-Type: application/json } And the response header says client-request-id: c0d1f2c4-e586-4094-9367-ed527dd28896 Strict-Transport-Security: max-age=31536000 request-id: c0d1f2c4-e586-4094-9367-ed527dd28896 Transfer-Encoding: chunked x-ms-ags-diagnostic: {"ServerInfo":{"DataCenter":"SouthEast Asia","Slice":"SliceA","Ring":"3","ScaleUnit":"002","Host":"AGSFE_IN_10","ADSiteName":"SIN"}} Duration: 2632.4966 Cache-Control: private Date: Tue, 27 Mar 2018 12:23:49 GMT Any idea where are we losing it? A: Your problem here is you're issuing the PATCH with a Content-Type of txt\plain. It should be application/json. You need to change this line: message.Content = new StringContent(addItemJsonString); to: message.Content = new StringContent(addItemJsonString, Encoding.UTF8, "application/json");
{ "pile_set_name": "StackExchange" }
Q: Mongodb upsert operation seems not atomic which throws DuplicateKeyException I have a mongodb database named 'msgdb', and a collection named 'roster'. The document in 'roster' is like below: { "userId": "sn99933289", "rosterGroups": [ { "groupId": "242326", "groupName": "buddy", "rosterItems": [ ] } ], "version": NumberInt(1) } I set the field '_id' as the shard key like below: db.runCommand({ shardcollection: "msgdb.roster", key:{ _id:"hashed" }}) The Java code which calls the upsert method: import com.mongodb.BasicDBObject; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; private void saveRoster(Roster roster) { BasicDBObject dbObject = new BasicDBObject(); mongoTemplate.getConverter().write(roster, dbObject); dbObject.remove("version"); dbObject.remove("_class"); Update update = new Update(); for (Map.Entry<String, Object> entry : dbObject.entrySet()) { update.set(entry.getKey(), entry.getValue()); } update.inc("version", 1); Criteria criteria = Criteria.where("_id").is(roster.getUserId()); Query query = new Query(criteria); mongoTemplate.upsert(query, update, "roster"); } I found the DuplicateKeyException from the application log. It seems the upsert operation is not atomic. More specific exception stack trace is as below. How to avoid this exception? Any help/hint is appreciated. org.springframework.dao.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error collection: msgdb.roster index: _id_ dup key: { : "sn88332138" }'; nested exception is com.mongodb.DuplicateKeyException: Write failed with error code 11000 and error message 'E11000 duplicate key error collection: msgdb.roster index: _id_ dup key: { : "sn88332138" }' at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:69) ~[spring-data-mongodb-1.7.1.RELEASE.jar:na] at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2011) ~[spring-data-mongodb-1.7.1.RELEASE.jar:na] at org.springframework.data.mongodb.core.MongoTemplate.execute(MongoTemplate.java:463) ~[spring-data-mongodb-1.7.1.RELEASE.jar:na] at org.springframework.data.mongodb.core.MongoTemplate.doUpdate(MongoTemplate.java:1086) ~[spring-data-mongodb-1.7.1.RELEASE.jar:na] at org.springframework.data.mongodb.core.MongoTemplate.upsert(MongoTemplate.java:1052) ~[spring-data-mongodb-1.7.1.RELEASE.jar:na] at com.suning.im.server.center.roster.RosterServiceImpl.saveRoster(RosterServiceImpl.java:235) ~[classes:na] at com.suning.im.server.center.roster.RosterServiceImpl.getRoster(RosterServiceImpl.java:68) ~[classes:na] at com.suning.im.server.center.roster.RosterServiceImpl.getRosterPresencesWithVirtual(RosterServiceImpl.java:251) ~[classes:na] at sun.reflect.GeneratedMethodAccessor54.invoke(Unknown Source) ~[na:na] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_25] at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_25] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) ~[na:1.7.0_25] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) ~[na:1.7.0_25] at java.lang.Thread.run(Thread.java:724) ~[na:1.7.0_25] A: Upsert is not atomic. This is insinuated by the Mongo documentation: https://docs.mongodb.org/v3.0/reference/method/db.collection.update/. To avoid inserting the same document more than once, only use upsert: true if the query field is uniquely indexed. So I would recommend using upsert only on fields indexed as unique. If you have multiple fields in the query statement, you could either work with a compound index or hash those fields together (for instance into the id of the document). Luckily you are using a unique index here as you are using the _id field. Wrapping your upsert in a try catch that issues an update request should solve your problem, as you are sure once in the catch block that the document exists.
{ "pile_set_name": "StackExchange" }
Q: how to print php as html text please, how to print php as html text ? for example: i have this php line if(defined('LOAD_VARS') AND LOAD_VARS === TRUE) i want to print it as html text so output will be if(defined('LOAD_VARS') AND LOAD_VARS === TRUE) i have tried this <textarea style="width:600px; height:30px;">if(defined('LOAD_VARS') AND LOAD_VARS === TRUE)</textarea> but it doesn't work and show error how i can do that please ? how A: Your question isn't very clear, but here goes: Close the PHP tag before outputting anything, or simply use print() or echo. Example 1: <?php print('if(defined(\'LOAD_VARS\') AND LOAD_VARS === TRUE)'); ?> Example 2 <?php // Your code that you want to be run. ?> <pre>if(defined('LOAD_VARS') AND LOAD_VARS === TRUE)</pre>
{ "pile_set_name": "StackExchange" }
Q: Bandwidth comparison between log shipping and transactional replication Which technique uses more network bandwidth: Log shipping Transactional Replication Can some one share any benchmarks for the same ? What would be the Memory and I/O impact on the Primary server when we use any one of the technique ? Thanks, Piyush Patel A: It depends on your workload. As a baseline, use Performance Monitor and log the network counters when not using Log Shipping or Transactional Replication and measure for 1 hour. Then setup Log Shipping and use Performance Monitor to log the network counters for 1 hour. Then setup Transactional Replication and use Peformance Monitor to log the network counters for 1 hour. The network bandwidth that Log Shipping and Transactional Replication consumes is the difference between the collections and the baseline. The same can be done for memory and I/O.
{ "pile_set_name": "StackExchange" }
Q: Do common JARs have to be repeated across WARs in an EAR? I have a JAR file for authorization. I need it for each of my WAR files. All the WAR files are packaged in an EAR file. Do I have to repeat this common JAR in every WAR, or is there a structure for common libraries? So my example looks something like this... big.ear - META-INF - MANIFEST.MF - application.xml - appl1.war - META-INF - MANIFEST.MF - WEB-INF - web.xml - lib - unique1.jar - unique2.jar - unique3.jar - common1.jar - jsps/html/etc - appl2.war - META-INF - MANIFEST.MF - WEB-INF - web.xml - lib - unique3.jar - unique4.jar - common1.jar - jsps/html/etc - appl3.war - META-INF - MANIFEST.MF - WEB-INF - web.xml - lib - unique5.jar - common1.jar - jsps/html/etc Each of my WAR applications can see common1.jar, but it is in the EAR three times. Where in the EAR structure could I put common1.jar so that appl1, appl2, and appl3 could see it without repeating it three times? A: The standard way is to put the JARs at the root of your EAR and reference them in the Class-Path attribute of the WARs' META-INF/MANIFEST.MF. See this article. Check your container's documentation to make sure it is supported.
{ "pile_set_name": "StackExchange" }
Q: Git command line - know if in submodule? Is there any way in git to know if you're in a submodule? You can do thinks like git submodule foreach in the parent directory but I can't seem to come up with a generic way to show that you're in a submodule if you're in one, or in any of the child directories inside the submodule. I guess you could find the repo root with git rev-parse --show-toplevel, and then cd-ing up a level, and finding the root of that repo again and then comparing the list of submodules to the current directory, but that seems so sticky... A: (Update April 2017 for Git 2.13, Q2 2017) There is now an official command to determine if a repo is a submodule of a parent repo: cd /path/to/potential/submodule/repo git rev-parse --show-superproject-working-tree See commit bf0231c (08 Mar 2017) by Stefan Beller (stefanbeller). (Merged by Junio C Hamano -- gitster -- in commit 3edcc04, 17 Mar 2017) rev-parse: add --show-superproject-working-tree In some situations it is useful to know if the given repository is a submodule of another repository. Add the flag --show-superproject-working-tree to git-rev-parse to make it easy to find out if there is a superproject. When no superproject exists, the output will be empty. Jethro Yu suggests in the comments: get super project path regardless inside/outside of submodule: git rev-parse --show-superproject-working-tree --show-toplevel | head -1 (Update 2014) As noted by Quentin Pradet, more recent Git submodule repos show a simple .git file instead of a .git folder. That .git file reference the path of the actual submodule git repo, stored in the parent repo .git/modules subfolder. (Original answer: Sept. 2011) The very nature of a submodule is for the git repo acting as submodule has no idea it is used as a submodule by a parent repo. One dirty trick would be to: change a file go back one level above the current repo try a "git status --ignore-submodules=none" restore the changed file. If you see the file in the result of the git status, your repo should be a submodule. If it is only a nested repo, the git status should ignore your nested repo entirely. A: Here is a shell function that you can use to detect this: function is_submodule() { (cd "$(git rev-parse --show-toplevel)/.." && git rev-parse --is-inside-work-tree) | grep -q true } Edit In response to your proposed script: Looking good. There is a bug in for line in $submodules; do cd "$parent_git/$line"; \ if [[ `pwd` = $_git_dir ]]; then return 0; fi; \ done because it won't cd back (so it would only work if the first submodule is a match). My version checks without changing directories; That could be done done by cd-ing in a subshell, but returning the exitcode is getting complicated that way I don't know where you get $_git_dir from - I used basename(1) to get that information (see below). There was also a problem with submodules containing a space in the name. In my version, there is still a problem with newlines in submodule names left, but I don't care enough to fix that. (Note the 'idiomatic' way to avoid having the while read in a subshell without needing new bash-isms like readarray) finally declaring all the vars local fixes potential problems when using this inside other scripts (e.g. when the outer script uses the $path variable...) I renamed _git_dir to top_level (which is less confusing, because GIT_DIR means something else) Remaining issues: I don't know whether git supports it (I don't think so) but this script could fail if the submodule directory is a symlink (because "$top_level/.." might resolve outside the containing repository) submodule names with newlines will not be recognized properly I also suggest you trap errors (either with 'set -e', 'trap "return 1" ERR' or similar) -- not in my script/exercise for reader #!/bin/bash function is_submodule() { local top_level parent_git module_name path # Find the root of this git repo, then check if its parent dir is also a repo top_level="$(git rev-parse --show-toplevel)" module_name="$(basename "$top_level")" parent_git="$(cd "$top_level/.." && git rev-parse --show-toplevel 2> /dev/null)" if [[ -n $parent_git ]]; then # List all the submodule paths for the parent repo while read path do if [[ "$path" != "$module_name" ]]; then continue; fi if [[ -d "$top_level/../$path" ]]; then return 0; fi done < <(cd $parent_git && git submodule --quiet foreach 'echo $path' 2> /dev/null) #return 1 fi return 1 } Usage if is_submodule; then echo "In a submodule!" else echo "Not in a submodule" fi A: try git rev-parse --git-dir which will return ".git" if and only if called from the project root: if `git rev-parse --git-dir` == ".git" // in root directory else // in submodule directory unless you set $GIT_DIR which will be the returned value in that case (see rev-parse): --git-dir Show $GIT_DIR if defined. Otherwise show the path to the .git directory. The path shown, when relative, is relative to the current working directory. If $GIT_DIR is not defined and the current directory is not detected to lie in a Git repository or work tree print a message to stderr and exit with nonzero status.
{ "pile_set_name": "StackExchange" }
Q: Splitting an formatted data list I have a list of data that has been formatted in a column even format: ['[ 0.93913063 0.28020878 0.2769496 ]', '[ 0.21672141 0.29633945 0.19763641]', '[ 0.74718183 0.33466203 0.13866566]', '[ 0.1067503 0.20448574 0.16817043]', '[ 0.1223612 0.11653754 0.13288494]', '[ 0.48761208 0.78240743 0.38697977]', '[ 0.4300345 0.50380231 0.48102237]'] I want to split this data into a list like: [(0.93913063,0.28020878,0.2769496),(0.21672141,0.29633945,0.19763641),(0.74718183,0.33466203,0.13866566),(0.1067503, 0.20448574,0.16817043),(0.1223612,0.11653754,0.13288494),(0.48761208,0.78240743,0.38697977),(0.4300345,0.50380231,0.48102237)] The problem I have had is I was going to split the data and then piece it all back together in the format I want, but there is not a consistent amount of spaces in between the values in the brackets. So this is what I was doing: def removefront(s): return s[2:] def removeend(s): return s[:-2] valuelist = [] i = 0 for x in xrange(0,len(data)): print data[i] a,b,d = data[i].split(' ') p1 = removefront(a) p3 = removeend(d) p1 = float(p1) p2 = float(b) p3 = float(p3) coord = (p1, p2, p3) i += 1 valuelist.append(coord) Any help is greatly appreciated. Thanks! A: This list comprehension feels a little Rube Goldberg-ish, but here's my crack at it. >>> l = ['[ 0.93913063 0.28020878 0.2769496 ]', '[ 0.21672141 0.29633945 0.19763641]', '[ 0.74718183 0.33466203 0.13866566]', '[ 0.1067503 0.20448574 0.16817043]', '[ 0.1223612 0.11653754 0.13288494]', '[ 0.48761208 0.78240743 0.38697977]', '[ 0.4300345 0.50380231 0.48102237]'] >>> [tuple(map(float,i[2:-1].split())) for i in l] Output [(0.93913063, 0.28020878, 0.2769496), (0.21672141, 0.29633945, 0.19763641), (0.74718183, 0.33466203, 0.13866566), (0.1067503, 0.20448574, 0.16817043), (0.1223612, 0.11653754, 0.13288494), (0.48761208, 0.78240743, 0.38697977), (0.4300345, 0.50380231, 0.48102237)]
{ "pile_set_name": "StackExchange" }
Q: A for loop with condition in it - Trying to make it a one liner for row,col in targets: if (board[row][col] == -1 and ((col != 0 and board[row][col - 1] != -1) or (col != len(board) - 1 and board[row][col + 1] != -1) or (row != 0 and board[row - 1][col] != -1) or (row != len(board) - 1 and board[row + 1][col] != -1))): return 1000 return min(penalty) Im trying to make it a one liner but doing: return [min(penalty), 1000][True in[(board[row][col] == -1 and ((col != 0 and board[row][col - 1] != -1) or (col != len(board) - 1 and board[row][col + 1] != -1) or (row != 0 and board[row - 1][col] != -1) or (row != len(board) - 1 and board[row + 1][col] != -1)) for row,col in targets)]] But its not the same thing. A: You could try this: return 1000 if any(condition(r, c) for r, c in targets) else min(penalty) Here, condition() is your long inner condition. But this will be harder to read and no faster than what you have already.
{ "pile_set_name": "StackExchange" }
Q: Create nested JSON with minimal-json? I'm using minimal-json (github) and am trying to create a nested JSON like so: String jsonInner = new JsonObject().add("Inner", "i").toString(); String jsonMiddle = new JsonObject().add("Middle", jsonInner).toString(); String jsonOuter = new JsonObject().add("Outer", jsonMiddle).toString(); In my debug console, the result looks like this: {"Outer":"{\"Middle\":\"{\\\"Inner\\\":\\\"i\\\"}\"}"} Not quite what I was expecting; there is a bit much escaping going on... I'm a bit slow today; can anyone please point out how to do this properly? A: What about: JsonValue inner = new JsonObject().add("Inner", "i"); JsonValue middle = new JsonObject().add("Middle", inner); String outerAsString = new JsonObjec().add("Outer", middle).toString(); ? The problem is that you add a serialized JSON as a String in middle and outer; this is not what you want.
{ "pile_set_name": "StackExchange" }
Q: Iterating w/ Pandas DataFrame and Changing Values I have a pandas dataframe where I want to assign a random number to each row based on a value in the row and write out a dataframe. So I'm trying: for index, row in person[person['AGE_R'] == 1].iterrows(): row = index, random.randint(1, 15) But I can't quite figure out how to write out a dataframe from it (not possible?). I been able to get out a list of tuples which I might be able to munge into a workable format, but I'm sure there's a better way. I previously tried: person[person['AGE_R'] == 1] = random.randint(1, 15) But that sets all the 1's of 'AGE_R to what ever the randint is. Useful, but not what I'm looking for. Any suggestions? Thank you! A: If you want to do vectorized operation, you can use numpy.random.randint: >>> df = pd.DataFrame({'AGE_R':[1,2,3,5,4,3,1]}) >>> df AGE_R 0 1 1 2 2 3 3 5 4 4 5 3 6 1 >>> df.ix[df['AGE_R'] == 1, 'AGE_R'] = np.random.randint(1, 15, len(df[df['AGE_R'] == 1])) >>> df AGE_R 0 5 1 2 2 3 3 5 4 4 5 3 6 11 Or you can use apply: >>> df.ix[df['AGE_R'] == 1, 'AGE_R'] = df.ix[df['AGE_R'] == 1].apply(lambda x: np.random.randint(1, 15), axis = 1) >>> df AGE_R 0 5 1 2 2 3 3 5 4 4 5 3 6 12
{ "pile_set_name": "StackExchange" }
Q: "бежать по лесу" vs "бежать через лес" бежать по лесу бежать через лес On the surface, they both seem to mean "running through the woods", but I wonder if they are nuanced somehow? A: The nuance is in the purpose бежать через лес - emphasizes the fact that forest is only a landscape feature on your way elsewhere which you're going to cross бежать по лесу - means running in(side) the forest with no connotation of the need to pass through it, it could be for jogging having no destination outside of it and no intention to leave it Likewise: ехать через поле/по полю, идти через дорогу/по дороге, красться через сад/по саду. With preposition через often verbs with prefix пере- are used: пере-плывать/-плыть (через) реку, пере-ходить/-йти (через) дорогу
{ "pile_set_name": "StackExchange" }
Q: htaccess RewriteRules not working on subdirectories I have a static HTML site that I'm trying to add some URL rewriting rules to via my .htaccess file. The site file directory looks like this: - index.htm - about-us [subdirectory] - index.htm - careers [subdirectory] - index.htm - contact [subdirectory] - index.htm - map.htm - privacy.htm - projects [subdirectory] - index.htm - education.htm - healthcare.htm - recreation.htm - residential.htm - hospitality.htm - services [subdirectory] - index.htm My goal is to remove the file extensions from the page URLs, append a trailing slash, and force a 301 redirect so that anyone trying to access the file in it's original format (i.e. https://example.com/projects/education.htm) would automatically be rewritten to it's cleaner format (i.e. https://example.com/projects/education/). I already have the index.htm files rewritten/redirected in the .htaccess file on the root of my site. Here's what I have so far: DirectoryIndex index.php index.html index.htm RewriteEngine On RewriteCond %{REQUEST_URI} (.*)/$ RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.htm -f RewriteRule ^(.+)/$ /$1/ [R=301,L] RewriteRule ^index\.htm$ / [R=301,L] RewriteRule ^(.*)/index\.htm$ /$1/ [R=301,L] I have the directory root files (index.htm) removed successfully from the URLs, but for the life of me, I can't seem to get the non-root files (i.e. education.htm) rewritten in the desired format. Can anyone shed some light on what I'm doing wrong? UPDATE As per @misorude's comment, I removed the 1st rewrite rule. I also changed the 301s to 302s (at least temporarily, to try and avoid rule caching issues). I also modified my existing rules to utilize the "+" character in my regex to force a real file or folder name in my rules. Finally, I added a new 3rd rule. This one is an attempt to find all subdirectory "non index" pages, and remove their file extensions, which appears to work. However, I'm getting 404 errors on those non index pages. All of my previously working index.htm rewrite rules are working just fine, but the non index ones throw 404 errors. Here's my update htaccess file: DirectoryIndex index.php index.html index.htm RewriteEngine On RewriteCond %{REQUEST_URI} (.*)/$ RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.htm -f # If we're on the root index page of the site, # remove index.htm from URL RewriteRule ^index\.htm$ / [R=302,L] # If we're on a subdirectory index page, remove the index.htm from the URL RewriteRule ^(.+)/index\.htm$ /$1/ [R=302,L] # If we're on a non-index page of a subdirectory, # remove the extension from the URL RewriteRule ^(.+)/(.+)\.htm$ /$1/$2/ [R=302,L] Any advice? A: Here is a complete solution by disabling MultiViews option and handling each case DirectoryIndex index.php index.html index.htm Options -MultiViews RewriteEngine On # redirect "/index.htm" or "/xxx/index.htm" to "/" or "/xxx/" RewriteCond %{REQUEST_FILENAME} -f RewriteCond %{THE_REQUEST} \s/([^/]+/)?index\.htm\s [NC] RewriteRule ^ /%1 [R=302,L] # redirect "/xxx/page.htm" to "/xxx/page/" RewriteCond %{REQUEST_FILENAME} -f RewriteCond %{THE_REQUEST} \s/([^/]+)/([^/]+)\.htm\s [NC] RewriteRule ^ /%1/%2/ [R=302,L] # rewrite back "/xxx/page/" to "/xxx/page.htm" RewriteCond %{DOCUMENT_ROOT}/$1/$2\.htm -f RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.htm [L]
{ "pile_set_name": "StackExchange" }
Q: Binding MVC WebGrid column to source's dictionary property value I'm using MVC's WebGrid throughout my application and it's been working great. I'm setting the columns for the grid in my controller code and then passing that to my view. I add a new column like this where columns is a List<MvcWebGridColumn>: columns.Add(new WebGridColumn { ColumnName = "Path", Header = "Full Path", Filter = ... }); And then in my view, I set the grid columns from my view model like this: @grid.GetHtml( footerStyle: "hide", mode: WebGridPagerModes.All, htmlAttributes: new { id = @Model.Id }, columns: @Model.Columns) Up until this point, setting the columns in the code has worked great as the columns have been known, first-level properties of my models. Now things are more complicated and I don't know how to handle it with the WebGrid. Here is an example model: public class Requirement { public string Id { get; set; } public string Path { get; set; } public Dictionary<string, string> Fields { get; set; } } I want to be able to set a WebGrid's column in the code using the value from the Field dictionary property's key. I'm trying this, but it's not working: columns.Add(new WebGridColumn { ColumnName = String.Format("Fields[\"{0}\"]", key), Header = label }); I tried also putting a method GetFieldValue(string key) method on my Requirement model, but it doesn't like that either. It seems like it can only handle exactly matching an object's property identifier. I'm not sure if this is possible using WebGrid out of the box or if I have to extend the functionality. Thanks in advance. A: I believe I just came up with a way to handle this that doesn't seem too hacky. To restate the problem, I believe the MVC WebGrid uses reflection to set the ColumnName property so the string you enter for that needs to be directly accessible via the object's API eg. "Id", "Field.Address.Name", etc. The problem in my case is that the value I need for my column's row comes from a Dictionary and it doesn't seem like you can pass a parameter (key, index, etc) into the ColumnName to get the value I need. My solution is to avoid using the ColumnName property of the WebGrid entirely when resolving the value to be displayed. I simply enter a value for the grid's model that I know exists for the ColumnName, in my case "Id". This is just used so the WebGrid will render. Then, since the Format of the WebGridColumn uses a dynamic function, I can define my column value using whatever I want: columns.Add(new WebGridColumn { ColumnName = "Id", Header = field.Label, Format = x => new HtmlString(x.Value.GetEntityFieldValue(field.Field)) }); I soon realized that this will mess up sorting. MVC WebGrid's black-box sort simply uses the ColumnName in the sort query so every column for me now has "?sort=Id". If you're not sorting, then you're OK. If you are, you'll have to implement a custom sorting solution like I'm currently doing.
{ "pile_set_name": "StackExchange" }
Q: How to convert strings in a list into list, to from[[list1],[list2]....[listm]] I have some data like: ['6005,280', '6005,2751', '6005,260'] and I want to convert them into a list like: [['6005','280'],['6005','2751'],['6005','260']] I use for i in range(len(mainText)): target_list.append(int(x) for x in mainText[i].split(',')) But got some crazy output like: [<generator object main.<locals>.<genexpr> at 0x000000DA61784C78>, <generator object main.<locals>.<genexpr> at 0x000000DA61784B10>, <generator object main.<locals>.<genexpr> at 0x000000DA61784CF0>] So what is the correct way to do that? Code: import csv def main(): inputfile=open('price.csv','r') mainText=mainPart(inputfile) ## print(mainText) target_list=[] for i in range(len(mainText)): target_list.append(int(x) for x in mainText[i].split(',')) print(target_list) def mainPart(file): ## import items with first row rowsWithEnter1=[row for row in file] ## del first row rowsWithEnter2=rowsWithEnter1[1:] rows=[] for i in range(len(rowsWithEnter2)): rows.append(rowsWithEnter2[i].strip('\n')) return rows main() A: When you have a comprehension (like int(x) for x in ...) inside parentheses, it is interpreted as a generator, which is a special type of object which can then be iterated over to produce a list. The crazy output you're seeing is because you've actually created a list of generators, instead of a list of lists. To interpret your comprehensions as lists instead of generators, you just need to put them in square brackets: for i in range(len(mainText)): target_list.append([int(x) for x in mainText[i].split(',')])
{ "pile_set_name": "StackExchange" }
Q: Hibernate how to get updated properties How to get which properties were updated after hibernate update? For example if I got SomeEntity se = new SomeEntity(); getHibernateTemplate().save(se); //then in some other method se.setProp1("some new value"); //then in 3th method getHibernateTemplate().update(se); If you tell hibernate to do dynamic update it will know witch properties were changed and update only them. Is there a way to get the ones that were changed or to check is specific property was changed? A: Ended up doing native sql query to compare the state in the db with the state in the entity before flush the session. Query query = session.createSQLQuery( "select t.someProp1 from someTable t where t.id = :entityId") .setParameter("entityId", entity.getId()); List result = query.list();
{ "pile_set_name": "StackExchange" }
Q: Passing struct to function and adding elements I'm new to C. I'm trying to pass a struct list to a function and within that function fill the list. Code is as follows: #include <stdio.h> #include <stdlib.h> struct Abc { int test; struct Abc *next; }; void demo_fill(struct Abc *data); int main(int argc, char **argv) { struct Abc *db = NULL; demo_fill(db); printf("%d\n",db->test); return 0; } void demo_fill(struct Abc *data) { int i; for( i = 0; i < 5; i++ ) { struct Abc *new; new = malloc(sizeof(struct Abc)); new->test = i; new->next = data; data = new; } } When running this a 'Segmentation fault (core dumped)' error occurs because the struct is still NULL when I try to print the first element. What am I doing wrong? A: You're passing the pointer by value. You need to pass a pointer to a pointer if you want the change the value of the caller's pointer: int main(int argc, char **argv) { struct Abc *db = NULL; demo_fill(&db); printf("%d\n",db->test); return 0; } void demo_fill(struct Abc **data) { int i; for( i = 0; i < 5; i++ ) { struct Abc *new; new = malloc(sizeof(struct Abc)); new->test = i; new->next = *data; *data = new; } }
{ "pile_set_name": "StackExchange" }
Q: Custom roles in ASP.NET I am working on an ASP.NET website which uses forms authentication with a custom authentication mechanism (which sets e.Authenticated programmatically on protected void Login_Authenticate(object sender, AuthenticateEventArgs e)). I have an ASP.NET sitemap. Some elements must be displayed only to logged in users. Others must be displayed only to one, unique user (ie. administrator, identified by a user name which will never change). What I want to avoid: Set a custom role provider: too much code to write for a such basic thing, Transform the existing code, for example by removing sitemap and replacing it by a code-behind solution. What I want to do: A pure code-behind solution which will let me assign roles on authenticate event. Is it possible? How? If not, is there an easy-to-do workaround? A: As Matthew says, building a principal and setting it yourself at the right moment is the easiest way to take advantage of all of the built in Role based goodies like SiteMap. But there is a much easier standards based method of implementing this than shown by MSDN. This is how I implement a simple role provider Global.asax using System; using System.Collections.Specialized; using System.Security.Principal; using System.Threading; using System.Web; using System.Web.Security; namespace SimpleRoles { public class Global : HttpApplication { private static readonly NameValueCollection Roles = new NameValueCollection(StringComparer.InvariantCultureIgnoreCase) { {"administrator", "admins"}, // note, a user can be in more than one role {"administrator", "codePoets"}, }; protected void Application_AuthenticateRequest(object sender, EventArgs e) { HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie != null) { FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); Context.User = Thread.CurrentPrincipal = new GenericPrincipal(Context.User.Identity, Roles.GetValues(ticket.Name)); } } } } To manually check the user in the context of a Page codebehind: if (User.IsInRole("admins")) { // allow something } Elsewhere just get the user off of the current context if (HttpContext.Current.User.IsInRole("admins")) { // allow something }
{ "pile_set_name": "StackExchange" }
Q: Why does mapStateToProps only update in this strange way ? (And what can be done about it ?) Using redux with react-native found that mapStateToProps updates only when another running phone-app window is switched into first. For example with the test code below expected the steps: Default Start test text is displayed. Press Dispatch Text Action button to yield: Updated Changed text is displayed instead of Start instead have: Need to switch to another running app window (Ex: Clock app), and then switch back to development app. Updated Changed text is displayed instead of Start The mapStateToProps function doesn't update the component unless we switch back and forth between the app windows first. Any ideas? Test code reducer import { combineReducers } from 'redux'; const test = (state = 'Start', action) => { switch(action.type){ case 'ADD': return('Changed') default: return state } } export default combineReducers({ test }) test action + container import { connect } from 'react-redux' import TestComp from '../components/TestComp' const mapStateToProps = (state) => ({ test: state.test }) const mapDispatchToProps = (dispatch) => ({ testDispatch: () => dispatch({type: 'ADD'}) }) export default connect( mapStateToProps, mapDispatchToProps )(TestComp) component import React, { Component } from 'react' class TestComp extends Component{ constructor(props){ super(props) this.test = props.test this.testDispatch = props.testDispatch } render(){ return( <View> <Text> {this.test} </Text> <Button title='Dispatch Test Action' onPress={() => this.testDispatch()} /> </View> ) } } export default TestComp A: The issue is that you are capturing the value of props.test in your constructor. This.test is never updated again for the lifecycle of the object, which is why you don't see the updates. Instead, you should remove this.test inside your TestComp component and use this.props.test instead.
{ "pile_set_name": "StackExchange" }
Q: Who generates HTTPS session keys? Some sources says that the web browser generates the session key. Now if the web browser generates it then its vulnerable for replay attacks. Also some sources says that the server generates a part of it and the rest the client generates. How does HTTPS generate session keys? A: Both the client and the server generate a Nonce which is used along with other data to generate the "Pre-Master Secret". Even after the connection has closed a session can be resumed and the same "Master Secret" is used. All of this is covered in The first few milliseconds of an HTTPS Connection.
{ "pile_set_name": "StackExchange" }
Q: How to update X++ map I would like to change value for the key in map. How can I do it? Is it possible? I have found only method insert(_key,_value) but I don't want to create new key with value, but change the value for the existing key. A: How to edit the key Just remove the old key, then reinsert with the new key. map = new Map(Types::String,Types::Real) map.insert("a", 1); map.insert("b", 2); map.insert("c", 3); map.remove("b"); // remove key map.insert("y", 2); // reinsert new key with value How to edit the value Just reinsert the value with insert. The key cannot have duplicates, instead it overwrites. Return Value Type: boolean true if the key did not already exist in the map and has been inserted; otherwise, false. Remarks If the key already exists in the map, the value is updated. For example to manually sum line amount grouping on item group: Map map = new Map(Types::String,Types::Real); SalesLine sl; while select sl where sl.SalesId == "123" { map.insert(sl.ItemGroup, sl.LineAmount + (map.exists(sl.ItemGroup) ? map.lookup(sl.ItemGroup) : 0); } Is equivalent to but performance-wise inferior to: select sum(LineAmount) sl group ItemGroup where sl.SalesId == "123";
{ "pile_set_name": "StackExchange" }
Q: SQL Server 2005: Insert one to many (1 Order-Many Charges) results into @table I have a list of Orders Orders OrderID CustomerID ProductID ------------------------------------- 1 32 15 2 16 28 3 7 20 4 32 16 and a list of charges which need to be applied to these Orders Charges ChargeID CustomerID ProductID Charge Desc -------------------------------------------------------------------- 1 32 0 8.99 Basic Cost Per Order 2 32 15 10.05 Subcharge: Delivery 3 16 28 8.99 Basic Cost Per Order 4 16 0 16.05 Subcharge: Delivery 5 7 20 17.99 Basic Cost Per Order Note: In charges, if a ProductID = 0, it means that the charge will be applied to all products. e.g. Charge 1 - the 8.99 will apply to all Products for Customer 32 Charge 2 - the 10.05 will only apply to product ID=15 for Customer 32 Thus: OrderID = 4 will not have the Subcharge Delivery since the ProductID is not found for customer 32 Question is : How do I fill the @tempQuote table with quotes for these orders? The required resultset in this case would thus be: OrderID ChargeID -------------------- 1 1 1 2 2 3 2 4 3 5 4 1 The problem is that I just can't simple insert the OrderIDs into the @tempQuotes table, and then apply charges, because there could be multiple charges and then I get the error Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , > >, >= or when the subquery is used as an expression Gold medal would obviously have been if there were some means of : if there are multiple charges, then for each multiple charge insert the orderid/chargeID into the @tempQuotes table e.g. Update the @tempQuotes table if there is only 1 row, or if there are multiple charges then insert each Order/Charge OR save into a @tempQuotes additional column all the ChargeIDs that apply e.g. OrderID, ChargeID 1 1,2 as opposed to updating the charges like for e.g. Insert into @tempQuotes(OrderID) select OrderID from #Orders Update t set ChargeID = (Select #Charges.ChargeID from @tempQuotes t inner join #Orders on t.OrderID = #Orders.OrderID inner join #Charges on #Orders.CustomerID = #Orders.CustomerID) from @tempQuotes t select * from @tempQuotes Setup of tables: IF OBJECT_ID('tempdb..#Orders') IS NOT NULL BEGIN drop table #Orders END IF OBJECT_ID('tempdb..#Charges') IS NOT NULL BEGIN drop table #Charges END create table #Orders( OrderID int identity(1,1), CustomerID int, ProductID int, ) Insert into #Orders(CustomerID,ProductID) values (32,15) Insert into #Orders(CustomerID,ProductID) values (16,28) Insert into #Orders(CustomerID,ProductID) values (7,20) Insert into #Orders(CustomerID,ProductID) values (32,16) create table #Charges( ChargeID int identity(1,1), CustomerID int, ProductID int, Charge decimal(10,2), [Desc] nvarchar(50), ) Insert into #Charges(CustomerID,ProductID,Charge,[Desc]) values (32, 0, 8.99, 'Basic Cost Per Order') Insert into #Charges(CustomerID,ProductID,Charge,[Desc]) values (32, 15, 10.05, 'Subcharge: Delivery') Insert into #Charges(CustomerID,ProductID,Charge,[Desc]) values (16, 28, 8.99, 'Basic Cost Per Order') Insert into #Charges(CustomerID,ProductID,Charge,[Desc]) values (16, 0, 16.05, 'Subcharge: Delivery') Insert into #Charges(CustomerID,ProductID,Charge,[Desc]) values (7, 20, 17.99, 'Basic Cost Per Order') declare @tempQuote table( OrderID int, ChargeID int ) declare @tempQuote table( OrderID int, ChargeID int ) A: This should work: SELECT O.OrderId, C.ChargeId FROM Orders O JOIN Charges C ON O.CustomerId = C.CustomerId AND (C.ProductId = O.ProductId OR C.ProductId = 0) ORDER BY O.OrderId, C.ChargeId Here is the sample Fiddle. And it produces these results: ORDERID CHARGEID 1 1 1 2 2 3 2 4 3 5 4 1
{ "pile_set_name": "StackExchange" }
Q: Safe implementation of script tag hack to do XSS? Like a lot of developers, I want to make JavaScript served up by Server "A" talk to a web service on Server "B" but am stymied by the current incarnation of same origin policy. The most secure means of overcoming this (that I can find) is a server script that sits on Server "A" and acts as a proxy between it and "B". But if I want to deploy this JavaScript in a variety of customer environments (RoR, PHP, Python, .NET, etc. etc.) and can't write proxy scripts for all of them, what do I do? Use JSONP, some people say. Well, Doug Crockford pointed out on his website and in interviews that the script tag hack (used by JSONP) is an unsafe way to get around the same origin policy. There's no way for the script being served by "A" to verify that "B" is who they say they are and that the data it returns isn't malicious or will capture sensitive user data on that page (e.g. credit card numbers) and transmit it to dastardly people. That seems like a reasonable concern, but what if I just use the script tag hack by itself and communicate strictly in JSON? Is that safe? If not, why not? Would it be any more safe with HTTPS? Example scenarios would be appreciated. Addendum: Support for IE6 is required. Third-party browser extensions are not an option. Let's stick with addressing the merits and risks of the script tag hack, please. A: Apologies to all who attempted to answer my question. It proceeded under a false assumption about how the script tag hack works. The assumption was that one could simply append a script tag to the DOM and that the contents of that appended script tag would not be restricted by the same origin policy. If I'd bothered to test my assumption before posting the question, I would've known that it's the source attribute of the appended tag that's unrestricted. JSONP takes this a step further by establishing a protocol that wraps traditional JSON web service responses in a callback function. Regardless of how the script tag hack is used, however, there is no way to screen the response for malicious code since browsers execute whatever JavaScript is returned. And neither IE, Firefox nor Webkit browsers check SSL certificates in this scenario. Doug Crockford is, so far as I can tell, correct. There is no safe way to do cross domain scripting as of JavaScript 1.8.5.
{ "pile_set_name": "StackExchange" }
Q: Converting a color image to grayscale issue in OpenCV I'm facing a problem, when I'm trying to convert a color image to a grayscale. The error is: "bad argument (array should be CvMat or IplImage) in cvGetSize", but I can manage to load the original color image and display it, when I'm commenting all the lines, which are related to the grayscale one. How can I fix this error ?. #include <opencv\cv.h> #include <opencv\highgui.h> #include <iostream> #include <stdio.h> int main(int argc, char** argv) { //Loading the color image IplImage* frame = cvLoadImage("lena.jpg"); //Converting the color image to grayscale IplImage* grayframe = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 1); cvCvtColor(frame, grayframe, CV_RGB2GRAY); //Creating a window for color image cvNamedWindow("Example1", CV_WINDOW_AUTOSIZE); //Creating a window for grayscale image cvNamedWindow("Example2", CV_WINDOW_AUTOSIZE); // Showing the color image cvShowImage("Example1", frame); // Showing the grayscale image cvShowImage("Example2", grayframe); //Showeing for X seconds cvWaitKey(2000); cvReleaseImage(&frame); cvDestroyWindow("Example1"); cvReleaseImage(&grayframe); cvDestroyWindow("Example2"); return 0; } A: why Iplimage ? try with Mat, if you would like to extend the examples in future. Mat image = imread("lena.jpg"); Mat gray; cvtColor(image,gray,CV_BGR2GRAY); this would with ease, will give you gray scale image. But, if there is a specific reason to use C api, then, the problem is at IplImage* grayframe = cvCreateImage(cvGetSize(frame), IPL_DEPTH_8U, 1); I don't know the exact reason for that, but, I could give you an alternative to run your code. int x= frame->width, y=frame->height; IplImage* grayframe = cvCreateImage(cvSize(x,y), IPL_DEPTH_8U, 1); Tyr it, it might work for you
{ "pile_set_name": "StackExchange" }
Q: apache spark stand alone connecting to mongodb with scala using casbah i would like to perform a Apache Spark map-reduce on 5 files and output them to mongodb. I would prefer not using HDFS since NameNodes are a single point of failure (http://wiki.apache.org/hadoop/NameNode). A. Is it possilbe to read multiple files in RDD, perform a map reduction on a key from all the files and use the casbah toolkit to output the results to mongodb B. Is it possible to use the client to read from mongodb into RDD, perform a map reduce and right output back to mongodb using the casbah toolkit C. Is it possible to read multiple files in RDD, map them with keys that exist in mongodb, reduce them to a single document and insert them back into mongodb I know all of this is possible using the mongo-hadoop connector. I just dont like the idea of using HDFS since it is a single point of failure and backUpNameNodes are not implemented yet. Ive read some things on line but they are not clear. MongoDBObject not being added to inside of an rrd foreach loop casbah scala apache spark Not sure whats going on there. The JSON does not even appear to be valid... resources: https://github.com/mongodb/casbah http://docs.mongodb.org/ecosystem/drivers/scala/ A: Yes. I haven't used MongoDB, but based on other things I've done with Spark, these should all be quite possible. However, do keep in mind that a Spark application is not typically fault-tolerant. The application (aka "driver") itself is a single point of failure. There's a related question on that topic (Resources/Documentation on how does the failover process work for the Spark Driver (and its YARN Container) in yarn-cluster mode), but I think it doesn't have a really good answer at the moment. I have no experience running a critical HDFS cluster, so I don't know how much of a problem the single point of failure is. But another idea may be running on top of Amazon S3 or Google Cloud Storage. I would expect these to be way more reliable than anything you can cook up. They have large support teams and lots of money and expertise invested.
{ "pile_set_name": "StackExchange" }
Q: Jargon professionnel : "suivi de la capacité" Dans mon milieu professionnel (industrie des technologies de l'information), on peut être amené à user de l'expression "suivi capacitaire" pour exprimer un "suivi de la capacité de quelque chose" (par exemple, au sujet de la capacité de stockage d'un serveur). Or il me semble que l'usage soit incorrect, car l'adjectif capacitaire se rapporte au suffrage (voir sur CNRTL) et donc plutôt à une capacité légale qu'à une capacité mesurable en volume. Un adjectif plus correct, dérivé du substantif "capacité", moins jargonisé si je puis me permettre, vous vient-il à l'esprit ? A: Peut-être « suivi quantitatif » : un peu comme « volumétrique » mais ce dernier est déjà utilisé pour autre chose. Ou peut-être « suivi des niveaux » comme s'il s'agissait d'une rivière qui risquait déborder. Ou « suivi du stockage ».
{ "pile_set_name": "StackExchange" }
Q: Promise is not a function? I'm getting a pretty standard error that I should be able to figure out but I am stuck like chuck ATM: first_query(): TypeError: ind_promise is not a function I have simplified the code down to its very basic core components and I cannot shake this error. router.get('/:cusId/email/start', auth.check, async (req, res) => { try { let cus_id = req.params.cusId; const pool = await poolPromise; let query; let request; query = ("SELECT (CUS_FIRST_NAME + ' ' + CUS_LAST_NAME) AS CUS_NAME, CUS_IND_ID FROM CUS WHERE CUS_STATUS = 'A' AND CUS_ID = @CUS_ID"); request = pool.request() .input('CUS_ID', sql.Int, cus_id); std.first_query(request, query) .then(async function(cus_rec) { let ind_promise = new Promise ((resolve, reject) => { resolve (1); }); ind_promise() .then((ind_id) => { console.log(ind_id); }) .catch((err) => { console.log('ind_promise(): ' + err.message); res.status(500); res.send(err.message) }); }) .catch (function(err) { console.log('first_query(): ' + err); res.status(500); res.send(err.message) }); } catch { console.log(err.message); res.status(500); res.send(err.message) } }); This is more than a little irritating as I am not new to promises. I know I am doing something very stupid but it's not obvious. Experts, please help. A: You called your promise right away and then you tried to invoke it like its a function let ind_promise = new Promise ((resolve, reject) => {resolve (1);}); ind_promise() Either change ind_promise to be a function, or call it without invoking it ind_promise.then
{ "pile_set_name": "StackExchange" }
Q: linux issue setenv command not found I develop a Tcl/Tk script tool in Linux. In order to run the tool, every time I need to set the environment variable like this in shell: setenv LD_LIBRARY_PATH /opt/lsf/9.1/linux2.6-glibc2.3-x86_64/lib:/abc/software/new_2015/GE/tcl_tk/lib64:/abc/software/new_2015/GE/tcl_tk/lib64 and then use "wish" interpreter to launch my tool: /abc/software/new2015/GE/tcl_tk/bin/wish mytool.tk To make it a little easy to use, I want design a shell script "abc_wish" and put the above command inside: #!/bin/sh setenv LD_LIBRARY_PATH /opt/lsf/9.1/linux2.6-glibc2.3-x86_64/lib:/abc/software/new_2015/GE/tcl_tk/lib64:/abc/software/new_2015/GE/tcl_tk/lib64 wish="/abc/software/new2015/GE/tcl_tk/bin/wish" exec $wish $@ And then I need just run: ./abc_wish mytool.tk But error message shows that setenv command not found!I am totally new to such system issues, need some help about these stuffs. Hope I have shown the issue clearly. A: setenv is a csh command, not a sh command. The equivalent in bash is export: #!/bin/sh export LD_LIBRARY_PATH=/opt/lsf/9.1/linux2.6-glibc2.3-x86_64/lib:/abc/software/new_2015/GE/tcl_tk/lib64:/abc/software/new_2015/GE/tcl_tk/lib64 exec wish "$@" You should also put $@ in quote, to ensure proper re-quoting of the expansion.
{ "pile_set_name": "StackExchange" }
Q: ErrorPage class deprecated in Spring Boot 1.4 In my working Spring Boot 1.4 application, I currently have import org.springframework.boot.context.embedded.ErrorPage; According to the documentation, as of 1.4 this class is deprecated in favor of org.springframework.boot.web.ErrorPage However, when I change the code to import org.springframework.boot.web.ErrorPage; I get an error The import org.springframework.boot.web.ErrorPage cannot be resolved How can this be fixed? A: The javdoc's wrong. The correct replacement is org.springframework.boot.web.servlet.ErrorPage. I've opened an issue so that we can fix the javadoc. Thanks for letting us know.
{ "pile_set_name": "StackExchange" }
Q: validating a sql element exists in mvc c# Hey guys I am trying to validate that a username exists in a database. I am having an issue with checking it against the database to see if that username exists. I have done some research and have no found that correct way to do it in mvc ( new to asp.net and mvc). If anybody could just point me in the right direction it would be greatly appreciated! Here is my validation method: private bool isValid(string UserName, string Password) { bool isValid = false; var user = db.User.Where(u => u.UserName == UserName); if (user != null) { isValid = true; } return isValid; } So far it lets anybody log in even if they aren't in the database. A: Try var user = db.User.Where(u => u.UserName == UserName).FirstOrDefault();
{ "pile_set_name": "StackExchange" }
Q: Javascript array access in Internet Explorer I've a HTML code snippet like follows: <form> <select name="mySelect"> <option value="1">text_1</option> <option value="2">text_2</option> </select> </form> I found out that in Internet Explorer, Javascript below can work: document.forms[0].mySelect.options(0).text But in Firefox or Chrome, it can not work and reports such error message: document.forms[0].mySelect.options is not a function In my opinion, mySelect.options should be an array, thus must be accessed by mySelect.options[0]. I also checked the DOM api and found no options function available. Does it mean in the IE javascript engine, all arrays can be treated as both a collection and a function? Any advice will be appreciated, thanks in advance! A: Notice, that options is not an array, it's HTMLCollection, which is an array-like object. This is also a host object, hence it can behave differently from JS objects. In IE you can call HTMLCollection as it was a function (at least in older IEs): select.options(vIndex [, iSubIndex] ); Here vIndex is either an integer representing an index, or a string referring name property. As you can have multiple similar names, iSubIndex is used to construct a collection of all elements that have a name or id property equal to the string, and then retrieves from this collection the element at the position specified by iSubIndex.
{ "pile_set_name": "StackExchange" }
Q: Orion internal server error with query operation (overflow sort) Using Orion context broker, sometimes I get the following error message when doing paginated queries (e.g. POST /v1/queryContext?offset=3900&limit=100): [{ "contextElement": { "type": "device", "id": ".*", "isPattern": "true"} "statusCode": { "code": "500", "details": "Error at querying MongoDB", "reasonPhrase": "Internal Server Error" } }] Looking into Orion log I find the following message: Database Error (Runner error: Overflow sort stage buffered data usage of 33557262 bytes exceeds internal limit of 33554432 bytes) How can I solve this problem, please? A: According to existing information (this and this), it could be due to an index is needed for the field used for sorting. Orion uses creDate for sorting entities result, so creating an index for that field could help, e.g.: db.entities.ensureIndex( { creDate: 1 } ) More information about recommended indexes for Orion can be found in the following section of the Orion manual.
{ "pile_set_name": "StackExchange" }
Q: IE7 dropdown menu moves to top, and jquery not showing The site in question is: http://shabalala.codedprojects.co.za/ You'll see the site has a dropdown menu at the top, which works fine except in IE7, it doesn't sit below the top nav but instead goes to the top of the page. Why is this? On the home page as well, there are two sections at the bottom, Latest News and Specials, which don't display at all on IE7. Is there something I can do to fix this as well? A: Try to remove top:100% for IE 7 in "nav ul ul" class..
{ "pile_set_name": "StackExchange" }
Q: How to get a value of arabic text from input text through change load function jquery I need to get a value (full names) in Arabic letters from input field so I can run a query using this value. I noticed when I typed in Arabic the javascript code did not work properly and I noticed as well if I make space between the words in English text the javascript code will catch only the first word and the other words will be missed. How can I solve this problem. I looking for the most sample way HTML Code <input type="text" name="member" id="member" class="input_field" required /> <div class="modal-body" id="fifth-choice"></div> Javascript Code $("#member").change(function() { $("#fifth-choice").load("menu1.php?member="+$("#member").val()); }); Many thanks A: Try to encode the url parameter by encodeURI $("#member").change(function() { $("#fifth-choice").load("menu1.php?member="+encodeURI($("#member").val())); });
{ "pile_set_name": "StackExchange" }
Q: WebGet with No Parameters or UriTemplate Fails I have a RESTful WCF web service with the following API: [WebGet(ResponseFormat = WebMessageFormat.Json)] MyResponseContract GetFileInfo(); When attempting to hit endpoint (using SOAPUI) I see the following error message: The server encountered an error processing the request. Please see the service help page for constructing valid requests to the service. I have SOAPUI set to hit it with a GET method call. When I switch it to a POST with no body, it fails with the following message: Method not allowed. This makes perfect sense: can't hit a GET with a POST. So I updated my code as follows: [WebInvoke(ResponseFormat = WebMessageFormat.Json)] MyResponseContract GetFileInfo(); And now I call it from SOAPUI with a POST method and it works. Curious. So I now change my code as follows: [WebInvoke(ResponseFormat = WebMessageFormat.Json, Method = "GET")] MyResponseContract GetFileInfo(); I've seen in a few posts that this is essentially equivalent to a WebGet attribute. This also does not work. So my question is: why doesn't this work as a WebGet even though I am not accepting parameters or using a custom UriTemplate? The Url I'm trying to hit it with (it's hosted locally in IIS) is: http://localhost/Utilities/API/GetFileInfo Update Given the comments below and the given answers, I am still faced with this problem. Some additional details. My web-layer web.config <?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> <customErrors mode="Off" /> </system.web> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <standardEndpoints> <webHttpEndpoint> <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" maxReceivedMessageSize="10000000" /> </webHttpEndpoint> </standardEndpoints> <behaviors> <endpointBehaviors> <behavior name="exampleBehavior"> <callbackDebug includeExceptionDetailInFaults="true" /> <enableWebScript /> <webHttp helpEnabled="true" /> </behavior> </endpointBehaviors> </behaviors> <bindings> <webHttpBinding> <binding name="WebHttpBinding" maxReceivedMessageSize="10000000" /> </webHttpBinding> </bindings> <client> <endpoint address="http://LOCALHOST/Utilities.AppService/API" binding="webHttpBinding" bindingConfiguration="WebHttpBinding" contract="Utilities.Common.API.IMyApi" behaviorConfiguration="exampleBehavior" /> </client> </system.serviceModel> </configuration> My app-layer web.config: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> <customErrors mode="Off" /> </system.web> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <standardEndpoints> <webHttpEndpoint> <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" maxReceivedMessageSize="10000000" /> </webHttpEndpoint> </standardEndpoints> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true" /> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer> </configuration> My service interface [ServiceContract(Namespace = "API")] public interface IMyApi { [WebGet] MyResponseContract GetFileInfo(); } My web-layer implementation [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)] public class MyApiWebService : ClientBase<IMyApi>, IMyApi { public MyResponseContract GetFileInfo() { return Channel.GetFileInfo(); } } My app-layer implementation [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)] public class MyApiAppService : IMyApi { public MyResponseContract GetFileInfo() { return new MyResponseContract(); } } My web-layer Global.asax: protected void Application_Start(object sender, EventArgs e) { RouteTable.Routes.Add(new ServiceRoute("API", new WebServiceHostFactory(), typeof(MyApiWebService))); } My app-layer Global.asax: protected void Application_Start(object sender, EventArgs e) { RouteTable.Routes.Add(new ServiceRoute("API", new WebServiceHostFactory(), typeof(MyApiAppService))); } I'm not sure how much more detail I can provide. As you can see, given the solutions provided, I have implemented everything suggested to no avail. Whether I am trying to hit this WebGet method by placing the web layer service url in the browser, or using SOAPUI, or trying to hit it with a C# unit test using a service client, I am unable to use WebGet. Thanks again for all of your help. And interesting note is that the App-layer URL works. But the web layer does not. So: localhost/Utilities.AppService/API/GetFileInfo works, whereas localhost/Utilities.WebService/API/GetFileInfo does not. A: So this may not have been obvious until I updated recently, but I have two RESTful services that communicate with each other but live in separate domains. The Web-Layer service is the first point of contact and the App-Layer service is the actual work-doer. This being the case, I was able to debug a bit further and found that the actual exception was a 405 (Method Not Allowed) on the call from the Web to App layers. I found this link after much digging that solved my issue. When using ClientBase<> as you method of communication between services you essentially need to reestablish the operation context between calls. Otherwise everything becomes a POST and, as such, only POSTs work. I hope this helps others, and I greatly appreciate everyone's help in debugging this. To demonstrate what this looks like, here is what my updated, working web service implementation looks like: [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)] public class MyApiWebService : ClientBase<IMyApi>, IMyApi { public MyResponseContract GetFileInfo() { MyResponseContract output = null; using(var context = new OperationContext(Channel as IContextChannel)) { output = Channel.GetFileInfo(); } return output; } } A: The .NET WCF web service by default is set up to send text encoded SOAP messages. This means that the HTTP method is POST and there are required headers to tell the service what method to call. I created a quick example using your service endpoint and here is the request generated from fiddler to talk to that endpoint. POST http://localhost/Utilities/API/GetFileInfo/Service1.svc HTTP/1.1 Content-Type: text/xml; charset=utf-8 SOAPAction: "http://tempuri.org/IService1/GetFileInfo" Host: localhost:8888 Content-Length: 136 Expect: 100-continue Connection: Keep-Alive <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><GetFileInfo xmlns="http://tempuri.org/"/></s:Body></s:Envelope> Getting back a response of HTTP/1.1 200 OK Cache-Control: private Content-Length: 398 Content-Type: text/xml; charset=utf-8 Server: Microsoft-IIS/8.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-8?B?QzpcV29ya1xFSVAgV29ya1xRdWVzdGlvbnNcV0NGR2V0VGVzdFxTZXJ2aWNlMS5zdmM=?= X-Powered-By: ASP.NET Date: Thu, 21 May 2015 19:47:49 GMT <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><GetFileInfoResponse xmlns="http://tempuri.org/"><GetFileInfoResult xmlns:a="http://schemas.datacontract.org/2004/07/WCFGetTest" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><a:BoolValue>true</a:BoolValue><a:StringValue>MyResponseContract </a:StringValue></GetFileInfoResult></GetFileInfoResponse></s:Body></s:Envelope> For you I think something in your SoapUI is not set correctly. Either the post data or the headers.
{ "pile_set_name": "StackExchange" }
Q: How to mass-create maps with different features centered? Can anyone explain if this is something that can be done? I have map consisting of a little under 40,000 acres. I would like to print a map based on the legal location with each section being centered on a separate map at a scale of 1:1,000, for a total of 130 individual maps. Each map will have the same data, the only thing that will change from map to map is the feature that is centered. Is it possible to have arc auto-create a map for each feature? I am using ArcMap 10.1 for desktop. A: You can do this using Data Driven Pages (DDP). Here is a basic guide for setting up DDP in ArcMap. I have started with some random polygons and points I created Turn on the Data Driven Pages toolbar (Customize > Toolbars > Data Driven Pages) and click on the Setup button In the Set Up Data Driven Pages dialog, select the layer you want to loop through (can be a page grid, or any other layer), and if you have any of the extra fields in that layer, such as Rotation, Page Number, etc. you can specify them in this dialog. If not you can leave them blank. Setting these can give you a bit more control over how your pages are displayed. On the next tab you can set your scale settings - easiest option here, if you want them all at 1:1000, is to just choose Center and Maintain Current Scale, and then you can set your layout scale to 1:1000 and it'll keep it at that. Alternatively you can play around with the other options here for potentially better results. On my Layout I have added scale text and from the Insert menu I have added some dynamic text which references a field I specified from within my polygon layer. This will display the text from that field for the polygon that is displayed on each page. And the end result is a number of pages that pan to each record as I step through them (using the buttons on the DDP toolbar), and the text updates for each new page. ArcMap can automatically step through each page when you export or print your map. This is done using the Pages tab in Export Map dialog's Options section, or the Data Driven Pages section of the Print dialog Export Map options: Print dialog options:
{ "pile_set_name": "StackExchange" }
Q: Convert Url with php How can I convert a string like this: [www.example.com?type=PC&brand=Dell&id=2] to [www.example.com/PC/Dell/2.html] thz for your help! A: If you want to map the first link into the second, to make the URLs on your site prettier, go with .htaccess and Mod_rewrite! This is the correct solution: $str = "[www.example.com?type=PC&brand=Dell&id=2]"; $str = trim($str,"[]"); //Remove square brackets, we'll add them back later $url = parse_url($str); //Parse the URL into an array $query = $url["query"]; //Part after the ? $parts = explode("&", $query); //Have each GET variable into an array element $parts = array_map(function($e) { return preg_replace("/[^=]+=/", "", $e); }, $parts); //Remove the part before the =. $parts = implode("/", $parts); //Implode it back into a string. $result = $url["path"] . "/" . $parts . ".html"; //Putting it back together $result = "[$result]"; //I promised I'll put it back! var_dump($result); A: Try this in your .htaccess Options +FollowSymLinks RewriteEngine on RewriteRule /(.*)/(.*)/(.*)\.html www.example.com?type=$1&brand=$2&id=$3
{ "pile_set_name": "StackExchange" }
Q: Where does local.properties go for android project? Getting this complaint from IntelliJ 13: 8:15:48 PM Gradle '<project>' project refresh failed: SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable. Build file '/<project>/build.gradle' line: 20 : Gradle settings I have tried to spam my local.properties in every directory I can think of but still getting this error. What gives? A: The local.properties file goes in the project's root level, in the same folder as the gradlew, gradlew.bat, settings.gradle and other files. This file should not be included in source control. After (incorrectly) including this in source control, then deleting the file locally, Android Studio re-created the file for me automatically. Here is the example content of this file: ## This file is automatically generated by Android Studio. # Do not modify this file -- YOUR CHANGES WILL BE ERASED! # # This file must *NOT* be checked into Version Control Systems, # as it contains information specific to your local configuration. # # Location of the SDK. This is only used by Gradle. # For customization when using a Version Control System, please read the # header note. #Thu Aug 14 14:49:26 PDT 2014 sdk.dir=C\:\\Program Files (x86)\\Android\\android-studio\\sdk Note the sdk.dir= reference to the location of the Android Studio SDK installation (which may be different on different machines). A: For MAC create file local.properties inside android/ and paste this line inside the file sdk.dir = /Users/USERNAME/Library/Android/sdk
{ "pile_set_name": "StackExchange" }
Q: Perfect way to make a header I am creating a web application in Laravel and I have a template for the header element. What I want to do is make the header fixed on the top. I have the following code to do it: .header{ background-color: #ffffff; width: 100%; height: 10%; display: flex; padding: 0.2em 0.2em 0.2em 0.2em; font-family: "Viga"; border: none; position: fixed; } But, the header appears some way down from the page and my margin-top to other elements aren't working as well. So, how do I make the header fixed at the top and still have all other styling working? Thanks A: When you give the height for a fixed element, overlapping issues might be arise, for such cases repel the rest of the content from the header. i.e., here the height of the header is 50px so repel it from the content by giving margin-top:50px; to the content. When you use position:absolute; or position:fixed; use top, left, right, bottom to mention its position where you want it to be Try this .header{ background-color: #ffffff; width: 100%; min-height: 50px; display: flex; /*padding: 0.2em 0.2em 0.2em 0.2em;*/ font-family: "Viga"; border: none; position: fixed; top:0; left:0; } body{background:red; height:7000px;} .content{color:#fff; margin-top:50px;} <header class="header"> <p>Header lays here!</p> </header> <div class="content"> <h1>Content heading</h1> <p>content content content content content content contentcontentcontentcontent contentcontent content content content content content content content</p> </div>
{ "pile_set_name": "StackExchange" }
Q: Python unit testing overriding module level functions Related to Python unit testing code which calls OS/Module level python functions. During my unit testing I overload some python system calls to get my tests to drive different paths of a module. This technique called Monkey Patch (in the related question) for tests in isolation. I am a bit worried about what happens when I run Python tests in parallel say like in "Nose". What happens when two tests are run in parallel and both want to mock the os.path.exists method? Is there a way to selectively override a system or module function in the context of my test? Take the following for example fixture.py (say that is the module under test) def my_func(): some_stuff test_fixture.py (say this is my test case) class MyTest(unittest.TestCase): def test_mine(self): fixture.my_func = my_new_func fixture.execute_some_func_that_calls_my_func() #What happens if another test is executing at the same time and accesses #my_func I don't want it to start executing my_new_func? A: I don't know if it's the best way, but I generally use try ... finally when I'm doing this in tests, in order to set then restore changes during each test. A brief example of this: class TestRawInput(unittest.TestCase): def test_raw_input(self): orig_raw_input = raw_input try: raw_input = lambda _: 'Alice' self.assertEquals(raw_input(), 'Alice') finally: raw_input = orig_raw_input An alternative could be to create a context manager for doing this, if it's a common operation in tests.
{ "pile_set_name": "StackExchange" }
Q: What is the probability of getting the exact number of expected digits ($0-9$) in $10^6$ digits of $\pi$? I noticed that at $1$ million digits of $\pi$, none of the digits has the "perfect" expected $100{,}000$ occurrences. My question is what is the probability (if the digits are truly random) of at least one of the digits having the "perfect" # of occurrences (in this case $100{,}000$)? To be more accurate as one reader pointed out, what is the probability of $1$ million randomly generated digits from $0$ to $9$ having this property? A: First an exact answer, then an approximate one. The number of sequences in which the digit $0$ appears exactly 100,000 times is $\binom{1000000}{100000}9^{900000}$. The number of sequences in which $0$ and $1$ each appear exactly 100,000 times is $\binom{1000000}{100000}\binom{900000}{100000}8^{800000}$. In general, the number of sequences in which the first $k$ digits each appear exactly 100,000 times is $$ (10 - k)^{1000000 - 100000k} \prod_{i=0}^{k-1} \binom{1000000 - 100000i}{100000}.$$ Using the inclusion-exclusion formula, the probability of at least one digit appearing exactly 100,000 times is $$10^{-1000000}\sum_{k = 1}^{10} (-1)^{k-1} \binom{10}{k} (10 - k)^{1000000 - 100000k} \prod_{i=0}^{k-1} \binom{1000000 - 100000i}{100000}.$$ I'm not sure what this number works out to be (though it seems feasible to put it into a computer), but if you call $X$ the number of times you get the digit $1$, it can be approximated by a normal variable with mean 100,000 and standard deviation $[1000000 (0.1)(0.9)]^{1/2} = 300$. So the probability that $X = 100000$ will be quite close to $\frac{1}{300\sqrt{2\pi}}$. I think the probability of more than one digit occurring exactly 100,000 times is relatively small, so I would expect the answer to be quite close to $10$ times this number, namely $\frac{1}{30\sqrt{2\pi}}$. This estimate can be improved by using a normal (or Stirling) approximation for the second term in the formula above. EDIT: The first-level approximation gives you a probability of 1.3298%. The more accurate second-level approximation gives you a probability of 1.3218%. EDIT: Using the full inclusion-exclusion formula, I get $1.321827895126123\%$. A: The problem is equivalent to throwing $N=10^6$ balls into $m=10$ urns (equiprobably) and asking for the probability that at least one urn $i$ has $X_i=N/m$ balls. This can be approximated (Poissonization) as $m$ iid Poisson variables $Y_i$ with mean $\lambda=E(X_i)=N/m$ The probability that one given urn gets $Y_i=\lambda$ balls is $$p = \frac{\lambda^\lambda}{\lambda!} e^{-\lambda} \approx \frac{\lambda^\lambda}{(\lambda/e)^\lambda \sqrt{2 \pi \lambda}} e^{-\lambda}= \sqrt{ \frac{m}{2 \pi N}} \approx 0.00126$$ The probabilty that some ball gets $Y_i=\lambda$ is $ 1-(1-p)^m \approx $ (which can be approximated by $m \, p$ - if you want to). Then, the desired probability is $0.012544\cdots$ Both approximations (the Poissonization and the Stirling formula) can be refined. Anyway, it's seen that the probability decreases as $1/\sqrt{N}$. Notice, BTW, that this gives the probability of "success" for fixed $N=10^6$ , not for all "tries" $n\le N$ - which would be a more difficult problem.
{ "pile_set_name": "StackExchange" }
Q: pyinstaller ImportError: C extension: No module named np_datetime not built I am running a virtual environment with Python 2.7 for my program. There seems to be a problem after creating the executable file on windows. I ran venv/Scripts/pyinstaller.exe -F main.py everything seems fine. But when i click on the created executable main.exe. There is an error. Tried and tested I have re-installed of pandas and pyinstaller Implemented the hook-pandas.py to the hooks folder in the environment. hook-pandas Ensured the environment is activated. Checked that the program is running fine before building executable. Re-created the environment. Yet after all that, I am prompted with this issue [see Importerror] when I run the executable file. It is an extreme pain to debug this because the command prompt displaying the error will not pause but close almost immediately. Similar issues Looking for Suggestions I am hoping for suggestions to troubleshoot Pyinstaller. Any resources to read up on would be nice. Usually, I have no trouble with python as Pycharm has several handy debugging tools that will help me identify the problem A: I ran into the same problem and found this thread, but I managed to solve it borrowing from the reference you posted (about pandas._libs.tslibs.timedeltas), so thank you for that! In that article, the module that resulted in the ImportError was, in fact pandas._libs.tslibs.timedeltas, if you look at the poster's logs. But the error you and I ran into refers to np_datetime instead. So, from the traceback logs, I finally figured out that the code we have to write in hook-pandas.py should be the following: hiddenimports = ['pandas._libs.tslibs.np_datetime'] Maybe that alone will solve your problem, HOWEVER, in my case, once I solved the np_datetime issue, other very similar ImportError problems arose (also related to hiddenimports regarding pandas), so, in case you run into the same issues, just define hiddenimports as follows: hiddenimports = ['pandas._libs.tslibs.np_datetime','pandas._libs.tslibs.nattype','pandas._libs.skiplist'] TL;DR: You can first try to write hiddenimports = ['pandas._libs.tslibs.np_datetime'] into hook-pandas.py. However, if for some reason you run into the exact same issues I did afterwards, try hiddenimports = ['pandas._libs.tslibs.np_datetime','pandas._libs.tslibs.nattype','pandas._libs.skiplist'] If you wish to dive deeper (or run into a different pandas ImportError than the ones I did), this is the code in pandas's __init__.py referenced in your traceback log (lines 23 to 35): from pandas.compat.numpy import * try: from pandas._libs import (hashtable as _hashtable, lib as _lib, tslib as _tslib) except ImportError as e: # pragma: no cover # hack but overkill to use re module = str(e).replace('cannot import name ', '') raise ImportError("C extension: {0} not built. If you want to import " "pandas from the source directory, you may need to run " "'python setup.py build_ext --inplace --force' to build " "the C extensions first.".format(module)) From that I went into the C:\Python27\Lib\site-packages\pandas_libs and C:\Python27\Lib\site-packages\pandas_libs\tslibs folders and found the exact names of the modules that resulted the errors. I hope that solves your problem as it did mine. Cheers!
{ "pile_set_name": "StackExchange" }
Q: largest singular value of gaussian random matrix Let $A = A_{ij}, 1\le i\le n,1\le j\le m,$ be a random matrix such that its entries are iid sub-Gaussian random variables with variance proxy $\sigma^2$. Show that there exits a constant $C>0$ such that $$ E||A|| \le C(\sqrt{m}+\sqrt{n}), $$ where $||A||=\sup_{|x|_2=1}|Ax|_2$ is the operator norm of $A$. This is problem 1.2b in this MIT opencourseware assignment. The result is proven as Theorem 5.32 of these random matrix theory notes, in the special case of gaussian $A_{ij}$, but that result cites another result. Based on the level of the accompanying notes preceding the problem set, I would not expect the cited result to be assumed of the students (I may be wrong of course). So I am wondering about a more direct proof, or whatever the instructor likely had in mind. A: I think you can imitate the proof of Theorem 1.19 from your notes. Apologies if my approach is a little clumsy. One can show that $\|A\| = \sup_{|u|_2 \le 1, |v|_2 \le 1} u^\top A v$. Then $E\|A\| = E[ \sup_{|u|_2\le 1, |v|_2 \le 1} u^\top A v]$. One can obtain an $1/2$-net $\mathcal{N}^n$ over $\mathcal{B}_2^n$ with $6^n$ points. Similarly one obtains a $1/2$-net $\mathcal{N}^m$ over $\mathcal{B}_2^m$ of size $6^m$. So writing $$u^\top A v = (u-x)^\top A (v-y) + x^\top A v + u^\top A y - x^\top A y$$ where $x \in \mathcal{N}^n$, $y \in \mathcal{N}^m$, and $|x-u|_2 \le 1/2$ and $|y-v|_2 \le 1/2$ yields $$E[\sup_{u \in \mathcal{B}_2^n, v \in \mathcal{B}_2^m} u^\top A v] \le E[\sup_{x \in \mathcal{N}^n, y \in \mathcal{N}^m} x^\top A y] + E[\sup_{x \in \mathcal{N}^n, v \in \mathcal{B}_2^m/2} x^\top A v] + E[\sup_{u \in \mathcal{B}_2^n/2, y \in \mathcal{N}^m} u^\top A y] + E[\sup_{u \in \mathcal{B}_2^n/2, v \in \mathcal{B}_2^m/2} u^\top A v]. $$ Rearranging leads to $$\frac{3}{4} E[\sup_{u \in \mathcal{B}_2^n, v \in \mathcal{B}_2^m} u^\top A v] \le E[\sup_{x \in \mathcal{N}^n, y \in \mathcal{N}^m} x^\top A y] + E[\sup_{x \in \mathcal{N}^n, v \in \mathcal{B}_2^m/2} x^\top A v] + E[\sup_{u \in \mathcal{B}_2^n/2, y \in \mathcal{N}^m} u^\top A y].$$ The first term on the right-hand side is the maximum of $6^{n+m}$ sub-Gaussian random variables with variance proxy $\sigma^2$, so it is $\le \sigma \sqrt{2 (m+n) \log 6}$. I believe you can bound the other two terms by doing a further net argument and obtaining the same $c \sigma \sqrt{m+n}$ rate. Finally $\sqrt{m+n} \le \sqrt{m} + \sqrt{n}$.
{ "pile_set_name": "StackExchange" }
Q: How to place images in radio group in android along with radio button in android I want to design radio buttons along with corresponding text and images.when I tried with linear layout inside the radio group,all the radio buttons are enabled.how can fix this A: this is how you can use image as well as radiobutton inside the radiogroup <RadioGroup android:id="@+id/radiogroup" android:layout_width="match_parent" android:layout_height="match_parent"> <RadioButton android:id="@+id/radio0" android:layout_margin="10dp" android:drawableRight="@drawable/ic_launcher_background" android:layout_gravity="center_vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <RadioButton android:id="@+id/radio1" android:layout_margin="10dp" android:drawableRight="@drawable/ic_launcher_background" android:layout_gravity="center_vertical" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </RadioGroup>
{ "pile_set_name": "StackExchange" }
Q: Why do Stackers consistently vote down humorous responses? I've noticed that humorous responses tend to get voted down quickly and regularly. Typically software developers have a keen sense of humor, and nurture it as a survival instinct. It does not make sense to me that Stackoverflow's default group responsive behaviour causes vote downs on humour! What is the driving force behind the peer pressure to answer seriously and in a straight-forward manner? A: There are plenty of websites you can go to if you want humor - SO is supposed to be about providing useful answers to useful questions. That's why I also vote down the "What's your favorite data structure"-type questions. They add little of value to SO - if they were phrased as "What's the best data structure in C++ for representing a phone directory", that would be ideal. I think the powers that be have basically stated that a small amount of programming-related humor is acceptable but they don't want the site being swamped. What I tend to do is look at the content of my "answer". If it provides useful information, I make an answer out of it, even if there's a little humor - see here for example. If it's all humor and not really useful, I'll either put it in as a comment (likely) or just move on (less likely, due to my personality type). A: Because none wants another Slashdot, where you have to dig around about 800 replies down before you get something useful. A: Use comments to make Jokes :) I personally like to Joke too, but I can also understand the more serious minded that jokes are out of place in serious answers, unless you use sarcasm to Joke but present the truth, however sarcasm doesn't seem to be recognizable by many folk here... so ... Right and Funny answers are fine IMHO
{ "pile_set_name": "StackExchange" }
Q: EMMC debug using oscilloscope I am performing electrical validation of EMMC interface using oscilloscope per JEDEC spec. One of the test is to validate setup and hold time for CMD and DATA signal both way (R&W).On scope,I can't tell the difference between data read/write. I was wondering if anyone knows how to tell the difference. Same goes for CMD in vs CMD out. Many thanks' A: If you have control over the firmware driving the eMMC, generate a sync pulse on an unused (or noncritical) GPIO. Then use this pulse to sync your 'scope to the host; now you can differentiate in/out by how delayed they are from the sync. For example, have the controller generate sync then immediately send a polling command on CMD. Now you can look at that command (CMD out) and immediately following it will be the response (CMD in). If you don't have access to the firmware, try putting a resistor in series with the signal. The signal will be a slightly lower voltage on the downstream side of the resistor. Experiment with resistor values to find one that produces a detectable voltage drop without trashing the signal too badly. If you're lucky there might already be a resistor in place for noise filtering and you can work with that.
{ "pile_set_name": "StackExchange" }
Q: Unable to Resolve Symbol on SQL code (PhpStorm issue) I am using PhpStorm 2016.1.2 and have been comfortably using PhpStorm for a couple of years. I have my Storm set up with the Database connection and displaying the MySQL database that my PHP pages connect to. The SQL is usually written within the PHP page in custom functions via a database connection class. An example code chunk: $checkData = $dataBaseSecure->getSelect( "SELECT check_login.fail_id, UNIX_TIMESTAMP(check_login.last_action) AS timer FROM check_login WHERE check_login.ip_addr = ? AND check_login.check_drop = ? ", $data, TRUE); Don't worry about the database PHP wrapper, this style and layout of SQL in PHP has been around on my work for a couple of years, in PhpStorm and works completely and accurately on the server and on all testings. As Of Yesterday (17th June 2016) I don't know what's changed but suddenly PhpStorm is now telling me, on all my SQL strings, across all my Projects: Unable to resolve symbol '<table name>' or Unable to resolve column '<column name>' And also (due to this) PhpStorm no longer carries out any auto-complete or organisation functions as I work on my SQL code. Solutions I've tried I have already tried to invalidate and revalidate my caches based on this answer to a similar question. But that hasn't helped. I have very carefully explored my settings but the PhpStorm Database tab successfully connects to the database, and as far as I'm aware I made no changes to cause this change in behaviour. I have looked over the various (and many) settings in PhpStorm preferences but seen nothing that has shone any light on this issue, or the changes I have tweaked have not resolved it. I have found this answer but this does not seem to apply as my table names are not variables. I have also found this post, which while dated 2014 shows a similar issue but not a suitable solution. I only have one database connection in most projects, but the number of databases doesn't seem to effect if this issue occurs. Fully escaping SQL queries with appropriate backticks around named entities does not resolve the issue. I have correctly configured my SQL dialect to the correct MySQL. Reading related posts I'm found on Stack Overflow has provided no useful information. I have no plugins in PhpStorm that relate to this issue or PHP/MySQL interaction. If you have any ideas how to resolve this please tell me. If you have specific preferences you'd like me to check please let me know and I can add them into the question, (there are so many preferences in PhpStorm I won't post them all here right now, as I'm sure most are not related to this issue). The Key is that this system was working perfectly two days ago!!! A: Please try re-synchronizing your DB schemas -- just in case if it somehow got corrupted or invalid. If it did not give any visual results -- try more radical version of it: close IDE open .idea subfolder for this project (the place where this project settings are stored) delete dataSources.ids file re-open project in IDE re-sync DB structure / re-create DB connection from scratch.
{ "pile_set_name": "StackExchange" }
Q: How to hide correctly input-group-addon span inside input-group I want to dynamically show or hide an input-group-addon inside an input-group. <div class="input-group"> <div class="form-control"></div> <span title="" class="input-group-addon" data-original-title=""> <span class="glyphicon glyphicon-plus"></span> </span> </div> Here is an example The problem is, that as soon as I hide the addon, the input's width isn't correct anymore. Is it generally not recommend to do this or am I doing something wrong? (I searched for a duplicate for this question, but I couldn't find anything) A: You need to use form.form-inline or set container width http://jsfiddle.net/eot1nst7/
{ "pile_set_name": "StackExchange" }
Q: Quotient Sheaves Let $X$ be a ringed space, and $J$ be a sheaf of ideals of the structure sheaf. Define, $Y = \{x\in X ~ | ~ J_x \not = \mathcal{O}_x\}$, this is a closed set. We have an inclusion $i:Y\to X$. Is there categorical justification that, $i_*i^*(\mathcal{O}/J) = \mathcal{O}/J $? I really do not want to work with the tedious constructions to justify that. I know that one has the following exact sequence, $$ 0 \to i_!i^*\mathcal{O}/J \to \mathcal{O}/J \to i_*i^*\mathcal{O}/J \to 0 $$ Now check that $F = i_!i^*\mathcal{O}/J$ has zero stalk for every $x\in X$. If $x\not \in Y$, then $F_x = 0$. If $x\in Y$, then $F_x = \mathcal{O}_x/J_x \not = 0$. And this is unforunate as it prevents the natural map $\mathcal{O}/J \to i_*i^*\mathcal{O}/J$ from being an isomorphism. A: Your exact sequence is wrong. One has the exact sequence (See Exc. I.1.19 in Hartshorne) $$0 \to j_{!}j^* \mathcal O/J \to \mathcal O/J \to i_*i^*\mathcal O/J \to 0,$$ where $i: Y \to X$ is the inclusion of the closed subset and $j: X \setminus Y =: U \to X$ is the inclusion of the open complement. For $x \in Y$, we have $(j_{!}j^* \mathcal O/J)_x=0$. For $x \in U$, we have $(j_{!}j^* \mathcal O/J)_x=(j^* \mathcal O/J)_x = (\mathcal O/J)_{j(x)} = (\mathcal O/J)_x=\mathcal O_x/J_x=0$, since $U$ is precisely the locus, where this quotient vanishes. Hence, we obtain that $\mathcal O/J \to i_*i^*\mathcal O/J$ is an isomorphism.
{ "pile_set_name": "StackExchange" }
Q: Exporting data in grid format splitting the last column I have a list of lists, and I displayed it in grid format. The grid is huge, so I will show here an example: list = {{2, 2, 2, {1, 3}}, {2, 1, 2, {1, 2}}, {1, 2, 2, {1, 4}}} Grid[list, Frame -> All] Now, I would like to export the data in Csv format, so to have 5 variables. What I did so far is: Export["list.csv", list, "CSV"] Problem is that in this way I have only four variables. What I need to do is to "split" the last column in two variables. Indeed, for each row it contains two values. So, in other words, I need to export a data set with five variables (the first column, the second column, the third column, and the values in the last column). In another grid I have a similar but more complicated issue. Here it is: list2 = {{2, 2, 2, {{1, 3} , {1, 2}}}, {2, 1, 2, {{1, 2}, {1, 3}}}, {1, 2, 2, {1, 4}}} Grid[list2, Frame -> All] As you can see, here sometimes I have two pairs of solutions in the last columns, sometimes only one. The data set I would like to export from that is similar to the first one. So, the first three variables correspond to the values in the first three columns. Moreover, I would like to extrapolate 4 variables from the last column (if it reports only a pair of solution, the last two variables should have missing values or whatever). Can someone help me please? Bonus question: is it possible to name the columns of the grid, so to export a data set with the first row containing the name of the variables? A: Is this what you are looking for? list = {{2, 2, 2, {1, 3}}, {2, 1, 2, {1, 2}}, {1, 2, 2, {1, 4}}}; listf = Flatten /@ list (* {{2, 2, 2, 1, 3}, {2, 1, 2, 1, 2}, {1, 2, 2, 1, 4}} *) list2 = {{2, 2, 2, {{1, 3}, {1, 2}}}, {2, 1, 2, {{1, 2}, {1, 3}}}, {1, 2, 2, {1, 4}}}; list2f = Flatten /@ list2 (* {{2, 2, 2, 1, 3, 1, 2}, {2, 1, 2, 1, 2, 1, 3}, {1, 2, 2, 1, 4}} *) max = Length /@ list2f // Max; PadRight[#, max, Null] & /@ list2f (* {{2, 2, 2, 1, 3, 1, 2}, {2, 1, 2, 1, 2, 1, 3}, {1, 2, 2, 1, 4, Null, Null}} *) To add column headings listf // Prepend[{"a", "b", "c", "d", "e"}]
{ "pile_set_name": "StackExchange" }
Q: How do they decide the key? Duke Ellington plays a beautiful solo Take the A Train in 1956 [see youtube live performance is awesome] I think it's in C and most transcripts are in C. But there is a video of him playing with the band years earlier and he calls out: "A Train in A flat". What's going on, does this have to do with band vs solo ? Horn transposing ? How do they decide the key ? A: Different instruments (and the voice, which is different on everybody) have strengths in different ranges. Usually, key choice is meant to capitalize on some particular characteristic of the instrument in question. This is most obvious with the voice. Let's say we're writing a song for a singer whose highest solid note is an A. We have a melody where the triumphant high note at the end is the 5th of the scale. Putting the piece in D makes that high note our singer's nice high A. Or we could key it in C to make it come out a little easier. This is why musical theater is full of such awkward keys--the original singer's best high note was a G-flat, and the high note is the tonic, so G-flat major it is! With saxophone, the core range is (written) D4-F6. The full range does extend past that in both directions, but that's generally where you want to hang out. So if you have control of the key, and you have a good idea of what you want to with it and where those notes should sit on the instrument, you can pick the key strategically. Concert A-flat is an alto sax's F, which is a pretty nice key to play in. A: In jazz, musicians make a habit of being able to play their tunes in all keys. In order to “hang” this is something you just need to know how to do. Part of the reason they did this was because they played the same tunes all the time and it kept them fresh and interesting to play and listen to. The fact that he called out Ab that one time is most likely arbitrary.
{ "pile_set_name": "StackExchange" }
Q: What does it mean for electric current to be a scalar? After reading the reasons for considering electric current as a scalar quantity, I was confused at a point which read "The magnitude and direction of current does not depend upon the direction of the flow of charge, that's why electric current is a scalar." What does it mean? How can it be explained in atomic point of view? A: "...direction of current does not depend upon the direction..." This strikes me as a particularly poorly worded explanation. I might even go as far as to say that it's outright incorrect. There are two equally valid ways to explain why current is a scalar quantity, and not a vector quantity despite the fact that it does move in a particular direction: Current is only measured as the amount of charge passing through a particular cross sectional area. Mathematically this is represented by the following equation: $$I=\int{\int_S{\vec{J}\cdot \hat{n}dA}}$$ where $\vec{J}$ is the current density. Current is the derivative of charge with respect to time. In other words, it's the amount of charge passing through a cross sectional area at any given time, or the amount of charge leaving or entering a particular enclosed area. This is mathematically expressed as $$I=\frac{dq}{dt}$$ Again, a scalar quantity. When measuring a current, there could be several different charge sources flowing in various different directions. Current only measures the net amount of these charges that flows through an area at any given time. Depending on the direction the charge flow is moving, it may contribute more or less to the overall current through the area. When direction is important, current density is normally the quantity considered.
{ "pile_set_name": "StackExchange" }
Q: Internet explorer 11 detection on server side We all know that IE11 detection does not work with server side languages because Microsoft has removed the IE/MSIE browser indication and now is fully "Mozilla". I also know that doing browser detection/version is risky but has served us all well in the past. some requirements for a website are things like: must work with certain version of firefox and above must work with certain version of chrome and above must work with certain version of safari's (some below and some newer) must work with IE >= 8 so here is the problem... IE11 indicates on my list that it is not supported. I want to support it from the web side of things on the server (ASP.NET/MVC) it is not clear exactly how to detect this from the server side. Does anyone know how? this is the user agent now being shown in IE 11: "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko" rv:11.0 tells us its IE11 however doing a parse on that will still mean that for example, it could be chrome of a certain version that is not supported in such a requirement or even firefox. so, what is the best way here to see if it is indeed IE 11 or higher? I am not so sure about searching from "Trident" and onwards because I don't know if other browsers use that or not. any direction is welcomed. A: Use a Regular Expression like: Regex.IsMatch(this.Request.UserAgent, @"Trident/7.*rv:11") Trident is the name of the rendering engine IE uses. Some other applications also use the Trident engine, as you can see in the Wikipedia article. But it shouldn't be a problem to search for Trident in the User Agent, since no other major browsers use Trident. Only IE11 uses Trident version 7 so if you search for Trident/7 with the regex, it should find IE11. A: To maintain compatibility with existing code, I created a custom provider so Request.Browser will return the information as expected. For example, Browser.Browser will be "IE" not "InternetExplorer", which is the new value after the hotfix is installed. Additionally, this approach returns the actual version of IE, not version 7 when in compatibility view. Note that Browser.Type will return "IE7" when in compatibility view in case you need to detect it, or you could easily modify the custom provider to change .Type as well. The approach is simple. Derive a class from HttpCapabilitiesDefaultProvider and set BrowserCapabilitiesProvider to an instance of your class. In Global.asax.cs: protected void Application_Start(Object sender, EventArgs e) { ... HttpCapabilitiesBase.BrowserCapabilitiesProvider = new CustomerHttpCapabilitiesProvider(); ... } Define your class: UPDATED TO INCLUDE MICROSOFT EDGE BROWSER public class CustomerHttpCapabilitiesProvider : HttpCapabilitiesDefaultProvider { public override HttpBrowserCapabilities GetBrowserCapabilities(HttpRequest request) { HttpBrowserCapabilities browser = base.GetBrowserCapabilities(request); // Correct for IE 11, which presents itself as Mozilla version 0.0 string ua = request.UserAgent; // Ensure IE by checking for Trident // Reports the real IE version, not the compatibility view version. if (!string.IsNullOrEmpty(ua)) { if (ua.Contains(@"Trident")) { if (!browser.IsBrowser(@"IE")) { browser.AddBrowser(@"ie"); browser.AddBrowser(@"ie6plus"); browser.AddBrowser(@"ie10plus"); } IDictionary caps = browser.Capabilities; caps[@"Browser"] = @"IE"; // Determine browser version bool ok = false; string majorVersion = null; // convertable to int string minorVersion = null; // convertable to double Match m = Regex.Match(ua, @"rv:(\d+)\.(\d+)"); if (m.Success) { ok = true; majorVersion = m.Groups[1].Value; minorVersion = m.Groups[2].Value; // typically 0 } else { m = Regex.Match(ua, @"Trident/(\d+)\.(\d+)"); if (m.Success) { int v; ok = int.TryParse(m.Groups[1].Value, out v); if (ok) { v += 4; // Trident/7 = IE 11, Trident/6 = IE 10, Trident/5 = IE 9, and Trident/4 = IE 8 majorVersion = v.ToString(@"d"); minorVersion = m.Groups[2].Value; // typically 0 } } } if (ok) { caps[@"MajorVersion"] = majorVersion; caps[@"MinorVersion"] = minorVersion; caps[@"Version"] = String.Format(@"{0}.{1}", majorVersion, minorVersion); } } else if (ua.Contains(@"Edge")) { if (!browser.IsBrowser(@"Edge")) { browser.AddBrowser(@"edge"); } IDictionary caps = browser.Capabilities; caps[@"Browser"] = @"Edge"; // Determine browser version Match m = Regex.Match(ua, @"Edge/(\d+)\.(\d+)"); if (m.Success) { string majorVersion = m.Groups[1].Value; string minorVersion = m.Groups[2].Value; caps[@"MajorVersion"] = majorVersion; caps[@"MinorVersion"] = minorVersion; caps[@"Version"] = String.Format(@"{0}.{1}", majorVersion, minorVersion); } } } return browser; } } A: I solved this by using the Regex below after having a knock out system to check what browser is being used to access the site. in this case, even if the browser "IE" is checked and returns false, I go ahead and use this regex and check to see if it is a match against the user agent: (?:\b(MS)?IE\s+|\bTrident\/7\.0;.*\s+rv:)(\d+) I hope this helps someone. I tested it and works fine. I also changed the rv to be 12 and upwards, and it works fine too in case if in IE12, they change rv to be 12.
{ "pile_set_name": "StackExchange" }
Q: Notation regarding Balls What is meant by the notation : $y \in \partial B_\epsilon (x_o)$ Where B is a Ball centred at $x_0$ with radius $\epsilon$ A: When you are in a normed space, with norm $\|\cdot \|$, then $$\partial B_\epsilon(x_0)=:\{x: \|x-x_0\|=\epsilon\},$$ the boundary of $B_\epsilon(x_0)$. More generally the notation $\partial E$, with $E$ a set, denotes its boundary.
{ "pile_set_name": "StackExchange" }
Q: Sugar forming tiny bubbles in microwaved coffee? When I heat up coffee in the microwave and then pour in sugar, a layer of tiny dense bubbles forms at the top of the glass and stays there for the duration of the drinking, diminishing slightly over time. When I prepare the coffee by other means of heating this does not happen. What causes those tiny bubbles? A: Upon addition of sugar to the superheated coffee, the formation of bubbles (phase transformation) occurs because the fine particles of sugar provide sites for the heterogeneous nucleation of gas from the liquid. When the introduction of a fine inoculant (such as sugar particles) results in sudden fizzing of a liquid, it is an indication that there has been minor superheating of that substance. Superheating tends to occur more in microwaves than on stovetops because people use metal saucepans/kettles on the stove, while generally using glass or glazed ceramic containers when heating a volume of water in a microwave oven. When water is heated in a glass or glazed ceramic container rather than a metal one, the very hard surface of the container means that there are few scratches on it to act as sites for the heterogeneous nucleation of gas. Fewer heterogeneous nucleation sites means less heat loss through the transformation of liquid to gas. This university site also makes a good point about the tendency for stovetop heating to cause localised superheating in the vicinity of the container walls... However, I think that this would tend to cause more boiling due to localised heating to the point that homogenous nucleation can occur (with the homogeneously nucleated bubbles then acting as further heterogenous nucleations sites) – not because of stirring of the water. With regard to why your bubbles remained present for the duration of drinking, I would hypothesise that this perhaps has something to do with the oils in the crema of the coffee, and/or reaction of the dissolved sugar to form something that increases the surface tension of the water. (Not sure what you would call the opposite of a surfactant effect). A final thing I would like to mention is that (as indicated on the UNSW page), microwaving liquids has the potential to result in violent reaction, or even explosion, of the liquid — in other words, you are risking serious burn injuries by taking a shortcut to heat it up. Adding a powder (like sugar or instant coffee) to superheated water is particularly bad because in doing so, you are introducing millions of nucleation sites at once. That said, you should also be aware that since gas bubbles themselves promote heterogeneous nucleation, simply placing a spoon in the cup can be enough to cause an 'explosion'. If you really need to microwave a liquid, (e.g., if you are cooking something), consider heating it in a microwave-safe plastic container that has been washed a few times (and is therefore abraded on the inside). You should also stop the microwave to check the temperature of the liquid at regular intervals, rather than nuking the fluid for an excessively long time.
{ "pile_set_name": "StackExchange" }
Q: table-cell content is different sizes I have number of circles with footer text displayed in a table. On all browsers the circle images are the same size, except for IE11 and edge. This is what I currently have (sorry for the large css dump - I really don't know what is causing the issue): .circle-container { display: table; } .circle { display: table-cell; table-layout: fixed; padding: 40px 20px; vertical-align: top; -webkit-transform: translateZ(0); transform: translateZ(0); box-shadow: 0 0 1px rgba(0, 0, 0, 0); -webkit-backface-visibility: hidden; backface-visibility: hidden; -moz-osx-font-smoothing: grayscale; cursor: pointer; } .circle>p { display: block; width: 100%; text-align: center; margin: 40px 0 0; } .circle>div { position: relative; } .circle>div:before { content: ''; position: absolute; border: #54314E solid 4px; top: 0; right: 0; bottom: 0; left: 0; -webkit-transition-duration: 0.3s; transition-duration: 0.3s; -webkit-transition-property: top, right, bottom, left; transition-property: top, right, bottom, left; border-radius: 50%; z-index: 1; } .circle>div>img { border-radius: 50%; width: 100%; height: auto; } .circle:hover>div:before, .circle:focus>div:before, .circle:active>div:before, .circle.active>div:before { top: -15px; right: -15px; bottom: -15px; left: -15px; } <div class="circle-container"> <div class="circle"> <div> <img src="http://placehold.it/350x350"> </div> <p><b>Corporate &amp; <br>Institutional <br>Banking</b></p> </div> <div class="circle"> <div> <img src="http://placehold.it/350x350"> </div> <p><b>Global <br>Transactional <br>Solutions &amp; <br>Client Experience</b></p> </div> <div class="circle"> <div> <img src="http://placehold.it/350x350"> </div> <p><b>Financial Markets</b></p> </div> <div class="circle"> <div> <img src="http://placehold.it/350x350"> </div> <p><b>International</b></p> </div> </div> I have noticed though that the issue is non-apparent when I remove the text under the circles: .circle-container { display: table; } .circle { display: table-cell; table-layout: fixed; padding: 40px 20px; vertical-align: top; -webkit-transform: translateZ(0); transform: translateZ(0); box-shadow: 0 0 1px rgba(0, 0, 0, 0); -webkit-backface-visibility: hidden; backface-visibility: hidden; -moz-osx-font-smoothing: grayscale; cursor: pointer; } .circle>p { display: block; width: 100%; text-align: center; margin: 40px 0 0; } .circle>div { position: relative; } .circle>div:before { content: ''; position: absolute; border: #54314E solid 4px; top: 0; right: 0; bottom: 0; left: 0; -webkit-transition-duration: 0.3s; transition-duration: 0.3s; -webkit-transition-property: top, right, bottom, left; transition-property: top, right, bottom, left; border-radius: 50%; z-index: 1; } .circle>div>img { border-radius: 50%; width: 100%; height: auto; } .circle:hover>div:before, .circle:focus>div:before, .circle:active>div:before, .circle.active>div:before { top: -15px; right: -15px; bottom: -15px; left: -15px; } <div class="circle-container"> <div class="circle"> <div> <img src="http://placehold.it/350x350"> </div> </div> <div class="circle"> <div> <img src="http://placehold.it/350x350"> </div> </div> <div class="circle"> <div> <img src="http://placehold.it/350x350"> </div> </div> <div class="circle"> <div> <img src="http://placehold.it/350x350"> </div> </div> </div> I need to retain the current functionality and layout. Note: I do not know how many circles w/ text there will be as this is generated, however p.length == .circle.length. This is why I opt'd to use table-cell in the first place as I thought it would mitigate manual setting of widths at "run time". A: table-layout:fixed only works when applied to display:table not table-cell, then add width:100% Note: The issue was happening with latest Firefox .circle-container { display: table; table-layout: fixed; width:100% } .circle { display: table-cell; padding: 40px 20px; vertical-align: top; -webkit-transform: translateZ(0); transform: translateZ(0); box-shadow: 0 0 1px rgba(0, 0, 0, 0); -webkit-backface-visibility: hidden; backface-visibility: hidden; -moz-osx-font-smoothing: grayscale; cursor: pointer; } .circle>p { display: block; width: 100%; text-align: center; margin: 40px 0 0; } .circle>div { position: relative; } .circle>div:before { content: ''; position: absolute; border: #54314E solid 4px; top: 0; right: 0; bottom: 0; left: 0; -webkit-transition-duration: 0.3s; transition-duration: 0.3s; -webkit-transition-property: top, right, bottom, left; transition-property: top, right, bottom, left; border-radius: 50%; z-index: 1; } .circle>div>img { border-radius: 50%; width: 100%; height: auto; } .circle:hover>div:before, .circle:focus>div:before, .circle:active>div:before, .circle.active>div:before { top: -15px; right: -15px; bottom: -15px; left: -15px; } <div class="circle-container"> <div class="circle"> <div> <img src="http://placehold.it/350x350"> </div> <p><b>Corporate &amp; <br>Institutional <br>Banking</b></p> </div> <div class="circle"> <div> <img src="http://placehold.it/350x350"> </div> <p><b>Global <br>Transactional <br>Solutions &amp; <br>Client Experience</b></p> </div> <div class="circle"> <div> <img src="http://placehold.it/350x350"> </div> <p><b>Financial Markets</b></p> </div> <div class="circle"> <div> <img src="http://placehold.it/350x350"> </div> <p><b>International</b></p> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: Where is $BASH_ENV usually set? I have twin Linux servers that should be configured identically, however ssh commands to one of them are failing for commands that require a path that's specified in ~/.bashrc. For example, I can use a command like pwd both interactively and through ssh, but if I try running a program that's located in an application bin folder, it only works in an interactive shell for one of the servers. The /etc/profile and /etc/environment file on both servers are identical, however $BASH_ENV is set to ~/.bashrc on the server that is working properly. I want to set $BASH_ENV on the server that's not working, but I'd prefer to set it in the same location as it's set in the working server. What are the places that Linux will run at the time of a non-interactive login, such as an ssh command from another computer? edit: The line in /etc/passwd for the user specifies /bin/bash on both servers. The ~/.bash_profile file for both servers is identical, and contains if [ -f ~/.bashrc ]; then . ~/.bashrc; fi. The only difference between the systems is that $BASH_ENV is a null string on the server that's not working, and I can't find where it's been set in the server that's working. edit 2: The ~/.ssh/environment file on both servers has BASH_ENV=~/.bashrc A: BASH_ENV is only going to be set via the environment, or another script that is sourced during initialization. For a non-interactive shell, it will only be trying to source additional files if that shell is also a login shell. (in which case it'll read ~/.bash_profile, ~/.bash_login, and ~/.profile...but if it was doing that, you wouldn't be experiencing an issue) The first place to look is the environment in which the subshell is being invoked. An exported BASH_ENV variable will be passed through. Keep in mind that this may be buried in a sourced file. It can be fed in as a parameter on the same line calling the script, i.e. BASH_ENV=blah /path/to/somecommand.sh. This stands out like a sore thumb so you probably would have caught it. If it's being set after you log in but you can't figure out where, you may need to look at what is responsible for constructing the login environment. All of the usual files that get sourced by a login shell. man bash for the exhaustive list. PAM: As freiheit suggested in the comments, check /etc/security/pam_env.conf, and any additional files that are referenced by pam_env.so. Other PAM modules could also be responsible, but if your PAM configs look identical this is probably not the case. sshd: It will scan the following files, in order: ~/.ssh/environment (before changing to the home directory; only if PermitUserEnvironment is enabled in sshd_config) ~/.ssh/rc (after changing to the home directory; always) /etc/ssh/sshrc (if ~/.ssh/rc is not present) Note: sshd will also scan for environment=value lines in the user's authorized keys file (if PermitUserEnvironment is enabled), but it is not clear from the man page where that step falls in the above sequence.
{ "pile_set_name": "StackExchange" }
Q: After assigning a parameter to a field, use the parameter or the field? If I have a method that receives a value as parameter and stores it in a field for later usage, but then goes on to use that value - why would I use the parameter instead of the field? private RailState _railState; public void UseParameter(RailState railState) { _railState = railState; railState.SetActive(); } public void UseField(RailState railState) { _railState = railState; _railState.SetActive(); } As far as i can see, an argument for using a parameter is that if the class would be changed later and the value would only be used in that method, a decent IDE would inform me that the field is never read from and thus unnecessary. An argument for using the field is that using the parameter won't work for value types. While this is obvious and intuitive for basic types like numbers, it might lead to surprises with unexpected structs. However, are there other arguments - one way or the other - that I am missing? A: As you pointed out, the field approach work well in all the cases (value and reference). This should be the preferred approach. Another reason speaking in favour of the field is refactoring: if your method grows to be very complex, you could more easily split in in simpler methods when using the field approach. The parameter could however be a better approach when handling unique operations related to the initialisation, especially in a multithreaded application, where the field could be altered by another method invoked in another thread. Hypothetical example: _railstate = railstate; railstate.incrementUseCount(1); // because use count of parameter is to be increased _railstate.activate(); // may be another thread already changed the field and decrementer use count of former field ? So rather than dogmatism, I'd recommend to really think of the semantic: do we want to address the parameter regardless of the object state ? Or do we intend to address the object corresponding to the object state (e.g.referred by the field) ?
{ "pile_set_name": "StackExchange" }
Q: Binding a View to my main window only shows me the type I'm trying to bind a View to my ContentControl. Currently, it just shows me the type (eg NameSpace.ViewModel.MainWindowViewModel) Although I will point out, I'm not sure if I'm approaching this correctly. My simple set up is I have a View (UserControl) which is empty other than a single control (which has been placed just for the visual). My MainWindow.xaml <Window x:Class="DelegateGoodExample.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:viewModel="clr-namespace:DelegateGoodExample.ViewModel" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <viewModel:MainWindowViewModel x:Key="Vm" /> </Window.Resources> <Grid> <ContentControl Height="147" Margin="53,132,60,0" VerticalAlignment="Top" Content="{StaticResource Vm}" /> </Grid> </Window> (There is nothing in the code behind). My MainWindowViewModel.cs namespace DelegateGoodExample.ViewModel { public class MainWindowViewModel { private object _currentView; public object CurrentView { get { return new View.QuickView(); } set { _currentView = value; } } } } So, my question is, Do I have to set a datacontext in this instance (and even if I do add it the results persist)? What have I done wrong? A: You are putting a viewmodel inside the ContentControl, not a view. Since your viewmodel class is not a UIElement and there is no DataTemplate to determine how it should be rendered, what gets displayed is simply its .ToString() representation. An immediate fix would be: <ContentControl Height="147" Margin="53,132,60,0" VerticalAlignment="Top" Content="{Binding Source={StaticResource Vm}, Path=View}" /> However, instead of doing things this way you should be putting your view inside the Grid directly, and the viewmodel should not have any knowledge of the view.
{ "pile_set_name": "StackExchange" }
Q: How to set code for designer legend in mapbasic last couple of days i am doing work on thematic maps using mapbasic. I am getting error while set the legend code. it giving me unrecognized command or code kind of error ... my code is Create Designer Legend From Window nMID Portrait Default Frame Title "# Legend" Font ("Arial",0,10,0) Default Frame Style "%" Font ("Arial",0,8,0) Frame From Layer 2 Using column object label default Frame From Layer 3 Using column object label default Frame From Layer 1 it giving error for Create Designer legend..... does anybody knows this.....??? BTW...happy new year to all A: If i insert that code into my mapbasic window it giving me unrecognized or syntax error.firstly i did all steps manually.while doing all steps i opened Mapbasic window in Mapinfo.then i got the code for all steps like . 1. open table 2. Open Table and built query to filter given task parameters 3. Set front window 4. Create thematic maps using Join 5. Create Legend 6.Create Layout from it.after completing this all steps i got Mapbasic code which i insert it into Mpabasic window by changing small small things.Now what i am not getting that is 1. Pagesetup code ( Portrait, Landscape etc) 2. How to erase border of existing map (Region Style). help me if possible.
{ "pile_set_name": "StackExchange" }
Q: What's the meaning of /proc/net/rotue columns? especially Flags column This is my android device shows: $ cat route Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT rmnet0 D532BD0A 00000000 0005 0 0 0 FFFFFFFF 0 0 0 rmnet0 0000000A 00000000 0001 0 0 0 000000FF 0 0 0 rmnet0 00000000 D532BD0A 0003 0 0 0 00000000 0 0 0 I am not familiar with the Linux kernel. After searching a lot , sadly I cannot find useful explanation. Can someone explain it? Especially for the Flags column, what's the meaning of 0001 0003 0005? It's OK to provide some reference as well. A: The flags column is a combination of the RTF_* flags. You can find them in linux/route.h For the other fields, have a look at fib_route_seq_show
{ "pile_set_name": "StackExchange" }
Q: How do I continuously update these coordinates? I want to move the rectangle horizontally,however,it enters the updateStageObjects() function several times but does not update the value of myRectangle.x.How do I fix this? <script type="text/javascript"> var interval = 10; var x=0; var y=0; var myRectangle; var context ; var canvas; function Rectangle(x, y, width, height, borderWidth) { this.x=x; this.y=y; this.width = width; this.height = height; this.borderWidth = borderWidth; } function DrawRects(){ myRectangle = new Rectangle (250,70,100,50, 5); context.rect(myRectangle.x,myRectangle.y,myRectangle.width,myRectangle.height); context.fillStyle="#8ED6FF"; context.fill(); context.lineWidth=myRectangle.borderWidth; context.strokeStyle="black"; context.stroke(); } function updateStageObjects() { var amplitude = 150; var centerX = 240; myRectangle.x += 100; alert(myRectangle.x+" "+myRectangle.y); } function clearCanvas() { context.clearRect(0,0,canvas.width, canvas.height); } function DrawRect(){ setTimeout(CheckCanvas,10); clearCanvas(); updateStageObjects(); DrawRects(); } function CheckCanvas(){ return !!(document.createElement('canvas').getContext); } function CheckSound(){ return !!(document.createElement('sound').canPlayType) } function CheckVideo(){ return !!(document.createElement('video').canPlayType) } function Checkstorage(){ return !!(window.localStorage) } function CheckVideo(){ return !!(document.createElement('video').canPlayType) } function DrawCanvas(){ if (CheckCanvas()){ canvas = document.getElementById('Canvas'); DrawRects(); setInterval(DrawRect, 10); } } </script> html <canvas id="Canvas" width="800px" height="800px" onclick="DrawCanvas()"> Nor supported</canvas> A: Every time you call updateStageObjects(), it is followed immediately by a call to DrawRects(), which creates a new rectangle at exactly (250,70,100,50, 5). So you'll never notice it increment by 100. You'll need to pass some numbers back and forth between these functions if you want one of them to remember the changes made in another.
{ "pile_set_name": "StackExchange" }
Q: Separating urls from a string? I have a textbox user profile area where users will put rss urls separated by 'return' or each URLs per line. Then it will be saved to database. Now how I get all the urls in an array? I know it is very basic question. Searched the web found lots of things and I got confused. How the I think little discussion will help. I also want to some validation like if users don't put any http:// before url the code will add it. And ignore URLs other then http:// protocols. My CMS is Wordpress so if there are any built in functions that might help me let me know. A: After using the explode function you'll want to do a foreach to do the validation you're looking for $urlArray = explode("\r", $_POST["textBox"]) if(!empty($urlArray)) { foreach($urlArray as $url) { //Do your regex checking here } } Depending on your skill level if RegEx is too complicated (though I'd really recommend learning it) you could look at using substr to evaluate each of the html lines as well, though this is a much less powerful version. An example would be: $htmlString = substr($url, 0, 7); if($htmlString != "http://") { $url = "http://" . $url; }
{ "pile_set_name": "StackExchange" }
Q: Laravel JWT Auth fetch user if token I'm using the jwt-auth package for Laravel. It's working great, but it seems that a user has to be authenticated or not. For instance some routes do not require authentication, but if the token is present it should still authenticate the user. The parameters I display to user from API can vary based on the type of users access. So admins will get some additional parameters. Right now it will always just throw token absent. But it should go through as normal and "IF" token is present, process it. Not sure if I need to create a custom middleware for this. class JWTAuthIfPresent { public function handle($request, Closure $next) { if (JWTAuth::getToken()) { JWTAuth::parseToken()->authenticate(); } return $next($request); } } This seems to work, but not sure if there is a better way or something already in the existing package. EDIT: Also this will not deal with any token issues, like token= or some invalid or expired token. If set it should still process the token normally. A: Ok, I was able to figure this out by simple extending the existing auth. namespace App\Http\Middleware; use JWTAuth; use Closure; use \Tymon\JWTAuth\Middleware\GetUserFromToken; class JWTAuthIfPresent extends GetUserFromToken { public function handle($request, Closure $next) { if (JWTAuth::getToken()) { return parent::handle($request, $next); } return $next($request); } }
{ "pile_set_name": "StackExchange" }
Q: Play video using AVPlayer I am getting frame buffer one by one from video file using AVAssetReader and doing some operation on the frame and then saving new frame to temp file using AVAssetWritter.Now I have temp file path where all new frame is saving one by one. Is there any way to play video at the time frames is continuously adding to temp file?? here is code to play video from temp path(where frames is continuously adding) - (void)loadAssetFromFile { AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:[(mMediaReader.mCameraRecorder) tempVideoFilePath ]] options:nil]; NSString *tracksKey = @"tracks"; [asset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:tracksKey] completionHandler: ^{ // Completion handler block. dispatch_async(dispatch_get_main_queue(), ^{ NSError *error = nil; AVKeyValueStatus status = [asset statusOfValueForKey:tracksKey error:&error]; if (status == AVKeyValueStatusLoaded) { self.mPlayerItem = [AVPlayerItem playerItemWithAsset:asset]; [mPlayerItem addObserver:self forKeyPath:@"status" options:0 context:&ItemStatusContext]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:mPlayerItem]; self.mPlayer = [AVPlayer playerWithPlayerItem:mPlayerItem]; [mPlayerView setPlayer:mPlayer]; [self play:nil]; } else { // You should deal with the error appropriately. NSLog(@"The asset's tracks were not loaded:\n%@", [error localizedDescription]); } }); }]; } - (IBAction)play:sender { [mPlayer play]; } And code inside the block never runs. A: Dividing the video in multiple sub videos worked for me. What I did instead of saving full video in one temp path. I divided that video in multiple sub videos and then replaced AVPlayerItem property of AVPlayer accordingly. So now functionality is working same as video streaming . :)
{ "pile_set_name": "StackExchange" }
Q: How to render html into a page but not as the entire view into an Node.js + express app? Intent I need to render portion of hmtl into a page. Problem The page is being rendered without styling or layout. I have a page that I need to be in plain html and not jade. But will still be using jade elsewhere. I followed along to a similar question and that works to direct to an html page. BUT the styles and layout if not being passed in. My previous page was cases.jade and started like this extends layout block content .row .twelve.columns h1 title Now my new page is cases.html and starts like this <div class="row"> <div class="twelve columns"> <h1>Before &amp; After Case Gallery</h1> and is routed to like this app.get('/cases', function (req, res) { res.render('cases.html'); }); and has this above it app.set('views', __dirname + '/views'); app.engine('html', require('ejs').renderFile); A: It seems like in your jade file, you're extending the layout page, so you include all your layout info. But in the HTML version you aren't importing any of the layout information. I see you're using ejs. Check out layouts, to see what to put into your template: <% include head %> <h1>Title</h1> <p>My page</p> <% include foot %> Here you'll want to do something like <%include layout %>, with your layout page stuff in layout.html. The include line will basically copy-paste the file's content into that spot.
{ "pile_set_name": "StackExchange" }
Q: Why does my web service response XML contain escape characters and how should they be handled? Here's the relevant (C#.NET) code: WebRequest webRequest = System.Net.WebRequest.Create(authenticationUrl); UTF8Encoding encoding = new UTF8Encoding(); ... var webResponse = webRequest.GetResponse(); var webResponseLength = webResponse.ContentLength; byte[] responseBytes = new byte[webResponseLength]; webResponse.GetResponseStream().Read(responseBytes, 0, (int)webResponseLength); var responseText = encoding.GetString(responseBytes); webResponse.Close(); Here's what the value of responseText looks like (as copied from Visual Studio while debugging the above code): "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<responseblock version=\"3.67\">\n <requestreference>X3909254</requestreference>\n <response type=\"ERROR\">\n <timestamp>2012-04-16 13:53:59</timestamp>\n <error>\n <message>Invalid field</message>\n <code>30000</code>\n <data>baseamount</data>\n </error>\n </response>\n</responseblock>\n" Why are there seemingly escape characters (e.g. \") in the response? Is this due to the way in which I'm converting the response stream to a string? What should I do instead (so that the value stored in the variable responseText can be parsed as 'standard' XML)? UPDATE – some more code that I was using: var resultXML = XElement.Parse(responseText); ... int errorCode = (int)(resultXML.Element("error").Element("code")); The problem was that the element error isn't a direct child of the root element of resultXML, hence my apparent inability to reference error (or its child element code). A: You see these characters only while debugging. I guess the purpose is that you can copy the whole string and insert it directly into C# code for further testing. Also, it's to be able to represent the whole string as one line. But all the \n's will be converted to real line breaks when you access the string in your code. So you can safely parse it. P.S. Why are you invoking the web request manually? Visual Studio will generate the stub code for you if you use the "Add Web Reference" feature in your solution tree. Then you don't have to care about XML - you'll work with objects Visual Studio generates basing on the WSDL description.
{ "pile_set_name": "StackExchange" }
Q: Искусство гуглить и дубликаты, или почему нас минусуют Дискуссии о дружелюбности SO породили мысль о вопросах-дубликатах, которыми я и сам невольно грешу время от времени. В процессе обсуждения в указаной выше теме один из старейших ветеранов даже выразился в том духе, что из за них ему вообще не хочется заходить на SO. Меня это как-то задело. И породило у меня мысль, которой я решил поделиться, чтобы узнать мнение сообщества (помидорами попрошу не кидаться). В чем причина дубликатов? В том, что навык гугления ниже минимально необходимого. Искал как умел, не нашел, пошел на SO. Если бы нашел, то и проблемы нет; в конце концов, оформление вопроса занимает куда как больше времени, чем составление хорошего запроса в гугл. Значит что? Значит человек просто не умеет это делать, он же себе не враг — тратить время, чтобы минусы собирать. Значит надо выделить навыки гугления в отдельную тему. Поиск гугл не шутка юмора, а серьезный инструмент, которым надо уметь пользоваться. Не все умеют. И здравый смысл, как впрочем и интуиция, подсказывают, что если помочь людям улучшить их навыки гугления, то многие проблемы с качеством вопросов уменьшат свой масштаб. Выходит, что гугл это единственный навигатор по SO для ищущего ответ, и другого навигатора у нас просто нет. Как вы думаете, как можно повлиять на ситуацию? Нужен ли гайд "Как правильно гуглить" в какой-то форме, от кого-то кто действительно умеет это делать, и внедрять его в справку? Может какие-нибудь небольшие статьи-заметки у наших уважаемых ветеранов попросить иногда выпускать, типо как я гуглил этот тяжелый случай, или 3 признака плохого запроса?.. Или что-то еще, я не знаю, но эта тема уже просто как заноза, давайте что-нибудь придумаем. A: Нужен ли гайд "Как правильно гуглить" в какой-то форме, от кого-то кто действительно умеет это делать, и внедрять его в справку? Сначала нужно научиться определять кто умеет гуглить. Помните Кубок Яндекса по поиску в интернет? Нужно устроить открытое соревнование по поиску (отдельно в поисковике; отдельно по enSo; отдельно по ruSO) и, сделав упор не на быстроте, а на тщательном логировании действий и объяснении шагов, выявлять типичные паттерны. Там-то как раз и взлетят очевидные для многих вещи: что знание одного ЯП помогает в новой области (знаешь sqrt в одном языке – сначала проверь, а не названа ли она и в другом языке так же) что хорошо помогает изучение литературы (можно '[AngleSharp] make get request', но для POST намного лучше заменить на '[AngleSharp] submit form') что вообще хорошо знать английский (я лично вижу огромную разницу в паттернах гугления у своих коллег, кто знает и кто не знает английский) что знание некоторых ключевых принципов многократно возмещает незнание множества казалось бы разных фактов Кроме того, нужно будет предварительно как-то обсудить, что делать с вопросами, которые плохо поддаются поиску. Скажем, кто-то предлагает конкретный JSON, который нужно распарсить при помощи JSON.Net. В текущей ситуации гораздо проще очередному страдальцу дать рыбу написать его конкретный кейс, чем пытаться вытащить более-менее подходящий пример (а они наверняка есть) – потому что просматривать придётся все вопросы по метке, а сузить словами вряд ли получится. Ну или надо написать большой гайд по десериализации, в котором рассмотреть все примеры и безжалостно закрывать на эталонный дубликат. Или – пример на десериализацию в Dictionary. Ну и в целом о гайде. Гайд конечно прочитают (кто их вообще читает?) от силы 10% – но всё равно гайд по поиску мне кажется очень хорошей идеей. Я во время парного программирования обожаю смотреть кто как гуглит, когда ему не хватает линкупадовских скетчей. Но я бы к гайду хотел подойти именно разглядывая большое количество примеров, а не путём составления общих рекомендаций. И вписать эти примеры в гайд.
{ "pile_set_name": "StackExchange" }
Q: mongoosedb expires property not expiring I've created a Schema which contains this property: expire: { type: Date, default: Date.now, expires: 60 } When a new document is created it successfully sets the expire field to the current datetime. No index is created on the collection. I subsequently added model.on('index',function(err){ console.log('index created'); if (err) { console.log(err); } }); Neither logs are occuring. So I'm assuming that mongoose is not even attempting to create the ttl index on the collection, but I don't see why not. Am I missing a step? am I meant to create the index myself? the mongoose docs seem to imply that mongoose handles creation of the index. A: mongoosejs does indeed handle the creation of the index as suspected. In order to find the problem I added an ensureIndexes call as follows: model.ensureIndexes(function (err) { console.log('ensure index', err) }) This then showed that one of the existing indexes (unique email addresses) was failing because of existing documents in the DB which were not unique. Fixing this problem the above code then works fine. Hope this helps anyone else who runs into problems with mongoose TTL.
{ "pile_set_name": "StackExchange" }
Q: Much worse performance with RBF kernel than linear in SVM in python scikit-learn I am performing some machine learning tasks using SVM. I suspect the data is non-linear so I also included the RBF kernel. I found that SVM with RBF kernel is MUCH worse than linear SVM. I wonder if I did something wrong with my classifier parameter specifications. My code as follows: from sklearn.svm import LinearSVC from sklearn.svm import SVC svm1 = LinearSVC() # performs the best, similar to logistic regression results which is expected svm2 = LinearSVC(class_weight="auto") # performs somewhat worse than svm1 svm3 = SVC(kernel='rbf', random_state=0, C=1.0, cache_size=4000, class_weight='balanced') # performs way worse than svm1; takes the longest processing time svm4 = SVC(kernel='rbf', random_state=0, C=1.0, cache_size=4000) # this is the WORST of all, the classifier simply picks the majority class A: With RBF try tuning your C and gamma parameters. Scikit-learn's grid search will help you. Here is an example to get you started: svc = SVC(...) params = {"C":[0.1, 1, 10], "gamma": [0.1, 0.01, 0.001]} grid_search = GridSearchCV(svc, params) grid_search.fit(X,y)
{ "pile_set_name": "StackExchange" }
Q: Will the new airmen certification standards make it more difficult to add ratings? As of June 15, 2016, the FAA has changed from PTS/Knowledge tests to the Airmen Certification Standards which is a relatively significant paradigm shift in how airmen are certified. The underlying reason to move to the ACS was to evolve the outdated PTS (practical test standards) and to align airmen certification towards risk management and the existing national airspace system. The question I have though is for people who have earned their certificates under the old PTS system and would like to add a rating like an Instrument rating, or another certification like commercial. Will the new ACS make it more difficult for existing pilots to add ratings? I'd like to know from the standpoint of part 141 and part 91 training centers. One of the reasons I ask is I went up with my CFI last week and went into some slow flight. I set up to bring the aircraft into the stall buffet and fly it a few knots above stall speed but he said that the new ACS said that the stall horn cannot sound during slow flight, which seems counter intuitive to me. The point of slow flight is to know how to handle the aircraft at or near stall. There is a lot of handling difference between VS0 and VS0+20kts. So that got me thinking, what would I have to relearn in pursuit of an instrument rating that would make it harder that I probably wouldn't have to under the old PTS? A: Not significantly. The fundamentals of evaluation have not changed, and certainly the fundamentals of your next rating haven't changed. A few of the specific tasks have changed between PTS and ACS, like the point you raise. And, yes, you will need to review the ACS or PTS (whichever is in effect for your next rating -- not all have transitioned) in detail, so that you're aware of what's expected of you. The major parts of any checkride will be your basic knowledge of the subject, your ability to move the aircraft through the air to standard, your ability to demonstrate sound judgment including a thorough evaluation of pre-flight risks and your overall attitude toward flying. That really hasn't changed with the ACS. The regulations have not changed either. The ACS is meant to give instructors and examiners a more holistic approach to evaluate the above factors.
{ "pile_set_name": "StackExchange" }
Q: How do I shorten the pull to refresh distance (threshold) in React Native Refresh Control I am trying to implement pull to refresh using Refresh Control in ScrollView. I need to modify the pulling distance/threshold of refresh control. I have checked for the related props to achieve it, but I can't any props related to this. <ScrollView contentContainerStyle={styles.subContainer} bounces={true} horizontal={false} refreshControl={ <RefreshControl refreshing={false} tintColor={'transparent'} onRefresh={() => { onSwipeDown(); }} /> } > {props.children} </ScrollView> Please help me guys. A: We can achieve this by onScroll event listener. <ScrollView contentContainerStyle={styles.subContainer} bounces={true} horizontal={false} onScroll={onSwipeDown} > {props.children} </ScrollView> onSwipeDown method const onSwipeDown = event => { console.log(event.nativeEvent.contentOffset.y); if (event.nativeEvent.contentOffset.y < 0) { // you can replace zero with needed threshold onRefresh(); //your refresh function } };
{ "pile_set_name": "StackExchange" }
Q: Jquery Find Selected Element via Selector vs Method I've a little confusion here, which is better to choose either directly used the selector or method in jquery For example : $("div p:first") with $("div p").first() -> it's same right Are there any condition that we choose selector rather than method? For example because selector run faster? (example only not the truth) A: They're actually almost the same $('div p:first') will return you the element once the first element of p in a div is found. $('div p').first() will iterate all p elements in div, then return the first one. If you check from console, they have different prevObject property. jQuery uses this object as a stack of the most recent filtering operation in the current chain and return the set of matched elements to its previous state. As they need this for their end() function. Taken from jQuery jQuery.fn = jQuery.prototype = { ... end: function() { return this.prevObject || this.constructor(); } }; If you want to talk about speed comparison, I'd suggest to go with the first one. Since you would not need to traverse to all p in a div
{ "pile_set_name": "StackExchange" }
Q: I am trying to get data from row to match into defined columns Using PHP / MySQL I have two tables one is customers the other is cust_data there is a field that matches the two it is ListID Now inside the cust_data table the data is listed as cust_data columns: ListID DataName DataValue 1 type something 1 Region something customers columns: ListID Name Address City State Zip Phone I want to get the results as Name Address City State Zip Phone Type Region A: SELECT customers.*, data_type.DataValue AS Type, data_region.DataValue AS Region FROM customers JOIN cust_data AS data_type ON ( data_type.ListID = customers.List_ID AND data_type.DataName = 'Type' ) JOIN cust_data AS data_region ON ( data_region.ListID = customers.List_ID AND data_region.DataName = 'Region' )
{ "pile_set_name": "StackExchange" }
Q: Adding functionality to view in admin mode I am developing a website, and I need to give 'admin' user CRUD(create/read/update/delete) functionality. I am developing using php and CodeIgniter. I have a view called gallery.php which display thumbnails, as grid. each thumbnail have 2 buttons below(edit,delete) the thumbnail. I want... admin user - need to see those 2 buttons. all rest wont see those 2 buttons. I what to use the same view(not to duplicate it...) and just hide those buttons in case user is not admin. What do I need to do? passing $is_admin to gallery.php seems to be a little ugly i guess. Thx A: when you login check its admin or not than store into session variable. no need to create same page again & again .. no need to pass variable into url.. just use session variable for checking its admin or not.
{ "pile_set_name": "StackExchange" }
Q: if statement within PHP Function function sendSMS($msg, $to, $profileID="(if (@$_GET['debug'] == "true") { echo "21409"; } else { echo "21410"; })", $user="User", $pass="Pass", $serverID="", $msgid="", $shortCode="00000"){ I would like it so that when Debug is called it gives a different number Debug True = 21409 Debug False = 21410 A: Why are you trying to write an if statement in the signature of the function?? And echo directly writes the string into the output stream. What you need to do is to establish the variable $profileId depending on $_GET[DEBUG] and use it in the statement that sends the email. function sendSMS($msg, $to, $user="User", $pass="Pass", $serverID="", $msgid="", $shortCode="00000"){ if ($_GET['debug'] == "true") { $profileID = "21409"; } else { $profileID= "21410"; } .... }
{ "pile_set_name": "StackExchange" }