text
stringlengths
64
81.1k
meta
dict
Q: Changed byte value solved this, but why? SAS: this range is repeated, or values overlap My BI department just ran into the SAS error: this range is repeated, or values overlap. I found some links they looked at and found that there was an error in a macro. The error was that the length of a numeric variable byte value was changed from 7 to 6 bytes created this error. Now when they changed it back to it's previous value everything is ok. What is this behaviour all about? Are there some logic in this? A: When reducing the length of a variable from 7 to 6 bytes, some numbers might get "truncated". 7 bytes can store integers up to 35,184,372,088,832 while 6 bytes can store only integers up to 137,438,953,472. Decimal numbers should always be length 8. See here for details.
{ "pile_set_name": "StackExchange" }
Q: Re-use a sub from a perl script in another script I have two perl scripts. Both have no "package" keyword or anything. One has a sub (and plus some free floating code too) that I want to use in another script, without running the free floating code in the process. A.pl sub my_sub { # do something } # do something else my_sub(); # do something else B.pl require A.pl; # but load only the subs, don't run anything my_sub(); Is this possible without having to separate out the sub in a separate .pm file and then loading it? A: require will run the code. So then you need A.pl to recognise the difference between being loaded and being called on the command line. I think it can be done, but you're kind of missing the point. Instead, I highly recommend reversing everything. Instead of having mammoth pl scripts, and no pm modules, reverse it and have tiny pl files whose sole function is to load module(s) and call into the function that encapsulates the functionality there. And then it's trivial to add new modules to hold shared form or functionality.
{ "pile_set_name": "StackExchange" }
Q: Update kubernetes secrets doesn't update running container env vars Currenly when updating a kubernetes secrets file, in order to apply the changes, I need to run kubectl apply -f my-secrets.yaml. If there was a running container, it would still be using the old secrets. In order to apply the new secrets on the running container, I currently run the command kubectl replace -f my-pod.yaml . I was wondering if this is the best way to update a running container secret, or am I missing something. Thanks. A: The secret docs for users say this: Mounted Secrets are updated automatically When a secret being already consumed in a volume is updated, projected keys are eventually updated as well. The update time depends on the kubelet syncing period. Mounted secrets are updated. The question is when. In case a the content of a secret is updated does not mean that your application automatically consumes it. It is the job of your application to watch file changes in this scenario to act accordingly. Having this in mind you currently need to do a little bit more work. One way I have in mind right now would be to run a scheduled job in Kubernetes which talks to the Kubernetes API to initiate a new rollout of your deployment. That way you could theoretically achieve what you want to renew your secrets. It is somehow not elegant, but this is the only way I have in mind at the moment. I still need to check more on the Kubernetes concepts myself. So please bear with me. A: For k8s' versions >v1.15: kubectl rollout restart deployment $deploymentname: this will restart pods incrementally without causing downtime. A: Assuming we have running pod mypod [mounted secret as mysecret in pod spec] We can delete the existing secret kubectl delete secret mysecret recreate the same secret with updated file kubectl create secret mysecret <updated file/s> then do kubectl apply -f ./mypod.yaml check the secrets inside mypod, it will be updated.
{ "pile_set_name": "StackExchange" }
Q: How do you call this typical file name order? log1.gz log10.gz log100.gz log101.gz log102.gz log103.gz A: As already stated in the comment, it is called lexicographic order in ascending direction; description can be found in this answer.
{ "pile_set_name": "StackExchange" }
Q: YiiPassword Extension Usage I extracted YiiPassword extension into protected/components/YiiPassword main.php: . . . 'import'=>array( 'application.models.*', 'application.components.*', 'application.components.YiiPassword.*', 'application.helpers.*', ), . . . User.php: (model) . . . public function behaviors() { return array( "APasswordBehavior" => array( "class" => "APasswordBehavior", "defaultStrategyName" => "bcrypt", "strategies" => array( "bcrypt" => array( "class" => "ABcryptPasswordStrategy", "workFactor" => 14 ), "legacy" => array( "class" => "ALegacyMd5PasswordStrategy", ) ), ) ); } . . . Ans also added thees three fields into tbl_user: salt - holds the per user salt used for hashing passwords password - holds the hashed password (Exist already) passwordStrategy - holds the name of the current password strategy for this user requiresNewPassword - a boolean field that determines whether the user should change their password or not and Now i only want use bcrypt, how to encode the user password and verify it at user-login? A: SOLVED The following test successfully done, ABcryptPasswordStrategyTest.php : <?php Yii::import("application.components.passwordStrategy.*"); Yii::import("application.models.*"); /** * Tests for the {@link ABcryptPasswordStrategy} class. * @author Charles Pick * @package packages.passwordStrategy */ class ABcryptPasswordStrategyTest extends CTestCase { public function testEncode() { $user=User::model()->findByAttributes(array('username'=>'user')); $strategy = new ABcryptPasswordStrategy(); $strategy->getSalt(true); $user->password = 'pass'; $user->save(); $this->assertTrue($user->verifyPassword("pass")); } } more info
{ "pile_set_name": "StackExchange" }
Q: Spring Batch multiple jobs at once started? In my spring batch i see following logs. INFO 5572 --- [ scheduling-1] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=sample]] launched with the following parameters: [{JobID=x}] INFO 5572 --- [ main] o.s.b.c.l.support.SimpleJobLauncher : Job: [FlowJob: [name=sample]] launched with the following parameters: [{run.id=1, JobID=y}] INFO 5572 --- [ scheduling-1] o.s.batch.core.job.SimpleStepHandler : Executing step: [step1] INFO 5572 --- [ main] o.s.batch.core.job.SimpleStepHandler : Executing step: [step1] Is this same log lines repeated by two threads or two jobs started at once ? A: According to your logs, two different job instances are executed by two different threads: scheduling-1 and main.
{ "pile_set_name": "StackExchange" }
Q: Get location of libasan from gcc/clang When I compile with -fsanitize=address, GCC/Clang implicitly make use of an ASAN dynamic library which provides runtime support for ASAN. If your built library is dynamically loaded by another application, it is necessary to set LD_PRELOAD to include this dynamic library, so that it gets run at application start up time. It is often not obvious which copy of libasan.so GCC/Clang expects to use, because there may be multiple copies of ASAN on your system (if you have multiple compilers installed.) Is there a reliable way to determine the location of the shared library you need to load? A: You can use -print-file-name flag: GCC_ASAN_PRELOAD=$(gcc -print-file-name=libasan.so) CLANG_ASAN_PRELOAD=$(clang -print-file-name=libclang_rt.asan-x86_64.so) You could also extract libasan path from the library itself via ldd: $ echo 'void foo() {}' | gcc -x c -fPIC -shared -fsanitize=address - $ ldd a.out | grep libasan.so | awk '{print $3}' /usr/lib/x86_64-linux-gnu/libasan.so.4
{ "pile_set_name": "StackExchange" }
Q: How to detect whether there is a textbox in a graph in Excel using VBA? The following macro generates a textbox on top of the y-axis to show the units. I use a textbox instead of the inbuilt legend format because it's more flexible. ActiveChart.Shapes.AddTextbox(msoTextOrientationHorizontal, 0, 0, 80, 20).Select With Selection.ShapeRange(1).TextFrame2.TextRange .Characters.Text = "[Units]" End With I want to add a conditional before this block so that the code stops if the textbox already exists. How can I 1) count how many textboxes there are in a graph (not in the whole sheet) and 2) check whether there is a textbox of the same dimension and position in the graph? Perhaps something like the following, but somehow restricted to textboxes? If ActiveSheet.Shapes.Count > 0 Then ... If ActiveSheet.Shapes(ActiveChart.Parent.Name).Count > 0 Then ... A: 1) count how many textboxes there are in a graph (not in the whole sheet) If the Chart is embedded in a worksheet then use this Sub ChartInSheetHasTextBox() Dim ws As Worksheet Dim objChart As ChartObject Dim cht As Chart '~~> Change this to the relevant worksheet Set ws = Sheet1 Set objChart = ws.ChartObjects(1) Set cht = objChart.Chart If cht.TextBoxes.Count > 0 Then MsgBox "Chart has a textbox" End If End Sub If the Chart is an independant sheet then use this Sub ChartSheetHasTextBox() Dim cht As Chart Set cht = Charts("Chart1") '<~~ Change this to the relevant name If cht.TextBoxes.Count > 0 Then MsgBox "Chart has a textbox" End If End Sub 2) check whether there is a textbox of the same dimension and position in the graph? Simply assign it to an object and work with it If cht.TextBoxes.Count > 0 Then Dim tb As TextBox Set tb = cht.TextBoxes(1) With tb Debug.Print tb.Width; tb.Height; tb.Top; tb.Left End With End If
{ "pile_set_name": "StackExchange" }
Q: My manager is not assigning me a new concrete project and i am only getting other colleagues defects My manager is not assigning me any newer projects or modules to work on. I was working on one project and my colleagues were working on other projects. I finished my project and my colleagues finished theirs. But my colleagues have moved on to work on some different modules and I am only getting my defects and also their defects to work on. I have asked my manager about any new requirements, he said will see. He has also not directly asked me to work on the defects, but is asking other colleagues to assign me their defects. How to deal with this. Is this normal or am I being sidetracked? A: If I were in your shoes, I would set up a meeting with your manager to discuss what projects you want to be on as well as what he envisions you to complete and progress at the company. You should make your intentions clear on how you want to advance and what projects you want to work on. If he is able to agree with you, then that's a good sign. However, if you notice that nothing has changed after that meeting, then perhaps it is time to move on to other opportunities.
{ "pile_set_name": "StackExchange" }
Q: LINQ to XML query and an extension method that converts an XML document to an XDocument Here is my XML document that is passed into the CreateListOfAddresses() method: <?xml version="1.0"?> <AddressValidateResponse> <Address ID="0"> <Address2>8 WILDWOOD DR</Address2> <City>OLD LYME</City> <State>CT</State> <Zip5>06371</Zip5> <Zip4>1844</Zip4> </Address> </AddressValidateResponse> Here is my method: private List<AddressBlockResponse> CreateListOfAddresses(XmlDocument xmlDoc) { // Convert XML document to xdocument so we can use LINQ. XDocument xDoc = xmlDoc.ToXDocument(); var address = from a in xDoc.Descendants("AddressValidateResponse") select new AddressBlockResponse { Order = int.Parse(a.Attribute("ID").Value), AddressLine2 = a.Element("Address2").Value, City = a.Element("City").Value, State = a.Element("State").Value, ZipCode = a.Element("Zip5").Value, ZipPlus4 = a.Element("Zip4").Value }; return address.ToList(); } Here is the extension method that converts my XML document to an XDocument type: public static XDocument ToXDocument(this XmlDocument xmlDocument) { using (var nodeReader = new XmlNodeReader(xmlDocument)) { nodeReader.MoveToContent(); return XDocument.Load(nodeReader); } } Here is my object: [Serializable] public struct AddressBlockResponse { // Standardized address returned from the service [DataMember(IsRequired = true)] public int Order; [DataMember(IsRequired = true)] public string AddressLine1; [DataMember(IsRequired = false)] public string AddressLine2; [DataMember(IsRequired = true)] public string City; [DataMember(IsRequired = true)] public string State; [DataMember(IsRequired = true)] public string ZipCode; [DataMember(IsRequired = true)] public string ZipPlus4; } Here is my problem: the CreateListOfAddresses() method returns Enumeration yielded no results What am I doing wrong? A: It looks like your issue is that AddressValidateResponse is the root node of your document. You should change it to: var address = from a in xDoc.Descendants("Address") select new AddressBlockResponse { // stuff }; Also when you are using xelements like City = a.Element("City").Value, You should do: City = (string)a.Element("City"), because if the element doesn't exist your program will throw a null reference exception. I know you will probably always have these xml nodes but I think it is just a good habit.
{ "pile_set_name": "StackExchange" }
Q: Swift 3 iOS compatibility I'm new to Apple developing and soon I will distribute my app via AppStore. So now I'm using Swift 3 and by default the deployment target is set to iOS 10.0 It means that I won't be able to make it run for example on iOS 8-9? 'Cos in Swift 3 I use new funcs which are not available in later OS A: You can make your app run on iOS 8 & 9 by setting the Deployment Target to one of these versions. Swift 3.x is compatible with iOS 8 and newer (I'm not sure, but it might be also compatible with iOS 7). The only difference to Swift 2.2 (regarding the system requirements) is that you have to use Xcode 8. When you set your Deployment Target to an earlier version than iOS 10, you should be aware that you cannot use APIs that are new in iOS 10. (except you use the #available operator) But using Swift 3 should be no problem. Edit: You can now upload apps written in Swift 3 using Xcode 8.0 GM A: You should use Swift 3.x (it's the latest version of Swift since this answer has been posted). iOS version is NOT related to the Swift version you should use, instead, some of the new provided apis do support a minimum version of the OS. But -again- it's not related to the programming language it self. For example: an application has been built via Swift 2.x (Deployment Target 9.x) should work on iOS 10; When updating the IDE (xcode), it will support -by default- the latest version of the programming language -Swift-. Also, You could do: if #available(iOS 10, *) { // use an api that requires the minimum version to be 10 } else { // use another api }
{ "pile_set_name": "StackExchange" }
Q: Understanding cross-domain user authentication Goal: Website1 sends Website2 user data through http requests. Problem: Website2 is ensured that the data came from Website1, and not some hacker. NOTE: I will not be using HTTPS, I realize that'd solve a big problem, but right now GAE doesn't support SSL for your own domain name: http://code.google.com/appengine/kb/general.html#httpsapps So I've made some great progress by encrypting and sending data between two sites, and the other is site able to decrypt and read the data. I'm on Google App Engine/Python/Django-nonreal, and this page was a great resource for getting pycrypto to work: http://code.activestate.com/recipes/576980/ Kn So I'm comfortable with knowing user data is encrypted and that you need to have the key to read it, but how could Website2 KNOW that the request came from Website1? What's stopping a hacker from sending the exact same request again, and Website2 thinking this hacker is valid to do stuff on Website2? For example, couldn't someone just listen in on the http request and record what the encrypted data was send across the line? And then the hacker could do their own request, with the same values that Website1 used before, and the hacker could do the same things to Website2 that Website1 could? Essentially the hacker would be telling Website2 that they are a valid signed-in user of Website1. Overall Goal: Website2 is told user data which only comes from requests from Website1. Any other requests from a hacker that uses the same encrypted data Website1 sent to Website2 won't work unless your Website1. Not sure if I explained well enough, or if its a pretty basic understanding that I just don't have, but thank you for your help. A: In order to prevent replay attacks, you'll need to include a nonce and MAC (Message Authentication Code). The MAC can simply be a HMAC-SHA1 of the encrypted message contents. The receiving side will compute the same MAC and make sure it matches. The key for the HMAC-SHA1 must be a secret known to both sides. This step is important - just because your data is encrypted doesn't mean it can't be tampered with. In particular, if the attacker can alter just the nonce (see next), you'll have problems. So use a proper MAC. The nonce should be within the encrypted portion of the message, and used only once ever. The receiving end should record the nonce and reject any future messages with the same nonce. This is the key to preventing replay attacks. You can avoid having to keep an infinite amount of nonces by also attaching an expiration date to the nonce. Messages received after the expiration date should be rejected. Nonces can be deleted from the seen-nonce database after the expiration date, plus a few hours to account for possible clock differences, passes. Generating the nonce can be tricky to do properly. Here's one technique: When your app server starts, create a new dummy datastore entity. Cache its key, as well as your startup timestamp, until your app server terminates. Also create a counter initialized to 0. When you need a nonce, generate it by hashing (entity key, startup timestamp, counter). Then increment the counter. You may delete the dummy datastore entity after a period longer than the greatest amount of expected clock drift passes. A few hours should be plenty.
{ "pile_set_name": "StackExchange" }
Q: How to show Remote Server data into MapView I am making an app in which i am fetching locations using JSON into Map,still i am getting map but without JSON Data to show multiple locations, my code is ok and it works fine, i just want to know by all of you experts where i need to put this line to show JSON data into Mapview: new DownloadWebPageTask().execute(); Below is my CODE:- public class MapView extends MapActivity { public GeoPoint point; TapControlledMapView mapView=null; // use the custom TapControlledMapView List<Overlay> mapOverlays; Drawable drawable; SimpleItemizedOverlay itemizedOverlay; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map_view); // new DownloadWebPageTask().execute(); mapView = (TapControlledMapView) findViewById(R.id.viewmap); mapView.setBuiltInZoomControls(true); mapView.setSatellite(false); // dismiss balloon upon single tap of MapView (iOS behavior) mapView.setOnSingleTapListener(new OnSingleTapListener() { public boolean onSingleTap(MotionEvent e) { itemizedOverlay.hideAllBalloons(); return true; } }); mapOverlays = mapView.getOverlays(); drawable = getResources().getDrawable(R.drawable.ic_launcher); itemizedOverlay = new SimpleItemizedOverlay(drawable, mapView); itemizedOverlay.setShowClose(false); itemizedOverlay.setShowDisclosure(true); itemizedOverlay.setSnapToCenter(false); class DownloadWebPageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { HttpClient client = new DefaultHttpClient(); // Perform a GET request for a JSON list HttpUriRequest request = new HttpGet("http://***.in/map.json"); // Get the response that sends back HttpResponse response = null; try { response = client.execute(request); } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Convert this response into a readable string String jsonString = null; try { jsonString = StreamUtils.convertToString(response.getEntity().getContent()); } catch (IllegalStateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Create a JSON object that we can use from the String JSONObject json = null; try { json = new JSONObject(jsonString); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ JSONArray jsonArray = json.getJSONArray("maps"); Log.e("log_tag", "Opening JSON Array "); for(int i=0;i < jsonArray.length();i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); String latitude = jsonObject.getString("latitude"); String longitude = jsonObject.getString("longitude"); String title = jsonObject.getString("title"); String country = jsonObject.getString("country"); double lat = Double.parseDouble(latitude); double lng = Double.parseDouble(longitude); Log.e("log_tag", "ADDING GEOPOINT"+title); point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)); OverlayItem overlayItem = new OverlayItem(point, title, country); itemizedOverlay.addOverlay(overlayItem); } }catch(JSONException e) { Log.e("log_tag", "Error parsing data "+e.toString()); } return jsonString; } @Override protected void onPostExecute(String result) { itemizedOverlay.populateNow(); mapOverlays.add(itemizedOverlay); if (savedInstanceState == null) { MapController controller = mapView.getController(); controller.setCenter(point); controller.setZoom(7); } else { // example restoring focused state of overlays int focused; focused = savedInstanceState.getInt("focused_1", -1); if (focused >= 0) { itemizedOverlay.setFocus(itemizedOverlay.getItem(focused)); } } } } } A: It is obvious you should call execute method after you initialize your map. I think your code should be like that: public class Test extends MapActivity { public GeoPoint point; MapView mapView=null; // use the custom TapControlledMapView List<Overlay> mapOverlays; Drawable drawable; SimpleItemizedOverlay itemizedOverlay; @Override public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map_view); // new DownloadWebPageTask().execute(); mapView = (TapControlledMapView) findViewById(R.id.viewmap); mapView.setBuiltInZoomControls(true); mapView.setSatellite(false); // dismiss balloon upon single tap of MapView (iOS behavior) mapView.setOnSingleTapListener(new OnSingleTapListener() { public boolean onSingleTap(MotionEvent e) { itemizedOverlay.hideAllBalloons(); return true; } }); mapOverlays = mapView.getOverlays(); drawable = getResources().getDrawable(R.drawable.ic_launcher); itemizedOverlay = new SimpleItemizedOverlay(drawable, mapView); itemizedOverlay.setShowClose(false); itemizedOverlay.setShowDisclosure(true); itemizedOverlay.setSnapToCenter(false); new DownloadWebPageTask().execute(); } class DownloadWebPageTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... urls) { HttpClient client = new DefaultHttpClient(); // Perform a GET request for a JSON list HttpUriRequest request = new HttpGet("http://***.in/map.json"); // Get the response that sends back HttpResponse response = null; try { response = client.execute(request); } catch (ClientProtocolException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Convert this response into a readable string String jsonString = null; try { jsonString = StreamUtils.convertToString(response.getEntity().getContent()); } catch (IllegalStateException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // Create a JSON object that we can use from the String JSONObject json = null; try { json = new JSONObject(jsonString); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try{ JSONArray jsonArray = json.getJSONArray("maps"); Log.e("log_tag", "Opening JSON Array "); for(int i=0;i < jsonArray.length();i++){ JSONObject jsonObject = jsonArray.getJSONObject(i); String latitude = jsonObject.getString("latitude"); String longitude = jsonObject.getString("longitude"); String title = jsonObject.getString("title"); String country = jsonObject.getString("country"); double lat = Double.parseDouble(latitude); double lng = Double.parseDouble(longitude); Log.e("log_tag", "ADDING GEOPOINT"+title); point = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)); OverlayItem overlayItem = new OverlayItem(point, title, country); itemizedOverlay.addOverlay(overlayItem); } }catch(JSONException e) { Log.e("log_tag", "Error parsing data "+e.toString()); } return jsonString; } @Override protected void onPostExecute(String result) { itemizedOverlay.populateNow(); mapOverlays.add(itemizedOverlay); if (savedInstanceState == null) { MapController controller = mapView.getController(); controller.setCenter(point); controller.setZoom(7); } else { // example restoring focused state of overlays int focused; focused = savedInstanceState.getInt("focused_1", -1); if (focused >= 0) { itemizedOverlay.setFocus(itemizedOverlay.getItem(focused)); } } } } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } }
{ "pile_set_name": "StackExchange" }
Q: linear shooting method and finite differences how can we use the linear shooting method to approximate this solution below: $$y'' + 4y = \cos(x), 0 \le x \le4, y(0) = 0, y(pi/4) = 0, h = \frac{\pi}{20}$$ My concern is with the RK-4 and setting this up so I can do some iterations can someone please provide a setup and possibly solve this so I can understand it well? Thanks A: We are given: $\tag 1 \displaystyle y'' + 4y = \cos(x), 0 \le x \le4, y(0) = 0, y\left(\frac{pi}{4}\right) = 0, h = \frac{\pi}{20}$ We know that if the linear boundary-value problem: $y'' = p(x)y' + q(x)y+r(x), a \le x \le b, y(a) = \alpha, y(b) = \beta$, satisfies: (i) $p(x), q(x)$, and $r(x)$ are continuous on $[a, b]$ (ii) $q(x) \gt 0$ on $[a, b].$ We can get a unique solution. For this problem, we have: $y_1(x): y'' = p(x) y' + q(x) y + r(x)$, and $y_2(x): y'' = p(x) y' + q(x) y$ So, $p(x) = 0$ $q(x) = 4$ $r(x) = \cos x$ With the same BCs given in $(1)$. For comparison purposes, $(1)$ has the exact solution: $$\tag 2 \displaystyle y(x) = \frac{1}{3} (\sin^2 x - \cos^2 x + \cos x - \sqrt 2 \sin x \cos x).$$ To apply the Linear Shooting Algorithm, we just do some setup, calculate the fourth order Runge-Kutta values over N and then output the approximations to our linearized functions. Step 1: $\displaystyle h = \frac{b-a}{N} = \frac{\frac{\pi}{4} - 0}{5} = \frac{\pi}{20}$ (this implies $N = 5$) $u_{1,0} = \alpha = 0$ $u_{2,0} = 0$ $v_{1,0} = 0$ $v_{2,0} = 1$ Step 2: For $i = 0, \ldots, N-1 = 5 - 1 = 4$, do Steps 3 and 4 (Runge - Kutta Method) Step 3 Set $\displaystyle x = a + i h = a + i\left(\frac{\pi}{20}\right)$ Step 4: $\displaystyle k_{1,1} = hu_{2,1} = \frac{\pi}{20}u_{2,1}$ $\displaystyle k_{1,2} = h[p(x)u_{2,i}+q(x)u_{1,i} + r(x)$ $\displaystyle k_{2,1} = h[u_{2,i} + \frac{1}{2}k_{1,2}]$ $\displaystyle k_{2,2} = h[p(x+ h/2)(u_{2,i} + \frac{1}{2}k_{1,2}) + q(x + h/2)(u_{1,i} + \frac{1}{2}k_{1,1}) + r(x + h/2)]$ $\ldots$ (You can now continue this as this is more an algorithms problem than a math problem - and you can find this algorithm on the web or any numerical analysis book). Step 5 Set $w{1,0} = \alpha$ $\displaystyle w_{2,0} = \frac{\beta - u_{1, N}}{v_{1,N}} = \frac{0 - u_{1,5}}{v_{1,5}}$ (you calculated these above) output($a, w_{1,0}, w_{2,0}$) Step 6 For $i = 1, \ldots, N = 5$, set $W1 = u_{1,i} + w_{2,0}v_{1,i}$ $W2 = u_{2,i} + w_{2,0}v_{2,i}$ $x = a + i h = a + i \frac{\pi}{20}$ output($x, W1, W2$), which are the $x_i, w_{i,1}, w_{2,i}$ STEP 7: Stop Of course, you should see similar results that converge to the values of the exact $y(x)$ starting at $x = 0$ and ending at $x = 4$, and you know the exact result to compare to from $(2)$. Hope that all makes sense!
{ "pile_set_name": "StackExchange" }
Q: Prevent a Window from beeing opened multiple times I've created a pop up window in c#. I have a button and when the user clicks the button the window pops up. My problem is that if the user happens to click the button multiple times, the window will be opened multiple times. Once the user has opened the window, I do not want the window to be opened again if the user clicks the button. Is this possible to achieve? My make the window pop up like this: PopUp myPopUp = new PopUp(); myPopUp.show(); I am using wpf. A: If the user needs to access the main window after the popup opened I would create a class member, that holds a reference to the popup and on closing the popup set that reference to null: PopPp myPopUp = null; private void OpenPopUp() { if(myPopUp == null) { myPopUp = new PopUp(); myPopUp.Closed += (x,y) => { myPopUp = null; }; myPopUp.Show(); } } If the user does not need to interact with the main window, while the popup is opened just use ShowDialog. It will prevent any input to the main window until the popup is closed: PopUp myPopUp = new PopUp(); myPopUp.ShowDialog();
{ "pile_set_name": "StackExchange" }
Q: Can COMMENTS in Postgres contain line breaks? I have a very long comment I want to add to a Postgres table. Since I do not want a very long single line as a comment I want to split it into several lines. Is this possible? \n does not work since Postgres does not use the backslash as an escape character. A: Just write a multi-line string: COMMENT ON TABLE foo IS 'This comment is stored in multiple lines'; You can also embed \n escape sequences in “extended” string constants that start with E: COMMENT ON TABLE foo IS E'A comment\nwith three\nlines.';
{ "pile_set_name": "StackExchange" }
Q: js undefined после присовения результата функции перемннной Функция getCountSteps вызывает внутри себя функцию step. В функции step перед return стоит console.log с возвращаемым массивом, который выводится как и ожидается. В функции getCountSteps записывается результат функции step в переменную, после чего console.log возвращается undefined Код: https://jsfiddle.net/jcz8g7he/ const getStepsCount = items => { /*Временное (или нет) решение для подсчета кол-ва ходов Закрашиваем все поле в тот цвет, ячеек которого больше всего Находим другой цвет и закрашиваем в наш Пока не закрасим все поле, кол-во итераций будет кол-вом шагов (возможно +1)*/ const count = items.length; //Кол-во ячеек let colorsCount = {}; //Объект цвет = его кол-во for (let i = 0; i < count; i++) { //Идем по всему массиву for (let j = 0; j < count; j++) { if (colorsCount.hasOwnProperty(items[i][j])) { //Если уже был такой цвет, увеличиваем его кол-во colorsCount[items[i][j]]++; } else { //Иначе, создаем colorsCount[items[i][j]] = 1; } } } const mainColor = Object.keys(colorsCount).reduce((result, item) => colorsCount[item] > colorsCount[result] ? item : result); //Цвет которого больше всего console.log(mainColor); let stepsCount = 0; for (let i = 0; i < count; i++) { //Идем по всем ячейкам for (let j = 0; j < count; j++) { if (items[i][j] != mainColor) { //Если ячейка не основного цвета, заменяем и счиатем шаги console.log('i = ' + i); console.log('j = ' + j); console.log(items[i][j]); items = step(items, i, j, items[i][j], mainColor); stepsCount++; console.log(items); } } } console.log(stepsCount); } const step = (items, row, column, colorOriginal, color, stack = []) => { /* Идем от стартовой ячейки во все стороны заменяя все возможные ячейки. Все замененные ячейки сохраняем в массив. Достаем последний элемент массива и кидаем в эту функцию в качестве главного элемента, из массива удаляем Продолжаем пока массив не будет пуст */ if (color == colorOriginal) { //Если заменяем цвет на такой же, возвращаем 0 return 0; } items[column][row] = color; let check = true; let i = 0; while (check) { //Идем "вверх" i++; if (column - i + 1 > 0) { //Если не верхняя ячейка и нужный цвет if (items[column - i][row] == colorOriginal) { items[column - i][row] = color; //Заменяем цвет stack.push({'column': column - i, 'row': row}); //Добавляем ячейку в стек для дальнейшних проверок } } else { //Иначе выходим с цикла check = false; i = 0; } } while (!check) { //Идем "вниз" i++; if (column + i < items.length) { //Если не нижняя ячейка и нужный цвет if (items[column + i][row] == colorOriginal) { items[column + i][row] = color; //Заменяем цвет stack.push({'column': column + i, 'row': row}); //Добавляем ячейку в стек для дальнейшних проверок } } else { //Иначе выходим с цикла check = true; i = 0; } } while (check) { //Идем "влево" i++; if (row - i + 1 > 0) { //Если не левая ячейка и нужный цвет if (items[column][row - i] == colorOriginal) { items[column][row - i] = color; //Заменяем цвет stack.push({'column': column, 'row': row - i}); //Добавляем ячейку в стек для дальнейшних проверок } } else { //Иначе выходим с цикла check = false; i = 0; } } while (!check) { //Идем "вправо" i++; if (row + i < items.length) { //Если не правая ячейка и нужный цвет if (items[column][row + i] == colorOriginal) { items[column][row + i] = color; //Заменяем цвет stack.push({'column': column, 'row': row + i}); //Добавляем ячейку в стек для дальнейшних проверок } } else { //Иначе выходим с цикла check = true; i = 0; } } if (stack.length != 0) { //Если массив не пустой const temp = stack.pop(); //Берем последний элемент step(items, temp.row, temp.column, colorOriginal, color, stack); //Заменяем от "последнего" элемента } else { console.log(items); return items; //Когда стек пуст, возвращаем новый массив } } const items = [ [ "itemGreen", "itemGreen", "itemGreen", "itemBlue" ], [ "itemBlue", "itemGreen", "itemGreen", "itemGreen" ], [ "itemGreen", "itemBlue", "itemGreen", "itemBlue" ], [ "itemGreen", "itemBlue", "itemGreen", "itemBlue" ] ]; getStepsCount(items); Надеюсь понятно в чем вопрос. Перед return стоит console.log и все ок, но после присвоения в перемннную результата этой функции, значение становится undefined. Не понимаю почему A: Вопрос решил. В JS чтобы работала рекурсивная функция надо сделать так const func = i => { if (i != 10) { i++; return func(i); } else return 0; } а не вот так, как я пробовал изначально const func = i => { if (i != 10) { i++; func(i); } else return 0; }
{ "pile_set_name": "StackExchange" }
Q: How to change reply-to and return-path header with gmail smtp in django I am using gmail smtp in my django website. I have a contact form where user put email and message then I send a mail to the admin with : email = EmailMessage('email subject', 'email message', settings.EMAIL_HOST_USER, ['[email protected]'], headers = {'Reply-To': '[email protected]', 'Sender': '[email protected]','from': '[email protected]','Return-Path': '[email protected]'}) email.send(fail_silently=False) email is sent/received correctly but when admin client select reply in gmail, it always reply to the settings.EMAIL_HOST_USER and not the user address. On the email original header the From and Return-path are set with the setting.EMAIL_HOST_USER A: Google violates the RFPs defining the expected operation of an SMTP server, rewriting the headers. This may be the root cause of your problem: http://lee-phillips.org/gmailRewriting/
{ "pile_set_name": "StackExchange" }
Q: changes of db details in local.xml not affecting I recently moved my magento store to Amazon cloud server and database to RDS database server. I made the necessary changes in local.xml and cleared the var/cache and var/session folder. But I don't know how the magento is still picking the old database details which I was using on old server. I think its not picking the details from local.xml but from some other cache stored somewhere else other than var/cache. I have even tried by renaming and deleting the local.xml file but still result is the same. Where else could be the configuration cached data be stored ? Please help. A: Make sure there are no local.xml.extra or local.xmlanything files in app/etc directory. (This happened with me sometimes. I had a habit of renaming old local.xml file to local.xml2 and Magento picks that local.xml2 file as a configuration file. So you should delete the old file or move it to some different location.) Make sure the Magento Caching/ Any other caching is disabled. There can be Full Page Cache Extensions installed in your Magento Setup. Refer this link Magento cache not getting cleared
{ "pile_set_name": "StackExchange" }
Q: Presenting a childViewController of a viewController by "presentViewController" causes error? There is a viewController here. In its addChildViewController function, I add a tableViewController as its child. Now, what we can see is the viewController's, but I want to show the tableViewController's tableView. I achieve this by: [viewController presentViewController:tableViewController animate:YES xxx:xxx] What I do in the 2nd step trigger some error:“Application tried to present modally an active controller.” So the question is: If I want to show a view of the childViewController of a viewController, couldn't I use presentViewController function? If so, why? How could I solve the problem? Thanks a lot for reading and answering. I've hunt for the reason for days. A: This is what gives you a clue for the answer "Application tried to present modally an active controller。" There are two solutions: 1.Instead of using presentViewController, you should use addSubview like this: [viewController.view addSubview:tableViewController.view]; 2.Instead of using addChildViewController: // [viewController addChildViewController:tableViewController]; [viewController.view presentViewController:tableViewController animate:YES completion:nil];
{ "pile_set_name": "StackExchange" }
Q: java.lang.UnsupportedClassVersionError for running Jena API on Tomcat 8 I am deploying Spring application on Tomcat 8 server. The application uses Jena API from this maven repository. When I open the application in browser, it shows the following message (the same application can be opened without any problem when I do not use Jena API): HTTP Status 500 - Handler processing failed; nested exception is java.lang.UnsupportedClassVersionError: org/apache/jena/query/QueryExecutionFactory : Unsupported major.minor version 52.0 (unable to load class org.apache.jena.query.QueryExecutionFactory) I tried to solve this problem by changing the version of Java for Tomcat 8. I opened sudo nano /etc/init/tomcat.conf and changed JAVA_HOME: env JAVA_HOME=/usr/lib/jvm/java-8-oracle/jre Then I restarted Tomcat 8 server and redeployed my application, but the same problem still exists. In fact I noticed that for some reason JRE 7 appears in the log message when starting the server: May 07, 2016 5:26:11 PM org.apache.catalina.startup.VersionLoggerListener log INFO: Java Home: /usr/lib/jvm/java-7-oracle/jre May 07, 2016 5:26:11 PM org.apache.catalina.startup.VersionLoggerListener log INFO: JVM Version: 1.7.0_80-b15 May 07, 2016 5:26:11 PM org.apache.catalina.startup.VersionLoggerListener log INFO: JVM Vendor: Oracle Corporation I am not sure if this might be a possible reason of why the problem is not fixed. Any solution is highly appreciated. P.S. I know that java.lang.UnsupportedClassVersionError happens because of a higher JDK during compile time and lower JDK during runtime. So, do I understand correctly that Jena API was compiled with lower JDK? A: Actually as far as I can see in the jar that you provide, the major version of Jena is 52 which means that it has been compiled with java 8, I believe that your problem is more due to the fact that you run tomcat with java 7 For more details about how to know the version of a class, please refer to this answer To indicate Tomcat which JDK to use, you need to set the JAVA_HOME to the path of a JDK not a JRE by doing this export JAVA_HOME=/usr/lib/jvm/java-8-oracle. More details here
{ "pile_set_name": "StackExchange" }
Q: Vue.js class is not instantiated I have a class named Artefact which contains a component AddArtefact. But the Instance Lifecycle Hooks (mounted, created...) are not called in the AddArtefact class and if you print this it shows null. But why is this? Artefact: <template> <div> <button v-show="selectedTab === 0" @click="AddArtefact">Add Artefact</button> <AddArtefact v-show="selectedTab === 1"></AddArtefact> </div> </template> <script lang="ts"> import {Vue, Prop, Component} from 'vue-property-decorator'; import $ from 'jquery'; import AddArtefact from '@/views/add/AddArtefact.vue'; @Component({ components: { AddArtefact, }, }) export default class Artefact extends Vue { private selectedTab: number = 0; private AddArtefact() { this.selectTab(1); } private selectTab(tab: number) { this.selectedTab = tab; } } </script> AddArtefact: <template> <div> <p>{{Test}}</p> <button @click="testClick">Test Button</button> </div> </template> <script lang="ts"> import {Vue, Component, Prop} from 'vue-property-decorator'; import $ from 'jquery'; export default class AddArtefact extends Vue { private Test: string = ''; private mounted() { this.Test = 'Test 123'; console.log('test'); } private testClick() { console.log('Test Click'); console.log(this); } } </script> A: You forgot to add @Component: @Component export default class AddArtefact extends Vue { And you can put the mounted in there too: @Component({ mounted(this: AddArtefact) { ... } }) export default class AddArtefact extends Vue {
{ "pile_set_name": "StackExchange" }
Q: iOS change callout when there is multiple items at same position Is there a way how can I change callout view when there are multiple annotations at same position? If there is one then just show normal callout and if there is more then I would like to show callout with text like: "3 items at this place" and then I would go to table view and then to detail (with one item at place just go to detail place). Is it possible? What's best way to do this? Thanks A: This technique is called clustering. Check out cocoacontrols.com for some approaches for doing this with MapKit.
{ "pile_set_name": "StackExchange" }
Q: VBA: Creating charts dynamically, inconsistent output I think the issue is that I am using series and not overwriting them, but I am uncertain how to write code that will not store/delete a series after a chart has been generated. Also, sometimes the charts generate as intended and other times they generate with both series and I can't discern a pattern in this behavior. Basically looking to create a chart that will only use the columns I am passing in on that particular iteration of the loop rather than storing previously generated series. The loop I'm using for generation: 'Loop for charts Dim vGen As Variant Dim vCurrent As Variant vGen = Array("NOx EFL", "NOx EFH", "NOx UAF", "NOx_EFA") ', "NOx DAF") For Each vCurrent In vGen Set Search = Cells.Find(What:=vCurrent, _ After:=Cells(1, 1), _ LookIn:=xlValues, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False) If Not Search Is Nothing Then Set Row_Start = Range(Search.Address).Offset(1, 0) Set Row_End = Range(Search.Address).Offset(row_count, 0) Set Data_Rng = Range(Row_Start, Row_End) Call make_chart(Fam_Rng, Data_Rng, Row_Start) End If Next vCurrent The chart creation function: Function make_chart(Fam, Data, Row_Start) Dim wbsheet As String sheetName = ActiveSheet.Name 'Dim Char As Chart' Title_Str = Range("A2").Value & " " & Row_Start.Offset(-1, 0).Value Set Char = Charts.Add 'With Worksheets("Charts").ChartObjects(Title_Str).Chart With Char .SeriesCollection(1).Values = Data .SeriesCollection(1).XValues = Fam '.ChartType = xlColumnClustered .HasTitle = True .ChartTitle.Text = Title_Str .HasLegend = False .Name = Title_Str End With Worksheets(sheetName).Activate End Function A: What range/data is selected at the time the chart is created can affect the outcome: I typically start by removing all series from any chart I create in code, before adding in the specific data I want to see. Untested: Sub make_chart(Fam, Data, Row_Start) Dim wbsheet As String sheetName = ActiveSheet.Name Dim Char As Chart Title_Str = Range("A2").Value & " " & Row_Start.Offset(-1, 0).Value Set Char = Charts.Add With Char For Each s In .SeriesCollection s.Delete Next s With .SeriesCollection.NewSeries() .Values = Data .XValues = Fam End With '.ChartType = xlColumnClustered .HasTitle = True .ChartTitle.Text = Title_Str .HasLegend = False .Name = Title_Str End With Worksheets(sheetName).Activate End Sub
{ "pile_set_name": "StackExchange" }
Q: What should the chkconfig line in a RHEL init.d script be set to for a process controller like supervisord? I'm trying to write a init.d script for the first time to start a supervisord process. Supervisor is a process controller/manager like runit, upstart, or systemd. I would like it to start automatically if the system reboots, so that it can start my applications. I used this tldp tutorial as a base to write an init.d script. It works fine but I don't understand how I should modify this line in the file: # chkconfig: 2345 95 05 The note in the tutorial for this line states: Although these are comments, they are used by chkconfig command and must be present. This particular line defines that on runlevels 2,3,4 and 5, this subsystem will be activated with priority 95 (one of the lasts), and deactivated with priority 05 (one of the firsts). This RHEL doc explains the various runlevels as so: 0 - Halt 1 - Single-user text mode 2 - Not used (user-definable_ 3 - Full multi-user text mode 4 - Not used (user-definable) 5 - Full multi-user grapical mode 6 - Reboot From these choices, I suppose I would like to run mine on 35, assuming that 1 is only for system administrators. There are a few example supervisord init.d scripts, for example here. I noticed that all of the RHEL init.d scripts contain the following line: # chkconfig: 345 83 04 In this case, what reason could the authors have to want it to be active on runlevel 4, which is "not used" ? The nginx init.d script that I installed contains this line: # chkconfig: - 86 16 What does the - mean for the runlevel here? Why does this line not contain a deactivate priority? How does one decide upon the priority levels for a process controller like supervisor? The scripts above chose 83 and 04, whereas the tldp tutorial chose 95 and 05. A: chkconfig: 345 83 04 In this case, what reason could the authors have to want it to be active on runlevel 4, which is "not used" ? Since runlevel 4 is not used, so it does not matter you set it on or off. 345 is easier to write, lazy approach. and you can always change it later by chkconfig --list supervisord chkconfig --level 4 supervisord off chkconfig --level 3 supervisord on The nginx init.d script that I installed contains this line: chkconfig: - 86 16 What does the - mean for the runlevel here? it means you have to replace the dash with the levels or keep as is to be set by chkconfig chkconfig: 345 86 16 Why does this line not contain a deactivate priority? 345 run levels 86 activate priority 16 deactivate priority How does one decide upon the priority levels for a process controller like supervisor? The scripts above chose 83 and 04, whereas the tldp tutorial chose 95 and 05. Those are examples, not really the real thing, they are set differently. The priority normally does not matter, because you do not power up or power down your machines regularly, I am not familiar with your apps, I would recommend this one. This url contains a different priority https://rayed.com/wordpress/?p=1496 chkconfig: 345 64 36 or keep as is, to let the chkconfig to configure it for you chkconfig: - 64 36 I checked my answer on my system centOS, new recommendation: use yum to install supervisord, keep the default priority as it is being tested by many others urname -r 2.6.32-573.12.1.el6.centos.plus.x86_64 Install supervisord: sudo yum install supervisor supervisor.noarch 0:2.1-9.el6 The default priority for this version of supervisord is: cat /etc/init.d/supervisord |grep chkconfig #chkconfig: - 95 04 Change on/off without changing the supervisord [gliang@www prima]$ chkconfig --list supervisord supervisord 0:off 1:off 2:off 3:off 4:off 5:off 6:off [gliang@www prima]$ sudo chkconfig --level 3 supervisord on [gliang@www prima]$ sudo chkconfig --level 4 supervisord off The S95 on level 3 has almost lowest priority, start late, shutdown first [gliang@www prima]$ ls -ltr /etc/rc3.d/|grep supervisor lrwxrwxrwx. 1 root root 21 Jan 29 08:02 S95supervisord -> ../init.d/supervisord [gliang@www prima]$ ls -ltr /etc/rc4.d/|grep supervisor lrwxrwxrwx. 1 root root 21 Jan 29 08:02 K04supervisord -> ../init.d/supervisord use this to list and to see the priority of all daemons on this level ls -ltr /etc/rc3.d/
{ "pile_set_name": "StackExchange" }
Q: Why misspelled android:name do not have a warning or error? I hava a receiver <receiver android:name=".AlarmReceiver" /> But the receiver's class name is AlarmReciver (misspelled) why android-sdk show this mistake or show this when running? A: Because that class is loaded by reflection, so compiler doesn't know that class doesn't exist (for the compiler, this a String, not a class name). When the JVM will attempt to load that class by reflection, it should throw a ClassNotFoundException indicating there's no such class.
{ "pile_set_name": "StackExchange" }
Q: What's wrong with this proof about the cardinality of N^N? Cantor's diagonalisation argument shows that $|N^N| = |R|$ so obviously $|N^N| > |N|$. $N^N$ is $N$ times itself, $N$ times. This is the set of $N$-tuples with elements in $N$. To prove that $|N^N| = |N|$ we need to find a bijection between $N$ and $N^N$, a function mapping an element of $N^N$ to an element of $N$. Elements $x$ of $N^N$ are of the form $x=(a_1, a_2, ..., a_i, ...)$ where the $a_i$s are elements of $N$. Consider the function $f(a_1, a_2,...a_i,...) = 2^{a_1}3^{a_2}...{p_i}^{a_i}...$ where $p_i$s are primes. This function is surjective because every natural number has a prime factorisation therefore every element in the range ($N$) is the image of at least one element in the domain ($N^N$) This function is injective because prime factorisation is unique so no natural number has two different prime factorisations. So $f(x_1) = f(x_2)$ only when $x_1=x_2$ This function is injective and surjective therefore it is a bijection This proves that $|N^N| = |N|$ But this is obviously wrong! What mistake have I made in this proof? A: Can a natural number be the product of infinitely many primes? For example $(1,1,1,\cdots)\mapsto2\cdot3\cdot5\cdots$ doesn't define a natural.
{ "pile_set_name": "StackExchange" }
Q: Scala return statements in anonymous functions Why does an explicit return statement (one that uses the return keyword) in an anonymous function return from the enclosing named function, and not just from the anonymous function itself? E.g. the following program results in a type error: def foo: String = { ((x: Integer) => return x) "foo" } I know it's recommended to avoid the return keyword, but I'm interested in why the explicit and implicit return statements have a different semantics in anonymous functions. In the following example, the return statement "survives" after m has finished executing, and the program results in a run-time exception. If anonymous functions didn't return from the enclosing function, it would not be possible to compile that code. def main(args: Array[String]) { m(3) } def m: (Integer => Unit) = (x: Integer) => return (y: Integer) => 2 A: Formally speaking return is defined as always returning from the nearest enclosing named method A return expression return e must occur inside the body of some enclosing named method or function. The innermost enclosing named method or function in a source program, f , must have an explicitly declared result type, and the type of e must conform to it. The return expression evaluates the expression e and returns its value as the result of f . The evaluation of any statements or expressions following the return expression is omitted. So it doesn't have different semantics in a lambda. The wrinkle is that, unlike a normal method, a closure created from a lambda can escape a call to the enclosing method and you can get an exception if there is a return in such a closure. If the return expression is itself part of an anonymous function, it is possible that the enclosing instance of f has already returned before the return expression is executed. In that case, the thrown scala.runtime.NonLocalReturnException will not be caught, and will propagate up the call stack. Now, as for "why". One lesser reason is aesthetic: lambdas are expressions and it's nice when an expression and all its subexpression have the same meaning no matter what the nesting structure. Neal Gafter talks about that at http://gafter.blogspot.com/2006/08/tennents-correspondence-principle-and.html The main reason it exists, though, is it allows you to easily simulate forms of control flow commonly used in imperative programming but still allows you to abstract things into higher order functions. As a toy example, Java's foreach construct (for (x : xs) { yada; }) allows a return inside the loop. Scala doesn't have a language level foreach. Instead, it puts foreach in the library (not counting "for expression" without yield since they just desugar to foreach). Having a non-local return means you can take a Java foreach and translate directly to a Scala foreach. BTW, Ruby, Smalltalk, and Common Lisp (off the top of my head) also have similar "non-local" returns. A: The return keyword is reserved for (class) methods, it cannot be used in functions. You can easily test that: object Foo { val bar = (i: Int) => return i + i } This gives <console>:42: error: return outside method definition object Foo { val bar = (i: Int) => return i + i } ^ Mostly you can treat methods and functions as the same, because of the function's apply method behaving syntactically like calling a method, and so-called eta-expansion allowing a method to be passed as a function argument. In this case, it makes a difference. When defining as method, it is legal: object Foo { def bar(i: Int): Int = return i + i } In summary, you should only use return in methods that allow conditional (early) returns. See this post for a discussion on methods versus functions.
{ "pile_set_name": "StackExchange" }
Q: Aggregating across multiple fields I thought I had this figured out, but it's eluding me. There's a MySQL database backending a web app that collects user surveys of various theme parks. There's a series of 30 questions, some have radio-button style multiple choice and some are checkbox-style. The responses are all stored in a relational table that resembles this: "id"|"q_id"| "a_id"|"u_id" |"p_id"| "1"| "1"| "1"|"8f699ecbd9f130df14c1e4e0a6383516"|"106397"| "2"| "1"| "2"|"8f699ecbd9f130df14c1e4e0a6383516"|"106397"| "3"| "2"| "1"|"8f699ecbd9f130df14c1e4e0a6383516"|"106397"| "4"| "3"| "1"|"8f699ecbd9f130df14c1e4e0a6383516"|"106397"| "7"| "3"| "3"|"8f699ecbd9f130df14c1e4e0a6383516"|"106397"| "8"| "3"| "4"|"8f699ecbd9f130df14c1e4e0a6383516"|"106397"| "9"| "1"| "2"|"348895be7b4affac001c9ba096d8c1d3"|"106397"| "10"| "1"| "3"|"348895be7b4affac001c9ba096d8c1d3"|"106397"| "11"| "3"| "2"|"348895be7b4affac001c9ba096d8c1d3"|"106397"| "13"| "3"| "3"|"348895be7b4affac001c9ba096d8c1d3"|"106397"| "1"| "1"| "3"|"8f699ecbd9f130df14c1e4e0a6383516"|"380486"| "3"| "2"| "2"|"8f699ecbd9f130df14c1e4e0a6383516"|"380486"| "4"| "3"| "2"|"8f699ecbd9f130df14c1e4e0a6383516"|"380486"| "7"| "3"| "4"|"8f699ecbd9f130df14c1e4e0a6383516"|"380486"| "8"| "3"| "4"|"8f699ecbd9f130df14c1e4e0a6383516"|"380486"| "11"| "3"| "2"|"348895be7b4affac001c9ba096d8c1d3"|"380486"| "13"| "3"| "3"|"348895be7b4affac001c9ba096d8c1d3"|"380486"| q_id is the question answered a_id is the option chosen u_id is the user that chose the option p_id is the amusement park they answered the question Thus, this table may contain multiple records where u_id, q_id and p_id are the same in the case of a checkbox-style question, but never one where u_id, q_id, p_id and a_id are the same. What I need to do is create a query that will give me a count of the total number of times each given question has been answered for a given amusement park. In this case, what I'd need is: "p_id"|"count" "106397"|"5" "380486"|"4" ...in other words, I need each p_id, with a count of the number of unique instances of both q_id and u_id. I thought this would work: SELECT distinct p_id, count(concat(q_id,u_id)) from responses group by p_id But that still seems to be counting two records that have the same values for q_id and u_id but different values of a_id twice, giving me: "p_id"|"count" "106397"|"10" "380486"| "7" What can I do to this query to make this aggregate function work? A: Bluefeet's answer is definitely one way to go. This is how you modify your approach to make it work: SELECT p_id, count(distinct concat(q_id,':',u_id)) from responses group by p_id; These are the changes that I made: Removed the distinct in select distinct. This is (generally) redundant with a group by. Changed the count() to count(distinct). You want to count distinct occurrence of this pair. Added a separator. That way (23, 4) doesn't get confused with (2, 34). Just in case.
{ "pile_set_name": "StackExchange" }
Q: How to import millions of records from SQL Server 2000 to Microsoft Excel 2010 I have around 3.5 million records that i want to import into a Excel 2010 file. I have tried using SQL Servers Import/Export Data Wizard and this worked but the problem was that it only copied about 65,000 out of the 3,500,000 records i need. This is due to a limit that is on Excel. I have tried to install PowerPivot to try increase the amount of records that could be inserted into excel but with no luck. Does anyone know how i would do this? A: I was able to do this thanks to jsobo's comment above. I first created a blank .csv file. Then i was able to use SQL Servers DTS Import/Export Wizard to add all the fields straight from the database to the .csv file
{ "pile_set_name": "StackExchange" }
Q: Java : BufferedImage to Bitmap format I have a program in which i capture the screen using the code : robot = new Robot(); BufferedImage img = robot.createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); Now i want to convert this BufferedImage into Bitmap format and return it through a function for some other need, Not save it in a file. Any help please?? A: You need to have a look at ImageIO.write. The Java Tutorials: Writing/Saving an Image If you want the result in the form of a byte[] array, you should use a ByteArrayOutputStream: ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(yourImage, "bmp", baos); baos.flush(); byte[] bytes = baos.toByteArray(); baos.close();
{ "pile_set_name": "StackExchange" }
Q: Add smooth transition when changing an element's display using JavaScript I've added a search bar in the header that is set to display: none by default and I used js to make it appear on a button click via assigning a .show class which contains display: block !important to the search bar element (#search). It's working fine but my only problem is the rough transition from display: none to block, so I've been looking into ways to make this transition smooth and most of the answers I found were using jQuery, which I don't really want to do since I'm still in the learning phase of js, so if there's a way I can do this using vanilla js, please help me with it. Here's my code https://jsfiddle.net/5jxLq9ck/ In CSS line 38, I add the .show utility class .show { display: block !important; } And I'm assuming I'll have to edit something in here (js) to get the desired effect: function showSearch(e) { e.preventDefault; if ( e.target.classList.contains("show-btn") || e.target.classList.contains("fas") ) { const searchBar = document.querySelector("#search"); searchBar.classList.add("show"); } } Additional question: is my use of e.preventDefault correct here? The functionality didn't work until I used it. Thanks a lot in advance. A: Here is an updated snippet, I've changed the input width for the animation. You can make it even more smooth by set the input height. const searchDiv = document.querySelector("#search-div"); // ADD EVENT LISTENERS searchDiv.addEventListener("click", showSearch); // FUNCTION: SHOW SEARCH BAR ON BUTTON CLICK function showSearch(e) { e.preventDefault; if ( e.target.classList.contains("show-btn") || e.target.classList.contains("fas") ) { const searchBar = document.querySelector("#search"); searchBar.classList.add("show"); } } /* GENERAL */ :root { --light-color: #ccc; --lighter-color: #f4f4f4; --dark-color: #333; --darker-color: #222; --brand-color: #ff4; --danger: #f44; --danger-dark: #c00; } * { margin: 0; padding: 0; box-sizing: border-box; } body { background: var(--dark-color); color: var(--light-color); font-family: "Trebuchet MS"; } ul li { list-style: none; } button, input { outline: none; } /* UTILITY */ .highlight { color: var(--brand-color); } .show { width: 300px !important; border: black 2px solid; padding: 0.6rem 1rem; } /* HEADER */ header { background: var(--darker-color); display: flex; flex-direction: row; align-items: center; text-align: center; justify-content: space-between; padding: 1.4rem 6rem; width: 100%; } #logo { font-size: 2.4rem; font-weight: 200; } #search-div { width: auto; height: auto; display: flex; gap: 0.4rem; } .show-btn { padding: 0.6rem 0.7rem; background: var(--light-color); border-radius: 5px; border: none; transition: ease-in 300ms; font-size: 1.2rem; cursor: pointer; height: 100%; margin-top: 2px; } .show-btn:hover { background: var(--brand-color); transition: ease-in 300ms; } #search { width: 0; background: var(--lighter-color); color: var(--darker-color); height: 100%; font-size: 1.2rem; border-radius: 2px; transition: ease-in 300ms; border: none; } <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Contact List</title> <link rel="stylesheet" href="css/style.css"> <script src="https://kit.fontawesome.com/3ad7573e76.js" crossorigin="anonymous"></script> </head> <body> <header> <div id="logo-div"> <h1 id="logo"> <span class="highlight"><i class="fas fa-user-friends"></i></span> My<span class="highlight">Contact</span>List </h1> </div> <div id="search-div"> <button class="show-btn"><i class="fas fa-search"></i></button> <input id="search" type="text" placeholder="Search contacts..."> </div> </header> <script src="js/main.js"></script> </body> </html>
{ "pile_set_name": "StackExchange" }
Q: Return a value if no rows selected are found Oracle Here's my simple query. If I query a record that doesn't exist then I will get nothing returned. SELECT CASE WHEN table1.column1= @column1 THEN 'XX' ELSE 'YY' END from table1 where table1.column2=@column2 It returns no rows selected. I tried ISNULL() .But not rectified I need to return 'YY' Could anyone helpme out..!! Thanks in Advance!! A: The query you have posted has @ symbol, which is not the default substitution character for variables in Oracle as in SQL-Server, unless you have used something like SET DEFINE @ and put quotes while passing string literals.Not sure if you are using it that way. I would suggest you to use a bind variable which is prefixed by a colon : Regarding your question I need to return 'YY' for no rows selected, you could put your case block inside an aggregate function, such as MAX, which will return a row with a null and COALESCE can then handle the nulls to give you the desired value, when there are no rows. SELECT COALESCE( MAX( CASE WHEN t.column1 =:column1 THEN 'XX' ELSE 'YY' END ),'YY') FROM table1 t WHERE t.column2 =:column2;
{ "pile_set_name": "StackExchange" }
Q: yes/no :Is $f(x) $ is irreducible over $\mathbb{Z}$? Is $f(x) = (x-1)(x-2)(x-3)(x-4) +1 $ is irreducible over $\mathbb{Z}$ ? My attempt: yes, by using Eisenstein criterion, $f(x)$ is not reducible. Is this correct? A: Hint: It is $$(5-5x+x^2)^2=(x-1)(x-2)(x-3)(x-4)+1$$
{ "pile_set_name": "StackExchange" }
Q: Does a teflon insert in an E3D V6 clone limit it's useable temperature so it can't print nylon? I'm new to this game, and recently upgraded the hotend on my Ender 3 Pro to a clone of an E3D V6, as I'm keen to do nylon prints at some point. I noticed however that this one I got has a teflon liner which seems to negate the advantage of a metal hotend entirely. I'm wondering what temperature it's safe to run this hot end up to? A: There are many types of heatbreak clones. In cour case, your clone effectively turns your hotend into an e3d Lite6, not an all-metal e3d v6. To function properly, the PTFE liner needs to butt against the nozzle or you will quickly develop leak and clog issues. This means, handle it like a Lite6, which has a max of 245 °C listed, but under usual operation should not exceed 230 °C.
{ "pile_set_name": "StackExchange" }
Q: programmatically show on-screen keyboard in windows7 in .NET Is there a way to programmatically open and show the Windows 7 on-screen keyboard using .NET? I've found two potential solutions but neither work. My app is WPF/.NET 4. The first approach is from the two following links, but they require the on-screen keyboard to already be open as they use the FindWindow Win32 call: http://hot-virtual-keyboard.com/development/q1/ Finding the class name of the On-Screen Keyboard? The other route I've tried was this (Show up the On Screen keyboard if the user sets the focus on a textfield. WPF with .Net 4 Client profile): Process.Start("osk.exe"); But this call just fails with a message box that says "Could not start On-Screen Keyboard". Any ideas? A: What platform do you compile your application for? If it's set to x86 that might cause that error if your system is 64 bit. Edit: Just found this question which might be helpful if this is actually the cause.
{ "pile_set_name": "StackExchange" }
Q: how can I edit the code button in wordpress I have installed prettyprint in my Wordpress theme. Now in order to use it, I need to wrap my code in: <pre class="prettyprint"> <code> code here </code> </pre> Now the code button on Wordpress html editor provides only the <code></code> tag. Now is there a way to edit this so that I can add the extra span? A: Add this in your functions.php: function my_quicktags() { wp_enqueue_script( 'my_quicktags' , get_template_directory_uri() . '/js/quicktags.js' , array('quicktags') ); } add_action('admin_enqueue_scripts' , 'my_quicktags'); Create a file called quicktags.js, place it into a js folder, in your theme directory. Copy all the content of your /includes/js/quicktags.js file. You can edit/delete/add anything, specially the last strings, which are the corresponding to editor tags. Now you can add your span: edButtons[15] = new qt.TagButton('span-1','My Span','<span class="myClass">','</span>','X'); That means: edButtons[position] = new qt.TagButton('ID','Display Name (value)','opening tag','ending tag','shortcut key');
{ "pile_set_name": "StackExchange" }
Q: Libreoffice won't start Trying to start Libreoffice, I get: /usr/bin/libreoffice: 161: exec: /usr/bin/oosplash: not found I messed up recently with libreoffice by executing: sudo sed -i 's/X-GIO-NoFuse=true/#X-GIO-NoFuse=true/' /usr/share/applications/libreoffice-* sudo sed -i 's/X-GIO-NoFuse=true/#X-GIO-NoFuse=true/' /usr/bin/libreoffice I tried: sudo apt-get remove libreoffice-core followed by: sudo apt-get install libreoffice Do you have any idea on how I can fix that? A: Try sudo apt-get --purge remove libreoffice-core and then sudo apt-get install libreoffice
{ "pile_set_name": "StackExchange" }
Q: MuPDF error when changing device orientation I use MuPDF library to view PDF on android application , it's ok when viewing the pdf on portrait pode , but once change the orientation to landscape the app crash. --------- beginning of crash 2019-01-14 15:50:41.288 24024-24225/com.niveales.wind A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x9 in tid 24225 (AsyncTask #4) 2019-01-14 15:50:41.314 24024-24035/com.niveales.wind I/art: Background sticky concurrent mark sweep GC freed 2151(88KB) AllocSpace objects, 7(140KB) LOS objects, 0% free, 56MB/56MB, paused 1.192ms total 175.641ms 2019-01-14 15:50:41.415 24519-24519/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 2019-01-14 15:50:41.416 24519-24519/? A/DEBUG: Build fingerprint: 'google/sdk_google_phone_x86/generic_x86:7.1.1/NYC/4316688:user/release-keys' 2019-01-14 15:50:41.416 24519-24519/? A/DEBUG: Revision: '0' 2019-01-14 15:50:41.416 24519-24519/? A/DEBUG: ABI: 'x86' 2019-01-14 15:50:41.416 24519-24519/? A/DEBUG: pid: 24024, tid: 24225, name: AsyncTask #4 >>> com.niveales.wind <<< 2019-01-14 15:50:41.416 24519-24519/? A/DEBUG: signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 0x9 2019-01-14 15:50:41.416 24519-24519/? A/DEBUG: eax 00000001 ebx 8e012df8 ecx 8e78a000 edx 00000000 2019-01-14 15:50:41.416 24519-24519/? A/DEBUG: esi 8e83ec80 edi 8e77d694 2019-01-14 15:50:41.416 24519-24519/? A/DEBUG: xcs 00000073 xds 0000007b xes 0000007b xfs 0000003b xss 0000007b 2019-01-14 15:50:41.416 24519-24519/? A/DEBUG: eip 8cf12b2a ebp acab5bc0 esp 8e77d4d0 flags 00210202 2019-01-14 15:50:41.418 24519-24519/? A/DEBUG: backtrace: 2019-01-14 15:50:41.418 24519-24519/? A/DEBUG: #00 pc 00144b2a /data/app/com.niveales.wind-1/lib/x86/libmupdf.so 2019-01-14 15:50:41.419 24519-24519/? A/DEBUG: #01 pc 001454ba /data/app/com.niveales.wind-1/lib/x86/libmupdf.so (pdf_process_contents+490) 2019-01-14 15:50:41.420 24519-24519/? A/DEBUG: #02 pc 000e024d /data/app/com.niveales.wind-1/lib/x86/libmupdf.so 2019-01-14 15:50:41.420 24519-24519/? A/DEBUG: #03 pc 000e0545 /data/app/com.niveales.wind-1/lib/x86/libmupdf.so (pdf_run_page_contents+261) 2019-01-14 15:50:41.420 24519-24519/? A/DEBUG: #04 pc 00046d1d /data/app/com.niveales.wind-1/lib/x86/libmupdf.so (fz_run_page_contents+173) 2019-01-14 15:50:41.420 24519-24519/? A/DEBUG: #05 pc 00038487 /data/app/com.niveales.wind-1/lib/x86/libmupdf.so (Java_com_artifex_mupdfdemo_MuPDFCore_drawPage+2087) 2019-01-14 15:50:41.420 24519-24519/? A/DEBUG: #06 pc 00db2013 /data/app/com.niveales.wind-1/oat/x86/base.odex (offset 0xc90000) 2019-01-14 15:50:41.695 22480-24462/? E/PhenotypeFlagCommitter: Retrieving snapshot for com.google.android.gms.rcs failed java.util.concurrent.TimeoutException: Timed out waiting for Task at arde.a(:com.google.android.gms@[email protected] (040700-223214910):29) at akat.a(:com.google.android.gms@[email protected] (040700-223214910):2) at akat.a(:com.google.android.gms@[email protected] (040700-223214910):19) at akat.a(:com.google.android.gms@[email protected] (040700-223214910):26) at qdv.a(:com.google.android.gms@[email protected] (040700-223214910):5) at qdv.a(:com.google.android.gms@[email protected] (040700-223214910):1) at com.google.android.gms.common.config.PhenotypeUpdateOperation.onHandleIntent(:com.google.android.gms@[email protected] (040700-223214910):3) at com.google.android.chimera.IntentOperation.onHandleIntent(:com.google.android.gms@[email protected] (040700-223214910):2) at duh.run(:com.google.android.gms@[email protected] (040700-223214910):12) at due.run(:com.google.android.gms@[email protected] (040700-223214910):9) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) at java.lang.Thread.run(Thread.java:761) Does anyone know what wrong here? A: Add this line in activity tag in manifest android:configChanges="orientation|screenSize"
{ "pile_set_name": "StackExchange" }
Q: cellForNextPageAtIndexPath not visible in swift2 I am implementing PFQueryTableViewController from Parse with sections and pagination. Because I am using sections, I need to set the 'load more' cell on my own. However, It seems that I can't access the method cellForNextPageAtIndexPath - I get an error: ''UITablView' does not have a member name 'cellForNextPageAtIndexPath' ' . I've looked around and the only resource on the subject seems to be this unanswered question: cellForNextPageAtIndexPath in swift Here's my code: override func tableView(tableView: UITableView, cellForNextPageAtIndexPath indexPath: NSIndexPath) -> PFTableViewCell? { return PFTableViewCell() } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject!) -> PFTableViewCell? { let objectId = objectIdForSection((indexPath.section)) let rowIndecesInSection = sections[objectId]! let cellType = rowIndecesInSection[(indexPath.row)].cellType var cell : PFTableViewCell if (indexPath.section == self.objects?.count) { cell = tableView.cellForNextPageAtIndexPath(indexPath) //'UITablView' does not have a member name 'cellForNextPageAtIndexPath' } switch cellType { case "ImageCell" : cell = setupImageCell(objectId, indexPath: indexPath, identifier: cellType) case "PostTextCell" : //cell = setupImageCell(objectId, indexPath: indexPath, identifier: "ImageCell") cell = setupTextCell(objectId, indexPath: indexPath, identifier: cellType) case "CommentsCell" : cell = setupCommentsCell(objectId, indexPath: indexPath, identifier: cellType) case "UpvoteCell" : cell = setupUpvoteCell(objectId, indexPath: indexPath, identifier: cellType) case "DividerCell" : cell = setupDividerCell(indexPath, identifier: cellType) default : print("unrecognised cell type") cell = PFTableViewCell() } cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } A: I know it's kind of late, but I just figured this out and wanted to share for future visitors. If you want to customize the usual "Load more..." pagination cell in parse, do the following: 1) Create a new class that subclasses PFTableViewCell. For our demo purposes, we will call it PaginationCell. 2) Replace all of the contents of the PaginationCell class with the following: import UIKit import Parse import ParseUI class PaginateCell: PFTableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: "paginateCell") } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } Above we just initialized the cell with a reuseIdentifier of "paginateCell." This programmatically sets the reuseIdentifier. 3) In your PFQueryTableViewController, implement the following method: override func tableView(tableView: UITableView, cellForNextPageAtIndexPath indexPath: NSIndexPath) -> PFTableViewCell? { } 3) Create a nib file. For our demo purposes I'll call the file paginateCellNib.xib. Design the custom cell however you want. Be sure to set the cell reuseIdentifier and make it match the one above. Set the custom class to the PaginationCell class we created above, and connect all IBoutlets to this class. 4) Now, replace the contents of the cellForNextPageAtIndexPath above with the following content: override func tableView(tableView: UITableView, cellForNextPageAtIndexPath indexPath: NSIndexPath) -> PFTableViewCell? { // register the class of the custom cell tableView.registerClass(PaginateCell.self, forCellReuseIdentifier: "paginateCell") //register the nib file the cell belongs to tableView.registerNib(UINib(nibName: "paginateCellNib", bundle: nil), forCellReuseIdentifier: "paginateCell") //dequeue cell let cell = tableView.dequeueReusableCellWithIdentifier("paginateCell") as! PaginateCell cell.yourLabelHere.text = "your text here" return cell }
{ "pile_set_name": "StackExchange" }
Q: How to improve Java generics wildcard signature I'm trying to create DI container get method, but struggling with signature. Currently I have this definition: public Object get(Class<?> key) { // returns instance of `?` } The part of my code which I dont like much is usage of the get method: IRouter router = (IRouter) container.get(IRouter.class); where I have to cast return with (IRouter). Any ideas how to change method signature to make usage like this? IRouter router = container.get(IRouter.class); Thanks in advance for any ideas! A: By using a scoped method parameterized type : public <T> T get(Class<T> key) { // ... return (T) foo; } Here I suppose that foo is not typed as T. If it is already typed as T you can of course return it without cast. You could so invoke it : IRouter router = container.get(IRouter.class);
{ "pile_set_name": "StackExchange" }
Q: CSS3 selector last element that is not of class X I'm trying to style the last element of class Y that is not of class X. Example HTML: <div class="container"> <div class="Y"></div> <div class="Y"></div> <!-- this I want to style --> <div class="X Y"></div> </div> I've tried both .Y:not(.X):last-child and .Y:not(.X):last-of-type but they do not produce the desired result in Chromium. I'm wondering if it even can be done in CSS3... A: This is not possible via CSS Selectors currently. The desired behavior is only specified in CSS Selectors level 4, the one you could need is :not(.X):nth-last-match(1, .Y), but currently no browser supports it. So, the best solution is to use jQuery as @BoltClock wrote in a comment or to generate the desired class in the html.
{ "pile_set_name": "StackExchange" }
Q: Django ORM: Dynamically determine another table name according one field value I hit one problem when generate orm query upon there tables. I have models here: class Task(models.Model): deliver = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, related_name='task') tasktype = models.PositiveSmallIntegerField(db_index=True) description = models.CharField(max_length=500, null=True, blank=True) delivertime = models.DateTimeField(default=now,db_index=True) deadlinetime = models.DateTimeField(null=True,db_index=True) relatedresourceid = models.PositiveIntegerField(null=True) suggestspendtime = models.PositiveIntegerField(null=True) subjectid = models.PositiveIntegerField(null=True) class Lesson(models.Model): name = models.CharField(max_length=200,null=True,blank=True) class Exam(models.Model): name = models.CharField(max_length=200,null=True,blank=True) So, here I wanna query from Task model, what's more, for every Task object in queryset: I wanna get a value with key "name" from Lesson or Exam model, i.e for every Task object, if tasktype is 1, then get name value from Lesson model (where pk==relatedresourceid), if tasktype is 2 , then take it from Exam model. I use Django1.8 and Mysql 5.6 Anyone know how to query using ORM? Thanks. A: You should model the situation in another way: class Task(models.Model): deliver = models.ForeignKey(settings.AUTH_USER_MODEL, blank=False, related_name='task') tasktype = models.PositiveSmallIntegerField(db_index=True) description = models.CharField(max_length=500, null=True, blank=True) delivertime = models.DateTimeField(default=now,db_index=True) deadlinetime = models.DateTimeField(null=True,db_index=True) relatedresourceid = models.PositiveIntegerField(null=True) suggestspendtime = models.PositiveIntegerField(null=True) subjectid = models.PositiveIntegerField(null=True) class Lesson(models.Model): name = models.CharField(max_length=200,null=True,blank=True) tasks = models.ManyToManyField(Task, related_name='lessons') class Exam(models.Model): name = models.CharField(max_length=200,null=True,blank=True) tasks = models.ManyToManyField(Task, related_name='exams') That way, you can easily have the name of the Lesson or Exam the Task belongs to <a task>.lessons or <a task>.exams For your current approach, you can take all names this way: [{'task_id':task.pk, 'name': Lesson.objects.get(pk=task.relatedresourceid).name if task.tasktype==1 else Exam.objects.get(pk=task.relatedresourceid).name} for task in Task.objects.all()] This will give you a list like: [{'task_id':1, 'name': <Lesson or Exam name 1>}, {'task_id':2, 'name': <Lesson or Exam name 2>}, ..., {'task_id':N, 'name': <Lesson or Exam name N>}]
{ "pile_set_name": "StackExchange" }
Q: Cannot save table in SQL Server 2005 I have added a column to a table in SQL Server 2005. When I attempt to save it, I get this message: Saving changes is not permitted. The change you have made require the following tables to be dropped and re-created. You have either made changes to a table that can't be re-created or enabled the option Prevent saving changes that require the table to be re-created. The column I added was nothing special, a nullable nvarchar(11) with no index or constraints. I have never seen this problem before, and have changed the table many times earlier. Anyone know what's going on, and where I should look for the mentioned option? A: Found it. It was actually an option in SQL Server Management Studio 2008 (which I am using, even though the DB in question is 2005), and not in the DB or server instance as I expected. The option is exactly as stated in the error message "Prevent saving changes that require the table to be re-created". I found it in Management Studio under Tools -> Options -> Designers, and it is obviously enabled by default. A very strange default indeed!
{ "pile_set_name": "StackExchange" }
Q: Highcharts highlight a column dynamically I have a chart of countries. I don't know what position my target country will end up at in the chart - it depends on the data. How to dynamically highlight it, e.g., change the column colour and the name colour? For example if my target country is Portugal, how to display this in a different colour than the others. https://jsfiddle.net/2vsd7knr/1/ Highcharts.chart('container', { chart: { type: 'column' }, title: { text: 'Monthly Average Rainfall' }, subtitle: { text: 'Source: WorldClimate.com' }, xAxis: { categories: [ 'Sweden', 'South_Korea', 'Israel', 'Russia', 'Canada', 'Portugal', 'Turkey', 'Iran', 'France', 'China', 'Belgium', 'Brazil' ], crosshair: true }, yAxis: { min: 0, title: { text: 'Rainfall (mm)' } }, tooltip: { headerFormat: '<span style="font-size:10px">{point.key}</span><table>', pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>', footerFormat: '</table>', shared: true, useHTML: true }, plotOptions: { column: { pointPadding: 0.2, borderWidth: 0 } }, series: [{ name: 'Tokyo', data: [49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }] }); A: Below is a guideline how to finds current points and change their color. Demo: https://jsfiddle.net/BlackLabel/bd8xL6m2/ chart: { type: 'column', events: { render() { let chart = this, x; chart.series[0].points.forEach(p => { if (p.category === targetCountry) { x = p.x; p.graphic.element.style.fill = 'red' } }) chart.xAxis[0].ticks[x].label.element.style.fill = 'red' } } }, API: https://api.highcharts.com/highcharts/chart.events.render
{ "pile_set_name": "StackExchange" }
Q: Difference in button width between Firefox and Chrome I know there are lots of FF/Chrome CSS questions, but I can't seem to find this exact one. Here is a JS Fiddle showing the problem: http://jsfiddle.net/ajkochanowicz/G5rdD/1/ (Apologies for the long CSS, this was copied from the site.) Essentially, Firefox and Chrome are giving me two different values for the inner most width of the button, 4 and 6. I'd like it to be 4 or less for both. What is causing this? A: Try adding the css below. Firefox add an extra padding at the button. input::-moz-focus-inner, button::-moz-focus-inner { padding: 0; border: 0; } Related: Remove extra button spacing/padding in Firefox Source: http://wtfhtmlcss.com/#buttons-firefox-outline A: You didn't specify a width other than auto. Different rendering engines think differently how websites should be rendered. How about changing the width to 4px and :hover to whatever you want?
{ "pile_set_name": "StackExchange" }
Q: Adding datepicker date with integer I have my code where I have three fields, datepicker an input field for integer value an input box for showing resulting date. I select the datepicker date and it reads in dd/mm/yyyy format, say 06/02/2018. Now I enter an integer value in next input box and click a button to show resulting date after adding integer to the date selected. On result my date shows in mm-dd-yyyy format with that integer added to the month part of the selected date i.e. if I add 3 days to my selected date 06/02/2018 it should show 09/02/2018 but instead it displays the resulting date as 06/05/2018. How can this resolve? Any insight and input are welcome. <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div class="panel panel-primary"> <div class="panel-heading">Registration Parameters</div> <br><br> <form class="form-horizontal" method="post" action="" > <div class="form-group"> <div class="col-md-6"> <div class="col-md-4"> <label for="username" class="control-label"><b>Date from:</b></label> </div> <div class="col-md-8 input-group date" > <input id="txtDate" name="title" class="form-control" placeholder="Start Date" value="" > </div> </div> <div class="col-md-6"> <div class="col-md-4"> <label for="username" class="control-label"><b>New Date formed:</b></label> </div> <div class="col-md-8"> <div class="input-group date"> <input id="follow_Date" name="days_for_start" disabled class="form-control" value="" > </div> </div> </div> <br><br><br><br> <input type="button" id="btn" value="Check New Date" /> <div class="col-md-6"> <div class="col-md-4"> <label for="username" class="control-label"><b>Extension days:</b></label> </div> <div class="col-md-8"> <input id="extdays" type="text" name="days_for_end" class="form-control" required="" value="" > </div> </div> </div> </form> </div> <script type="text/javascript"> $(document).ready(function () { $('#txtDate').datepicker({ dateFormat:'mm/dd/yy', }); }); function getdate() { var tt = document.getElementById('txtDate').value; var input = document.getElementById('extdays').value; if (input == "" || input==null){ input =0 } if(tt != ''){ var date = new Date(tt); var newdate = new Date(tt); newdate.setDate(newdate.getDate() + parseInt(input)); var dd = newdate.getDate(); var mm = newdate.getMonth() + 1; var y = newdate.getFullYear(); var someFormattedDate = mm + '/' + dd + '/' + y; document.getElementById('follow_Date').value = someFormattedDate; } } </script> A: Finally got the result. Had to parse the input date and convert, <script> $(document).ready(function () { $( "#txtDate" ).datepicker({ //dateFormat: "dd/mm/yy" dateFormat: "dd/mm/yy" }); }); function getdate() { var tt = document.getElementById('txtDate').value; var input = document.getElementById('extdays').value; if (input == "" || input==null) { input =0 } var initial = tt.split(/\//).reverse().join('/'); // to change the format var date = new Date(initial); var newdate = new Date(date); newdate.setDate(newdate.getDate() + parseInt(input)); var dd = newdate.getDate(); var mm = newdate.getMonth() + 1; var y = newdate.getFullYear(); var someFormattedDate = dd + '/' + mm + '/' + y; document.getElementById('follow_Date').value = someFormattedDate; } </script>
{ "pile_set_name": "StackExchange" }
Q: Data Structure Behind Amazon S3s Keys (Filtering Data Structure) I'd like to implement a data structure similar to the lookup functionality of Amazon S3. For context, Amazon S3 stores all files in a flat namespace, but allows you to look up groups of files by common prefixes in their names, therefore replicating the power of a directory tree without the complexity of it. The catch is, both lookup and filter operations are O(1) (or close enough that even on very large buckets - S3's disk equivalents - both operations might as well be O(1))). So in short, I'm looking for a data structure that functions like a hash map, with the added benefit of efficient (at the very least not O(n)) filtering. The best I can come up with is extending HashMap so that it also contains a (sorted) list of contents, and doing a binary search for the range that matches the prefix, and returning that set. This seems slow to me, but I can't think of any other way to do it. Does anyone know either how Amazon does it, or a better way to implement this data structure? A: Just to validate my claim that a regular TreeMap should suffice for any bucket with as many as 1,000,000 entries, here's a very simple test case that gives some numbers (attention: this is not meant as a microbenchmark, it's just to get a feeling for the magnitude of this problem). I've used randomly generated UUIDs to mimic keys (If you'd replace dashes with slashes, you would even get kind of a directory structure). Afterwards, I've put them into a regular java.util.TreeMap and finally queried them with map.subMap(fromKey, toKey). public static void main(String[] args) { TreeMap<String, Object> map = new TreeMap<String, Object>(); int count = 1000000; ArrayList<String> uuids; { System.out.print("generating ... "); long start = System.currentTimeMillis(); uuids = new ArrayList<String>(count); for (int i = 0; i < count; i++) { uuids.add(UUID.randomUUID().toString()); } System.out.println((System.currentTimeMillis() - start) + "ms"); } { System.out.print("inserting .... "); long start = System.currentTimeMillis(); Object o = new Object(); for (int i = 0; i < count; i++) { map.put(uuids.get(i), o); } System.out.println((System.currentTimeMillis() - start) + "ms"); } { System.out.print("querying ..... "); String from = "be400000-0000-0000-0000-000000000000"; String to = "be4fffff-ffff-ffff-ffff-ffffffffffff"; long start = System.currentTimeMillis(); long matches = 0; for (int i = 0; i < count; i++) { Map<String, Object> result = map.subMap(from, to); matches += result.size(); } System.out.println((System.currentTimeMillis() - start) + "ms (" + matches/count + " matches)"); } } and here is some sample output from my machine (1,000,000 keys, 1,000,000 range queries): generating ... 6562ms inserting .... 2933ms querying ..... 5344ms (229 matches) Inserting 1 key took an average of 0.003 ms (certainly more towards the end though) while querying a sub range with 229 matches took 0.005 ms per query. That's some pretty sane performance, isn't it? After increasing the number to 10,000,000 keys and queries, the numbers are as follows: generating ... 59562ms inserting .... 47099ms querying ..... 444119ms (2430 matches) Inserting 1 key took an average of 0.005 ms while querying a sub range with 2430 matches took 0.044 ms per query. Even though querying got 10 times slower (at the end, it's iterating through all matches which always is O(n)) the performance still isn't too bad either. As S3 is a cloud service, I'd assume that it's pretty much limited by networking anyway. Hence there's no urgent need for an extremely fancy data structure to get the required performance. Still, some features are missing from my test case, most notably concurrency and persistence. Nevertheless, I think I've shown that a regular tree structure is sufficient for this use case. If you want to do something fancy, experiment with subtree read-write locking and maybe a replacement for .subMap(fromKey, toKey);
{ "pile_set_name": "StackExchange" }
Q: having trouble parsing XML data with javascript and prototype 1.7 I have a basic question relating to AJAX, XML, and Prototype. I am trying to parse this XML Document: <?xml version="1.0" encoding="utf-8"?> <NavigationData> <OrderOfCategories> <CategoryName Num="1">location</CategoryName> <CategoryName Num="2">real_estate</CategoryName> <CategoryName Num="3">services</CategoryName> <CategoryName Num="4">learning</CategoryName> <CategoryName Num="5">automobile</CategoryName> <CategoryName Num="6">personals</CategoryName> <CategoryName Num="7">community</CategoryName> <CategoryName Num="8">for_sale</CategoryName> <CategoryName Num="9">classifides</CategoryName> </OrderOfCategories> </NavigationData> using this javascript code (for an example): function createNav (response) { var xmlData = response.responseXML.documentElement.getElementsByTagName("CategoryName")[1].childNode[0].nodeValue; window.alert(xmlData); } // end of FUNCTION createNav function loadNav () { new Ajax.Request("http://www.listedcities.com/listings/geo_templates/freshstart/external/xml/global_data.xml", { method: 'get', contentType: 'text/xml', onSuccess: createNav, onFailure: function () { window.alert("failed") } }); } The function loadNav loads the XML file and passes it on to the other function to be parsed. The reason for this is that the application loads multiple xml files rather than one large file and the filenames for the smaller XML files are stored in the 'global_data.xml' XML file. The issue I run into with this code is that the alert passes on a 'null' value or in some cases doesn't fire anything at all. I am hoping to get the alert to fire with the 1st node value in the 'global_data.xml' file. Any help would be much appreciated around these parts. Take care. A: I managed to hack away at the issue to get this line of code that worked: var xmlData = response.responseXML.documentElement.getElementsByTagName("CategoryName")[1].childNodes[0].nodeValue; I needed the extra childNodes[x] reference in there.
{ "pile_set_name": "StackExchange" }
Q: Are these two Proj4 string treated differently? will any argument get ignored or overrided? I have knowledge enough to play around Proj4s string but I have not found any question about this yet. I have these two Proj4 strings. +proj=eqdc +lat_0=39 +lon_0=-96 +lat_1=33 +lat_2=45 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=-0.9956,1.9013,0.5215,0.025915,0.009416,0.0011599,-0.00062 +units=m +no_defs and this one below (+datum=NAD83 is added in front of +ellps=... +towgs84=...) +proj=eqdc +lat_0=39 +lon_0=-96 +lat_1=33 +lat_2=45 +x_0=0 +y_0=0 +datum=NAD83 +ellps=GRS80 +towgs84=-0.9956,1.9013,0.5215,0.025915,0.009416,0.0011599,-0.00062 +units=m +no_deft In case you wonder, The 7-parameters argument in both strings is from this post. I wonder if: In the 2nd string, will +ellps=... +towgs83=... override +datum=NAD83 during transforming projection? I have two file about the same data projected by 1st string and 2nd string. I am going to transform them to any NAD83-based projection or NAD83 latlong(EPSG-4269). Will Proj4 transform the data projected by 2nd string to the new NAD83-based projection with or without datum shift because I had +datum=NAD83 in the Proj4 string and in front of +ellps=... +towgs84=...? 2.1 After projecting 1st-string-projected data and 2nd-string-projected data to the same NAD83 projection, will or will not I have two same results? A: I can't say how it goes in theory but it is easy to test what happens in practice with gdaltransform utility http://www.gdal.org/gdaltransform.html gdaltransform -s_srs EPSG:4326 -t_srs "+proj=eqdc +lat_0=39 +lon_0=-96 +lat_1=33 +lat_2=45 +x_0=0 +y_0=0 +ellps=GRS80 +towgs84=-0.9956,1.9013,0.5215,0.025915,0.009416,0.0011599,-0.00062 +units=m +no_defs" -80 36 Result: 1429512.75999231 -207252.541637988 1.35481430124491 gdaltransform -s_srs EPSG:4326 -t_srs "+proj=eqdc +lat_0=39 +lon_0=-96 +lat_1=33 +lat_2=45 +x_0=0 +y_0=0 +datum=NAD83 +ellps=GRS80 +towgs84=-0.9956,1.9013,0.5215,0.025915,0.009416,0.0011599,-0.00062 +units=m +no_deft" -80 36 Result: 1429512.75999231 -207252.541637988 1.35481430124491 Result is the same to the very last decimal.
{ "pile_set_name": "StackExchange" }
Q: Manipulate elements of arrays dynamically without for loop in ruby I have an array in ruby and i want to change the values of it's elements dynamically depending on a particular attribute. Suppose i have an array, array = [123,134,145,515] And i want to manipulate this elements like getting all the elements multiplied by a parameter, how can i get it done without having to do it explicitly each time using for loop? A: For this, you can use something like the collect method in ruby for arrays. You can write a method which can be called whenever required passing the array and parameter as argument. For instance you can write a method similar to this ; array = [123,134,145,515] parameter_value = 2 Now, depending on the requirement you can define a method like this : array.collect {|x| x * parameter_value} In this case, this would return an array similar to this : array = [246, 268, 290, 1030]
{ "pile_set_name": "StackExchange" }
Q: execute input jquery event only when there's a pause I have a search input box on a simple form that automatically fetches remote data based on what's entered. A minimum 3 characters is needed to trigger the search. e.g. typing smi will retrieve all staff whose lastname starts with "smi". E.g. Smith, Smithson and etc I guess my issue is that if I type "Smit", 2 searches are done. I was hoping it is possible to: search only if it meets minimum 3 characters requirement search only if there's a pause Is this possible? if yes, how? Thanks a lot A: As in this JSFiddle .. Updated: Sorry forgot about the min 3 characters condition and the multi-requests issue var search, timer; $('#search1').on('keyup', function () { search = $('#search1').val(); $('#result').html('Min 3 characters'); if(search.length > 2){ //min char number 3 clearTimeout(timer); $('#result').html('loading..'); timer = setTimeout(function () { $('#result').html(search); }, 2000); // time to wait before executing, 2000 milli seconds here } }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="search" id="search1" /> <p id="result"></p>
{ "pile_set_name": "StackExchange" }
Q: Is it possible to have SVN vendor branch in a git repository? I'm having a local project and I want to use a git repository as versioning software. As I'm using an external software on a SVN server as base for my project I think the best way is to have it as a vendor branch in my git project so external changes don't affect my code and I can merge the vendor branch in the main trunk from time to time. Is it possible to mix git and SVN like this? What is the best project layout and how do I actually merge the vendor branch in the main trunk? A: I now did it like this: How do I import a third party lib into git?
{ "pile_set_name": "StackExchange" }
Q: Creating Instagram Bot using selenium library So I am trying to create insta bot that opens up a specific hashtag in search bar and then navigates to it. I have been having a problem to navigate bot to search bar it always tells me that path is not able to be found, any ideas how can I make bot target search bar and send hashtag keys to it? here is my code: from selenium import webdriver from time import sleep from insta import username,password,hashtag class InstaBot(): def __init__(self): self.driver = webdriver.Chrome() def login(self): self.driver.get('https://www.instagram.com/') sleep(3) #loggin in to instagram with facebook fb_btn = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/main/article/div[2]/div[1]/div/form/div[1]/button') fb_btn.click() #logging into acc email = self.driver.find_element_by_xpath('//*[@id="email"]') email.send_keys(username) pswd = self.driver.find_element_by_xpath('//*[@id="pass"]') pswd.send_keys(password) login_btn = self.driver.find_element_by_xpath('//*[@id="loginbutton"]') login_btn.click() sleep(4) self.driver.find_element_by_xpath("//button[contains(text(), 'Not Now')]")\ .click() #navigating to search bar and sending hashtag into it hashtag = self.driver.find_element_by_xpath('//*[@id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[1]/a/svg') hashtag.send_keys(hashtag) A: You can navigate to the search bar by executing JavaScript: SCRIPT = f"document.getElementsByClassName('XTCLo x3qfX')[0].value = '{SEARCH_VALUE}'" driver.execute_script(SCRIPT) However, if you just want to go to a hashtag page, I would recommend using driver.get(f"https://www.instagram.com/explore/tags/{HASHTAG}/")
{ "pile_set_name": "StackExchange" }
Q: Insert query not working in codeigniter I am trying to run an insert query from codeigniter by using the following code $this->db->query($query); but I am getting the following error: Error Number: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 4 INSERT INTO order_bank (creation_date, order_type, so_no, material_no, description, order_qty, no_of_panels, division, job_number, customer_group, sales_office, sales_group, project_name, project_manager, net_value_myr, credit_status, so_delivery_date, order_delivery_date) VALUES ( '2013-07-01', 'ZTOR', 3058627219, 101900000000, 'SUPPLY, MODIFY, INSTALL TEST VCU', 1, 0, 'AIS (TSM)', 'SC139203J01', 'Industry', 'SEA', 'DOM', 'MELAKA', 'Phua Tiang Hai', 42954.55, '', '2013-07-11', '2013-07-05'); Filename: C:\wamp\www\system\database\DB_driver.php Line Number: 330 But when I am running the above query in phpmyadmin its working perfectly. Please help me in sorting out the issue A: Use active records provided by Codeigniter, that would be much more safer and simpler! http://ellislab.com/codeigniter/user-guide/database/active_record.html Example:- $this->db->set('description', $description); $this->db->set('order_qty', $order_qty); $this->db->set('no_of_panels', $no_of_panels); $this->db->set('division', $division); $this->db->set('job_number', $job_number); $this->db->set('customer_group', $customer_group); $this->db->set('sales_office', $sales_office); $this->db->set('sales_group', $sales_group); $this->db->set('project_name', $project_name); $this->db->set('project_manager', $project_manager); $this->db->set('net_value_myr', $net_value_myr); $this->db->set('credit_status', $credit_status); $this->db->set('so_delivery_date', $so_delivery_date); $this->db->set('order_delivery_date', $order_delivery_date); $this->db->insert('order_bank'); or if your data are stored in an array then you can do it simply running $this->db->insert('order_bank', $data);
{ "pile_set_name": "StackExchange" }
Q: Foreign row not deleted (have cascade), why? I have a problem where my child row is not deleted when my parent row is deleted even tho I have ON DELETE CASCADE. My parent table looks like this: CREATE TABLE `rw_profiles` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, ... PRIMARY KEY (`id`), KEY `profiles_logo_id_foreign` (`logo_id`), KEY `profiles_subscription_id_foreign` (`subscription_id`), KEY `profiles_deleted_at_name_index` (`deleted_at`,`name`), CONSTRAINT `profiles_logo_id_foreign` FOREIGN KEY (`logo_id`) REFERENCES `rw_profile_logos` (`id`), CONSTRAINT `profiles_subscription_id_foreign` FOREIGN KEY (`subscription_id`) REFERENCES `rw_subscription_types` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci My child table looks like this: CREATE TABLE `rw_profile_access` ( `profile_id` int(10) unsigned NOT NULL, `user_id` int(10) unsigned NOT NULL, ... UNIQUE KEY `profile_access_profile_id_user_id_unique` (`profile_id`,`user_id`), KEY `profile_access_user_id_foreign` (`user_id`), CONSTRAINT `profile_access_profile_id_foreign` FOREIGN KEY (`profile_id`) REFERENCES `rw_profiles` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `profile_access_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `rw_users` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci The foreign key is "installed" on rw_profile_access without problem, but when I delete a row from rw_profiles, the corresponding row (with rw_profiles.id=rw_profile_access.profile_id) from profile_access doesn't delete itself. Why doesn't the child row delete itself when I delete a parent row? The foreign_key_checks value is on if I run the query below. SHOW Variables WHERE Variable_name='foreign_key_checks' A: Must've been something wrong with mariadb-server (version 10.0.10), I remove it and is now using mysql-server instead, now it works like it should.
{ "pile_set_name": "StackExchange" }
Q: How can I use public-key encryption for luks? I have been running luks with the following commands: $ sudo dd if=/dev/urandom of=/keyfile bs=1024 count=4 $ sudo cryptsetup luksFormat /dev/XXX keyfile $ sudo cryptsetup luksDump /dev/XXX And it shows me as following message: Version: 1 Cipher name: aes Cipher mode: cbc-essiv:sha256 Hash spec: sha1 Payload offset: 4096 MK bits: 256 MK digest: f3 79 af 60 e6 34 5c 6e 27 6a e4 fe b6 f0 b2 95 8a 85 5c 31 MK salt: 14 33 6b 95 f8 3d a9 e2 84 67 85 a1 18 be 70 58 af 10 10 28 c5 5b d1 1a 31 8e 8f e1 5a 93 51 12 MK iterations: 45250 UUID: 776d4a78-3487-42df-8d3c-38708fdea60d Key Slot 0: ENABLED Iterations: 181146 Salt: da cf b7 36 fc 98 7c 5c 73 68 ca 44 f4 00 55 52 47 46 68 50 bf aa 2e bb ac 47 83 0f 76 05 a6 05 Key material offset: 8 AF stripes: 4000 According to the output, Cipher name is aes and it is not public key encryption. Is it used to encrypt just the master key, or does it encrypt contents too? If it only encrypts the master key, how is contents encrypted? I'm sure aes also very secure. But I think that public key encryption is more secure than other methods such as aes. Thus, I tried to find out how to use gpg or any other encryption methods for luks at the man page of cryptsetup, but I could not find a solution. How can I use public-key encryption for luksFormat? A: Public key encryption is really only useful if you want to have other people encrypt messages to you, and you don't want to go to the trouble of secretly giving them your secret encryption key. So you post your public key for the world to see and encrypt messages to you, that only you can read. It would be of no benefit to you personally encrypting your files on your own computer. It could be assumed that public key encryption is less secure than conventional encryption (like AES, Blowfish, Camellia...) since you're handing out part of the encryption information (the public part). Though in practice they are both effectively "unbreakable" in any human lifetime. And you may not know how the public-key encryption program PGP/GPG actually works, it conventionally encrypts messages, and then encrypts the conventional key using public key encryption. Here's a quote from some older (but still valid) PGPi documentation explaining it, and a bit about why someone may think one method is more secure than the other, if they're only comparing key sizes: PGP combines some of the best features of both conventional and public key cryptography. PGP is a hybrid cryptosystem. When a user encrypts plaintext with PGP, PGP first compresses the plaintext. Data compression saves modem transmission time and disk space and, more importantly, strengthens cryptographic security. Most cryptanalysis techniques exploit patterns found in the plaintext to crack the cipher. Compression reduces these patterns in the plaintext, thereby greatly enhancing resistance to cryptanalysis. (Files that are too short to compress or which don't compress well aren't compressed.) PGP then creates a session key, which is a one-time-only secret key. This key is a random number generated from the random movements of your mouse and the keystrokes you type. This session key works with a very secure, fast conventional encryption algorithm to encrypt the plaintext; the result is ciphertext. Once the data is encrypted, the session key is then encrypted to the recipient's public key. This public key-encrypted session key is transmitted along with the ciphertext to the recipient. ... The combination of the two encryption methods combines the convenience of public key encryption with the speed of conventional encryption. Conventional encryption is about 1,000 times faster than public key encryption. Public key encryption in turn provides a solution to key distribution and data transmission issues. Used together, performance and key distribution are improved without any sacrifice in security. ... However, public key size and conventional cryptography's secret key size are totally unrelated. A conventional 80-bit key has the equivalent strength of a 1024-bit public key. A conventional 128-bit key is equivalent to a 3000-bit public key. Again, the bigger the key, the more secure, but the algorithms used for each type of cryptography are very different and thus comparison is like that of apples to oranges. If you wanted to use some method involving GPG to use your public key to encrypt the passphrase or keyfile to your LUKS container, you could do that if you wanted. But then if your GPG private key were ever compromised or lost, so too would your LUKS container. And you can choose a different cipher with cryptsetup, it would use the cipher to encrypt all the data. See man cryptsetup for info like: --cipher, -c <cipher-spec> Set the cipher specification string. And under a default Ubuntu at least these ciphers should be supported: loop-AES: aes, Key 256 bits plain: aes-cbc-essiv:sha256, Key: 256 bits LUKS1: aes-xts-plain64, Key: 256 bits
{ "pile_set_name": "StackExchange" }
Q: Why can I not setAttribute('onclick', function() { ... })? I tried this: <div id="a">A</div> <div id="b">B</div> <script> let a = document.getElementById('a'); let b = document.getElementById('b'); a.onclick = function() { alert('hi from a'); }; b.setAttribute('onclick', function() { alert('hi from b'); }); </script> Clicking on A shows a an alert. Clicking on B emits this error message: Uncaught SyntaxError: Function statements require a function name. Why? https://codepen.io/issactrotts/pen/yLYEXKZ A: Attribute values are strings, not functions. Use addEventListener instead.
{ "pile_set_name": "StackExchange" }
Q: Closed form solution to $x\log_2(1+\frac{a}{x}) = b$ using Lambert W. Is there an expression for the solution to \begin{equation} x\log_2(1+\frac{a}{x}) = b \end{equation} where $a$ and $b$ are constants, and $x$ is the variable? I am aware that there are no solutions that can be expressed in terms of elementary functions, but perhaps there is one using the Lambert W function? A: Yes; the first reasonable step is to isolate the logarithm so that we can get rid of it; dividing through by $x$ (which can't be $0$ if $b$ is non-zero) yields: $$\log_2\left(1+\frac{a}x\right)=\frac{b}x$$ and rewriting $\log_2(x)$ in terms of the natural logarithm as $\frac{\log(x)}{\log(2)}$ and rearranging gives: $$\log\left(1+\frac{a}x\right)=\frac{b\log(2)}x.$$ we then raise $e$ to the power of each side to get: $$1+\frac{a}x=e^{\frac{b\log(2)}x}.$$ Now, this looks kind of nasty; we need the exponent to be a simpler form before we can apply the product log - in particular, let $u=\frac{-b\log(2)}x$ and $\alpha=\frac{a}{b\log(2)}$. Then we write $$1-\alpha u = e^{-u}$$ which simplifies to $$(1-\alpha u)e^u = 1.$$ which is starting to look more manageable - but that addition on the left is still kind of worrisome - but we can get it out with another substitution. If we let $v$ be such that $u=v+\frac{1}{\alpha}$, then we get: $$-\alpha v e^{v+\frac{1}{\alpha}}=1$$ $$ve^v=-\frac{e^{-\frac{1}{\alpha}}}{\alpha}$$ Oh goody! We can definitely apply the product log to that: $$v=W\left(-\frac{e^{-\frac{1}{\alpha}}}{\alpha}\right)$$ meaning $$u=W\left(-\frac{e^{-\frac{1}{\alpha}}}{\alpha}\right)+\frac{1}{\alpha}$$ and hence $$x=\frac{-b\log(2)}{W\left(-\frac{e^{-\frac{1}{\alpha}}}{\alpha}\right)+\frac{1}{\alpha}}$$ and subbing in for the $\alpha$'s and doing careful simplification yields $$x=\frac{-b\log(2)}{W\left(-\frac{b}a2^{-b/a}\log(2)\right)+\frac{b\log(2)}a}$$ A: Yet another: $$ \begin{align} x\log_2\left(1+\frac ax\right)&=b\tag{1}\\ 1+\frac ax&=e^{b\log(2)/x}\tag{2}\\ 1+\frac ax&=2^{-b/a}e^{\large\frac{b\log(2)}a\left(1+\frac ax\right)}\tag{3}\\ \color{#00A000}{-\frac{b\log(2)}a\left(1+\frac ax\right)}e^{\color{#00A000}{\large-\frac{b\log(2)}a\left(1+\frac ax\right)}}&=-\frac{b\log(2)}a2^{-b/a}\tag{4}\\ -\frac{b\log(2)}a\left(1+\frac ax\right)&=\mathrm{W}\!\left(-\frac{b\log(2)}a2^{-b/a}\right)\tag{5}\\ x&=\bbox[5px,border:2px solid #F0C060]{\frac{-ab\log(2)}{b\log(2)+a\mathrm{W}\!\left(-\frac{b\log(2)}a2^{-b/a}\right)}}\tag{6}\\ &=\bbox[5px,border:2px solid #F0C060]{\frac{-\lambda a}{\lambda+\mathrm{W}\!\left(-\lambda e^{-\lambda}\right)}}\tag{7} \end{align} $$ Explanation: $(2)$: multiply by $\frac{\log(2)}x$ and exponentiate $(3)$: add $\frac{b\log(2)}a$ to the exponent and divide by $2^{b/a}$ $(4)$: multiply both sides by $-\frac{b\log(2)}ae^{\large-\frac{b\log(2)}a\left(1+\frac ax\right)}$ $(5)$: apply $\mathrm{W}$ $(6)$: algebraically solve for $x$ $(7)$: substitute $\lambda=\frac{b\log(2)}a$ Note that in $(7)$, it appears that $\mathrm{W}\!\left(-\lambda e^{-\lambda}\right)=-\lambda$, making the denominator $0$. However, when the argument of $\mathrm{W}$ is negative, there are two branches. Thus, we need to use the other branch of $\mathrm{W}$ so that the denominator is not $0$.
{ "pile_set_name": "StackExchange" }
Q: set the first value in Dropdown list as default value in php How to set the first value that comes in the dropdown list as the default value in php? The first value should be by default selected when i open my page A: This can be achievable using selected attribute of selectbox: <select name="youselectbox"> <option value="1" selected>Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select> Edit : Give your selectbox a id say "selectme" <select name="youselectbox" id="selectme"> Then on load use this jQuery : $(document).ready(function() { $("#selectme").prop("selectedIndex", 0); // here 0 means select first option }); For more information SEE and FIDDLE DEMO
{ "pile_set_name": "StackExchange" }
Q: Get SQL Select progress like SSMS Is it possible to receive SELECT or Procedure Execution progress from SQL Database using .Net framework? Whenever you select big data in SSMS, it shows you progress of execution, I mean it gives you +=500 - 500 rows. Can I make same in my WinForm project? A: It's pretty simple to do that with ADO.NET/SQL Server. You can simply hook up an event to SqlInfoMessageEventHandler like this: { SqlConnection sqlConnection = new SqlConnection(“................”); sqlConnection.Open(); sqlConnection.InfoMessage += new SqlInfoMessageEventHandler(ProgressStatus); // Execute your long running query here } private void ProgressStatus(object sender, SqlInfoMessageEventArgs e) { if (e.Errors.Count > 0) { string message = e.Errors[0].Message; int state = e.Errors[0].State; // Set status of the progress bar // progressBar1.Value = state; } } And in your SQL statement/stored procedure if you have multiple statements to execute, you might choose to report the status of those statements i.e. SELECT ............ FROM .......... INNER JOIN ............. INNER JOIN ............ RAISERROR('Message',10,25) WITH NOWAIT SELECT ............ FROM .......... INNER JOIN ............. INNER JOIN ............ RAISERROR('Message',10,50) WITH NOWAIT SELECT ............ FROM .......... INNER JOIN ............. INNER JOIN ............ RAISERROR('Message',10,75) WITH NOWAIT SELECT ............ FROM .......... INNER JOIN ............. INNER JOIN ............ RAISERROR('Message',10,100) WITH NOWAIT NOWAIT option will force the message to be delivered to the client immediately instead of waiting until everything is done. BTW maybe I misunderstood the question, and you need to paginate results and report progress on pages, then you will need a different answer.
{ "pile_set_name": "StackExchange" }
Q: What must I do with a solution file showing under my web site? I have just been handed an ASP.NET web site project, without a parent solution. I created a new solution, and added the web site project under the solution, as I am always more comfortable grouping all my work under a solution, even project-less web sites. Now, when I open the solution, then expand the web site folder, I see the solution file appears under the web site folder, yet I have checked and it isn't duplicated here. How do I get rid of the solution file item under the web site? OUTCOME: It turns out that I somehow confused folders and had both my solution and web site under the same folder, and as Chris Lively says below, all files under a web site appear in solution explorer. A: If you really want a solution, create the solution file one directory up from where the website is. Website projects are going to automatically include every file it finds along the site path. If your solution file is in the same directory, then it is going to be added. My recommendation is to move the solution file, then convert it to a web application project.
{ "pile_set_name": "StackExchange" }
Q: C#: Making an Installer that installs both a WPF application (ClickOnce) and a Windows Service I currently have a VS Solution with 2 projects: a WPF application and a Windows Service. Now, I have managed to get ClickOnce working in installing my WPF application, but I also want a Windows Service to be installed (the one in the project) during this installation. I have found ways how to programmatically start a windows service with C# code, but is there any way to incorporate this in my ClickOnce installation (because I need ClickOnce's benefit of automatic updates and such)? A: I don't think you can deploy a windows service via ClickOnce in a normal fashion. http://social.msdn.microsoft.com/Forums/en-US/winformssetup/thread/1bb64760-9622-4ca6-a1a6-3ce53e641f21 ClickOnce deploy a Windows Service?
{ "pile_set_name": "StackExchange" }
Q: Multiply font size of children It might be impossible to do but I would like to add a css (ideally exclusively css) that multiply font size of all the children elements. For example, if you have various font sizes: <h1>This is heading 1</h1> <h2>This is heading 2</h2> <h3>This is heading 3</h3> I would like to add a class: <div class="multiply-font"> <h1>This is heading 1</h1> <h2>This is heading 2</h2> <h3>This is heading 3</h3> </div> such as all the sizes will be multiplied by a factor. Therefore, will be X times bigger/smaller than without the class etc... A: If you declare the font-size for the multiply-font-class, this is exactly what will happen, if you use the em unit. em refers to your font size (or the vertical height of your font, to be precise) with 1 em as your default size. If you declare with .multiply-font{ font-size: 2em; } the result should be exactly as described (with the font size twice as large).
{ "pile_set_name": "StackExchange" }
Q: jQuery submit when another function is ok I using 2 jquery script, function in my form. How to do when the first function have error I can't submit form. My actual code: <script> $(document).ready( function () { $("form#eee").on('click', function () { if ($('input[name^="rr"]:checked').length>0) { return true; } else { alert("minimum one options!"); return false; } } ); } ); $("input[type=number]").on('click keydown keyup',function() { var min = $('input[name^="Min"]').val(); var max = $('input[name^="Max"]').val(); if (min < max) { $('.error').text(""); } else { $('.error').text("min>max"); } }); </script> <script> $('#form').on('submit', function (e) { e.preventDefault(); var formul = $('#form').serialize(); $.ajax({ type: 'POST', data: formul, url: 'action', success: function (html) { $('.returner').html(html); }, error: function () { alert('error!!') } }) }) </script> Now code working, but for example when I min>max i can press submit button. ho to do when min >max block submit button. A: Disable or enable your input button in the first function, like this: $("input[type=number]").on('click keydown keyup',function() { var min = $('input[name^="Min"]').val(); var max = $('input[name^="Max"]').val(); if (min < max) { $('.error').text(""); $('input[type="submit"]').prop('disabled', true); } else { $('.error').text("min>max"); $('input[type="submit"]').prop('disabled', false); } }); If possible, then use the HTML ID of the submit button, instead of the selector I'm using.
{ "pile_set_name": "StackExchange" }
Q: Sort string array in special style what we need to do if we want to sort our string Array in a special form? For example we have this: players = new string[12] {"soccer","12","man","swim","3","woman","volleyball","12","man","baseball","13","man"}; now we want to sort Array by this form:(its just my desire order and don't have any logic) sort = new string[4] {"swim","baseball","volleyball","soccer"} and finally have: out = [{swim,3,woman},{baseball,13,man},{volleyball,12,man},{soccer,12,man}] A: You have one big string array which contains all of your player details. This is not the best solution. Create player objects which contains all of the properties and put that in an array. Then you can create custom sorting. Player object: public class Player { public string Type { get; set; } public string Gender { get; set; } public int AmountOfPlayers { get; set; } public int Order { get; set; } } Create your array list of Player objects: List<Player> list = new List<Player>(); list.Add(new Player() { Type = "swim", Gender = "women", AmountOfPlayers = 3, Order = 1 }); list.Add(new Player() { Type = "soccer", Gender = "men", AmountOfPlayers = 12, Order = 4 }); list.Add(new Player() { Type = "volleyball", Gender = "men", AmountOfPlayers = 12, Order = 3 }); list.Add(new Player() { Type = "baseball", Gender = "men", AmountOfPlayers = 13, Order = 2 }); Sorting: var sortedList = list.OrderBy(c => c.Order); A: The other answers make a good point about creating a class to hold your data, but it can be done without it: var ordered = Enumerable.Range(0, players.Length / 3) .Select(i => new string[] { players[i*3], players[i*3+1], players[i*3+2] }) .OrderBy(a => Array.IndexOf(sort, a[0])) .ToArray(); If you have sports in the players array that are not present in the sort array, you can filter them out. var ordered = (from i in Enumerable.Range(0, players.Length / 3) let index = Array.IndexOf(sort, players[i*3]) where index >= 0 select new string[] { players[i*3], players[i*3+1], players[i*3+2] } ).OrderBy(a => Array.IndexOf(sort, a[0])).ToArray();
{ "pile_set_name": "StackExchange" }
Q: Not able to send JSON response to other activity and show it in toast I am able to register json data to my server, I am even getting response, but not able to show it in toast as well as send it to other activity (main activity). I converted the response to string and tried to send to my mainactivity using getter but I am not able to see it in Log.i, even in toast that I mentioned. Here's my code: class SendJsonDataToServer extends AsyncTask<String, String, String> { String j; @Override protected String doInBackground(String... params) { String JsonResponse = ""; String JsonDATA = params[0]; HttpURLConnection urlConnection = null; BufferedReader reader = null; try { URL url = new URL("http://gstedge.com/test/invoice/api.php?param=signup"); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); // is output buffer writter urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Accept", "application/json"); //set headers and method Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8")); writer.write(JsonDATA); // json data writer.close(); InputStream inputStream = urlConnection.getInputStream(); //input stream StringBuffer buffer = new StringBuffer(); if (inputStream == null) { // Nothing to do. return null; } reader = new BufferedReader(new InputStreamReader(inputStream)); String inputLine; while ((inputLine = reader.readLine()) != null) buffer.append(inputLine + "\n"); if (buffer.length() == 0) { // Stream was empty. No point in parsing. return null; } JsonResponse = buffer.toString(); j= JsonResponse; //response data Log.i("o/p:", JsonResponse); //send to post execute } catch (IOException e) { e.printStackTrace(); } finally { if (urlConnection != null) { urlConnection.disconnect(); } if (reader != null) { try { reader.close(); } catch (final IOException e) { Log.e("wtf", "Error closing stream", e); } } } return JsonResponse; } I was not able to get response in onpostexecute as well so I removed it and thought to convert it in string and send it using getter and parse it in other activity. I am able to see response in log.i("o/p") mentioned above in the code, but I don't know why its not getting sent. Here's my mainactivity code: public class MainActivity extends AppCompatActivity { EditText emailview, numberview, pwview; Button registerview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); emailview = (EditText) findViewById(R.id.et1); numberview = (EditText) findViewById(R.id.et2); pwview = (EditText) findViewById(R.id.et3); registerview = (Button) findViewById(R.id.btn1); } public void hit(View v) { String email = emailview.getText().toString(); String contact = numberview.getText().toString(); String pw = pwview.getText().toString(); JSONObject a = new JSONObject(); try { a.put("mail", email); a.put("num", contact); a.put("pass", pw); } catch (JSONException e) { e.printStackTrace(); } if (a.length() > 0) { new SendJsonDataToServer().execute(String.valueOf(a)); } SendJsonDataToServer S = new SendJsonDataToServer(); String Jr = S.getJR(); Log.i("out:",Jr); Toast.makeText(MainActivity.this, Jr, Toast.LENGTH_LONG).show(); Intent i= new Intent(MainActivity.this,UserAreaActivity.class); startActivity(i); } } The toast I see is empty. A: Explanation: Because you are creating two different objects of SendJsonDataToServer First: new SendJsonDataToServer().execute(String.valueOf(a)); Second: SendJsonDataToServer S = new SendJsonDataToServer(); So these two objects will get different memory allocation. when you get response by this code String Jr = S.getJR(); then you will get the response that was created in different object from the object you got response. So Jr will be obviously empty. That's why you cannot print the response that you expect. Solution: First: You need to execute Toast.makeText(MainActivity.this, Jr, Toast.LENGTH_LONG).show(); in @Override protected void onPostExecute(String result) { Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show(); } method in your AsyncTask like this. Second: If you want to send this result to your second activity then you should write code like this in your onPostExecute method. @Override protected void onPostExecute(String result) { Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show(); Intent i = new Intent(MainActivity.this, UserAreaActivity.class); i.putExtra("result", result); startActivity(i); } and write this code in onCreate() method of UserAreaActivity Bundle bundle = getIntent().getExtras(); String result = bundle.getString("result"); Toast.makeText(UserAreaActivity.this, result, Toast.LENGTH_LONG).show(); Now you will be able to use result in this activity.
{ "pile_set_name": "StackExchange" }
Q: 日本語に違和感: プロフィールページのタブ「質問数」 隣の「回答」タブと命名基準が合っていません。 A: 質問
{ "pile_set_name": "StackExchange" }
Q: Deriving instance Typeable with context I am writing function set wor working with HTTP requests and need to create a set of Exceptions for handling failures. Here it is data HStream ty => ErrorResponse ty = ErrorResponse (Response ty) data HStream ty => HttpException ty = WrongURIException String | ConnException ConnError | RequestException (ErrorResponse ty) instance HStream ty => Exception (HttpException ty) where WrongURIException corresponds to malformed uri, ConnException to errors in TCP stack and RequestException to handle responses with non-2xx response codes. Before declaring instance Exception on line 3 I should derive Typeable but I'm lost in types. How should I it? A: Might I suggest not doing that. Datatype contexts are bad in pretty much every way possible. There's a reason that they've been deprecated. If you really, really, want them, use GADTs. If you don't use contexts, this is trivial {-# LANGUAGE DeriveDataTypeable #-} import Data.Typeable import Data.Data data ErrorResponse ty = ErrorResponse (Response ty) deriving(Data, Typeable, Show) data HttpResponse ty = WrongURIException String | ConnException ConnError | RequestException (ErrorResponse ty) deriving(Data, Typeable, Show) instance (Typeable ty, Show ty) => Exception (HttpException ty) In particular as of GHC 7.8 you can't make your own instances for Typeable and Data, so deriving is the correct way.
{ "pile_set_name": "StackExchange" }
Q: Locally defined Double array makes the program crash I have the following variables defined locally in a function member of a class in C++: double coeff, mincoeff, minratio, equality[100][5000], tableau[51][5052], x[50][100]; When running the program crashes. When I comment out equality array it works but If I do not comment it out, it make the program crashes. It is not true for tableau array and it always works with 'tableau' array and without 'equality' array. I saw a post to use malloc() function to assign space dynamically like : double *equality; equality = malloc(500000*sizeof(double)); But it gives me an error of no conversion from void* to double*. Is there another way? A: allocate eqaulity on the heap and when you're done with it free memory: int main() { double** equality = new double* [100]; for(int i(0); i < 100; i++) equality[i] = new double[5000]; for(int i = 0; i < 100; i++) delete[] equality[i]; delete[] equality; equality = NULL; std::cout << std::endl; return 0; }
{ "pile_set_name": "StackExchange" }
Q: Extrema of an infinite product of sinc functions Consider the function $$f(x)=\prod_{n=0}^\infty\operatorname{sinc}\left(\frac{\pi \, x}{2^n}\right),\tag1$$ where $\operatorname{sinc}(z)$ denotes the sinc function. It arises as a Fourier transform of the Rvachev $\operatorname{up}(x)$ function, which is basically a shifted version of the Fabius function (see, for example $^{[1]}$$\!^{[2]}$$\!^{[3]}$). Curiously, if we take a finite partial product from $(1)$ with at least 2 terms, its Fourier transform will be a continuous piecewise-polynomial function with finite support (and with continuous derivatives of progressively higher orders as we include more terms). We restrict our attention only to $x\ge0$. The function $f(x)$ has zeros at positive integers, and oscillates with a quickly decaying amplitude. Its signs on the intervals between consecutive zeros follow the same pattern as the Thue–Morse sequence. It appears that $f(x)$ has exactly one extremum on each interval between consecutive zeros (minimum or maximum, depending on its sign on that interval) — but I have not been able to find a complete rigorous proof of it. Can you propose one? Update: I extracted the second part of my original question into a separate one and edited it significantly. The following is just an interesting observation: Let us denote the value of the extremum on the interval $n<x<n+1$ as $\epsilon_n$. The absolute values of the extrema $|\epsilon_n|$ generally tend to decrease as $n$ increases, but they do not decrease strictly monotonically and, in fact, show quite irregular behavior, sometimes increasing sporadically. Here is how their graph looks on log scale: A: About the first question, an idea might be to use the Weierstrass product $$\text{sinc}\left(\frac{\pi z}{2^n}\right)=\prod_{m\geq 1}\left(1-\frac{z^2}{(2^n m)^2}\right)$$ such that $$ f(z)=\prod_{n\geq 0}\text{sinc}\left(\frac{\pi z}{2^n}\right)=\prod_{m\geq 1}\left(1-\frac{z^2}{m^2}\right)^{\nu_2(m)+1} $$ $$ f'(z) = -2z\left(\sum_{m\geq 1}\frac{\nu_2(m)+1}{m^2-z^2}\right)\prod_{m\geq 1}\left(1-\frac{z^2}{m^2}\right)^{\nu_2(m)+1}.$$ The term $-\sum_{m\geq 1}\frac{\nu_2(m)+1}{m^2-z^2}$ has a simple pole with a positive residue at each $m\in\mathbb{N}^+$. In particular such function is increasing on the connected components of its domain $\cap \mathbb{R}^+$ and there cannot be more than one stationary point for $f$ between two consecutive zeroes. The presence of the mildly erratic function $\nu_2$ also explains the apparent irregularity in the distribution of the stationary values for $f$. On the other hand by the previous formula for $f'$ (which essentially is a rephrasing of the Gauss-Lucas theorem) it is reasonable to expect that the stationary points converge to the midpoints of the intervals defined by the zeroes of $f$, hence an estimation for the decay of the stationary values can be performed by summation by parts, considering the average values of $\nu_2$ over larger and larger intervals.
{ "pile_set_name": "StackExchange" }
Q: How to fetch the content of iframe in a php variable? My code is somewhat like this: <?php if($_REQUEST['post']) { $title=$_REQUEST['title']; $body=$_REQUEST['body']; echo $title.$body; } ?> <script type="text/javascript" src="texteditor.js"> </script> <form action="" method="post"> Title: <input type="text" name="title"/><br> <a id="bold" class="font-bold"> B </a> <a id="italic" class="italic"> I </a> Post: <iframe id="textEditor" name="body"></iframe> <input type="submit" name="post" value="Post" /> </form> The texteditor.js file code is: $(document).ready(function(){ document.getElementById('textEditor').contentWindow.document.designMode="on"; document.getElementById('textEditor').contentWindow.document.close(); $("#bold").click(function(){ if($(this).hasClass("selected")){ $(this).removeClass("selected"); } else{ $(this).addClass("selected"); } boldIt(); }); $("#italic").click(function(){ if($(this).hasClass("selected")){ $(this).removeClass("selected"); } else{ $(this).addClass("selected"); } ItalicIt(); }); }); function boldIt(){ var edit = document.getElementById("textEditor").contentWindow; edit.focus(); edit.document.execCommand("bold", false, ""); edit.focus(); } function ItalicIt(){ var edit = document.getElementById("textEditor").contentWindow; edit.focus(); edit.document.execCommand("italic", false, ""); edit.focus(); } function post(){ var iframe = document.getElementById("body").contentWindow; } Actually I want to fetch data from this text editor (which is created using iframe and javascript) and store it in some other place. I'm not able to fetch the content that is entered in the editor (i.e. iframe). Please help me out in this. A: You can't do that because it is not allowed. Javascript is not allowed access to other frames/iframes, as it would result in a security breach. Try to implement your editor inline in a <div></div> instead of iframe
{ "pile_set_name": "StackExchange" }
Q: Not able to update image path in my database I m not able to update image path in my sql database in php. It is not showing any error also.I want set profile picture of user(like facebook) so for that i had done coding but it is not working can any one help me in finding my error. profilepicture.php <!-- Step 3--> <?php <?php /**********MYSQL Settings****************/ $host="localhost"; $databasename="photo_db"; $user="root"; $pass=""; /**********MYSQL Settings****************/ $conn=mysql_connect($host,$user,$pass); if($conn) { $db_selected = mysql_select_db($databasename, $conn); if (!$db_selected) { die ('Can\'t use foo : ' . mysql_error()); } } else { die('Not connected : ' . mysql_error()); } ?> function GetImageExtension($imagetype) { if(empty($imagetype)) return false; switch($imagetype) { case 'image/bmp': return '.bmp'; case 'image/gif': return '.gif'; case 'image/jpeg': return '.jpg'; case 'image/png': return '.png'; default: return false; } } if (!empty($_FILES["uploadedimage"]["name"])) { $file_name=$_FILES["uploadedimage"]["name"]; $temp_name=$_FILES["uploadedimage"]["tmp_name"]; $imgtype=$_FILES["uploadedimage"]["type"]; $ext= GetImageExtension($imgtype); $imagename=$_FILES["uploadedimage"]["name"]; //$imagename=date("y-d-m")."-".time().$ext; $target_path = "images/".$imagename; if(move_uploaded_file($temp_name, $target_path)) { $query_upload="UPDATE signup SET profilepicture='$target_path' WHERE uname='[email protected]' limit 1 " ; $qry=mysql_query($query_upload) or die("error in $query_upload == ".mysql_error()); if(!$qry) { die("mySQL error: ". mysql_error()); } else { header("location:index.php"); } } else { exit("Error While uploading image on the server"); } } ?> index.html <html> <head> <script type="text/javascript"> function performClick(node) { var evt = document.createEvent("MouseEvents"); evt.initEvent("click", true, false); node.dispatchEvent(evt); var theFile = document.getElementById("theFile"); // the file is the first element in the files property } </script> </head> <body> <a href="profilepicture.php" onclick="performClick(document.getElementById('theFile'));">Edit</a> <input type="file" id="theFile" name="uploadedimage" style="visibility:hidden;" /> </body> </html> A: Add some blanks in your sql string: $query_upload="UPDATE signup". " SET profilepicture='$target_path'". " WHERE uname='[email protected]' limit 1 " ; Your querystring generates: UPDATE signupSET profilepicture=$target_pathWHERE uname='[email protected]' limit 1 ; and that should give you a syntax error.
{ "pile_set_name": "StackExchange" }
Q: Proving $\lim_{x\to2} 3x^2 = 12$ using the epsilon-delta definition Here is a proof for $\lim_{x\to2} 3x^2 = 12$ We are given some $\epsilon > 0$, and we need to find $\delta$ such that $0 < |x-2| < \delta \Rightarrow |3x^2 - 12| < \epsilon$ The inequality $|3x^2 - 12| < \epsilon$ will be more useful if it is in terms of $x-2$ rather than x, since the inequality $0 < |x-2| < \delta$ is in terms of $x-2$. For simplicity, let $z = x-2$. Then we wish to find $\delta$ such that $0 < |z| < \delta \Rightarrow |3(z+2)^2 - 12| < \epsilon$ We can simplify this to $0 < |z| < \delta \Rightarrow |3z^2 + 12z| < \epsilon$ However, we know that $|3z^2 +12z|\leq|3z^2|+|12z|=3z^2 + 12|z|$. So it suffices to find $\delta$ such that $0 < |z| < \delta \Rightarrow 3z^2 + 12|z| < \epsilon$ If $ 0 < |z| < \delta$, then $3z^2 + 12|z| < 3\delta^2 + 12\delta = 3\delta(4 + \delta)$. Thus it suffices to choose $\delta$ such that $3\delta(4 + \delta) < \epsilon$ The $4 + \epsilon$ term is somewhat annoying. We can make it simpler by assuming that $\delta \leq 1$. If we assume that $\delta \leq 1$, then $4+\delta \leq 5$, and the inequality that we need becomes simply $3\delta(4+\delta) \leq 15\delta < \epsilon$ To force this to be true, we select $\delta = \frac{\epsilon}{15}$. (In the unlikely event that $\epsilon > 15$, we can just take $\delta = 1$.) We then conclude that $0 < |z| < \delta \Rightarrow |3x^2 - 12| < 3\delta(4 + \delta) \leq 15\delta=\epsilon$. Thus, for any $\epsilon < 15$, we have found that $\delta = \frac{\epsilon}{15}$ satisfies the $\delta$-$\epsilon$ condition: $0 < |x-2| < \delta \Rightarrow |3x^2 - 12| < \epsilon$ and hence we have stablished that $\lim_{x\to2} 3x^2 = 12$ What I don't understand is why just because something is greater than $|3z^2 + 12z|$ It suffices to find $\delta$ using it. I mean by that logic couldn't I say something like $|3z^2 + 12z| \leq |3z^2 + 12z| + z^{5000000}$, so it suffices to find $\delta$ such that $0 < |z| < \delta \Rightarrow|3z^2 + 12z| + z^{5000000} < \epsilon$ Any help would be appreciated A: [Not a direct answer to your question. But too long to be a comment.] I appreciate your effort writing down the long question. But I strongly dislike the way your textbook gives the proof: it makes things look so complicated and that's not the way we do analysis in practice! Here is what one could do. Let $0<\epsilon<1$. One wants to find $\delta>0$ so that the following implication is true $$ 0<|x-2|<\delta\Rightarrow |x^2-4|<\epsilon. $$ Observe that $|x^2-4|<\epsilon$ is equivalent to $$ |x-2|\cdot|x+2|<\epsilon\tag{1} $$ One can see that when $x$ is getting "close" to $2$, $|x-2|$ can be as small as possible while $|x+2|$ remains bounded by some fixed number. This is the essential point to give the proof. To make it precise, choose $\delta=\epsilon$. Then if $0<|x-2|<\delta$, we have $$ |x-2|\cdot |x+2|\leqslant\epsilon (\epsilon +4)<5\epsilon\tag{2} $$ where we use the triangle inequality $|x+2|\leqslant |x-2|+4$. I claim that (2) completes the proof by the following easy exercise. Exercise. Show that the following statements are equivalent: There exists some constant $C$ such that for every $\epsilon>0$, $|A|\leqslant C\epsilon$. For every $\epsilon>0$, $|A|\leqslant \epsilon$. For every $\epsilon$ with $0<\epsilon<1$, $|A|\leqslant \epsilon$. I would like to repeat a remark I made in another answer: One important tactic that is seldom mentioned in elementary real analysis or calculus textbooks is that when doing an estimate in analysis, one should never worry about the constant in front of one's epsilon. As Terry Tao points out in one of his excellent blog posts on problem solving strategies in real analysis: Don’t worry too much about exactly what $\varepsilon$ (or $\delta$, or $N$, etc.) needs to be. It can usually be chosen or tweaked later if necessary. A: [This is an answer directly answering your confusion.] ... We can simplify this to $$0 < |z| < \delta \Rightarrow |3z^2 + 12z| < \epsilon\tag{a}$$ However, we know that $|3z^2 +12z|\leq|3z^2|+|12z|=3z^2 + 12|z|$. So it suffices to find $\delta$ such that $$0 < |z| < \delta \Rightarrow 3z^2 + 12|z| < \epsilon\tag{b}$$ So here is your question: why "it suffices to find $\delta$ such that (b) is true" while what we want is (a). Suppose you have found a $\delta$ such that (b) is true. Then since "we know that" $$ |3z^2 +12z|\leq|3z^2|+|12z|=3z^2 + 12|z|\tag{c}, $$ we have $$ 0 < |z| < \delta \Rightarrow |3z^2 + 12z| \leq 3z^2 + 12|z|< \epsilon. $$ The reason to work on (b) instead of (a) is not only it is logically correct but also it is useful to find out a $\delta$ one needs. It is logically correct but useless to say that it suffices to find $\delta$ such that $$ 0<|z|<\delta\Rightarrow |3z^2+12z|+z^{10000}<\epsilon. $$
{ "pile_set_name": "StackExchange" }
Q: TSQL only pull data if another date field is the previous business day 1) I'm need only to pull data if the the openddate is equal to the PrevBiz date. I think the where/and statement would be Openddate = PrevBiz, but not sure. It wasn't working for me and could be because the date format isn't matching. Any Suggestions? DECLARE @TODAY DATE = GETDATE() DECLARE @PREVFIRST CHAR(8) = CONVERT(CHAR(8), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0), 112) DECLARE @PREVLAST CHAR(8) = CONVERT(CHAR(8), DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), -1), 112) DECLARE @PREVBIZ CHAR(12) = DATEADD(DAY, CASE DATENAME(WEEKDAY, CONVERT(CHAR(12), @TODAY,112)) WHEN 'SUNDAY' THEN -2 WHEN 'MONDAY' THEN -3 ELSE -1 END, DATEDIFF(DAY, 0, CONVERT(CHAR(12), @TODAY, 112))) SELECT TOP 10 CURRENTDATE =@TODAY, FIRST_OF_MONTH =@PREVFIRST, LASTDAY_OFMONTH =@PREVLAST, PREVBIZ =@PREVBIZ, DATEADD(DAY, CASE DATENAME(WEEKDAY, CONVERT(DATE, @TODAY,101)) WHEN 'SUNDAY' THEN -2 WHEN 'MONDAY' THEN -3 ELSE -1 END, DATEDIFF(DAY, 0, CONVERT(DATE, @TODAY, 101))) AS PREVIOUSBIZDATE, OpendDate FROM [USBI_DW].[USBI].[vw_NameAddressBase] where IsCurrent = 1 Here's my results: A: declare @TODAY datetime = convert(date,GETDATE()) declare @PREVBIZ datetime = DATEADD(DAY, CASE DATENAME(WEEKDAY,@TODAY) WHEN 'SUNDAY' THEN -2 WHEN 'MONDAY' THEN -3 ELSE -1 END,@TODAY) declare @iToday int = convert(nvarchar(8),@TODAY, 112) , @iPrevBiz int = convert(nvarchar(8),@PREVBIZ, 112) select top 10 CURRENTDATE =@iToday, PREVBIZ =@iPrevBiz, OpendDate from [USBI_DW].[USBI].[vw_NameAddressBase] where IsCurrent = 1 and OprendDate = @iPrevBiz hope your view contains int date attribute ( because of DateWarehouse specific)
{ "pile_set_name": "StackExchange" }
Q: R: String Operations on Large Data Set (How to speed up?) I have a large data.frame (>4M rows) in which one column contains character strings. I want to perform several string operations/match regular expressions on each text field (e.g. gsub). I'm wondering how I can speed up operations? Basically, I'm performing a bunch of gsub(patternvector," [token] ",tweetDF$textcolumn) gsub(patternvector," [token] ",tweetDF$textcolumn) .... I'm running R on a 8GB RAM Mac and tried to move it to the cloud (Amazon EC2 large instance with ~64GB RAM), but it's not going very fast. I've heard of the several packages (bigmemory, ff) and found an overview about High Performance/Parallel Computing for R here. Does anyone have recommendations for a package most suitable for speeding up string operations? Or knows of a source explaining how apply the standard R string functions (gsub,..) to the 'objects' created by these 'High Performance Computing packages' ? Thanks for your help! A: mclapply or any other function that allows for parallel processing should speed up the task significantly. If you are not using parallel processing you are only using only 1 CPU, no matter how many CPUs your computer has available.
{ "pile_set_name": "StackExchange" }
Q: Applications of mathematics All of us have probably been exposed to questions such as: "What are the applications of group theory...". This is not the subject of this MO question. Here is a little newspaper article that I found inspiring: Madam, – In response to Marc Morgan’s question, “Does mathematics have any practical value?” (November 8th), I wish to respond as follows. Apart from its direct applications to electrical circuits and machinery, electronics (including circuit design and computer hardware), computer software (including cryptography for internet transaction security, business software, anti-virus software and games), telephones, mobile phones, fax machines, radio and television broadcasting systems, antenna design, computer game consoles, hand-held devices such as iPods, architecture and construction, automobile design and fabrication, space travel, GPS systems, radar, X-ray machines, medical scanners, particle research, meteorology, satellites, all of physics and much of chemistry, the answer is probably “No”. – Yours, etc, PAUL DUNNE, The Irish Times - Wednesday, November 10, 2010 The above article article seems to provide an ideal source of solutions to a perennial problem: How to tell something interesting about math to non-mathematicians, without losing your audience? However, I am embarrassed to admit that I have no idea what kind of math gets used for antenna designs, computer game consoles, GPS systems, etc. I would like to have a list applications of math, from the point of view of the applications. To make sure that each answer is sufficiently structured and developed, I shall impose some restrictions on their format. Each answer should contain the following three parts, roughly of the same size: • Start by the description of a practical problem that any layman can understand. • Then I would appreciate to have an explanation of why it is difficult to solve without mathematical tools. • Finally, there should be a little explanation of the kind of math that gets used in the solution. ♦♦  My ultimate goal is to have a nice collection of examples of applications of mathematics, for the purpose of casual discussions with non-mathematicians. ♦♦ As usual with community-wiki questions: one answer per post. A: Sending a man to the Moon (and back). Hilbert once remarked half-jokingly that catching a fly on the Moon would be the most important technological achievement. "Why? "Because the auxiliary technical problems which would have to be solved for such a result to be achieved imply the solution of almost all the material difficulties of mankind." (Quoted from Hilbert-Courant by Constance Reid, Springer, 1986, p. 92). The task obviously required solving plenty of scientific and technological problems. But the key breakthrough that made it all possible was Richard Arenstorf's discovery of a stable 8-shaped orbit between the Earth and the Moon. This involved the development of a numerical algorithm for solving the restricted three-body problem which is just a special non-linear second order ODE (see also my answer to the previous MO question). Another orbit, also mapped by Arenstorf, was later used in the dramatic rescue of the Apollo 13 crew. A: One typical way that GPS is invoked as an application of mathematics is through the use of general relativity. Most people have a rough idea of what the GPS system does: there are some (27) satellites flying in the sky, and a GPS device on the surface of the earth determines its position by radio communication with the satellites. It is also pretty clear that this is a hard problem to solve, with or without mathematics. The basic idea is that if your GPS device measures its distance between 3 different satellites, then it knows that it lies on three level sets which must intersect at a point. This is the standard idea of triangulation. Of course measuring distance is hard to do, and relativity comes into play in many different, nontrivial ways, but there is one way in particular that is interesting and easy to explain. If one uses the euclidean metric to determine the distance (so, straight lines) from the GPS to the satellite, then it will be impossible to determine the location on the earth to a high degree of accuracy. So instead the GPS system uses the kerr metric, that is the lorentz metric that models spacetime outside of a spherically symmetric, rotating body. Naturally this metric gives a different, more accurate distance between the observer on earth and the satellite. The thing that is surprising to people is that the switch from euclidean to kerr is required to get really accurate gps readings. In other words, without relativity you might not be able to use that iphone app to find your car in the grocery store parking lot. People are often surprised and interested to learn that the differences between relativity and newtonian gravity really are observable. Other standard examples are the precession of the perihelion of mercury (which was a famous unsolved problem before the introduction of GR) and the demonstration that light rays do not travel along straight lines by photographing the sun during an eclipse. This last observation demonstrated, for instance, that the metric on the universe is not the trivial flat one. A: Here are some examples to quote my favorite one: In 1998, mathematics was suddenly in the news. Thomas Hales of the University of Pittsburgh, Pennsylvania, had proved the Kepler conjecture, showing that the way greengrocers stack oranges is the most efficient way to pack spheres. A problem that had been open since 1611 was finally solved! On the television a greengrocer said: “I think that it's a waste of time and taxpayers' money.” I have been mentally arguing with that greengrocer ever since: today the mathematics of sphere packing enables modern communication, being at the heart of the study of channel coding and error-correction codes. In 1611, Johannes Kepler suggested that the greengrocer's stacking was the most efficient, but he was not able to give a proof. It turned out to be a very difficult problem. Even the simpler question of the best way to pack circles was only proved in 1940 by László Fejes Tóth. Also in the seventeenth century, Isaac Newton and David Gregory argued over the kissing problem: how many spheres can touch a given sphere with no overlaps? In two dimensions it is easy to prove that the answer is 6. Newton thought that 12 was the maximum in 3 dimensions. It is, but only in 1953 did Kurt Schütte and Bartel van der Waerden give a proof. The kissing number in 4 dimensions was proved to be 24 by Oleg Musin in 2003. In 5 dimensions we can say only that it lies between 40 and 44. Yet we do know that the answer in 8 dimensions is 240, proved back in 1979 by Andrew Odlyzko of the University of Minnesota, Minneapolis. The same paper had an even stranger result: the answer in 24 dimensions is 196,560. These proofs are simpler than the result for three dimensions, and relate to two incredibly dense packings of spheres, called the E8 lattice in 8-dimensions and the Leech lattice in 24 dimensions. This is all quite magical, but is it useful? In the 1960s an engineer called Gordon Lang believed so. Lang was designing the systems for modems and was busy harvesting all the mathematics he could find. He needed to send a signal over a noisy channel, such as a phone line. The natural way is to choose a collection of tones for signals. But the sound received may not be the same as the one sent. To solve this, he described the sounds by a list of numbers. It was then simple to find which of the signals that might have been sent was closest to the signal received. The signals can then be considered as spheres, with wiggle room for noise. To maximize the information that can be sent, these 'spheres' must be packed as tightly as possible. In the 1970s, Lang developed a modem with 8-dimensional signals, using E8 packing. This helped to open up the Internet, as data could be sent over the phone, instead of relying on specifically designed cables. Not everyone was thrilled. Donald Coxeter, who had helped Lang understand the mathematics, said he was “appalled that his beautiful theories had been sullied in this way”.
{ "pile_set_name": "StackExchange" }
Q: HoHOA behaves differently when values are pushed I have the following data: eya XLOC_000445_Change:10.3_q:0.003 atonal1 six XLOC_00099_Change:70.0_q:0.095 atonal1 six-eya XLOC_0234324_Change:19.8_q:0.05 atonal1 eya XLOC_00010_Change:6.5_q:0.22 c-myc six XLOC_025437_Change:1.1_q:0.018 c-myc six-eya XLOC_001045_Change:2.3_q:0.0001 c-myc eya XLOC_000115_Change:7.3_q:0.03 ezrin six XLOC_000001_Change:7.9_q:0.00006 ezrin six-eya XLOC_0234322_Change:9.0_q:0.0225 ezrin six-eya XLOC_091345_Change:9.3_q:0.005 slc12a2 eya XLOC_000445_Change:9.9_q:0.3 atonal1 six XLOC_00099_Change:7.0_q:0.95 atonal1 six-eya XLOC_0234324_Change:9.8_q:0.5 atonal1 And have tried building a HoHoA as follows: #!/usr/bin/perl use warnings; use strict; Method 1: Pushing array values onto HoH: while (<$input>) { chomp; push @xloc, $1 if ($_ =~ /(XLOC_\d+)/); push @change_val, $1 if ($_ =~ /Change:(-?\d+\.\d+|-?inf)/); push @q_value, $1 if ($_ =~ /q:(\d+\.\d+)/); my @split = split('\t'); push @condition, $split[0]; push @gene, $split[2]; } push @{ $experiment{$gene[$_]}{$condition[$_]} }, [ $xloc[$_], $change_val[$_], $q_value[$_] ] for 0 .. $#change_val; Method 2: Assigning values to HoHoA on the fly: while (<$input>) { chomp; my $xloc = $1 if ($_ =~ /(XLOC_\d+)/); my $change = $1 if ($_ =~ /Change:(-?\d+\.\d+|-?inf)/); my $q_value = $1 if ($_ =~ /q:(\d+\.\d+)/); my @split = split('\t'); my $condition = $split[0]; my $gene = $split[2]; $experiment{$gene}{$condition} = [ $xloc, $change, $q_value ]; } Both work fine - insofar as I get the data structure I want. However, only the first method (pushing) ensures that genes that exist as duplicates (in this case atonal1) are represented twice in the HoHoA. My downstream code was originally made to handle HoHoA built in the second fashion, and I can't for the life of me work out why both approaches are handled differently in the follwing code: Downstream code: my (%change, %seen, $xloc, $change_val, $q_value); for my $gene (sort keys %experiment) { for my $condition (sort keys %{$experiment{$gene}}) { $seen{$gene}++; # Counts for each occurrence of gene if ( (not exists $change{$gene}) || (abs $change{$gene} < abs $experiment{$gene}{$condition}[1]) ) { # Has a larger change value $change{$gene} = $experiment{$gene}{$condition}[1]; } } } print Dumper \%change; When I run the above code on either approach I get: Output for method 1: $VAR1 = { 'atonal1' => [ 'XLOC_0234324', '9.8', '0.5' ], 'c-myc' => undef, 'ezrin' => undef, 'slc12a2' => undef, }; Output for method 2: $VAR1 = { 'atonal1' => '9.9', # i.e. the largest change value for each condition/gene 'c-myc' => '6.5', 'ezrin' => '9.0', 'slc12a2' => '9.3', }; What I want is: $VAR1 = { 'atonal1' => [ '9.9', '70.0' # This is the difference - i.e the both values are added to the hash `%change` ], 'c-myc' => '6.5', 'ezrin' => '9.0', 'slc12a2' => '9.3', }; I have no idea what's creating the difference UPDATE I'll post the Dumper output for %experiment after values have been pushed on using Method 1: $VAR1 = { 'atonal1' => { 'eya' => [ [ 'XLOC_000445', '10.3', '0.003' ], [ 'XLOC_000445', '9.9', '0.3' ] ], 'six' => [ [ 'XLOC_00099', '70.0', '0.095' ], [ 'XLOC_00099', '7.0', '0.95' ] ], 'six-eya' => [ [ 'XLOC_0234324', '19.8', '0.05' ], [ 'XLOC_0234324', '9.8', '0.5' ] ] }, 'c-myc' => { 'eya' => [ [ 'XLOC_00010', '6.5', '0.22' ] ], 'six' => [ [ 'XLOC_025437', '1.1', '0.018' ] ], 'six-eya' => [ [ 'XLOC_001045', '2.3', '0.0001' ] ] }, 'ezrin' => { 'eya' => [ [ 'XLOC_000115', '7.3', '0.03' ] ], 'six' => [ [ 'XLOC_000001', '7.9', '0.00006' ] ], 'six-eya' => [ [ 'XLOC_0234322', '9.0', '0.0225' ] ] }, 'slc12a2' => { 'six-eya' => [ [ 'XLOC_091345', '9.3', '0.005' ] ] }, }; A: Let's take your data and reformat it a bit. I'm not saying this is the way you need to format your data. I'm just doing it this way to get a better understanding of what it represents: GENE XLOC CHANGE Q VALUE CONDITION ======== ==================== ======= ======== ========== eya XLOC_000445_Change: 10.3_q: 0.003 atonal1 six XLOC_00099_Change: 70.0_q: 0.095 atonal1 six-eya XLOC_0234324_Change: 19.8_q: 0.05 atonal1 eya XLOC_00010_Change: 6.5_q: 0.22 c-myc six XLOC_025437_Change: 1.1_q: 0.018 c-myc six-eya XLOC_001045_Change: 2.3_q: 0.0001 c-myc eya XLOC_000115_Change: 7.3_q: 0.03 ezrin six XLOC_000001_Change: 7.9_q: 0.00006 ezrin six-eya XLOC_0234322_Change: 9.0_q: 0.0225 ezrin six-eya XLOC_091345_Change: 9.3_q: 0.005 slc12a2 eya XLOC_000445_Change: 9.9_q: 0.3 atonal1 six XLOC_00099_Change: 7.0_q: 0.95 atonal1 six-eya XLOC_0234324_Change: 9.8_q: 0.5 atonal1 Are my column assumptions correct? First, I recommend that you use split to split up your values instead of regular expressions. Do this on a line-by-line basis. Perl is pretty efficient at optimization. 90% of programming is debugging and supporting your program. Trying to be efficient by compressing multiple steps into a single step just make things harder to understand with very little value returned in optimization. Let's take each line, and break it out: while ( my $line = <$input> ) { chomp $line; my ( $gene, $more_data, $condition ) = split /\s+/, $line; At this point: $gene = 'eye' $more_data = 'XLOC_000445_Change:10.3_q:0.003'; $condition = 'atonal1` # I'm not sure what this is... Now, we can split out $more_data: my ( $xloc, $change, $q_value ) = split /:/, $more_data; $xloc =~ s/^XLOC_//; $change =~ s/_q$//; Now we have: $xloc = '000445'; $change = '10.3'; $q_value = '0.003'; Does this make more sense? One of your problems is you're attempting to store data in a very, very complex structure without really thinking about what that data represents. Let's say your data is this: a gene may contain multiple conditions, Each gene-condition combination can have a result. This result contains an xloc, q_value, and change. That means your data should look like this: $experiment{$gene}->{$condition}->{XLOC} = $xloc; $experiment{$gene}->{$condition}->{Q_VALUE} = $q_value; $experiment{$gene}->{$condition}->{CHANGE} = $change; However, I see gene = eya, condition = atonal1 twice in your list. Maybe you need something more along the lines of this: a gene may contain multiple conditions, Each gene-condition combination can have multiple results. Each result contains an xloc, q_value, and change. If that's the case, your data structure should look something like this: $experment{$gene}->{$condition}->[0]->{XLOC} = $xloc; $experment{$gene}->{$condition}->[0]->{Q_VALUE} = $q_value; $experment{$gene}->{$condition}->[0]->{CHANGE} = $change; This isn't an answer. I'm just trying to get a handle on what your data is and what you are trying to store in that data. Once we have that settled, I can help you with the rest of your program. Let me know if my understanding of what your data represents is accurate. Add a comment to this answer, and update your question a bit. Once I know I'm on the right track, I'll show you how you can more easily manage this structure and keep track of everything in it. Now that I knew I was on the right track, the solution was fairly simple: Object Oriented Programming! Let me explain: Each experiment consists of a Gene-Condition pair. This is what I key my experiments on. I create a Local::Condition for each of these Gene-Condition pairs. Inside of this I store my array of results. My results contain three item. Behold: The Answer! What I decided to do is to create a results object. This object contains the XLoc, Change, and Q Value of that result. By packing my results into an object, I have fewer issues trying to keep track of it. So what we have is this: We have experiments. Each _experiment consists of a gene/condition pair which we key our experiments on. Each gene/condition experiment consists of an array of results. Now, it's a lot easier to keep track of what is going on. For each line, I create a Local::Result type of object that contains the set of results of that gene/condition pair. So, all I have to do is push my results onto that gene/condition array which represents my set of results # # Create a Result for this experiment # my $result = Local::Result->new( $xloc, $change, $q_value ); # # Push this result onto your $gene/condition experiment # push @{ $experiments{$gene}->{$condition} }, $result; Note my syntax here is very spelled out. I have a hash called %experiments that are keyed by Genes. Each gene contains Conditions for that gene. This Gene/Condition pair is an array of results. Object Oriented syntax can be a bit complex to get use to, but there is an excellent tutorial in the Perl documentation. By using object oriented programming, you group together details that you otherwise must track. #! /usr/bin/env perl use strict; use warnings; use feature qw(say); use autodie; use Data::Dumper; my %experiments; while ( my $line = <DATA> ) { my ($condition, $more_data, $gene) = split /\s+/, $line; my ($xloc, $change, $q_value) = split /:/, $more_data; $xloc =~ s/^XLOC_(.*)_Change/$1/; $change =~ s/_q$//; my $result = Local::Result->new( $xloc, $change, $q_value ); push @{ $experiments{$gene}->{$condition} }, $result; } printf "%-10.10s %-10.10s %10.10s %-4s %-7s\n\n", "Gene", "Condition", "XLoc", "Chng", "Q Value"; for my $gene ( sort keys %experiments ) { for my $condition ( sort keys %{ $experiments{$gene} } ) { for my $result ( @{ $experiments{$gene}->{$condition} } ) { printf "%-10.10s %-10.10s %10.10s %-4.1f %-7.1f\n", $gene, $condition, $result->xloc, $result->change, $result->q_value; } } } package Local::Result; sub new { my $class = shift; my $xloc = shift; my $change = shift; my $q_value = shift; my $self = {}; bless $self, $class; $self->xloc($xloc); $self->change($change); $self->q_value($q_value); return $self; } sub xloc { my $self = shift; my $xloc = shift; if ( defined $xloc ) { $self->{XLOC} = $xloc; } return $self->{XLOC}; } sub change { my $self = shift; my $change = shift; if ( defined $change ) { $self->{CHANGE} = $change; } return $self->{CHANGE}; } sub q_value { my $self = shift; my $q_value = shift; if ( defined $q_value ) { $self->{Q_VALUE} = $q_value; } return $self->{Q_VALUE}; } package main; __DATA__ eya XLOC_000445_Change:10.3_q:0.003 atonal1 six XLOC_00099_Change:70.0_q:0.095 atonal1 six-eya XLOC_0234324_Change:19.8_q:0.05 atonal1 eya XLOC_00010_Change:6.5_q:0.22 c-myc six XLOC_025437_Change:1.1_q:0.018 c-myc six-eya XLOC_001045_Change:2.3_q:0.0001 c-myc eya XLOC_000115_Change:7.3_q:0.03 ezrin six XLOC_000001_Change:7.9_q:0.00006 ezrin six-eya XLOC_0234322_Change:9.0_q:0.0225 ezrin six-eya XLOC_091345_Change:9.3_q:0.005 slc12a2 eya XLOC_000445_Change:9.9_q:0.3 atonal1 six XLOC_00099_Change:7.0_q:0.95 atonal1 six-eya XLOC_0234324_Change:9.8_q:0.5 atonal1
{ "pile_set_name": "StackExchange" }
Q: On the resolvent set of an unbounded operator Suppose $A$ is the infinitesimal generator of a $C_0$ semigroup $S(t)$ on an Hilbert space $X$. If $$\langle Ax, x\rangle \leq \omega \|x \|^2 \ \ \ \forall x \in \mathfrak{D}(A)$$ then $$\|S(t)\| \leq e^{\omega t} \ \ \forall t \geq 0$$ How do I prove this? Notice that $A$ is unbounded, closed and densely defined, but we don't know anything else. My idea until now is to prove that we are in the hypotheses of the Hille-Yosida theorem, namely that: $$\rho(A) \supset (\omega, \infty) \ \ \ \mathrm{and} \ \ \ \|R_{\lambda}\| \leq \frac{1}{\lambda - \omega} \ \ \forall \lambda > \omega$$ In particular, it is easy to see that if $\omega < \lambda \in \rho(A)$ then the second hypothesis is immediately satisfied. Therefore, I only need to show that $(\omega, \infty) \subset \rho(A)$. Now, if by contradiction we assume that $\lambda > \omega$ is not in $\rho(A)$, then the image $\mathfrak{R}(\lambda I- A) \not = X$. Therefore, there exists a $y \not = 0$ such that $$\langle x - Ax, y \rangle = 0 \ \ \ \forall x \in \mathfrak{D}(A)$$ I would like to show that $y = 0$, but I don't know how to do it. Notice, for instance, that $y \in \mathfrak{D}(A^*)$, but we don't know if $A^*$ is dissipative. At the same time, we don't know if $y \in \mathfrak{D}(A)$. How can I approach this problem? A: Because $\frac{d}{dt}(S(t)x=AS(t)x$ for all $t > 0$ (and as a right derivative at $0$,) then $$ \frac{d}{dt}\|S(t)x\|^2=\frac{d}{dt}\langle S(t)x,S(t)x\rangle \\ = \langle AS(t)x,S(t)x\rangle+\langle S(t)x,AS(t)x\rangle \\ \le 2w\langle S(t)x,S(t)x\rangle = 2w\|S(t)x\|^2 $$ Therefore, for all $t \ge 0$, $x\in X$, $$ \frac{d}{dt}\|S(t)x\|^2-2w\|S(t)x\|^2 \le 0 \\ \frac{d}{dt}(e^{-2wt}\|S(t)x\|^2) \le 0 \\ e^{-2wr}\|S(r)x\|^2|_{r=0}^{r=t} \le 0 \\ e^{-2wt}\|S(t)x\|^2 \le \|S(0)x\|^2 \\ \|S(t)x\|^2 \le e^{2wt}\|x\|^2 \\ \|S(t)x\| \le e^{wt}\|x\|. $$ Because this holds for all $x$, it follows that $$ \|S(t)\| \le e^{wt},\;\;\; t \ge 0. $$
{ "pile_set_name": "StackExchange" }
Q: Help with a SQL Query I am wanting to perform a Threshold query, whereby one would take the Value of a field from Today, and compare it to the value from yesterday, this query would look something like this, but obviously, it is wrong, and I can't find how to do it: select TableB.Name, TableA.Charge, ( select Charge from TableA where (DateAdded >= '13/10/2009' and DateAdded < '14/10/2009') ) from TableA inner join TableB on TableB.ID = TableA.ID where TableA.DateAdded >= '10/14/2009' order by Name asc Just a quick note, I am looking for two CHARGE fields, not the dates. The date manipulation is simply for Today and Yesterday, nothing more. At the end of this, I want to do a calculation on the two returned charge fields, so if its easier to show that, that would also be great. Thanks in advance Kyle EDIT1: The data I am looking for is like so: Yesterday, we input a charge of 500 to MachineA Today we input a charge of 300 to MachineA We run the query, and results I need are as follows: Name = MachineA Charge = 300 YesterdayCharge = 500 A: If you really need previous date (including weekends etc), then following query should do the job. Otherwise please post data samples and expected results: SELECT TableB.Name, TableA.Charge, prev.Charge AS PrevCharge FROM TableA INNER JOIN TableB ON TableA.ID = TableB.ID LEFT JOIN TableA prev ON TableA.ID = prev.ID --// use this if DateAdded contains only date --AND TableA.DateAdded = DATEADD(day, +1, prev.dateAdded) --// use this if DateAdded contains also time component AND CONVERT(DATETIME, CONVERT(CHAR(8), TableA.DateAdded, 112), 112) = DATEADD(day, +1, CONVERT(DATETIME, CONVERT(CHAR(8), prev.dateAdded, 112), 112)) edit-1: added option in JOIN for cases when DateAdded contains time as well
{ "pile_set_name": "StackExchange" }
Q: C# Replace two specific commas in a string with many commas I am trying to change the date format in each line from commas to hyphens. The index of the comma separating the month and day day and year varies. lines_in_List[i] = lines_in_List[i].Insert(0, cnt + ","); // Insert Draw # in 1st column string one_line = lines_in_List[i]; // 0,5,1,2012,1,10,19,16,6,36,,, // 1,11,5,2012,49,35,23,37,38,28,,, // 2,12,10,2012,8,52,53,54,47,15,,, // ^-^--^ replace the ',' with a '-'. StringBuilder changed = new StringBuilder(one_line); changed[3] = '-'; changed[5] = '-'; changed[3] = '-'; lines_in_List[i] = changed.ToString(); } A: You can use the overload of IndexOf that takes an initial offset to begin searching. http://msdn.microsoft.com/en-us/library/5xkyx09y.aspx int idxFirstComma = line.IndexOf(','); int idxSecondComma = line.IndexOf(',', idxFirstComma+1); int idxThirdComma = line.IndexOf(',', idxSecondComma+1); Use those indices to do your replacements. To efficiently replace those characters (without creating lots of temporary string instances), check this out: http://www.dotnetperls.com/change-characters-string That snippet converts the string to a character array, does the replacements, and creates one new string.
{ "pile_set_name": "StackExchange" }
Q: Prove: $T=\{u\subseteq X:u^C finite\}\cup \{\emptyset\}$ is a topology Let there be $X$ and let $T=\{u\subseteq X:u^C finite\}\cup \{\emptyset\}$ Prove $T$ is a topology: $\emptyset \in T$ and $X\subseteq X$ where $X^C=\emptyset$ is finite so $X\in T$ let $u_\alpha\in T$ we have to prove that $\cup_{\alpha\in I}u_\alpha\in T$, how can it be done? let $u_i\in T$ we have to prove that $\cap_{1\leq i \leq n}u_i\in T$ so $\cap_{1\leq i \leq n}u_i=(\cup_{1\leq i \leq n}u^C_i)^C$ is it correct? A: 2) Discern two cases: $u_{\alpha}=\varnothing$ for every $\alpha\in I$ some $\alpha_0$ exists with $\alpha_0\neq\varnothing$ First bullet: $\bigcup_{\alpha\in I}u_{\alpha}=\varnothing\in T$. Second bullet: $(\bigcup_{\alpha\in I}u_{\alpha})^{\complement}\subseteq u_{\alpha_0}^{\complement}$ so the complement of the union is - as a subset of a finite set - finite itself. 3) Not correct. If the intersection is empty then we are ready. If not then: $(\bigcap_{1\leq i\leq n}u_i)^{\complement}=\bigcup_{1\leq i\leq n}u_i^{\complement}$ which is - as a finite union of finite sets - finite itself.
{ "pile_set_name": "StackExchange" }
Q: A passage in the newman proof of the prime number theorem. In the proof of the statement that $\theta(x) \sim x$ based on the fact that $\int_1^\infty { \frac{\theta(x) - x}{x^2}dx } < \infty$ We assume that for some $\lambda > 1$ there are arbitrarily large x with $\theta(x) \geq \lambda x$ and since $\theta(x)$ is non-decreasing, we have $\int_x^{\lambda x} { \frac{\theta(t) - t}{t^2}dt } \leq \int_x^{\lambda x} { \frac{\lambda x- t}{t^2}dt } = \int_1^{\lambda} { \frac{\lambda - t}{t^2}dt }$ and we have a contradiction. my question is: why in the last equality we choose arbitrarily x = 1? or where does the last equality comes from? thank you A: Substitute $t\leftarrow xt$, $dt\leftarrow xdt$ and voila.
{ "pile_set_name": "StackExchange" }
Q: vs. Server Fault I just discovered networkengineering.se. What kinds of questions are appropriate here but not appropriate for Server Fault? I ask because somebody on Super User just asked a question regarding network administration of a public urban wifi network, and I wasn't sure where to redirect them. The question seems to make sense to me both here and on Server Fault, but Server Fault has a wider user base and more activity, hence a better chance for an answer, while networkengineering seems hyper-specialized - is it a proper subset of Server Fault or does it provide new topics not covered there? A: SF came along first, and was targeted at IT professionals taking care of servers/networks and has built up a great community. The problem though is that the majority of the site is dedicated to server related questions/problems. Network professionals didn't tend to frequent the site or consider it a valued resource. NE was started as a place for network professionals to address network questions specifically without having the extra "noise" of questions/answers that weren't necessarily of interest to them. Is there overlap? Absolutely, and that is often the case within the SE community. Ask Ubuntu is a subset of Unix & Linux which can also overlap with SF. Heck, when you get down to it, there isn't anything you can ask on SF that wouldn't be on topic on Super User. Neither should the SF community remove networking from their scope. There are many places where the systems administrators will also be in charge of the network. It makes sense for them to use the community that they may be most comfortable with personally. The same is true for Unix/Linux questions. Since the NE site is still new and in beta, your assertion that SF has a wider user base and more activity is true. However, the counter point is two fold: first that the extra activity could allow a question to more easily "fall through the cracks" and second much of their user base is quite comfortable with servers but not as much with networks. Here at NE, the user base is clearly network oriented and as long as we keep getting content and users, eventually we will be the clear choice for professional network questions. Until then, I would tend to say the network answers on NE tend to be of better quality than those provided on SF, but SF may often produce a faster answer. A: tl;dr NE is focused, SF is more broad Many of the community members here are also on SF, and I think almost every question here on NE could be asked on SF. But the point of NE is to only cover Net Eng. So the signal-to-noise ratio [for our on-topic material] is vastly higher than on SF. I would be surprised if a question asked here didn't get a better response than on SF.
{ "pile_set_name": "StackExchange" }
Q: Zend_PDF: Remove html contents from PDF document I have created function getPdf in my custom controller public function getPdf() { $pdf = new Zend_Pdf(); $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4); $imagePath="C:\Users\Hp\Desktop\landscape3.jpg"; $image = Zend_Pdf_Image::imageWithPath($imagePath); $page->drawImage($image, 40,764,240, 820); $pdf->pages[] = $page; $pdf->save('myfile.pdf'); } It generates PDF with image but in magento1.7 folder. I have tried the following lines $pdfString = $pdf->render(); header("Content-Disposition: attachment; filename=mydownloads.pdf"); header("Content-type: application/x-pdf"); echo $pdfString; It generates PDF document in Downloads folder but when I open it.An error message is displayed:Adobe reader couldn't open myfile.pdf because it's not either a supported file type or because the file has been damaged............ When I open mydownloads.pdf in text editor (notepad), I notice presence of html contents(the contents of current phtml file in which getPdf() function is called) with pdf's own contents.I even tried to disable view rendering in magento1.7 by using $vr = Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer'); $vr->setNoRender(true); $layout = Zend_Layout::getMvcInstance(); $layout->disableLayout(); but unfortunately it didn't work in magento1.7.Then I tried to echo the contents of $pdfString by removing those two lines of header function like $pdfString = $pdf->render(); return $pdfString; It simply contained Pdf's own contents. Then I realised that presence of html contents is due to these two lines header("Content-Disposition: attachment; filename=mydownloads.pdf"); header("Content-type: application/x-pdf"); Can anybody help me in resolving this issue. So that PDF document is generated in download folder. How to remove html contents from pdf document? A: Creating the PDF file To create the PDF document in a server folder of your choice, you could use something like this: $sImagePath = 'C:\Users\Hp\Desktop\landscape3.jpg'; $sPdfPath = 'C:\Users\Hp\Desktop\my.pdf'; $oPdf = new Zend_Pdf(); $oPage = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4); $oImg = Zend_Pdf_Image::imageWithPath($sImagePath); $oPage->drawImage($oImg, 40, 764, 240, 820); $oPdf->pages[] = $oPage; $sContent = $oPdf->render(); file_put_contents($sPdfPath, $sContent); Providing a download link It seems that you also want to provide a link for your users, so that they can download the PDF, once it has been created. See How to make PDF file downloadable in HTML link? for more on this. Example of creating and downloading using a controller Note, this is a quick and dirty hack, misusing the Mage_Cms_IndexController just to quickly prove and demonstrate the principle being used. Porting this to your custom controller should be a piece of cake, anyway. Tested and working fine on a fresh Magento 1.7.0.2 instance and using FF15 and IE9: class Mage_Cms_IndexController extends Mage_Core_Controller_Front_Action { const PDF_PATH = '/home/user/public_html/magento-1-7-0-2/'; public function indexAction($coreRoute = null) { // Create the PDF file $sImagePath = '/home/user/public_html/magento-1-7-0-2/media/catalog/category/furniture.jpg'; $sPdfPath = self::PDF_PATH . 'myfurniture.pdf'; $oPdf = new Zend_Pdf(); $oPage = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4); $oImg = Zend_Pdf_Image::imageWithPath($sImagePath); $oPage->drawImage($oImg, 40, 764, 240, 820); $oPdf->pages[] = $oPage; $sContent = $oPdf->render(); file_put_contents($sPdfPath, $sContent); // Echo the download link echo '<a href="cms/index/download/pdf/myfurniture">Download myfurniture.pdf</a>'; return; /* $pageId = Mage::getStoreConfig(Mage_Cms_Helper_Page::XML_PATH_HOME_PAGE); if (!Mage::helper('cms/page')->renderPage($this, $pageId)) { $this->_forward('defaultIndex'); } */ } public function downloadAction() { // Cancel if the `pdf` param is missing if (!$sPdfName = $this->getRequest()->getParam('pdf', false)) { return $this->_forward('noRoute'); } // Sanitize passed value and form path $sPdfName = preg_replace('[a-z0-9]', '', $sPdfName); $sPdfPath = self::PDF_PATH . $sPdfName . '.pdf'; // Cancel if file doesn't exist or is unreadable if (!file_exists($sPdfPath) || !is_readable($sPdfPath)) { return $this->_forward('noRoute'); } // Set proper headers header('Content-Type: application/pdf'); header("Content-Disposition: attachment; filename=" . urlencode($sPdfName . '.pdf')); header('Content-Transfer-Encoding: binary'); header("Content-Length: " . filesize($sPdfPath)); // Send readfile($sPdfPath); } // : } Just temporarily copy/paste this to your app/code/core/Mage/Cms/controllers/IndexController.php file, adjust the paths, and start testing. Loading the homepage of your Magento installation should show you a download link for the PDF then.
{ "pile_set_name": "StackExchange" }
Q: Objects duplicating every component mount. How can I make it run only once ? In react My object is a independent js file that I created. componentDidMount() { const node = ReactDOM.findDOMNode(this); const widgetBuild = new window.WidgetFormBuilder({ form: $(node).parents('#dynamic_form_wrapper') }); widgetBuild.initForm(); } A: I already fixed i just added a .destroy() function in my WidgetFormBuilder. :) WidgetFormBuilder.prototype.destroyBuilder = function () { const self = this; const destroyEvents = function () { $(self.form).unbind(); }; destroyEvents(); return this; };
{ "pile_set_name": "StackExchange" }
Q: how to use meld for reviewing remote changes. Using git as dvcs I'm using GIT as my DVCS, on Ubuntu 10.04. Simply running: meld . in your current working directory is awesome...shows what are the diffs from your working folder to last commit. I'd like to be able to do the same thing in other circumstances. Say I want to review the changes after I've fetched a remote branch? How would I do that? How can I review the differences with meld between two local branches... I'd love to know if there was a relatively simple way to do that. Thx. A: If you like meld for comparing files and resolving merges, you should probably set the config options diff.tool and merge.tool to meld, e.g. git config diff.tool meld You can then use git difftool master origin/master to view the differences between your local master and the most recently fetched version of master from origin. However, that will only show the differences one file at a time - you have to exit meld and hit enter to see the changes in the next file. If you'd like to see all the differences between two branches in meld, using its recursive view, there's not a one-line way of doing that, I'm afraid. However, I wrote a short script in answer to a very similar question that takes two refs (e.g. two branches), unpacks them to temporary directories and runs meld to compare the two: View differences of branches with meld? Anyway, if you've just run git fetch you can compare the differences between your master and the version from origin using that script with: meld-compare-refs.py master origin/master ... or compare two local branches with: meld-compare-refs.py master topic1
{ "pile_set_name": "StackExchange" }
Q: Teensy++ 2.0: How to get a PWM output from pins OC2A & OC2B I'm doing a project that requires a lot of PWM's and I've gotten 6 of the 9 PWM capable pins to work, but I'm struggling to get the last 3 running. To get the OC1A-C Pins running a PWM, I did this: DDRB = 0xE0 //Pins B7,B6 & B5 to output TCCR1A |= (1 << COM1A1) | (1 << COM1A0) |(1 << COM1B1) | (1 << COM1B0) | (1 << COM1C1) | (1 << COM1C0) | (1 << WGM10); TCCR1B |= (1 << WGM12) | (1 << CS11); //Test PWM Values OCR1A = 0x10; OCR1B = 0x20; OCR1C = 0x30; However, when I try to do the the same for OC2A and OC2B, nothing happens: DDRB = 0x10 //B4 to output DDRD = 0x02 //D1 to output TCCR2A |= (1 << COM2A1) | (1 << COM2A0) |(1 << COM2B1) | (1 << COM2B0) | (1 << WGM20); TCCR2B |= (1 << WGM22) | (1 << CS21); //Test PWM Values OCR2A = 0x40; OCR2B = 0x50; So what else do I need to set to get the PWM on those pins working? A: You've select waveform mode 5 (WGM22=1, WGM21=0, WGM20=1). This means: "Phase Correct PWM where OCR2A is the TOP value". This means that the timer will count up to the value in OCR2A and then count back down to zero. The OC2A pin won't have an output in this mode, and the OC2B pin will be set when counting up on a compare match between OCR2B and TCNT2 and cleared when the compare match occurs when counting back down. As you have set the OCR2B value to be higher than OCR2A, then a compare match will never happen because the counter starts counting back down before it happens. This means you will not get any output on OC2B either. This mode is designed for if you want a specific PWM frequency at the expense of a PWM output and you set OCR2B<=OCR2A. I believe what you want is either waveform mode 3 (WGM22=0, WGM21=1, WGM20=1) or waveform mode 1 (WGM22=0, WGM21=0, WGM20=1). These are "Fast PWM" and "Phase Correct PWM" respectively, but which use 0xFF as the TOP value. In this mode, both outputs can be used to generate a PWM signal with a fixed frequency but independent duty cycle (the frequency depends on the prescaler settings and clock frequency). Just for reference, the above is based on Table 16-7 on page 158 of the datasheet.
{ "pile_set_name": "StackExchange" }
Q: Jquery Map Highlight I'm using http://plugins.jquery.com/project/maphilight for highlighting areas when I hover over an image map, but I'd also like to keep it highlighted when clicked. When another area is clicked, the previous one should fade out and the new one stay highlighted. Has anyone seen this done or know a way to do this? Many thanks, C A: ImageMapster: http://www.outsharked.com/imagemapster - my jQuery plugin that does exactly this! You want to use the singleSelect option, e.g. http://jsfiddle.net/jamietre/ufAF6/
{ "pile_set_name": "StackExchange" }
Q: When I edit my comment to add @user, it is not visible after apply edit? I noticed 2 or 3 times that when I post comment and after that try to edit it and set @user (to reply to comment or answer) in front of the text after applying changes @user is missing. Why is that? A: If "user" is the owner of the post then they will get notified of your comment.
{ "pile_set_name": "StackExchange" }
Q: Problem with xml I am novice to xml...I just started studying xml....I have the following doubts.. The following is my xml code <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE book [ <!ELEMENT book (page)> <!ELEMENT page (heading,#PCDATA)> ]> <note> <page> hhh<heading>c</heading><heading>s</heading> </page> </note> When i opened this in browser ,it shown that there is an error with #PCDATA...when i replaced it with PCDATA it showed no error...According to my DTD, page can contain exactly one heading element...am i right?But when i opened it in browser it showed no error even if i have two heading elements..Why did it happen..Also what is the difference between CDATA and PCDATA.... A: Use this: <?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE note [ <!ELEMENT note (page)> <!ELEMENT page (#PCDATA|heading)*> <!ELEMENT heading (#PCDATA)> ]> <note> <page> hhh<heading>c</heading><heading>s</heading> </page> </note> PCDATA is text that WILL be parsed by a parser. The text will be examined by the parser for entities and markup. CDATA is text that will NOT be parsed by a parser. Tags inside the text will NOT be treated as markup and entities will not be expanded. A: My advice is to pick up some solid validating parser, for example AltovaXML (Community Edition) is very straightforward to use: altovaxml -validate document.xml Let's look what's wrong with your DTD. First of all your document element (root) is not named book, so we got first error from here: Error in referenced Schema or DTD. Element does not match root element name 'book' from the DTD. Second thing is that heading is not declared: Element has not been declared. Finally to allow mixed content put choice with #PCDATA (that means parsed character data) at first and heading element: Finally your DTD is: <!DOCTYPE note [ <!ELEMENT note (page)> <!ELEMENT page (#PCDATA | heading)*> <!ELEMENT heading (#PCDATA)> ]>
{ "pile_set_name": "StackExchange" }
Q: Magento 1.9 checkout/onepage after login redirect to checkout/onepage Am using Magento 1.9. When customer login in checkout/onepage page, it redirect to customer/account. I want to remove this flow. If customer login in checkout/onepage page redirect to same page I mean checkout/onepage page. I tried this but no use admin > System > Configuration > Customer > Customer Configuration > Loggin Option then make Redirect Customer to Account Dashboard after Logging in make it NO A: You have to rewrite in local : app/code/core/Mage/Customer/controllers/AccountController.php, the loginPostAction() then replace $this->_loginPostRedirect(); with $this->_redirectReferer();
{ "pile_set_name": "StackExchange" }
Q: How to hide icons from ActionBar? I'm looking to hide a icons from the ActionBar depending on variables. Is there a simple way to do this? Will I need to use onPrepareOptionsMenu() and if so how? A: To hide menu items you should use the setVisible() method on your menu item inside your activity onPrepareOptionsMenu() override after your menu has been inflated. For example: @Override public boolean onPrepareOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.example, menu); if(showItem) { menu.findItem(R.id.icon).setVisible(true); } else { menu.findItem(R.id.icon).setVisible(false); } return true; } If you have declared your variable inside onCreate(), it will be limited to the scope of onCreate() and therefore inaccessible inside onPrepareOptionsMenu(). For example, instead of this: @Override protected void onCreate(Bundle savedInstanceState) { boolean showItem = false; // ... } Declare it like this: public boolean showItem = false; @Override protected void onCreate(Bundle savedInstanceState) { // ... } Also if you want to change the visibility on button press for example, you will need to call the invalidateOptionsMenu() method to reload the menu.
{ "pile_set_name": "StackExchange" }
Q: AVSpeechSynthesizer output as file? AVSpeechSynthesizer has a fairly simple API, which doesn't have support for saving to an audio file built-in. I'm wondering if there's a way around this - perhaps recording the output as it's played silently, for playback later? Or something more efficient. A: This is finally possible, in iOS 13 AVSpeechSynthesizer now has write(_:toBufferCallback:): let synthesizer = AVSpeechSynthesizer() let utterance = AVSpeechUtterance(string: "test 123") utterance.voice = AVSpeechSynthesisVoice(language: "en") var output: AVAudioFile? synthesizer.write(utterance) { (buffer: AVAudioBuffer) in guard let pcmBuffer = buffer as? AVAudioPCMBuffer else { fatalError("unknown buffer type: \(buffer)") } if pcmBuffer.frameLength == 0 { // done } else { // append buffer to file if output == nil { output = AVAudioFile( forWriting: URL(fileURLWithPath: "test.caf"), settings: pcmBuffer.format.settings, commonFormat: .pcmFormatInt16, interleaved: false) } output?.write(from: pcmBuffer) } } A: As of now AVSpeechSynthesizer does not support this . There in no way get the audio file using AVSpeechSynthesizer . I tried this few weeks ago for one of my apps and found out that it is not possible , Also nothing has changed for AVSpeechSynthesizer in iOS 8. I too thought of recording the sound as it is being played , but there are so many flaws with that approach like user might be using headphones, the system sound might be low or mute , it might catch other external sound, so its not advisable to go with that approach.
{ "pile_set_name": "StackExchange" }
Q: Text at the end of the table I am experiencing another problem with my table I would like to include a long note at the end of the table. The code I wrote is: \documentclass{article} \usepackage{rotating} \usepackage{xcolor} \renewcommand{\baselinestretch}{1.3} \setlength{\topmargin}{0cm} \setlength{\oddsidemargin}{0.1cm} \setlength{\leftmargin}{1cm} \setlength{\textwidth}{15.5cm} \setlength{\textheight}{23.0cm} \begin{document} \begin{sidewaystable} \centering \footnotesize{ \def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi} \caption{\textbf{Subjective Freedom and Preferences for Redistribution - Alternative Instruments}\label{table8}} \begin{tabular}{l*{9}{c}} \hline\hline &\multicolumn{4}{c}{\textbf{Fst Stage}}&\multicolumn{2}{c}{\textbf{Snd Stage}}&\multicolumn{1}{c}{\textbf{LL}}&\multicolumn{1}{c}{\textbf{$\rho$=0}} &\multicolumn{1}{c}{\textbf{Obs.}}\smallskip \\ &\multicolumn{1}{c}{\textbf{First Lag SF}}&\multicolumn{1}{c}{\textbf{Second Lag SF}}&\multicolumn{1}{c}{\textbf{Settler}}&\multicolumn{1}{c}{\textbf{Genetic}}&\multicolumn{1}{c}{\textbf{SF}}&\multicolumn{1}{c}{\textbf{Fairness}}& & &\\ &\multicolumn{1}{c}{\textbf{(Country Average)}}&\multicolumn{1}{c}{\textbf{(Country Average)}}&\multicolumn{1}{c}{\textbf{Mortality}}&\multicolumn{1}{c}{\textbf{Distance}}&& &&&\\ \hline \noalign{\medskip} 1. Using second lag of SF &0.017***&0.013**{\textcolor{white}{*}}& & &0.010***&0.188***&-46,770.27&-0.071***&98,673 \medskip \\ 2. Using rate of settler mortality &0.071***& &-0.018***& &0.010***&0.180***&-50,073.15&-0.035***&98,673 \medskip \\ 3. Using genetic distance &0.083***& &-0.016***&-0.051*** &0.010***&0.181***&-49,175.98 &-0.038***&98,673 \medskip \\ 4. Using latitude &0.003*{\textcolor{white}{**}}& & & &0.010***&0.208***&-65,841.53 &-0.073***&98,673 \medskip \\ 5. Endogenous SF &0.015***& & & &0.010***&0.208***&-210,549.47 &-0.068***&98,673 \\ \hline\hline \multicolumn{10}{l}{\footnotesize Notes: ***, ** and * denote significance at 1\%, 5\% and 10\%, respectively. In model 1, we include the second lag of subjective freedom as a country average. In model, reported in row 2, we add the log of settler mortality to the first lag of subjective freedom. In model 3, we augment model 2, by adding the log of genetic distance. In this case, we use US as reference country. In model reported in row 4 we drop the continent dummy and we include the (log) of latitude, measured as the distance of capital city to the Equator. Finally, in model 5 we endogeneize subjective freedom using the lag of average SF in a country. }\\ \multicolumn{10}{l}{\footnotesize Standard errors in parentheses}\\ \end{tabular}} \end{sidewaystable} \end{document} The main problem is that the text does non follow the end of the table, but it is incredibly longer. Is there any way I can write a footnote, which stays within the width of the table. A: I have partially re-done your table to fit a page in portrait mode, using tabularx which X columns take all the available space; note the starting command that allows this: \begin{tabularx}{\textwidth}{...} You can fill the remaining content. The notes below have been added as regular text, but I don't think this should give you any issues. If there are, feel free to comment. Also, remember to use the geometry package to set the margins. Output Code \documentclass[12pt]{article} \usepackage[a4paper, margin=2cm]{geometry} \usepackage{rotating} \usepackage{xcolor} \usepackage{caption} \usepackage{booktabs, array, multirow} \usepackage{tabularx} \newcolumntype{Y}{>{\centering\let\newline\\\arraybackslash}X} \newcolumntype{Z}{>{\raggedright\bfseries\let\newline\\\arraybackslash}p{3cm}} \newcolumntype{C}{>{\centering\bfseries\arraybackslash}m{5mm}} \begin{document} \begin{table}\footnotesize \captionsetup{justification=centering,margin=1cm} \centering \caption{\bfseries Subjective Freedom and Preferences for Redistribution Alternative Instruments} \label{table8} {\renewcommand{\arraystretch}{2} \begin{tabularx}{\textwidth}{CZYYYYY} % header \toprule & & Using second lag of SF & Using rate of settler mortality & Using genetic distance & Using latitude & Endogenous SF \\ \midrule \multirow{5}{*}{\rotatebox{90}{1st Stage}} & First Lag SF\newline\tiny{Country average} & & \\ & Second Lag SF\newline\tiny{Country average} & & \\ & Settler Mortality & & \\ & Genetic Distance & & \\ \midrule \multirow{2}{*}{\rotatebox{90}{2nd Stage}} & SF & & \\ & Fairness & & \\ \midrule & LL & & \\ & $p=0$ & & \\ \bottomrule \end{tabularx}} \end{table}\noindent {\footnotesize Standard errors in parentheses. \\ \textbf{Notes:} ***, ** and * denote significance at 1\%, 5\% and 10\%, respectively. In model 1, we include the second lag of subjective freedom as a country average. In model, reported in row 2, we add the log of settler mortality to the first lag of subjective freedom. In model 3, we augment model 2, by adding the log of genetic distance. In this case, we use US as reference country. In model reported in row 4 we drop the continent dummy and we include the (log) of latitude, measured as the distance of capital city to the Equator. Finally, in model 5 we endogeneize subjective freedom using the lag of average SF in a country.} \end{document}
{ "pile_set_name": "StackExchange" }
Q: Hands still smell like gasoline after multiple washings, it is safe to handle food? I have been reparing my weed wacker, so I have the gasoline/oil mixture on my hands. I have washed them twice with hand soap, once with orange soap scrub, once with dish soap, once with hand sanitizer, and finally once with white vinegar. The white vinegar has done the best job so far. Could I have stopped after a few washings, or it is still unsafe to handle food if I can still smell the gasoline in my hands? A: With as much as you've done, you are safe my friend. Odor residue isn't the same as actually having those chemicals still coating your epidermis to mix with food prep to a concerning degree. It's probably worse that you've mixed so much alkaline with the natural acidity of your epidermal layer, leading to certain skin problems in the long run. If you're that worried about neutralizing the odor, you can mix baking soda with water (one part baking soda to 3 parts water and rub the paste on your hands) or vanilla extract with water (a few drops into a cup or so of water) and soak your hands in it for a bit. Then wash off lightly with a nonabrasive soap. Those combined with the vinegar should be pretty effective. Also, you may want to consider wearing disposable gloves for work involving chemicals.
{ "pile_set_name": "StackExchange" }
Q: Poor use of dictionary? I've read on here that iterating though a dictionary is generally considered abusing the data structure and to use something else. However, I'm having trouble coming up with a better way to accomplish what I'm trying to do. When a tag is scanned I use its ID as the key and the value is a list of zones it was seen in. About every second I check to see if a tag in my dictionary has been seen in two or more zones and if it has, queue it up for some calculations. for (int i = 0; i < TagReads.Count; i++) { var tag = TagReads.ElementAt(i).Value; if (tag.ZoneReads.Count > 1) { Report.Tags.Enqueue(tag); Boolean success = false; do { success = TagReads.TryRemove(tag.Epc, out TagInfo outTag); } while (!success); } } I feel like a dictionary is the correct choice here because there can be many tags to look up but something about this code nags me as being poor. As far as efficiency goes. The speed is fine for now in our small scale test environment but I don't have a good way to find out how it will work on a massive scale until it is put to use, hence my concern. A: If you are going to do a lot of lookup in your code and only sometimes iterate through the whole thing, then I think the dictionary use is ok. I would like to point out thought that your use of ElementAt is more alarming. ElementAt performs very poorly when used on objects that do not implement IList<T> and the dictionary does not. For IEnumerables<T> that do not implement IList the way the nth element is found is through iteration, so your for-loop will iterate the dictionary once for each element. You are better off with a standard foreach. A: I believe that there's an alternative approach which doesn't involve iterating a big dictionary. First of all, you need to create a HashSet<T> of tags on which you'll store those tags that have been detected in more than 2 zones. We'll call it tagsDetectedInMoreThanTwoZones. And you may refactor your code flow as follows: A. Whenever you detect a tag in one zone... Add the tag and the zone to the main dictionary. Create an exclusive lock against tagsDetectedInMoreThanTwoZones to avoid undesired behaviors in B.. Check if the key has more than one zone. If this is true, add it to tagsDetectedInMoreThanTwoZones. Release the lock against tagsDetectedInMoreThanTwoZones. B. Whenever you need to process a tag which has been detected in more than one zone... Create an exclusive lock against tagsDetectedInMoreThanTwoZones to avoid more than a thread trying to process them. Iterate tagsDetectedInTwoOrMoreZones. Use each tag in tagsDetectedInMoreThanTwoZones to get the zones in your current dictionary. Clear tagsDetectedInMoreThanTwoZones. Release the exclusive lock against tagsDetectedInMoreThanTwoZones. Now you'll iterate those tags that you already know that have been detected in more than a zone! In the long run, you can even make per-region partitions so you never get a tagsDetectedInMoreThanTwoZones set with too many items to iterate, and each set could be consumed by a dedicated thread!
{ "pile_set_name": "StackExchange" }
Q: 2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why? Good evening friends: I have in mind 2 ways for clearing a content in a defined range of cells of a VBA project (in MS Excel): Worksheets("SheetName").Range("A1:B10").ClearContents Worksheets("SheetName").Range(Cells(1, 1), Cells(10, 2)).ClearContents The problem is that the second way show me an error '1004' when I'm not watching the current Worksheet "SheetName" (in other words, when I haven't "SheetName" as ActiveSheet). The first way work flawlessly in any situation. Why does this happen? How can I use the "Second way" without this bug? A: It is because you haven't qualified Cells(1, 1) with a worksheet object, and the same holds true for Cells(10, 2). For the code to work, it should look something like this: Dim ws As Worksheet Set ws = Sheets("SheetName") Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents Alternately: With Sheets("SheetName") Range(.Cells(1, 1), .Cells(10, 2)).ClearContents End With EDIT: The Range object will inherit the worksheet from the Cells objects when the code is run from a standard module or userform. If you are running the code from a worksheet code module, you will need to qualify Range also, like so: ws.Range(ws.Cells(1, 1), ws.Cells(10, 2)).ClearContents or With Sheets("SheetName") .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents End With A: That is because you are not fully qualifying your cells object. Try this With Worksheets("SheetName") .Range(.Cells(1, 1), .Cells(10, 2)).ClearContents End With Notice the DOT before Cells?
{ "pile_set_name": "StackExchange" }
Q: The smallest power e in Fermat's little theorem I have an exercise that is connected to Fermat's little theorem. I should prove that the smallest positive integer $e$ for which $a^e \equiv {1} \pmod{p}$ must be a divisor of $p - 1$. Also, there are some hints: Divide $p - 1$ by $e$, obtaining $p - 1 = ke + r$, where $0 \le r \lt e$, and use the fact that $a^{p-1} \equiv a^e \equiv 1 \pmod{p}$. I have no ideas except $a^{ke + r} \equiv a^e \equiv 1$. I will be appreciated for any help and hints. A: You want to prove $r=0$, so assume otherwise. Then $a^r\equiv a^{ke+r}\equiv 1$, contradicting the definition of $e$.
{ "pile_set_name": "StackExchange" }
Q: Converting Map>> to Set using Java 8 I have a map Map<LocalDate, Map<LocalDate, List<Request>>> and i want to convert that to Set<String>, String is id in Request class using Java8 Request class class Request{ private String id; public void setId(String id){ this.id =id; } public String getId(){ return this.id; } } I know traditional way of doing it, but looking to achieve this using Java 8 options(Stream, Map, Collect..) I was trying this, was getting compilation error Set<String> values = map.values().stream() .map(dateMap -> dateMap.values().stream() .map(request -> request.stream() .map(Request::getId)).flatMap(Set::stream).collect(Collectors.toSet())); Thanks A: First, create a stream from the map values and chain a map operation to the map values and then consecutively flatten with flatMap and finally map to the request ids and collect to a set implementation. Set<String> resultSet = map.values() .stream() .map(Map::values) .flatMap(Collection::stream) .flatMap(Collection::stream) .map(Request::getId) .collect(Collectors.toSet());
{ "pile_set_name": "StackExchange" }