qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
list
response
stringlengths
0
115k
6,546,323
I've got a Sax parser class which is used in Swing application and in web project deployed to a GlassFish. The class parses xml files. It works perfectly in Netbeans IDE Swing application(in the IDE) and web project. But when I Clean and Build swing app into a one .jar it doesn't recognize anymore symbols like ī, ķ, ļ, ā from xml file. The same problem happens if I compile and run it through cmd. Had the same problem in web project - sorted using Glassfish configuration. The question is how to solve this problem in swing app? here is a peace of code: ``` public void parseDocument(String filePath) { try { XMLReader xr = XMLReaderFactory.createXMLReader(); xr.setContentHandler(this); InputSource is = new InputSource(new FileReader(filePath)); is.setEncoding("UTF-8"); xr.parse(is); }catch(SAXException se) { se.printStackTrace(); }catch (IOException ie) { ie.printStackTrace(); } } ``` No help from setEncoding() method.
2011/07/01
[ "https://Stackoverflow.com/questions/6546323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/824578/" ]
You have already answered your question, however the other way that you could deal with this is to explicitly set the conversion when you open the file. ``` public void parseDocument(String filePath) { try { XMLReader xr = XMLReaderFactory.createXMLReader(); xr.setContentHandler(this); Reader reader = new InputStreamReader(new FileInputStream(filePath); InputSource is = new InputSource(reader, "UTF-8"); is.setEncoding("UTF-8"); xr.parse(is); }catch(SAXException se) { se.printStackTrace(); }catch (IOException ie) { ie.printStackTrace(); } } ``` The big difference between this, and your solution in the question is that we are using InputStreamReader on top of a FileInputStream. According to the javadoc for [FileReader](http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileReader.html), it always opens the file in the "default character set", that is why your solution works, since you are changing the default character set. You can also explicitly say which character set you want to open the file in, but to do that you need to use the combination of InputStreamReader and FileInputStream.
20,676,390
Hi All I am very new to oracle. I have a view having a where condition where brand in ('HP') Now my report will run for HP Brand But tomorrow if i want to run the report for different brand without modified the view or report So i think i need a create something like look up table Please suggest the process how to create and how to pass the value to my view
2013/12/19
[ "https://Stackoverflow.com/questions/20676390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2192310/" ]
How do you expect them to be executed in order if there is no dependency between them? `$.when` doesn't have and cannot have an influence on the evaluation of the promise, it just waits until each of the promises is resolved. Your code is way more complicated then it needs to be. `$.ajax` already returns a promise which gets resolved when the Ajax response was received, so you can just return it from the functions. If you want to execute them in sequence, you can chain them via [`.then`](http://api.jquery.com/deferred.then/): > > These filter functions can return a new value to be passed along to the promise's `.done()` or `.fail()` callbacks, or they can return another observable object (Deferred, Promise, etc) which will pass its resolved / rejected status and values to the promise's callbacks. > > > So your code simplifies to: ``` function aaa() { w("begin aaa"); return $.ajax({ type: "GET", data: { m: 5 } }).done(w); } function bbb() { w("begin bbb"); return $.ajax({ type: "GET", data: { m: 1 } }).done(w); } aaa().then(bbb).done(function() { w('ok'); }); ``` Here, `aaa().then(bbb)` creates the dependency you need. It basically means "once `aaa`'s promise is resolved, execute `bbb`". In addition, `.then` returns a new promise, which gets resolved when the promise returned by `bbb` gets resolved, which allows you to execute a function when the promises of both, `aaa` and `bbb` are resolved. Maybe these help you to understand promises (and deferreds) better: * [Deferred versus promise](https://stackoverflow.com/q/17308172/218196) * <http://learn.jquery.com/code-organization/deferreds/> --- Example without `$.ajax`: ``` function aaa() { var def = new $.Deferred(); setTimeout(function() { def.resolve(21); }, 3000); return def.promise(); } function bbb(v) { var def = new $.Deferred(); setTimeout(function() { def.resolve(v * 2); }, 1000); return def.promise(); } // aaa -> bbb -> console.log // The value is logged after 3 + 1 seconds aaa().then(bbb).done(function(v) { console.log(v); }); // 42 // (aaa | bbb) -> console.log // The value is logged after max(3, 1) seconds and both resolved values are // passed to the final promise $.when(aaa(), bbb(5)).done(function(v) { console.log(v); }); // [21, 10] ```
37,053,294
We measured some performnace tests and I noticed that the CPU is running a lot of time in kernel mode. I'd like to know why is that. **The application**: it's classic Azure Cloud service web role where Owin is listening under the IIS and Owin itself serves just static files that are cached in memory (so there should be only a little performance penalty and everyting should be pretty fast). The content is copied via `await stream.CopyToAsync(response.Body)` to output stream. The test itself looks like this in gatling: ``` val openLoginSet = exec(http("ROOT") .get("/") .headers(Headers105Test2.headers_0) .resources( http("MED: arrow-down-small.png").get(uriIconAssets + "/arrow-down-small.png").headers(Headers105Test2.headers_1), http("MED: arrow-up-small.png").get(uriIconAssets + "/arrow-up-small.png").headers(Headers105Test2.headers_1), http("MED: close-medium.png").get(uriIconAssets + "/close-medium.png").headers(Headers105Test2.headers_1), http("MED: decline-medium.png").get(uriIconAssets + "/decline-medium.png").headers(Headers105Test2.headers_1), http("MED: help-medium.png").get(uriIconAssets + "/help-medium.png").headers(Headers105Test2.headers_1), http("MED: submit-medium.png").get(uriIconAssets + "/submit-medium.png").headers(Headers105Test2.headers_1), http("MED: delete-medium.png").get(uriIconAssets + "/delete-medium.png").headers(Headers105Test2.headers_1), http("MED: en-us.js").get("/en-us.js").headers(Headers105Test2.headers_8), http("MED: cloud_logo_big.png").get("/assets/cloud_logo_big.png").headers(Headers105Test2.headers_1), http("MED: favicon.ico").get("/favicon.ico").headers(Headers105Test2.headers_0)) val httpProtocol = http .baseURL("https://myurl.com") .inferHtmlResources() val openLoginSenario = scenario("OpenOnly").exec(repeat(400, "n") { exec(openLoginSet).pause(3,6) }) setUp(openLoginSenario.inject(rampUsers(150) over (3 minutes))) .protocols(httpProtocol) .maxDuration(3 minutes) ``` (I shortened the test to run 3 minutes just to catch data to show here) There are 3 computers that run this gatling test, each up to 150 concurrent threads, so 450 threads in total. What I see is that there is a lot running code in kernel and W3wp process doesn't take most of the CPU: **Captured CPU when the test just started (the cpu is rising when new threads are added):** [![The test just started](https://i.stack.imgur.com/gOAa5.png)](https://i.stack.imgur.com/gOAa5.png) **Captured CPU when the tests are nearly before end:** [![Before end of the test](https://i.stack.imgur.com/FyDRh.png)](https://i.stack.imgur.com/FyDRh.png) The kernel mode looks pretty bad and I'm not sure what might cause it. There should be almost no locks involved. When reading what else might cause the high kernel mode, I found that DPCs might cause it. So I captured some DPC data as well, but I'm not sure what's normal and what not. Anyway, the graph with DPC max times is also included in the sshot. The vmbus.sys takes most significant time from all DPCs. That means that the Azure instance is not any bare metal (not suprising) and that the instance shares it's computional power with others. As I understand it, vmbus.sys is responsible for communication between e.g. network card itself and the hosted HyperV instance. Might running in HyperV be the main cause for low performance? I'd like to know where to look and how to find out what causes the kernel mode in my situation. --- Some more data: Part of DPC data **when the test started** (taken in 30 sec): ``` Total = 17887 for module vmbus.sys Elapsed Time, > 0 usecs AND <= 1 usecs, 137, or 0.77% Elapsed Time, > 1 usecs AND <= 2 usecs, 2148, or 12.01% Elapsed Time, > 2 usecs AND <= 4 usecs, 3941, or 22.03% Elapsed Time, > 4 usecs AND <= 8 usecs, 2291, or 12.81% Elapsed Time, > 8 usecs AND <= 16 usecs, 5182, or 28.97% Elapsed Time, > 16 usecs AND <= 32 usecs, 3305, or 18.48% Elapsed Time, > 32 usecs AND <= 64 usecs, 786, or 4.39% Elapsed Time, > 64 usecs AND <= 128 usecs, 85, or 0.48% Elapsed Time, > 128 usecs AND <= 256 usecs, 6, or 0.03% Elapsed Time, > 256 usecs AND <= 512 usecs, 1, or 0.01% Elapsed Time, > 512 usecs AND <= 1024 usecs, 2, or 0.01% Elapsed Time, > 1024 usecs AND <= 2048 usecs, 0, or 0.00% Elapsed Time, > 2048 usecs AND <= 4096 usecs, 1, or 0.01% Elapsed Time, > 4096 usecs AND <= 8192 usecs, 2, or 0.01% Total, 17887 ``` Part of DPC data **when the test was ending** (taken in 30 sec): ``` Total = 141796 for module vmbus.sys Elapsed Time, > 0 usecs AND <= 1 usecs, 7703, or 5.43% Elapsed Time, > 1 usecs AND <= 2 usecs, 21075, or 14.86% Elapsed Time, > 2 usecs AND <= 4 usecs, 17301, or 12.20% Elapsed Time, > 4 usecs AND <= 8 usecs, 38988, or 27.50% Elapsed Time, > 8 usecs AND <= 16 usecs, 32028, or 22.59% Elapsed Time, > 16 usecs AND <= 32 usecs, 11861, or 8.36% Elapsed Time, > 32 usecs AND <= 64 usecs, 7034, or 4.96% Elapsed Time, > 64 usecs AND <= 128 usecs, 5038, or 3.55% Elapsed Time, > 128 usecs AND <= 256 usecs, 606, or 0.43% Elapsed Time, > 256 usecs AND <= 512 usecs, 53, or 0.04% Elapsed Time, > 512 usecs AND <= 1024 usecs, 26, or 0.02% Elapsed Time, > 1024 usecs AND <= 2048 usecs, 11, or 0.01% Elapsed Time, > 2048 usecs AND <= 4096 usecs, 10, or 0.01% Elapsed Time, > 4096 usecs AND <= 8192 usecs, 53, or 0.04% Elapsed Time, > 8192 usecs AND <= 16384 usecs, 3, or 0.00% Elapsed Time, > 16384 usecs AND <= 32768 usecs, 1, or 0.00% Elapsed Time, > 32768 usecs AND <= 65536 usecs, 5, or 0.00% Total, 141796 ``` % DPC Time from start to end of the test [![enter image description here](https://i.stack.imgur.com/eViH6.png)](https://i.stack.imgur.com/eViH6.png) We also suspected that we reached the network limits - so the tests 'download' so much data that the network adapter's limits are reached. This might be true during end of the test (when there are maximal number of threads), but this doesn't explain why the there is so much kernel mode time even at the beginning of the test. Just to show how much data is sent - the volume of sent data (cyan line) is 2 orders of magnitude lower than capacity of the network adapter. [![enter image description here](https://i.stack.imgur.com/UVz3a.png)](https://i.stack.imgur.com/UVz3a.png)
2016/05/05
[ "https://Stackoverflow.com/questions/37053294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75224/" ]
This might not help you directly. but we had some performance issues after moving an application to cloud. Please find the discussion here: [Huge performance drop after moving to Azure](https://stackoverflow.com/questions/36477242/huge-performance-drop-after-moving-to-azure) After a lot of investigation finally we found out our issue was with the Transient Fault Handling mechanism. It used to go and read the `web.config` each time causing huge CPU usage which was not an issue with same code in non-cloud environment. We handled it by using a Singleton pattern around it. Hope it helps you to find out if there is any such issues with the application. Cheers. :)
20,322,956
I am trying to create a graph using Morris JS by creating an Angular JS directive. My directive code is: ``` Reporting.directive('morrisLine', function(){ return { restrict: 'EA', template: '<div id="call-chart">test2</div>', scope: { data: '=', //list of data object to use for graph xkey: '=', ykey: '=' }, link: function(scope,element,attrs){ new Morris.Line({ element: element, data: [ { year: '2008', value: 20 }, { year: '2009', value: 10 }, { year: '2010', value: 5 }, { year: '2011', value: 5 }, { year: '2012', value: 20 } ], xkey: '{year}', ykey: ['value'], }); } }; }); ``` The Error code I am getting when I check the console on my browser is : ``` TypeError: Cannot call method 'match' of undefined at Object.t.parseDate (eval at <anonymous> (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:4904), <anonymous>:1:9523) at n.eval (eval at <anonymous> (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:4904), <anonymous>:1:3297) at n.t.Grid.r.setData (eval at <anonymous> (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:4904), <anonymous>:1:3888) at n.r (eval at <anonymous> (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:4904), <anonymous>:1:1680) at new n (eval at <anonymous> (http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js:3:4904), <anonymous>:1:11953) at link (http://127.0.0.1:8000/static/js/app/directives/directives.js:94:20) at j (http://127.0.0.1:8000/static/js/libs/angular/angular.min.js:43:157) at e (http://127.0.0.1:8000/static/js/libs/angular/angular.min.js:38:463) at e (http://127.0.0.1:8000/static/js/libs/angular/angular.min.js:38:480) at e (http://127.0.0.1:8000/static/js/libs/angular/angular.min.js:38:480) <div morris-line="" class="ng-isolate-scope ng-scope" style="position: relative;"> ``` The part the error code is pointing at is the part that says ``` element : element, ``` I am new to Angular JS and directives and am hoping someone can point me in the right direction of how to deal with this problem. Thank you!
2013/12/02
[ "https://Stackoverflow.com/questions/20322956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1886984/" ]
this is how I did with morris chart. Example is barchart: ``` sampleApp.directive('barchart', function() { return { // required to make it work as an element restrict: 'E', template: '<div></div>', replace: true, // observe and manipulate the DOM link: function($scope, element, attrs) { var data = $scope[attrs.data], xkey = $scope[attrs.xkey], ykeys= $scope[attrs.ykeys], labels= $scope[attrs.labels]; Morris.Bar({ element: element, data: data, xkey: xkey, ykeys: ykeys, labels: labels }); } }; }); ``` then you can use it with this element: ``` <barchart xkey="xkey" ykeys="ykeys" labels="labels" data="myModel"></barchart> ``` where myModel is the array of data to be pass in directive, it should have the proper format to be compatible with morris charts. take a close look on how this object is being pass in "link" function in the directive. Here is a working and complete example: <http://jsbin.com/ayUgOYuY/5/edit?html,js,output>
16,988,378
I have Relative layout with two elements. One of those is hidden. Something like this (simplified for the example) ``` <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/fullscreenimage" android:layout_width="match_parent" android:layout_height="match_parent" /> <AbsoluteLayout android:id="@+id/layout_overlay" android:layout_width="200dp" android:layout_height="100dp" android:layout_centerInParent="true" android:visibility="gone" > <ImageView android:id="@+id/imageView_option1" android:layout_width="100dp" android:layout_height="100dp" android:layout_x="0dp" android:layout_y="0dp" android:src="@drawable/image1" android:tag="1" /> <ImageView android:id="@+id/imageView_option2" android:layout_width="100dp" android:layout_height="100dp" android:layout_x="100dp" android:layout_y="0dp" android:src="@drawable/image2" android:tag="2" /> </AbsoluteLayout> </RelativeLayout> ``` After detecting long press (and not lifting the finger) on fullscreen image I want to show those options and highlight the option, that is under users finger. I change the visibility of the overlay layout, but touchListeners on option images are never called. Tried returning false from touchlistener of fullscreen image, that is called all the time but the listener on option image is never called.
2013/06/07
[ "https://Stackoverflow.com/questions/16988378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/651770/" ]
You can use [SharpDX](http://sharpdx.org/), which actually provides wrappers for Direct2D. This will provide access to the "best" (or at least most current) hardware accelerated 2D drawing API for Microsoft platforms.
56,611,946
I am trying to make a for-loop that is based on simulated metadata. **Data** is representing the data contents. **Meta** is representing 3 different metadata types. If there is a 1 it means the meta is present in the data, if there is a 0 it means it is not present. **Size** represents the size of each data if the metadata is present. So if there is metadata of *1 1 1* with the size of 3: * That represents meta 1 first 3 elements in the array, meta 2 next 3 elements in the array, meta 3 next 3 elements in array. The problem I am having is correctly reading it in sequential order from left to right, and if it runs out of data not to create new one, just stop reading from the array. If we have a data of [1, 2, 3, 4, 5] and meta of 1, 1, 1, size 1 it should be: Meta 1: 1 Meta 2: 2 Meta 3: 3 Or if it was data of [1, 2, 3 4, 5, 6, 7, 8, 9, 10, 11, 12] and a meta of 1, 0, 1, size 4, it should be: Meta 1: 1 2 3 4 Meta 2: Nothing Meta 3: 5 6 7 8 > > What I have so far: > > > ```js let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let meta = [1, 0, 1]; let size = 4; for (let i = 0; i < 3; i++) { if (meta[i]) { if (i == 0) { console.log('Meta', 1); for (let i = 0; i < size; i++) { console.log(data[i]); } } if (i = 1) { console.log('Meta', 2); for (let i = 0; i < size; i++) { console.log(data[i] + size); } } if (i = 2) { console.log('Meta', 3); for (let i = 0; i < size; i++) { console.log(data[i] + size + size); } } } } ```
2019/06/15
[ "https://Stackoverflow.com/questions/56611946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8813179/" ]
You can remove your inner if-statements as they are duplications and instead use the variable `i` to print the `i`th plus one's meta value. In the snippet below I have created a variable `j` which is used to keep track of which point in the data we're at. This is used to jump in segments of `size` when each `meta` is found. Then in the inner for loop I loop from `j` to `j+size` which is a particular portion of your `data` array of length `size`. See example below: ```js let data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let meta = [1, 0, 1]; let size = 4; let j = 0; for (let i = 0; i < meta.length; i++) { console.log('Meta', i+1); if (meta[i]) { for(let k = j; k < j+size && k < data.length; k++) { console.log(data[k]); } j+=size; } else { console.log("-- Nothing --"); } } ```
31,804,170
In my app I'm trying to use the newly introduced element sharing between activities. Everything works like a charm if the shared element is with fixed position (e.g. `android:layout_gravity="top"`) but the problem comes when the view is anchored. My first activity looks like this: ``` <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/tools" xmlns:auto="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" /> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content"> ... </android.support.design.widget.AppBarLayout> <android.support.design.widget.FloatingActionButton android:id="@+id/play_all" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|right" android:layout_margin="24dp"/> </android.support.design.widget.CoordinatorLayout> ``` My second activity looks like this ``` <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:auto="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent" /> <android.support.design.widget.FloatingActionButton android:id="@+id/play" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="16dp" android:elevation="10dp" android:src="@drawable/ic_action_play" auto:layout_anchor="@+id/appbar" android:transitionName="fab_button" auto:layout_anchorGravity="bottom|right" /> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="192dp"> ... </android.support.design.widget.AppBarLayout> ... </android.support.design.widget.CoordinatorLayout> ``` The code I use is as follows: ``` Intent intent = ...; ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(this, view, "fab_button"); startActivity(intent, options.toBundle()); ``` If I use the `layout_anchor` and `layout_anchorGravity` attributes the transition between the two FABs is done with no animation. If the second FAB is with fixed position, it works perfectly. What am I doing wrong?
2015/08/04
[ "https://Stackoverflow.com/questions/31804170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2243615/" ]
This might be a bit late, but I found a way around the issue. You have to wrap your shared element into a layout, and put the anchor on that layout: ``` <FrameLayout android:layout_width="wrap_content" android:layout_height="wrap_content" auto:layout_anchor="@+id/appbar" auto:layout_anchorGravity="bottom|right"> <android.support.design.widget.FloatingActionButton android:id="@+id/play" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="16dp" android:elevation="10dp" android:src="@drawable/ic_action_play" android:transitionName="fab_button" /> <FrameLayout/> ```
58,174,762
I've been getting an issue that says: `warning: format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘uint8_t * {aka unsigned char *}` and I am not sure why this is happening because I thought int and uint8\_t were interchangeable. Here is my code: ``` uint8_t** fileRead(char* file, int* pointer) { FILE* file = fopen(file, "r"); int count = 0; pointer = &count; fscanf(file, "%d", &count); //this retrieves a single integer uint8_t** result = (uint8_t**) malloc(*pointer * sizeof(uint8_t*)); while (file != NULL) { for (uint8_t i = 0; i < *pointer; i++) { uint8_t* a = (uint8_t*) malloc(sizeof(uint8_t)); uint8_t* b = (uint8_t*) malloc(sizeof(uint8_t)); uint8_t* c = (uint8_t*) malloc(sizeof(uint8_t)); fscanf(file, "%d", a); fscanf(file, "%d", b); fscanf(file, "%d", c); if (a == NULL || b == NULL || c == NULL) { uint8_t* npointer = NULL; fclose(file); free(result); return NULL; } else { result[i][0] = *a; result[i][1] = *b; result[i][2] = *c; free(a); free(b); free(c); } } } return result; } ``` and the errors are occuring at the following lines: ``` fscanf(file, "%d", a); fscanf(file, "%d", b); fscanf(file, "%d", c); ``` Thank you so much in advance
2019/09/30
[ "https://Stackoverflow.com/questions/58174762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12109035/" ]
> > I thought int and uint8\_t were interchangeable. > > > They are not - `int` (signed or unsigned) must be *at least* 16 bits wide (it may be wider, but not narrower)1. `uint8_t`, as the name suggests, is 8 bits wide. You need to use the format specifier `%hhu` to read a numeric value into a `uint8_t` or `unsigned char` object. --- 1. Strictly speaking, an `int` must be able to represent all values in *at least* the range `[-32767..32767]`. That requires at least 16 bits. Some architectures (which I've never used) have "padding bits" that contribute to the word size, but aren't used to store a value. So, for example, you could have a 9-bit machine with 18-bit words, but an implementation on that system could still choose to just use 16 bits to represent an `int` value - two of the bits simply aren't used.
48,833,976
I am failing to understand what the expression `*(uint32_t*)` does. I have broken the statement down to an example that declares the parts so I can try and interpret what each one does. ``` uint32_t* ptr; uint32_t num *(uint32_t*)(ptr + num); // <-- what does this do? ``` I don't understand the last bit in the example, what happens when the expression `*(uint32_t*)(ptr + num);` executes during runtime?
2018/02/16
[ "https://Stackoverflow.com/questions/48833976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5552548/" ]
`uint32_t` is a numeric type that guarantees 32 bits. The value is unsigned, meaning that the range of values goes from 0 to 232 - 1. This ``` uint32_t* ptr; ``` declares a pointer of type `uint32_t*`, but the pointer is uninitialized, that is, the pointer does not point to anywhere in particular. Trying to access memory through that pointer will cause undefined behaviour and your program might crash. This ``` uint32_t num; ``` is just a variable of type `uint32_t`. This ``` *(uint32_t*)(ptr + num); ``` `ptr + num` returns you a new pointer. It is called pointer arithmetic. It's like regular arithmetic, only that compiler takes the size of types into consideration. Think of `ptr + num` as the memory address based on the original `ptr` pointer plus the number of bytes for `num` `uint32_t` objects. The `(uint32_t*) x` is a cast. This tells the compiler that it should treat the expression `x` as if it were a `uint32_t*`. In this case, it's not even needed, because `ptr + num` is already a `uint32_t*`. The `*` at the beginning is the dereferencing operator which is used to access the memory through a pointer. The whole expression is equivalent to ``` ptr[num]; ``` Now, because none of these variables is initialized, the result will be garbage. However, if you initialize them like this: ``` uint32_t arr[] = { 1, 3, 5, 7, 9 }; uint32_t *ptr = arr; uint32_t num = 2; printf("%u\n", *(ptr + num)); ``` this would print 5, because `ptr[2]` is 5.
42,116,395
Say I want to delete a set of adjacent columns in a DataFrame and my code looks something like this currently: ``` del df['1'], df['2'], df['3'], df['4'], df['5'], df['6'] ``` This works, but I was wondering if there was a more efficient, compact, or aesthetically pleasing way to do it, such as: ``` del df['1','6'] ```
2017/02/08
[ "https://Stackoverflow.com/questions/42116395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6054427/" ]
Well, Bootstrap does not support specific modal events for the modal actions buttons. So, I believe you will have to handle the events yourself like so. ``` $("#myModal").on("click",".btn-default", function(){ // code }); $("#myModal").on("click",".btn-primary", function(){ // code }); ```
46,923,131
``` private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { Ontrip _ontrip = new Ontrip(_FNAME); string _query2 = "select CContactno from CustomerTbl where CUsername = @USERNAME"; string _query3 = "select Price from TransactionTypeTble T join PendingTransTbl P ON P.TransType = T.TransType "; string _query4 = "select VehicleDescription from DriverTbl D join VehicleSpecTbl V ON D.VehicleType = V.VehicleType"; SqlConnection _sqlcnn = new SqlConnection("Data Source=MELIODAS;Initial Catalog=WeGo;Integrated Security=True"); _sqlcnn.Open(); try { SqlDataReader _reader = null; SqlCommand _cmd = new SqlCommand("Select CFName+' '+CLName from CustomerTbl where CUsername=@USERNAME", _sqlcnn); SqlParameter _param = new SqlParameter(); _param.ParameterName = "@USERNAME"; _param.Value = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); _cmd.Parameters.Add(_param); _reader = _cmd.ExecuteReader(); //for displaying users name in the label while (_reader.Read()) { _ontrip._txtboxUsername.Text = _reader.GetString(0); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } using (SqlCommand _sqlcmd = new SqlCommand(_query2, _sqlcnn)) { try { SqlDataReader _reader = null; SqlParameter _param = new SqlParameter(); _param.ParameterName = "@USERNAME"; _param.Value = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(); _sqlcmd.Parameters.Add(_param); _reader = _sqlcmd.ExecuteReader(); //for displaying users name in the label while (_reader.Read()) { _ontrip._txtboxContact.Text = _reader.GetString(0); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } ``` Is their a way for me to read the query and display the output, when i run this code their is an error saying that their is already an open data reader associated with the command. I should be displaying multiple data in a textbox
2017/10/25
[ "https://Stackoverflow.com/questions/46923131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8815467/" ]
> > Alarm Managers no longer work in the background in Android 8 (Oreo) > > > I am not aware of anything regarding `AlarmManager` that changed in Android 8.0. Feel free to point to documentation or an issue tracker entry to validate your claim. Or, file your own issue with a reproducible test case. > > But in Android Oreo / 8.0, this isn't allowed anymore. > > > Sure it is, at least as well as it worked in Android 6.0 through 7.1. Doze mode and app standby have screwed with `AlarmManager`, but that's not new to Android 8.0. > > Most background services, receivers, etc. are fairly limited. > > > They can still raise a `Notification`, which is what your question indicates that you want to do. > > Does anyone know of a way to do this in Android Oreo in a way that it works even when the app is in the background? > > > Use `AlarmManager`. Since you are writing what amounts to an alarm clock app, [use `setAlarmClock()`](https://developer.android.com/reference/android/app/AlarmManager.html#setAlarmClock(android.app.AlarmManager.AlarmClockInfo,%20android.app.PendingIntent)).
68,201,171
How do I also pass the arraylist 'end' as a parameter inside the begin method along with the 'start' arraylist? ``` List<String> start = new ArrayList<String>(); List<String> end = new ArrayList<String>(); public static void begin(List<String> start) { } ```
2021/06/30
[ "https://Stackoverflow.com/questions/68201171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16236351/" ]
Just simply add it to the parameter list of the method: ``` List<String> start = new ArrayList<String>(); List<String> end = new ArrayList<String>(); public static void begin(List<String> start, List<String> end) { } ``` and call the method like this: ``` begin(start, end); ```
16,940,105
I'm a little confused how containers works. I have containers: ![enter image description here](https://i.stack.imgur.com/dZyPz.png) And i try to manage this in my `MainViewController`. But when i control-drag it into my .h file i'm getting ``` @property (weak, nonatomic) IBOutlet UIView *liveContainer; ``` Why this is an UIView class? This mean that is self.view my `BaseButtonContainerView`? But I have `BaseButtonContainerViewController`, and in debug i see that `viewDidLoad` is called. Can i get access to `BaseButtonContainerViewController` methods from `MainViewController`?
2013/06/05
[ "https://Stackoverflow.com/questions/16940105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1317394/" ]
Storyboards like to do everything in the `prepareForSegue` so just assign your segue an identifier. In this case we'll assume you set it to `baseButtonContainerSegue` in IB. Then in `prepareForSegue` use : ``` - (void) prepareForSegue:(UIStoryboardSegue*)segue sender:(id)sender { if ([segue.identifier isEqualToString:@"baseButtonContainerSegue"]) { self.liveContainer = segue.destinationViewController; } } ``` Just make sure that you have a `UIViewController` property `liveContainer`, (specifically in your case you would want to have a `BaseButtonContainerViewController` property). I am not exactly sure why you have to do it this way but I am guessing it has something to do with memory management. Say you leave that screen and your containers are deallocated. Then when you go back you may lose your connection to them. This way the segues would be called again and you could grab them as properties. Again, I am not sure, so if someone else does please enlighten me!
26,716,795
I am developing an application in PHP connected with SQL Server 2008 R2, my requirement is getting list of input / output parameters (METADATA) from procedure(s) and generating run time forms on the screen. I have around fifty scenarios e.g. get order details, get pending orders etc. So instead of developing those 50 screens,I have decided to generate these forms on run time. Now I Googled my problem a bit and I came to know this feature is given in SQL Server 2012 by using **sp\_describe\_first\_result\_set**. Reference: [link](http://raresql.wordpress.com/2012/07/04/sql-server-2012-sp_describe_first_result_set-system-stored-procedure/) Is there a way to achieve this in SQL Server 2008?
2014/11/03
[ "https://Stackoverflow.com/questions/26716795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3368239/" ]
The next query returns a list of stored procedures and their parameters from the current database: ``` select pr.object_id [procedure_id] , pr.name [procedure_name] , p.parameter_id , p.name [parameter_name] , p.is_output from sys.parameters p join sys.procedures pr on p.object_id = pr.object_id order by pr.object_id, p.parameter_id ```
27,114,425
How can I access an RGB mat as a 1D array? I looked at the documentation but couldn't find how the 3 channel data is laid out in that case. I'm trying to loop over each pixel with 1 for loop going from `n=0` to `n = img.rows*img.cols - 1`, and access R, G, and B values at each pixel. Any help would be greatly appreciated.
2014/11/24
[ "https://Stackoverflow.com/questions/27114425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2121792/" ]
I don't really understand why you really need only 1 loop, so I will propose you several options (including 1 or 2 for-loops) that I know by experience to be efficient. If you really want to iterate over all the values with only one loop in a safe way, you can reshape the matrix and turn a 3-channel 2D image into a 1-channel 1D array using `cv::Mat::reshape(...)` ([doc](http://docs.opencv.org/modules/core/doc/basic_structures.html?highlight=reshape#Mat%20Mat::reshape%28int%20cn,%20int%20rows%29%20const)): ``` cv::Mat rgbMat = cv::imread(...); // Read original image // As a 1D-1 channel, we have 1 channel and 3*the number of pixels samples cv::Mat arrayFromRgb = rgbMat.reshape(1, rgbMat.channels()*rgbMat.size().area()); ``` There are two caveats: * `reshape()` returns a new `cv::Mat` reference, hence its output needs to be assigned to a variable (it won't operate in-place) * you are not allowed to change the number of elements in the matrix. OpenCV stores the matrix data in row-major order. Thus, an alternative is to iterate over the rows by getting a pointer to each row start. This way, you will not do anything unsafe because of possible padding data at the end of the rows: ``` cv::Mat rgbMat = cv::imread(...); for (int y = 0; y < rgbMat.size().height; ++y) { // Option 1: get a pointer to a 3-channel element cv::Vec3b* pointerToRgbPixel = rgbMat.ptr<cv::Vec3b>(y); for (int x = 0; x < rgbMat.size().width; ++x, ++pointerToRgbPixel) { uint8_t blue = (*pointerToRgbPixel )[0]; uint8_t green = (*pointerToRgbPixel )[1]; uint8_t red = (*pointerToRgbPixel )[2]; DoSomething(red, green, blue); } // Option 2: get a pointer to the first sample and iterate uint8_t* pointerToSample = rgbMat.ptr<uint8_t>(y); for (int x = 0; x < rgbMat.channels()*rgbMat.size().width; ++x) { DoSomething(*pointerToSample); ++pointerToSample; } } ``` Why do I like the iteration over the rows ? Because it is easy to make parallel. If you have a multi-core computer, you can use any framework (such as OpenMP or GCD) to handle each line in parallel in a safe way. Using OpenMP, it as easy as adding a `#pragma parallel for` before the outer loop.
371,486
This is a question about practice and publication of research mathematics. On the [Wikipedia Page for Experimental Mathematics](https://en.wikipedia.org/wiki/Experimental_mathematics#cite_note-3), I found the following quote: > > Mathematicians have always practised experimental mathematics. Existing records of early mathematics, such as Babylonian mathematics, typically consist of lists of numerical examples illustrating algebraic identities. However, modern mathematics, beginning in the 17th century, developed a tradition of publishing results in a final, formal and abstract presentation. The numerical examples that may have led a mathematician to originally formulate a general theorem were not published, and were generally forgotten. > > > My question concerns the last two sentences. I've heard several of my professors complaining about precisely this: in many mathematics papers, one can read the whole paper without ever understanding how the authors came up with the arguments in the first place. **Questions**: 1.) (Historical:) Why did mathematicians stop publishing motivational steps when publishing mathematics? (For example, were there particular schools of mathematicians who actively advocated for this?) 2.) Is there any movement amongst mathematicians today to change this tradition? (By this, I do not mean movement on a personal level; I know that many mathematicians motivate results in their publications with preliminary calculations they have performed when they initially thought about the problem. Instead, what I am looking for is a movement on the *community level* to initiate a change) 3.) There seems to be a lot of disadvantages to the above practice; by communicating how one *thinks* about a problem, others would be able to copy the author's ways of thinking which will add to the knowledge of the greater mathematical community. Is there any practical benefit for *not* motivating results in papers? **Clarification.** By "publication", I mean everything that one makes available to the greater mathematical community (so anything that one makes available on one's webpage is included (e.g. preprints) as well as anything uploaded to the ArXiv. 4.) Is the assertion made in the last two sentences in the quote accurate. (Thanks to YCor for pointing this out.)
2020/09/12
[ "https://mathoverflow.net/questions/371486", "https://mathoverflow.net", "https://mathoverflow.net/users/152049/" ]
There is a small ambiguity in the expression *motivate a result*. You seem to use it for **(A)**: "explain why the authors came out with certain arguments, definitions, methods etc, in order to prove the result". But it can also refer to **(B)**: "explain why they think the result is interesting/important; what is it aimed for; what is the reason to do such a research, why we should buy it". It is true that the issue **(A)** is sometimes neglected in written papers (maybe it's more present in seminars, in anecdotical form); possible good reasons are: * mental paths that lead to the truth in some cases may help, yes, but in some other may be convoluted and distorted and of no help; the final point of view may be far shorter, clearer and simpler for understanding the logical structure. * the editorial issue of saving room in an article. * another (maybe less good) reason, a bit of vanity: remove all scaffolding and leave an aesthetic, shining and unintelligible object -- and let you think the author is genius. I'd say issue **(A)** becomes important, both from the historical and pedagogical side, later, once **(B)** is agreed and the result accepted in the mathematical community. Artists have always been protective about their tools and methods; it's their bread. Here are some historical examples. * I think the habit of vanity mentioned above was quite common in the European mathematical style of a century ago or more, and hopefully has been reduced in favor of a more pedagogical American style. * In Tartaglia's time, mathematicians would not even give you a proof, just the plain result. * Everybody would like to know how Gauss reached his neat conclusions, for instance. But the introduction of a paper is not necessarily the best moment and place. * Archimedes wrote the computation of the surface area of the sphere in perfect style and rigor, by means of the exhaustion method. But the explanation of how he arrived to "four times the largest inscribed circle" is not there. He first computed the volume of the sphere, by means of his favorite tool, the lever. He explained this later, in a letter to Erathostenes, *The Method*, a magnificent piece of scientific communication.
58,482,435
Following is the `df.head()` of a DataSet with Date set as index. ``` Article_ID Country_Code Sold_Units Date 2017-01-01 3576 AT 1 2017-01-02 1579 FR 1 2017-01-02 332 FI 2 2017-01-03 3576 AT 1 2017-01-03 332 SE 1 ``` The Country Code has 4 values 'AT, FR, FI, SE'. I want to append these 4 country\_codes to every single date if they are not present on those dates and impute their values to 0 in Article\_ID and Sold\_Units. The Example output should basically look like this: ``` Article_ID Country_Code Sold_Units Date 2017-01-01 3576 AT 1 2017-01-01 0 FR 0 # FR FI SE added with 0s. 2017-01-01 0 FI 0 2017-01-01 0 SE 0 2017-01-02 0 AT 0 # AT, SE added 2017-01-02 1579 FR 1 2017-01-02 332 FI 2 2017-01-02 0 SE 0 2017-01-03 3576 AT 1 2017-01-03 0 FR 0 # FR, FI added 2017-01-03 0 FI 0 2017-01-03 332 SE 1 ``` How can I add such default values for every country code?
2019/10/21
[ "https://Stackoverflow.com/questions/58482435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11801923/" ]
Solutions for unique `DatetimeIndex` with `Country_Code` combinations: Create `MultiIndex` by added `Country_Code` to `DatetimeIndex` with all combinations of unique values of datetimes with codes with [`DataFrame.reindex`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.reindex.html): ``` df = (df.set_index('Country_Code', append=True) .reindex(pd.MultiIndex.from_product([df.index.unique(), df['Country_Code'].unique()], names=['Date','Country_Code']), fill_value=0) .reset_index(level=1)) print (df) Country_Code Article_ID Sold_Units Date 2017-01-01 AT 3576 1 2017-01-01 FR 0 0 2017-01-01 FI 0 0 2017-01-01 SE 0 0 2017-01-02 AT 0 0 2017-01-02 FR 1579 1 2017-01-02 FI 332 2 2017-01-02 SE 0 0 2017-01-03 AT 3576 1 2017-01-03 FR 0 0 2017-01-03 FI 0 0 2017-01-03 SE 332 1 ``` Or use [`DataFrame.unstack`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.unstack.html) with [`DataFrame.stack`](http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.stack.html): ``` df = (df.set_index('Country_Code', append=True) .unstack(fill_value=0) .stack() .reset_index(level=1)) print (df) Country_Code Article_ID Sold_Units Date 2017-01-01 AT 3576 1 2017-01-01 FI 0 0 2017-01-01 FR 0 0 2017-01-01 SE 0 0 2017-01-02 AT 0 0 2017-01-02 FI 332 2 2017-01-02 FR 1579 1 2017-01-02 SE 0 0 2017-01-03 AT 3576 1 2017-01-03 FI 0 0 2017-01-03 FR 0 0 2017-01-03 SE 332 1 ``` Solution for multiple values per datetimes with country codes: Error means data are like: ``` print (df) Article_ID Country_Code Sold_Units Date 2017-01-01 3576 AT 1 2017-01-02 1579 FI 1 <-FI 2017-01-02 332 FI 2 <-FI 2017-01-03 3576 AT 1 2017-01-03 332 SE 1 ``` --- ``` df = (df.groupby(['Date','Country_Code']) .sum() .unstack(fill_value=0) .stack() .reset_index(level=1)) print (df) Country_Code Article_ID Sold_Units Date 2017-01-01 AT 3576 1 2017-01-01 FI 0 0 2017-01-01 SE 0 0 2017-01-02 AT 0 0 2017-01-02 FI 1911 3 2017-01-02 SE 0 0 2017-01-03 AT 3576 1 2017-01-03 FI 0 0 2017-01-03 SE 332 1 ```
17,732,726
I have an expandable container in CSS. When collapsed it looks like.(below) * first * second * third If I expand the first item this happens(below) * first +second +third The float left looks like it causing the problem, but without it formatting is off. How can I make everything else wrap after expanded. ``` div.wrapper{ float:left; position:relative; margin: 30px 30px 30px 30px; } ```
2013/07/18
[ "https://Stackoverflow.com/questions/17732726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1938745/" ]
Well, it looks like most of my problems stem from the fact that I'm not an admin on my system. I have managed to write datasets with the above technique given that I have write privileges on the directory with my account (duuh). Allas, the x command is stubborn and won't work lest I get myself an admin account. So, two choices to «solve» this problem: 1. Get administrator privileges. or 2. Forget the workspace manager. Use OleObjects. While less elegant and perhaps more time consuming upon execution (not tested) OleObject will let me use SAS to its full extent. Here is the VBA code: ``` Dim OleSAS As Object Set OleSAS = CreateObject("SAS.Application") OleSAS.Visible = True OleSAS.Top = 1 OleSAS.Title = "Automation Server" OleSAS.Wait = True OleSAS.Submit(yourSAScode) OleSAS.Quit Set OleSAS = Nothing ``` If you want to run a specific process and change some macro variables as with \*ProcessBody; just do OleSAS.Submit("%let "& variable\_name & "=" & "yourValue") and OleSAS.Submit("%include" & your\_program). Anyway, I'm pretty sad of loosing the Log report return that I had with the Worspace Manager, it was really great for fast debugging. Hope this was usefull.
9,227,864
For instance, how to convert the following array: ``` $array1 = array("value1" => "20", "value2" => 40, array("value3" => 60)); ``` To: ``` $array1 = array("value1" => "20", "value2" => "40", array("value3" => "60")); ```
2012/02/10
[ "https://Stackoverflow.com/questions/9227864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/990164/" ]
``` array_walk_recursive($array, function (&$value) { $value = (string)$value; }); ```
5,698,260
This may be a simple question but I have not been able to find a satisfactory answer. I am writing a class in Java that needs to take in a .csv file filled with doubles in three columns. Obviously a .csv file uses commas as the delimiters, but when I try setting them with my scanner, the scanner finds nothing. Any advice? ``` Scanner s = null; try { s = new Scanner(source); //s.useDelimiter("[\\s,\r\n]+"); //This one works if I am using a .txt file //s.useDelimiter(", \n"); // This is what I thought would work for a .csv file ... } catch (FileNotFoundException e) { System.err.format("FileNotFoundException: %s%s", e); } catch (IOException e) { System.err.format("IOException: %s%n", e); } ``` A sample input would be: 12.3 11.2 27.0 0.5 97.1 18.3 etc. Thank you for your time! EDIT: fixed! Found the correct delimiters and realized I was using hasNextInt() instead of hasNextDouble(). /facepalm
2011/04/18
[ "https://Stackoverflow.com/questions/5698260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/694253/" ]
Consider the following: ``` first,second,"the third",fourth,"the,fifth" ``` Should only be five - the last comma is in a quote block, which should not get split. Don't reinvent the wheel. There are open source libraries to handle this behavior. A quick google search yielded <http://opencsv.sourceforge.net/> and I'm sure there's others.
228,773
By default the `alt` + mouse combination activates the window menu. The *activate the window menu* shortcut is currently set to `alt`+`space` The `Alt`-RMB key combo is used in blender for selecting edge loops.
2012/12/13
[ "https://askubuntu.com/questions/228773", "https://askubuntu.com", "https://askubuntu.com/users/112543/" ]
Install the compizconfig-settings-manager package and run ccsm. At `General | General Options | Key bindings | Window Menu` click on `Alt<Button3>`, de-select `Enabled` and click `OK`. P.S. If this doesn't work, assign a different key to `Window Menu`. Thanks to Morichalion.
36,383,372
I'm trying to change the design of my hamburger navigation as the user scrolls. I feel I have come semi close <https://jsfiddle.net/g95kk7yh/6/> ``` $(document).ready(function(){ var scroll_pos = 0; $(document).scroll(function() { scroll_pos = $(this).scrollTop(); if(scroll_pos > 10) { $(".navigation").css('background', 'rgba(255, 0, 0, 0.5)'); $(".navigation span").css('background', '#bdccd4'); } else { $(".navigation").css('background', 'transparent'); $(".navigation span").css('background', '#fff'); } }); }); ``` Here is what I'm trying to achieve [![enter image description here](https://i.stack.imgur.com/Gc5gh.png)](https://i.stack.imgur.com/Gc5gh.png) The main problem I'm having is assigning the correct width and height of the red box without repositioning the navigation menu as a whole. Also is it possible to only have these changes at 600px and under (as you can see this is when the hamburger menu shows).
2016/04/03
[ "https://Stackoverflow.com/questions/36383372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4358910/" ]
I have used @potatopeelings post and have changed few lines and added. ``` .myClass { margin-right: -25px; width: 85px; height: 85px; background-color: rgba(255, 0, 0, 0.5); } ``` Fiddle: <https://jsfiddle.net/moj7z2b4/2/>
10,628,401
I have recently started working with the vtk package and I see this odd notation that they include `;` after closing curly braces `}`. Here is an example from `vtkUnstructuredGrid.h` ``` // Description: // Standard vtkDataSet API methods. See vtkDataSet for more information. int GetDataObjectType() {return VTK_UNSTRUCTURED_GRID;}; ``` It's not needed and QtCreator also correctly detects this by saying `extra ;` when parsing the code. I'm curious what could be the reason for this? Maybe readability?
2012/05/17
[ "https://Stackoverflow.com/questions/10628401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/928594/" ]
As QtCreator correctly detects, *that* is definitely an extra semicolon that not only is useless, but can also cause compiler warnings and confusion. For example GCC with the `-Wpedantic` flag [will trigger](http://coliru.stacked-crooked.com/a/95a272dfbb6e6430): > > warning: extra ';' > > >
16,226,472
I'm trying to set up the MongoDB auto reconnection feature via Mongoose. Every way that I have tried to pass the option has had no effect, or at least the `reconnected` event isn't being emitted. What I've tried: ``` mongoose.createConnection("mongodb://localhost:27017/test", { auto_reconnect: true }); mongoose.createConnection("mongodb://localhost:27017/test", { autoReconnect: true }); mongoose.createConnection("mongodb://localhost:27017/test", { server: { auto_reconnect: true } }); mongoose.createConnection("mongodb://localhost:27017/test", { server: { autoReconnect: true } }); ``` If one of these is correct, the `reconnected` event should be triggered and a message should be logged in the console, however this never happens. If there is a delay before the reconnection, does anyone know how to configure it? Thanks in advance For anyone looking into this, take a look at [this](https://github.com/LearnBoost/mongoose/issues/1479) and [this](https://github.com/LearnBoost/mongoose/issues/1672) issue in mongoose repository.
2013/04/25
[ "https://Stackoverflow.com/questions/16226472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2083599/" ]
I had the same question as you, and robertklep's solution didn't work for me either. I found when MongoDB service is stopped, an error event is triggered, but the connection.readyState is still 1 (connected). That may be why it didn't auto reconnect. This is what I have now: ``` var db = mongoose.connection; db.on('connecting', function() { console.log('connecting to MongoDB...'); }); db.on('error', function(error) { console.error('Error in MongoDb connection: ' + error); mongoose.disconnect(); }); db.on('connected', function() { console.log('MongoDB connected!'); }); db.once('open', function() { console.log('MongoDB connection opened!'); }); db.on('reconnected', function () { console.log('MongoDB reconnected!'); }); db.on('disconnected', function() { console.log('MongoDB disconnected!'); mongoose.connect(dbURI, {server:{auto_reconnect:true}}); }); mongoose.connect(dbURI, {server:{auto_reconnect:true}}); ```
2,742,356
Any ideas on what that error means? I have an attachment media type image with a full URL specified and I am seeing this error.
2010/04/30
[ "https://Stackoverflow.com/questions/2742356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/329473/" ]
I know that this is old post but if someone need solution then it is to wrap media in brackets [] like this: ``` {"media": [ { "type": "image", "src": "http://icanhascheezburger.files.wordpress.com/2009/03/funny-pictures-kitten-finished-his-milk-and-wants-a-cookie.jpg", "href": "http://icanhascheezburger.com/2009/03/30/funny-pictures-awlll-gone-cookie-now/" }, { "type": "image", "src": "http://photos.icanhascheezburger.com/completestore/2009/1/18/128768048603560273.jpg", "href": "http://ihasahotdog.com/upcoming/?pid=20869" }] ``` } Because it is array of media... You can find more info here: <http://developers.facebook.com/docs/guides/attachments/> and here <http://developers.facebook.com/docs/reference/rest/stream.publish/> j.
40,703,424
I have an one text file. This file has 5 rows and 5 columns. All the columns are separated by "|" (symbol). In that 2nd column(content) length should be 7 characters. If 2nd column length is more than 7 characters. Then,I want to remove those extra characters without opening that file. **For example:** ``` cat file1 ``` > > ff|hahaha1|kjbsb|122344|jbjbnjuinnv| > > > df|hadb123\_udcvb|sbfuisdbvdkh|122344|jbjbnjuinnv| > > > gf|harayhe\_jnbsnjv|sdbvdkh|12234|jbjbnj| > > > qq|kkksks2|datetag|7777|jbjbnj| > > > jj|harisha|hagte|090900|hags| > > > For the above case 2nd and 3rd rows having 2nd column length is more than 7 characters. Now i want to remove those extra characters without open the input file using awk or sed command I'm waiting for your responses guys. Thanks in advance!!
2016/11/20
[ "https://Stackoverflow.com/questions/40703424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7185058/" ]
Take a substring of length 7 from the second column with awk: ``` awk -F'|' -v OFS='|' '{ $2 = substr($2, 1, 7) }1' file ``` Now any strings longer than 7 characters will be made shorter. Any strings that were shorter will be left as they are. The `1` at the end is the shortest *true* condition to trigger the default action, `{ print }`. If you're happy with the changes, then you can overwrite the original file like this: ``` awk -F'|' -v OFS='|' '{ $2 = substr($2, 1, 7) }1' file > tmp && mv tmp file ``` i.e. redirect to a temporary file and then overwrite the original.
13,083,418
I have a set of dictionaries with some key-value pairs. I would like to know the most efficient way to split them in halves and then apply some processing on each set. I suppose there exists some one liner out there... i.e. if I have the dictionaries A,B,C,D, I would like to have the resulting sets: (A,B), (A,C), (A,D) and NOT the remaining sets (C,D),(B,D),(B,C)
2012/10/26
[ "https://Stackoverflow.com/questions/13083418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1776491/" ]
`itertools` and one-liners usually belong in the same sentence: ``` >>> import itertools >>> s = ['A', 'B', 'C', 'D'] >>> i = itertools.product(s[0], s[1:]) >>> list(i) [('A', 'B'), ('A', 'C'), ('A', 'D')] ```
33,214,380
I am currently writing test cases using TestNg. I populate objects using PodamFactory. I have following test case structure. ``` @Test public void testIt(){ ARespObject resp = PodamFactory.manufacturePojo(ARespObject.class); String responseXml = new JaxbStringTransformer().transform(resp); // a new object with all the same data ARespObject respActual = responder.getObj(responseXml); Assert.assertTrue(TestUtils.areEqual(respActual , resp)); } public static <T extends Object> boolean areEqual(T sourceObj, T target) { if (sourceObj == null && target == null) { return true; } if (sourceObj == target) { return true; } if (sourceObj.getClass() != target.getClass()) { return false; } if (sourceObj != null && target != null) { return stringifyObject(sourceObj).equals(stringifyObject(target)); } return false; } public static String stringifyObject(Object obj) { String result = ""; ObjectWriter ow = new JaxbJacksonObjectMapper().writer().withDefaultPrettyPrinter(); try { result = ow.writeValueAsString(obj); } catch (JsonGenerationException e1) { LOG.error(e1); } catch (JsonMappingException e1) { LOG.error("JsonMappingException: " + e1); } catch (IOException e1) { LOG.error("IOException: " + e1); } return result; } ``` I need to know if writeValueAsString(obj) will always provide same structure for both objects(i.e. its output will be stable) and following ``` stringifyObject(sourceObj).equals(stringifyObject(target)); ``` is a valid check. I am concerned about whether it will ever give me different ordering of variables inside the ARespObject.
2015/10/19
[ "https://Stackoverflow.com/questions/33214380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5462398/" ]
Rather than formatting the objects to strings for comparison, convert them to "tree model" (JsonNode implementations). ObjectNode implements equals/hashCode/toString etc to reasonably imitate JSON equivalence, so it will disregard the order of properties for example. ``` ObjectMapper mapper = new ObjectMapper(); JsonNode treeNode = mapper.convertValue(obj, JsonNode.class); ``` (typically you will actually get an ObjectNode back, but you can just probably just use the JsonNode interface) The tree model classes will also perform a simple JSON formatting for toString() output, so "expected" and "actual" printouts should be readable (although not as pretty as with the pretty printer)
59,341,133
I have set scheduledTimer in a view Controller. But when got to anther view controller, previous view controller timer is continue.Here is my code ``` var timer: Timer? = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: false) ``` Here is function ``` @objc func runTimedCode() { //Api Calling } ``` when I go to anther viewController, previous Api calling is continue. Please help me to scheduledTimer go another page/viewcontroller
2019/12/15
[ "https://Stackoverflow.com/questions/59341133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3972291/" ]
In your example, there is a typo `adminstrators`, it should be `administrators`. **Solution** ``` resource "google_compute_instance" "win-dev-instance" { project = "my_pro_1" zone = "eu-west2-b" name = "win-dev-instance" machine_type = "n1-standard-2" boot_disk { initialize_params { image = "windows-server-2016-dc-v20191210" } } network_interface { network = "default" access_config {} } metadata = { windows-startup-script-cmd = "net user /add devuser Abc123123 & net localgroup administrators devuser /add" } } ```
282,751
I've a simple push/pop implementation in my program: ```c void Push(int* stack, int top, int item) { if (top == SIZE - 1) { printf("Overflow\n"); return; } else if (item == INT_MIN) { printf("Item size out of bounds\n"); return; } stack[++top] = item; } int Pop(int* stack, int top) { if (top == -1) { printf("Empty\n"); return INT_MIN; } return stack[top--]; } ``` In the `Pop()` function, I've wanted to return some kind of error code when the stack is empty but since all of the `int` values are valid returns: Can I resort to reserving `INT_MIN` for this? Is this a 'good practice', have unwanted consequences etc?
2023/01/22
[ "https://codereview.stackexchange.com/questions/282751", "https://codereview.stackexchange.com", "https://codereview.stackexchange.com/users/268076/" ]
This is a classic example of in-band error signalling, and it's not a good idea (I think you suspect this, having asked about it). You need to separate the data from the error/success status of the function. There are several ways to do this, but most of them involve a return value for one, and a pointer argument for the other. For instance, ``` bool Push(int *stack, int *top, int item); int Pop(const int *stack, int *top, bool *success); ``` Note that `stack` should be `const`, and this function will not work correctly unless `top` is passed by reference. Also, for your error prints, you should usually print to `stderr` and not `stdout`.
46,896
I'm working on a logo in Illustrator where the pieces have black outer glows to give depth to a paper-fold style logo theme. ![enter image description here](https://i.stack.imgur.com/V9Da7.jpg) The shadows on the *outside of the logo text* are just a result of the effect needed to achieve what I want on the *inside of the logo text*. I want to contain the outer glows so that they only appear within the bounds of the letters, not showing up against the background. How can I do this? For a fast, rough example of my goal, I took this into photoshop and pajnted over the shadows I want to hide: ![enter image description here](https://i.stack.imgur.com/Gypvv.jpg) In photoshop, I could just mask the edges of this properly, but I need it done in Illustrator, in vector.
2015/02/06
[ "https://graphicdesign.stackexchange.com/questions/46896", "https://graphicdesign.stackexchange.com", "https://graphicdesign.stackexchange.com/users/14858/" ]
You *will* want to use an outer glow, in order to retain the shadow effect. The best way I think to achieve this is to *mask* your shapes, so their effects don't extend beyond the total shape. Proceed as follows: 1. Copy all shapes and paste in front (`Edit > Paste in Front` or `Ctrl / Cmd` +`Alt`+`Shift`+`V`); 2. With just the new shapes selected, unite them with the `Pathfinder` palette (the first icon); 3. With the resulting shapes still selected, choose `Object > Compound Path > Make`; 4. In the `Appearance` palette, click the 'stop board' icon to remove the path's appearance (and mainly, the copy of the glow effect); 5. Add your original art to your selection; 6. Make a `Clipping Mask` by choosing `Object > Clipping Mask > Make` (or `right-click > Make Clipping Mask`). You can edit the clipping mask as well as its contents separately by entering `Isolation Mode`.
46,161,057
**Problem:** Remove the substring `t` from a string `s`, repeatedly and print the number of steps involved to do the same. **Explanation/Working:** > > **For Example:** `t = ab`, `s = aabb`. In the first step, we check if `t` is > contained within `s`. Here, `t` is contained in the middle i.e. `a(ab)b`. > So, we will remove it and the resultant will be `ab` and increment the > `count` value by 1. We again check if `t` is contained within `s`. Now, `t` is > equal to `s` i.e. `(ab)`. So, we remove that from `s` and increment the > `count`. So, since `t` is no more contained in `s`, we stop and print the > `count` value, which is 2 in this case. > > > **So, here's what I have tried:** 1. ***Code 1:*** ``` static int maxMoves(String s, String t) { int count = 0,i; while(true) { if(s.contains(t)) { i = s.indexOf(t); s = s.substring(0,i) + s.substring(i + t.length()); } else break; ++count; } return count; } ``` I am just able to pass 9/14 test cases on Hackerrank, due to some reason (I am getting *"Wrong Answer"* for rest of the cases). After a while, I found out that there is something called `replace()` method in Java. So, I tried using that by replacing the `if` condition and came up with a second version of code. 2. ***Code 2:*** ``` static int maxMoves(String s, String t) { int count = 0,i; while(true) { if(s.contains(t)) s.replace(t,""); //Marked Statement else break; ++count; } return count; } ``` But for some reason (I don't know why), the *"Marked Statement"* in the above code gets executed infinitely (this I noticed when I replaced the *"Marked Statement"* with `System.out.println(s.replace(t,""));`). I don't the reason for the same. Since, I am passing only 9/14 test cases, there must be some logical error that is leading to a *"Wrong Answer"*. How do I overcome that if I use **Code 1**? And if I use **Code 2**, how do I avoid infinite execution of the *"Marked Statement"*? Or is there anyone who would like to suggest me a **Code 3**? Thank you in advance :)
2017/09/11
[ "https://Stackoverflow.com/questions/46161057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8593507/" ]
Try saving the new (returned) string instead of ignoring it. ``` s = s.replace(t,""); ``` **replace** returns a new string; you seemed to think that it alters the given string in-place.
58,664,293
I have problems with FutureBuilder starting twice. First it fetch the data correctly, returning my StartScreen, then after few seconds, the StartScreen rebuilds and I noticed that the FutureBuilder fires again. Here is my code and it's pretty simple, so I wonder what may the problem be?!? ``` class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { FirebaseUser user; @override void initState() { // TODO: implement initState super.initState(); getNewestlocation(); } @override void dispose() { super.dispose(); } @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'APP', theme: buildTheme(), home: FutureBuilder<FirebaseUser>( future: Provider.of<AuthService>(context).getUser(), builder: (context, AsyncSnapshot<FirebaseUser> snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.error != null) { print('error'); return Text(snapshot.error.toString()); } user = snapshot.data; print('user here $user'); return snapshot.hasData ? StartScreen(user) : LoginScreen(); } else { return LoadingCircle(); } }, ), ); } } ``` Can anyone help me with this, please?
2019/11/01
[ "https://Stackoverflow.com/questions/58664293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5843195/" ]
The future is firing again because you're creating it in the build method at the same time as the FutureBuilder. From the [FutureBuilder docs](https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html): > > The future must have been obtained earlier, e.g. during State.initState, State.didUpdateConfig, or State.didChangeDependencies. It must not be created during the State.build or StatelessWidget.build method call when constructing the FutureBuilder. If the future is created at the same time as the FutureBuilder, then every time the FutureBuilder's parent is rebuilt, the asynchronous task will be restarted. > > > So to prevent it from firing you'd have to do something like this: ``` class _MyAppState extends State<MyApp> { Future<String> _myString; @override void initState() { super.initState(); _myString = _fetchString(); } @override Widget build(BuildContext context) { return Scaffold( body: FutureBuilder( future: _myString, builder: (context, snapshot) { // build page stuff... }, ), ); } } Future<String> _fetchString() async { print('running future function'); await Future.delayed(Duration(seconds: 3)); return 'potatoes'; } ``` Note, to access a provider in initState() you have to set listen to false, as detailed in [this](https://stackoverflow.com/a/56170753/11709863) answer.
44,822,652
I am new to magento & I was installing an extension into my magento version 2.1.7 but the system readiness check shows the following error currently megento is present in my system with windows 8 operating system. [Error shown while installing extension in magento2.1](https://i.stack.imgur.com/81I0v.png) [Error shown while installing extension in magento2.1](https://i.stack.imgur.com/Dhp6C.png) I have tried the below given solutions but no any solution is worked with it my magento directory also & from my system32 also. ``` php ls -al <your Magento install dir>/var/.setup_cronjob_status ``` It is showing the following response. ``` Could not open input file:ls ``` I also tried the below code ``` php crontab -u magento2.1 -l ``` & ``` php crontab -u Admin -l ``` where **magento2.1** is the **user name** of my Magento & **Admin** is my **system name**. Both the code given an error as follows ``` Could not open input file:crontab ``` I am running this magento with Php **version 7.0.2** & **Xampp version 7.0.20-0-VC14** Whether it is an error of not having cron in my system or something else? Any Idea?
2017/06/29
[ "https://Stackoverflow.com/questions/44822652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4586760/" ]
Try to run the cron files of Magento by run the cron file separately. Just simply go to the root directory of your Magento open command prompt there & run the below commands > > php bin/magento cron:run > > > php update/cron.php > > > php bin/magento setup:cron:run > > >
26,930,635
I am working on an ELK-stack configuration. logstash-forwarder is used as a log shipper, each type of log is tagged with a type-tag: ```java { "network": { "servers": [ "___:___" ], "ssl ca": "___", "timeout": 15 }, "files": [ { "paths": [ "/var/log/secure" ], "fields": { "type": "syslog" } } ] } ``` That part works fine... Now, I want logstash to split the message string in its parts; luckily, that is already implemented in the default grok patterns, so the logstash.conf remains simple so far: ```java input { lumberjack { port => 6782 ssl_certificate => "___" ssl_key => "___" } } filter { if [type] == "syslog" { grok { match => [ "message", "%{SYSLOGLINE}" ] } } } output { elasticsearch { cluster => "___" template => "___" template_overwrite => true node_name => "logstash-___" bind_host => "___" } } ``` The issue I have here is that the document that is received by elasticsearch still holds the whole line (including timestamp etc.) in the message field. Also, the @timestamp still shows the date of when logstash has received the message which makes is bad to search since kibana does query the @timestamp in order to filter by date... Any idea what I'm doing wrong? Thanks, Daniel
2014/11/14
[ "https://Stackoverflow.com/questions/26930635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1098584/" ]
The reason your "message" field contains the original log line (including timestamps etc) is that the grok filter by default won't allow existing fields to be overwritten. In other words, even though the [SYSLOGLINE pattern](https://github.com/elasticsearch/logstash/blob/master/patterns/linux-syslog), ``` SYSLOGLINE %{SYSLOGBASE2} %{GREEDYDATA:message} ``` captures the message into a "message" field it won't overwrite the current field value. The solution is to set the [grok filter's "overwrite" parameter](http://logstash.net/docs/1.4.2/filters/grok#overwrite). ``` grok { match => [ "message", "%{SYSLOGLINE}" ] overwrite => [ "message" ] } ``` To populate the "@timestamp" field, use the [date filter](http://logstash.net/docs/1.4.2/filters/date). This will probably work for you: ``` date { match => [ "timestamp", "MMM dd HH:mm:ss", "MMM d HH:mm:ss" ] } ```
15,431,652
We are using Azure Virtual machines to host our application in the cloud. Couple of virtual machines are hosting web front-end(state-less) and one virtual machine is hosting SQL Server (data is stored in Data Disk). As we all know, these virtual machines consist of OS Disk and Data Disk(optional) which uses VHD files stored in blob storage. We are using geo-redundant blob storage which stores these VHD files. We are now planning for disaster recovery for our cloud application. So if a Microsoft data center is down, is it possible to spin up virtual machines in another data center with the help of OS Disk and Data Disk stored in geo-replicated storage?
2013/03/15
[ "https://Stackoverflow.com/questions/15431652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/511625/" ]
You are not supposed to use geo-replicated storage with SQL Server data disks. This is documented at <https://msdn.microsoft.com/library/azure/dn133149.aspx>. Specifically, the document states "When creating a storage account, disable geo-replication as consistent write order across multiple disks is not guaranteed. Instead, consider configuring a SQL Server disaster recovery technology between two Azure data centers".
15,872,414
I am completely new to jQuery. When working with jQuery, I disconnected the Internet to check if my webpage works fine without an Internet connection. It displayed some thing which is not required. When I saw the source code, it displayed: ``` <link rel="stylesheet" href="http://jquery.com/jquery-wp-content/themes/jquery/css/base.css?v=1"> ``` So I downloaded the code and kept it in my root folder. Still it's not working well. Can we work with jQuery while offline? Here is my code: ```html <!doctype html> <!-- [if IE 7 ]> <html class="no-js ie ie7 lte7 lte8 lte9" lang="en-US"> <![endif] --> <!-- [if IE 8 ]> <html class="no-js ie ie8 lte8 lte9" lang="en-US"> <![endif] --> <!-- [if IE 9 ]> <html class="no-js ie ie9 lte9>" lang="en-US"> <![endif] --> <!-- [if (gt IE 9)|!(IE)]> <!-- > <html class="no-js" lang="en-US"> <!--<![endif] --> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title> Home</title> <meta name="author" content="jQuery Foundation - jquery.org"> <meta name="description" content="jQuery: The Write Less, Do More, JavaScript Library"> <meta name="viewport" content="width=device-width"> <link rel="stylesheet" href="http://jquery.com/jquery-wp-content/themes/jquery/css/base.css?v=1"> <script src="jquery.min.js"></script> <!--[if lt IE 7]><link rel="stylesheet" href="css/font-awesome-ie7.min.css"><![endif]--> <script>try{Typekit.load();}catch(e){}</script> <meta name="generator" content="WordPress 3.5.1" /> </head> <body> <!--[if lt IE 7]> <p class="chromeframe">You are using an outdated browser. <a href="http://browsehappy.com/">Upgrade your browser today</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to better experience this site.</p> <![endif]--> <header> <section id="global-nav"> <nav> <div class="constrain"> <ul class="links"> <li><a href="home.jsp">Home</a></li> <li class="dropdown"><a href="CreatPatient.jsp">Patient</a> <ul> <li><a href="CreatePatient.jsp">Create Patient</a></li> <li><a href="Edit Patient">Edit Patient</a></li> </ul> </li> <li class="dropdown"><a href="Appointments.jsp">Appointments</a> <ul> <li><a href="CreateAppointments.jsp">Create Appointments</a></li> <li><a href="EditAppointments.jsp/">Edit Appointments</a></li> </ul> </li> <li class="dropdown"><a href="#">Reports</a> <ul> <li><a href="PreOperative.jsp">Pre Operative</a></li> <li><a href="IntraOperative.jsp">Intra Operative</a></li> <li><a href="PostOperative.jsp">PostOperative</a></li> </ul> </li> </ul> </div> </nav> </section> </header> </body> </html> ``` When I remove this line: ``` <link rel="stylesheet" href="http://jquery.com/jquery-wp-content/themes/jquery/css/base.css?v=1"> ``` It creates a problem. I have downloaded jQuery and kept on the desktop. The HTML file is also on the desktop. Why is it not working?
2013/04/08
[ "https://Stackoverflow.com/questions/15872414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2156338/" ]
Yes, it's possible. You've mentioned that you downloaded the file - that's a good first step, but you also have to change all the `href` and `src` references. For example, ``` <link rel="stylesheet" href="http://jquery.com/jquery-wp-content/themes/jquery/css/base.css?v=1"> ``` should become ``` <link rel="stylesheet" href="base.css"> ``` --- Also remember to get the offline version of the jQuery JS library, too: Download [jquery.js](http://code.jquery.com/jquery-1.9.1.min.js), put it in your root folder & reference it: ``` <script src="jquery-1.9.1.min.js"></script> ``` And if you want it in a subdirectory: ``` <script src="[subdirectory-name]/jquery-1.9.1.min.js"></script> ``` --- Remember that **both files** need to be offline and in your working local directory. This means that you **cannot remove the stylesheet *nor* the jQuery JS library**. Keep both of them, in the local formats I've mentioned above. Also, putting the `<script>` tag in the `<head>` is bad practice; move it just before the `</body>` tag instead. --- Your code should now look (in short, note that I haven't put much) like: ```html ... <html class="no-js" lang="en-US"> <head> ... <link rel="stylesheet" href="base.css"> ... </head> <body> ... <script src="jquery.min.js"></script> </body> </html> ``` Again, make sure that `base.css` and `jquery.min.js` are the **exact file names** and are **in the same folder as this `.html` file**
68,283
![schematic](https://i.stack.imgur.com/2H0XB.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2f2H0XB.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/) This is the code that I'm using to get the temperature: ``` #define COEFF_A 0.8662984364E-03 #define COEFF_B 2.780704551E-04 #define COEFF_C -0.9395108479E-07 float VRT, Temp; float Vref = 2.52; void setup() { Serial.begin(9600); analogReference(EXTERNAL); } void loop() { long Resistance; VRT = analogRead(A3); Resistance = 10000 / ((1023.0 / VRT) - 1); Temp = log(Resistance); Temp = 1 / (COEFF_A + (COEFF_B * Temp) + (COEFF_C * pow(Temp, 3))); Temp += -273.15; Serial.println(Temp); delay(500); } ``` I know that the calculation should be: `V = Vref × VRT ÷ 1023` but i don't know how to implant it in this code, any help appreciated. --- Update ====== After Edgar Bonet [answer](https://arduino.stackexchange.com/a/68288/57281), the edited code is: ``` #define COEFF_A 0.8662984364E-03 #define COEFF_B 2.780704551E-04 #define COEFF_C -0.9395108479E-07 float VRT, Temp, VR; void setup() { Serial.begin(9600); analogReference(EXTERNAL); } void loop() { long Resistance; VRT = analogRead(A3); VR = 2.52 * VRT / 1024; Resistance = 10000 * VR / (2.52 - VR); Temp = log(Resistance); Temp = 1 / (COEFF_A + (COEFF_B * Temp) + (COEFF_C * pow(Temp, 3))); Temp += -273.15; Serial.println(Temp); delay(500); } ``` But the temperature reading is 2 centigrade less than what it should be, when i remove the `analogReference(EXTERNAL);` it shows the normal/correct temperature readings.
2019/08/30
[ "https://arduino.stackexchange.com/questions/68283", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/57281/" ]
The formula to get the analog voltage from the ADC reading is:     V = Vref × reading ÷ 1024 (yes, it's 1024, not 1023). The formula to get the thermistor resistance from the measured voltage is:     R = Rref × V ÷ (Vref − V) where Rref is your 10 kΩ pull-up. You can combine these two formulas in order to get the resistance directly from the ADC reading:     R = Rref × reading ÷ (1024 − reading) You may notice that, while doing this simplification, Vref cancels out. It's not an error. The readings you get with this setup are indeed independent of your reference voltage. --- **Update 1**: After the OP's edit, we now have a *completely different* question. The question is now: how come the readings do depend on the reference voltage that is used, whereas in theory they should not. The answer lies most likely in the ADC calibration. If high accuracy is a requirement, the correct formula for the measured voltage is     V = Vref × (reading + Eoff) ÷ (1024 + Egain) where Eoff and Egain are the offset error and the gain error respectively. These errors are not knows *a priori*, and they are usually neglected when the accuracy requirement is low. The datasheet only gives constraints on how big these errors can be. The actual values depend on the specific microcontroller and can somewhat depend on the reference voltage. The only solution to get rid of these errors is to calibrate your own ADC. See [Response of the Arduino ADC](https://wiki.logre.eu/index.php/R%C3%A9ponse_de_l%27ADC_d%27un_Arduino/en) for an example on how this could be done. --- **Update 2**: If I had to program this in an Arduino, I would rather simplify the calculations as much as possible before coding: * do *not* compute the measured analog voltage, nor the resistance, as they are not needed * compute instead the ratio R/Rref directly from the analog reading * rewrite the calibration polynomial as a function of log(R/Rref) instead of log(R) (which actually means log(R/(1 Ω))) * optimize the evaluation of the polynomial by using [Horner's method](https://en.wikipedia.org/wiki/Horner%27s_method). With these optimizations, we get: ```cpp // Coefficients of polynomial fit of log(R/Rref) -> 1/T. const float c0 = 3.3540165e-3; const float c1 = 2.5416075e-4; const float c2 = -2.5959644e-6; const float c3 = -9.3951087e-8; // Convert ADC reading to temperature in deg. C. static float temperature(int reading) { float R_ratio = reading / (1024.0 - reading); // = R / Rref float x = log(R_ratio); float inverse_T = c0 + x*(c1 + x*(c2 + x*c3)); return 1/inverse_T - 273.15; } void loop() { int reading = analogRead(A3); Serial.println(temperature(reading)); deay(500); } ```
31,200,442
I'm a little bit confused about when the all process exit: 1. When the main thread exits - do we exit from all process? 2. When one of the threads calls `exit(1)` - *do we exit exit from all process?* 3. When one of the threads calls `return 0` - *do we exit exit from all process?* *Is it different if the main thread calls it or another thread?* 4. When one of the threads calls `return NULL` - *do we exit exit from all process? Is it different if the main thread calls it or another thread?*
2015/07/03
[ "https://Stackoverflow.com/questions/31200442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3479031/" ]
1. When the main thread exits - do we exit from all process? > > As already explained [here](https://stackoverflow.com/questions/11875956/main-thread-exit-does-other-exit-too#comment15804566_11876049), when the main thread (or any thread) calls exit, or when the initial > invocation of main returns, the entire process exits. But the main > thread can exit with pthread\_exit without affecting other threads. > > > 2. When one of the threads calls exit(1) - do we exit exit from all process? > > Yes, we do. > > > 3. When one of the threads calls return 0 - do we exit exit from all process? > > No, we don't. We only return back from that thread. > > > From the [link](http://www.cs.cf.ac.uk/Dave/C/node29.html), A thread can terminate its execution in the following ways: > > > * By returning from its first (outermost) procedure, the threads start routine > * By calling pthread\_exit(), supplying an exit status > * By termination with POSIX cancel functions > > > The void pthread\_exit(void \*status) is used terminate a thread in a > similar fashion the exit() for a process. > > > 4. When one of the threads calls return NULL - do we exit exit from all process? > > It's same as calling `return 0`, as NULL is defined to be 0. So, same > answer as for the above question. > > > 4b. \*Is it different if the main thread calls it (`return 0` or `return NULL`) or another thread? \* > > Yes, if main thread calls, refer answer to question 1 and if another > thread calls, refer answer to question 3. > > > In nutshell, if `main` exits or returns, it makes the entire process to exit. To avoid this, `pthread_exit` can be used which waits till the last thread terminates. If a thread calls `exit()`, it makes the entire process to exit, and if it calls `return NULL` or `return 0` or `pthread_exit`, only that particular thread exits.
67,458,891
I'm on laravel 8, and on my project I want to trigger some sort of notification for example if the user succesfully update their account then on return it will give some notification that update is success, I want it to be modal or alert. I've tried the withMsg or with inside my controller but none of them works, I tested the function with button trigger action and it works, but I want it to activated automatically. also forgot to mention that when I was still on stock laravel template the message function works, until I change to other template it won't work again does anyone have a solution? thanks
2021/05/09
[ "https://Stackoverflow.com/questions/67458891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4984785/" ]
It sounds like you're referring to a `flash` message where information is stored in the session and displayed on the next request (or longer if you wish). The Laravel documentation explains [how to set a flash message in the session](https://laravel.com/docs/8.x/session#flash-data). There are some excellent resources available on how to compose flash messages, whether as an alert or as a modal. Laracasts has such a tutorial on [flash messaging and modals](https://laracasts.com/series/hands-on-community-contributions/episodes/7). [SweetAlert](https://sweetalert2.github.io/) is a popular package for creating modal notifications and there is a 'sweet` (pun intended) [package for Laravel](https://realrashid.github.io/sweet-alert/) that wraps the original package into a nice API for you to use in your Laravel projects.
655,651
I'm looking for an example of how to do a long running HTTP call from Flex/Actionscript to a Java server that supports Comet. Also long running http calls are usually used for pushing data from the server to the client, I would like to used for "streaming" data to the client, for example data for a large table. The client should show already some data before the call is finished. I know that LCDS from Adobe supports this, but I'm interested in a low level implementation that would get the data directly using HTTP.
2009/03/17
[ "https://Stackoverflow.com/questions/655651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26056/" ]
Do you have examples of articles that are too simple? Are these too simple: [devshed](http://www.devshed.com/c/a/Multimedia/Game-Programming-using-SDL-Getting-Started/) or [gpwiki](http://gpwiki.org/index.php/C:SDL_tutorials) ? You might consider studying the topics separately. For example Bruce Eckels has, IMO, the best C++ books, "Thinking in C++ I & II" that will take you from novice to expert (including SQA techniques like unit testing) and they are available for [free.](http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html) I've found that C++ is a harsh mistress and if you aren't prepared for the language, no tutorial specific to 'SDL and Games' will help much - this is true for any other advanced libraries, toolkits, etc.
42,858,048
I am trying to build [freetype2](https://www.freetype.org/) using my own build system (I do not want to use Jam, and I am prepared to put the time into figuring it out). I found something odd in the headers. Freetype defines macros like this: ``` #define FT_CID_H <freetype/ftcid.h> ``` and then uses them later like this: ``` #include FT_CID_H ``` I didn't think that this was possible, and indeed Clang 3.9.1 complains: ``` error: expected "FILENAME" or <FILENAME> #include FT_CID_H ``` * What is the rationale behind these macros? * Is this valid C/C++? * How can I convince Clang to parse these headers? --- This is related to [How to use a macro in an #include directive?](https://stackoverflow.com/questions/40062883/how-to-use-a-macro-in-an-include-directive/40063340#40063340) but different because the question here is about compiling freetype, not writing new code.
2017/03/17
[ "https://Stackoverflow.com/questions/42858048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256041/" ]
I will address your three questions out of order. > > **Question 2** > > > Is this valid C/C++? > > > Yes, this is indeed valid. Macro expansion can be used to produce the final version of a `#include` directive. Quoting C++14 (N4140) [cpp.include] 16.2/4: > > A preprocessing directive of the form > > > > ``` > # include pp-tokens new-line > > ``` > > (that does not match one of the two previous forms) is permitted. The preprocessing tokens after `include` > in the directive are processed just as in normal text (i.e., each identifier currently defined as a macro name is > replaced by its replacement list of preprocessing tokens). If the directive resulting after all replacements does > not match one of the two previous forms, the behavior is undefined. > > > The "previous forms" mentioned are `#include "..."` and `#include <...>`. So yes, it is legal to use a macro which expands to the header/file to include. > > **Question 1** > > > What is the rationale behind these macros? > > > I have no idea, as I've never used the freetype2 library. That would be a question best answered by its support channels or community. > > **Question 3** > > > How can I convince Clang to parse these headers? > > > Since this is legal C++, you shouldn't have to do anything. Indeed, user @Fanael has [demonstrated](https://godbolt.org/g/2DiIL0) that Clang is capable of parsing such code. There must be some problem other problem in your setup or something else you haven't shown.
145,239
If I get a new credit card with $5000 credit line and 0% intro APR for the first year, and use all the credit limit at the beginning, will this drops my credit score? If I pay back this money like $500 per month through 10 months, will I get back all the lost scores? Can I even build credit( I mean improve my credit score) by doing this? (Although my reason for doing this is needing a 0% loan at the moment, but I also like to prevent my credit score too).
2021/09/27
[ "https://money.stackexchange.com/questions/145239", "https://money.stackexchange.com", "https://money.stackexchange.com/users/-1/" ]
Credit scores aren't that deterministic. There are lots of factors that go into your score, and it's impossible to be certain how a single action (other than missing a payment) will affect your credit. In general, though, opening a new account and maxing it out will reduce your credit score, but it will go back up over time so long as you pay down the balance and do not miss any payments. It may no to go back *completely*, but a good payment history, which is the main factor in your credit score, should have a positive impact. However, I'd make sure you understand the *reason* for "needing a 0% loan". Are you spending more than you make? If you have an unexpected expense like a medical bill - can you negotiate with the provider for a payment plan or a reduction in the total bill? Do you have a realistic plan to pay everything back before the intro rate runs out that doesn't require any lucky breaks? It's very important to have a firm control over your finances before trying to use credit cards as "loans". It doesn't take much as all to go from "free money" (or miles) to crushing credit card debt.
5,706,173
Yesterday I programmed a small piece code in C++ which contains a loop and an array. In the program I need to reset the array every time the loop starts over. However, if I use ``` memset(sum,sizeof(sum),0); ``` Then the array won't be reset to all 0. For this program I used: ``` for (i=0;i<sizeof(sum)/sizeof(int);i++) sum[i]=0; ``` instead. However, I think a loop is not as clear as a function, and it requires an additional variable, not to mention this is a million times uncool than the wizardry of memset() function. Could you guys enlighten me on this?
2011/04/18
[ "https://Stackoverflow.com/questions/5706173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/688653/" ]
You're actually writing the size of sum into the 0 first bytes. You should be doing `memset(sum,0,sizeof(sum))` instead. (In other words, the arguments are *target*, *data* and *length* and you provided data and length in the wrong order.)
163,969
Given a string of printable ASCII text (including newlines and spaces) that contains at least one character that is neither a newline nor a space, output a truthy value if the string is rectangular, and a falsey value otherwise. **Additionally, the source code for your solution must be rectangular**. A string is rectangular if it meets all of the following conditions: 1. The first line and the last line contain no spaces. 2. The first and last character of each line is not a space. 3. All lines have the same number of characters. For example, the following text is rectangular: ``` abcd e fg hijk ``` This text, however, is not rectangular (requirement #3): ``` 1234 567 8900 ``` Test Cases ---------- Truthy: ``` sdghajksfg ``` ``` asdf jkl; ``` ``` qwerty u i op zxcvbn ``` ``` 1234 5 6 7890 ``` ``` abcd e fg hijk ``` Falsey: ``` a b c ``` ``` 123 456 7 9 ``` ``` 12 345 ``` ``` qwerty uiop zxcvnm ``` ``` 1234 567 8900 ``` --- This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest solution in bytes wins.
2018/05/02
[ "https://codegolf.stackexchange.com/questions/163969", "https://codegolf.stackexchange.com", "https://codegolf.stackexchange.com/users/-1/" ]
[C (gcc)](https://gcc.gnu.org/), ~~127~~ ~~125~~ ~~124~~ 118 bytes ================================================================== * Saved two bytes by golfing `r*=!e&(!t|t==c);` to `r>>=e||t&&t-c;`. *(This golf was the inspiration for my recent C tips answer [Inverse flag update](https://codegolf.stackexchange.com/a/164010/73111).)* * Saved a byte by golfing `*(_-2)` to `_[~1]`. * Saved six bytes by golfing `*_++-10||(...)` to `*_++<11?...:0` and utilizing the placeholder zero `...:0` (which is not used constructively) to golf the `c++` increment. Those golfs allowed some further loop reshuffling. * When one can use multiple falsey values, [114 bytes](https://tio.run/##hZDrbsIwDIV/b0@RVVqV9CK1tIWxEvEgyxS1ISmFYVgadiPs1UurDWlMWif5hyV/xz4@IqyEaFsdyEAEJudYLAvtcXJQW401NVTQKPd4V74/i@O59umNcV3cDQJJrPX4LEksf/iMH/vGmlAEgkoa3QvfJx4Pk5G1WNKY5NpS2QGu2zH5sd0UNWByuL7a6RqMwo5Bc3S7YOAEiGOnWVTLYrVuVOUQkv9FFc1CMVitn/Ih6vlVavPOYI9qtN0x@HgTLyUMKeJRkjLIEBozmNxNo0EPpeh6iVTFYFmv1t/s3jTYcX7K1KUMlUhc7lW/PTBIs94Bmg6DDJI0G0LOCaB9fQ4ANv8c7wMYTxh073/9f2xP) could be possible. ```c r,e,c,t;_(char*_){for(r=1,t=c=0;*_;*_++<11?r*=(t||(t=c,!e))&*_>32&_[~1]>32&t==c,c=e=0:c++)*_-32||(e=1);r>>=e||t&&t-c;} ``` [Try it online!](https://tio.run/##hZDrTsMwDIV/w1OESlRJm0pruwsjpHsQgqIuS7puzBtpxm0dr15awSSGRJH8w5K/Yx8fFRVKNY2lmirqmMRqmdtAkoPZWmx5TB1XfMAC2VYY3sXxzAYcu7rG7YBeaUL8QGZp4sv7j/ihaxxvB4prPrhVYUgCGaVJi2seE2azjOu6dr7vIsWOzSYvAZPD5cXOluAM9hyaoeuFAI8iib1qUSzz1boyhUcI@4vKq4URsFo/sj7q6UVb9yZgj0q03Ql4f1XPc@hTxEk6FDBCaCxgcjMd9HqYq7bXyBQCluVq/c3uXYU976fMnMvQHKnzvea3BwHDUecATftBAelw1IecEkD78hQAbP453gUwngho3//6/9h8Ag "C (gcc) – Try It Online") *[Source layout achieving a taller rectangle.](https://tio.run/##hZDrboJAEIV/l6fYkpTscokiqLV09UG6zQaWXUTraJelN9FXp5jWpDYpTebHJPOdmTNHBIUQbat96QvfJByLZapdTvZqq7GmoW@ooMPE5V153r0VhgvtUmyaBncT/1oS4rh8Ho0c/nAMH0@Nod3AElTS4Z3wPOLyIBp1vKQhSfR8TmXTGMcxgUgOg0G7SUvAZG9d7XQJRmHboAW6yRnYPuLYrvJima7WlSpsQpK/qLTKFYPV@inpo55fpTbvDGpUou2OwcebeMmgTxGOopjBGKEJg@ntbNjrIRNdL5EqGCzL1fqbrU2FbfunTF3KUIbE5V712wODeHxygGb9IIMoHvch5wRQXZ4DgM0/x08BTKYMuve//j@0nw)* Explanation =========== *The following explains the 124 bytes long version.* ```c r,e,c,t;_(char*_){ // `r` is the boolean result flag, `e` a boolean flag if the current line contains // a space, `t` the first line's width, `c` the current line's current width for(r=1,t=c=0;*_;c++) // initialize, loop through entire string *_-32|| // if the current char is a space, (e=1), // the current line contains a space *_++-10|| // if the current char is a newline (char pointer `_` now incremented) (r*=(t||(t=c,!e)) // if t is not yet set, the current line is the first line; set it // to this line's length, check that no spaces where found &*_>32 // the next line's first char should not be a space &_[~1]>32 // this line's last char should not have been a space &t==c,c=~0,e=0); // the line lengths should match, reset `c` and `e` to zero // (`~0 == -1`, countering the loop's increment of `c`) r>>=e||t&&t-c;} // return boolean flag, check that the last line does not contain spaces, // there was either no newline or line lengths match // (here) equivalent to `r*=!e&(!t|t==c)` ``` [Try it online!](https://tio.run/##hVPbcpswEH1uvmLjmbpg44kd59IMQ/ohpQOyWEAxlhwh4lzc/Lq7ku04xAnlCdDu2XNZ8VHB@WajAwx4YMLE4yXTg8R/AfucnUGqUxA1mBJhplSFTILGuqkM5BUrAkgxBfZ2ZP@ByF05b7RGaaASkj6UNEzI@gQ@f2gSwdRLxpEwTeoQcqHrbf@PGlYiMyWd8fQInU73n67qBHKlPR1NAhPxaBwOkpAPh74dIqQwglXimcZUSi0JS6umKIGahUaojRayIJaDZDQ9X6@PWH4QZ@2y/uy5W30eRhM/ONb3pSn7bjd2OBxNxu3BXWMlrhyWCw6WSkiDGtIkBalWJJdrXFAHZr6jpgeRZ9Zrj4wJTtH3D@gWTioDT2igRhMc092twSGV0BaCMF2hGkVN1LnLqUJZ2Bh5iXxOJ8zQ0K16irhEiiBXjcwcZH@Q3E7PP0JaDhIf36Lf8nHy61I1VeZkzPCdqwSV/H6d/GmhOah3zNgnKCV7oL1HlG0wE5F9PHodBxiN/fDAy/m01VjvcRbMcFJMt4bMsuvLZOauDVnzjFp1ueelr2OIIhhNUvKMjKFwaT@3s2h9ifdbxKByC08569vbCNdr0@@bEQ//HvA0mkbL1m1tReFg2S5dyBRuV2K3p7uYgs64XYQrVgMK@27T3a@o0m1/nDGd6i2YD3jfiAdWWYlkWUorfIp979SsbQx@ulkQN89/Ofm2JG9M7vUM/ILvWSx7ASRer86Kkt3N67zo@X74VRWrszyWd/Mq7Kq6X6E2T7FsQIBaxvL5kT/MZFfH5Hx6EctLgKtYXv@8GXdymHF6pxtQxLIUd/NdbWNqr9d735a322AGvI2bf@QQy4tLywBuugtjOb247CrZOwCN2BsgF/8Zbg24uo4lyd/q/7v5Bw "C (gcc) – Try It Online")
28,249,695
I am trying to code a little game and therefore trying to move an object in a certain area. To get somewhat of a border I am trying to add up positions. However I will simplify this for you and this is what does not work: (in JS) ``` parseInt( $('#w'+w ).css( 'top' ) + $('#w'+w ).css( 'height' ) ) ``` this should just add up the top position with the height of this element. When I print this out it will tell me it is 100. But when I print height and top without adding them up its height = 500 and top = 100 ( This is how it is in the css code ). If i swap height and top and add this up the result is 500, so the first element. I got similar calculations, which fit. Any suggestions what went wrong in my code?
2015/01/31
[ "https://Stackoverflow.com/questions/28249695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3913490/" ]
[JSON.parse()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) might be what you're looking for if you have a way to get that JSON string. Something like.. ``` var data = '{"gold":"or not", "mine":"or hot", "Paris":"i hate one"}'; var object = JSON.parse(data); console.log(object.Paris); ```
2,959,118
I've got an input like so: I'd like to use jQuery to grab that element, and add the function call foo() to the change event. Currently I can get it done, but there are two hacks involved. My (working) code: ``` $(":input[name*=myfield]").change( function( $(":input[name*=myfield]") ) { foo(); }); )}; ``` There are two hacks in there I'd like to eliminate. 1. Keeping in mind that the input names are multidimensional arrays, how can I use the :input[name=somename], versus [name\*=someone]? I'd imagine it's faster using an exact name rather than \*=, but I can't get the escape sequence correct for the brackets on the multidimensional arrays. 2. Can I chain the call together so that I don't have to select the element twice? Is the standard practice for that to select the HTML element into a var, then use that var? Or can I chain it together? Thanks for the help. Still working on getting my footing in JS/JQ.
2010/06/02
[ "https://Stackoverflow.com/questions/2959118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40707/" ]
1 - to escape brackets and other meta-characters, use `\\[`. See [Selectors](http://api.jquery.com/category/selectors/). 2 - `$(":input[name*=myfield]").change(foo);`
5,728,750
This fiddle aligns vertically in FFOX4, IE8 but the label text appears slighlty out of line in IE7. <http://jsfiddle.net/6hQ8e/1/> Is there any way to fix this other than with hacks/conditional CSS?
2011/04/20
[ "https://Stackoverflow.com/questions/5728750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256077/" ]
Remove this line from your CSS: ``` .selection label{padding:0; width:auto; vertical-align:bottom;} ``` And replace with the following CSS: ``` .selection label{float: none; padding:0; width:auto; vertical-align:middle;} .selection input{float: none} ```
941,146
Some data is displayed in a datagridview (Winform). I have a requirement to mail the table represented in the datagridview in a similar format (Rows, Columns etc). What is the easiest was I can do it? How to convert that to html table with Column headers and preserving the column width.
2009/06/02
[ "https://Stackoverflow.com/questions/941146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87968/" ]
I don't know if there is any framework level conversion that can take place. But it should be a pretty simple matter to iterate through the grids rows, and cells, and recreate it in HTML with the Width's in place. *Written off the cuff, please excuse its incompleteness and any simple mistakes, but I think you can get the basic idea here.* ``` StringBuilder sb = new SringBuilder(); sb.AppendLine("<table>"); sb.AppendLine(" <tr>"); foreach(DataGridViewColumn column in grid.Columns) { sb.AppendLine(" <td>" + column.HeaderText + "</td>"); } sb.AppendLine(" </tr>"); foreach(DataGridViewRow row in grid.Rows) { sb.AppendLine(" <tr>"); foreach(DataGridViewCell cell in row.Cells) { sb.AppendLine(" <td width=\"" + cell.Width + "px\">" + cell.Value + "</td>"); } sb.AppendLine(" </tr>"); } sb.AppendLine("</table>"); ```
1,980
Is it possible for non-mods to initiate tag synonym requests?
2018/02/15
[ "https://mechanics.meta.stackexchange.com/questions/1980", "https://mechanics.meta.stackexchange.com", "https://mechanics.meta.stackexchange.com/users/675/" ]
April 2018 ========== Done in March ------------- **Responsive design pt2:** Speced out the changes for Ask a Question experience. Implemented search, tags and users pages. Also, worked out how what adjustments need to be made to support ads with our responsive design. **OpenID deprecation:** [Announced the deprecation plan](https://meta.stackexchange.com/questions/307647/support-for-openid-ends-on-july-1-2018). Removed the ability to create new accounts with external OpenID providers (Yahoo, AOL, Blogger, Live Journal and Steam). Added the ability for existing users to add email/pw login option for their current account. Fleshed out the rest of the plan through July end of support date. **Teams features:** We rolled out a number of improvements for our Teams alpha users including improvements for tags, emails, new question notification, and team newsletter prefs. **Quack Overflow:** April Fools has come and gone, but Quack Overflow will live on in our hearts and this [Rubber Ducking Wikipedia page](https://en.wikipedia.org/wiki/Rubber_duck_debugging) (thanks for whoever did that!). **Top bar for Enterprise customers:** Moved the SO top bar to Stack Overflow for Enterprise. **Sponsorship pilot:** DAG provided support for the [sponsorship pilot](https://meta.stackexchange.com/questions/307861/sponsorship-pilot-bringing-resources-back-to-stack-exchange) that was announced last month. --- In progress ----------- **Responsive design pt3:** Implementing Ask a Question page and support for ads. Fixing lots of bugs. Target is to release to Teams users. **Tag subscriptions:** We are almost done with this work for Teams, really. Should launch to team's users real soon now. This month we will begin making sure it will scale to SO.com. **Custom question lists** (aka Custom favorite searches): Finished spec and designs for adding support for filter and sort controls to all question lists and the ability to save custom question list views. Ran user testing on the designs. All clear to start implementation. Goal is to reintroduce some form of the functionality that used to be called [New Nav](https://meta.stackoverflow.com/questions/359643/retiring-new-navigation-beta-in-preparation-for-navigation-3-0/360311#360311). **User satisfaction survey:** Understanding user satisfaction levels based on quarterly user satisfaction survey is an important data point for most sites. In the past we have relied exclusively on anecdotal feedback to evaluate satisfaction. This month we will be building an automated system to randomly select users and prompt them via email to fill out a survey. This system will be tested on Teams alpha users and will be expanded to others over time. --- Starting in April ----------------- *Each of the items below describes some work that is planned for the coming month. As needed, we will directly engage the community to help shape the work.* **Network site themes:** As mentioned in the [ch-ch-ch-changes post](https://meta.stackexchange.com/questions/307862/ch-ch-ch-changes-left-nav-responsive-design-themes) we are simplifying our themes. Goal for this month is to get the infrastructure plugged in, design themes for 10+ of our most highly themed/highly traffic sites, gather feedback from those communities and lock down the roll out plan for the May/June. **Teams features:** TeamDAG continues to add a bunch of features for Teams including Left nav improvements, inline mentions, testing automation, a ton of clean up items and Teams product page/launch support. **AaQ dupe finder/question wizard:** We made limited progress on this front, but things are picking up steam and we are planning to have a prototype ready for community feedback this month.
3,057,498
If I am going to use the code: ``` extract( array( 'key.name' => 'value', 'somekey' => 'somevalue' ) ) ``` Is there some way for me to retrieve the first value? E.g. `${'key.name'}` or similar. I know I can retrieve the second value with `$somekey` but I am curious if its possible with `.` in the name.
2010/06/16
[ "https://Stackoverflow.com/questions/3057498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/291809/" ]
<http://nl.php.net/manual/en/function.extract.php> > > Checks each key to see whether it has a valid variable name. > > > Nope, it won't extract 'key.name'. You can inspect the $GLOBALS array to see it isn't there.
13,606,582
I tried this solution: ``` iptables -I OUTPUT -p tcp --dport 2195 -j ACCEPT /etc/init.d/iptables stop /etc/init.d/iptables start ``` but still can't access the port. If there are more ports that I have to open for APNS let me know.
2012/11/28
[ "https://Stackoverflow.com/questions/13606582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432497/" ]
How about: ``` iptables -A INPUT -p tcp --dport 2195 -j ACCEPT service iptables restart ``` [This](https://serverfault.com/questions/148781/unable-to-connect-to-apns-with-java-apns) may help too.
12,835,884
I have two dates and want to find number of days including both dates, I tried something like this: ``` select datediff("d", '10/11/2012', '10/12/2012') ``` It is showing 1, but I want the result as 2 because we have 2 days 11 and 12.
2012/10/11
[ "https://Stackoverflow.com/questions/12835884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/949995/" ]
The latest version of SQL introduced support for adding integers! Yay. ``` select datediff("d", '10/11/2012', '10/12/2012') + 1 ^^^^^ ```
8,356,641
Android version 2.2+ Is there any way that I can still get the values from the acceleration sensor even after the screen is turned off (I already made my program as an activity)? When the screen-on is timeout, I will release the wake lock that I used to wake up the phone (to turn the screen on) Note: When I tried my program in the debugging mode (connected to my computer), it worked fine. P/s: There is one funny thing, when I tried my program on my sony arc s (stock rom 2.3.4), it stopped sending values from acc sensor after about 10 minutes, but in my friend's phone, he uses cooked rom Cyanogenmod 7, it stopped sending immediately after the screen had turned off. This made me wonder that would android have shallow sleep mode and deep sleep mode. I assumed that in shallow sleep mode, all activities would be able to run normally, but in deep sleep mode, only system activities could run. Am I right? Thank you!
2011/12/02
[ "https://Stackoverflow.com/questions/8356641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/552279/" ]
You can use [Injector.createChildInjector](https://google.github.io/guice/api-docs/latest/javadoc/com/google/inject/Injector.html#createChildInjector-com.google.inject.Module...-): ``` // bind shared singletons here Injector parent = Guice.createInjector(new MySharedSingletonsModule()); // create new injectors that share singletons Injector i1 = parent.createChildInjector(new MyModule1(), new MyModule2()); Injector i2 = parent.createChildInjector(new MyModule3(), new MyModule4()); // now injectors i1 and i2 share all the bindings of parent ```
7,439,525
**Issue**: In ASP.NET 4.0, I use my SSRS 2005 server's `ReportService2005.asmx` web service to get a list of reports. Also in .NET, I use Entity Framework to communicate with my MS-SQL 2005 database. When I use Visual Studio Development Server as my web server, calls to SSRS and SQL work fine. But when I switch to IIS 5.1, both SSRS and Entity code produce errors. I use *only* Windows/Integrated Authentication in IIS. **Errors**: For SSRS, I get `The request failed with HTTP status 401: Unauthorized.` For Entity Framework, I get `Login failed for user ''. The user is not associated with a trusted SQL Server connection.` **Attempted Solutions**: In the Web.Config I added `<identity impersonate="true" />` and that fixed Entity Framework errors but not SSRS errors. I expanded the `identity` reference to include *my* username and password, and that fixed all errors. **Question**: Why does specifying my username and password fix the errors, and why does SQL say I am not specifying a username (`''`)? I thought Windows Authentication automatically impersonated the current user. How can I fix this without hardcoding a "service" account into the web.config?
2011/09/16
[ "https://Stackoverflow.com/questions/7439525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489560/" ]
Windows or Integrated authentication means that user is identified using windows credentials (or token) but it does not means that the request in running under that user. ASP.NET run-time will execute the request under worker process (App Pool) identity unless you configure it to impersonate some other identity. So when you are accessing the site using development server, the server is running under your identity and so access to SSRS and Sql Server is done under your identity and it works. When you loaded your site under IIS, ASP.NET request would be run under whatever identity is configured for the application pool. Typically this identity is local user and hence access to network resources such as SSRS or Sql Server would be denied. Adding `<identity impersonate="true" username="your name" ../>`, ASP.NET will run requests under your identity and that should work for both SSRS and Sql Server. The curious case here is `<identity impersonate="true" />` - under this setting, ASP.NET will impersonate currently authenticated windows identity. However, for this to work correctly, you have configure both IIS and ASP.NET on integrated authentication and deny anonymous access (in ASP.NET as well as IIS). Failing to do so may result in not authenticating current user's identity and the request would be run under anonymous user's identity (as configured in IIS). If you marked integrated authentication in IIS but not in ASP.NET then identity would not be passed to the ASP.NET request. You need to check your environment to see what exact scenario you had faced but ultimate result was your ASP.NET request was running under credential that has access to SQL Server but not to SSRS.
3,832,964
How do you call `operator<<(std::ostream &os, const ClassX &x)` from inside gdb ? In other words, how do you print an object in gdb ? `call std::cout<<x` or `call operator<<(std::cout, x)` don't seems to work for me! Any ideas?
2010/09/30
[ "https://Stackoverflow.com/questions/3832964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38924/" ]
The only way I found was this: ``` call 'operator<<(std::ostream&, myclass&)'(mycout, c) ``` Since `std::cout` wasn't visible to gdb for some reason, I had to resort to creating my own like this: ``` std::ostream mycout(std::cout.rdbuf()); ``` You haven't stated any reasons for wanting to do this but won't `print yourvariable` be easier? If this is an absolute must you could have a `Print` method in your class and call that from `operator<<` and then call the `Print` method on your object from gdb. Do take note that stdout is probably buffered in gdb so you won't be seeing any output unless you redirect it somehow. See [this](http://sourceware.org/ml/gdb/2006-08/msg00237.html) discussion from gdb's mailing archive regarding this issue.
62,525,495
I need to have a SQL query added on to my `IQueryable` in the Azure Mobile App Service backend table controller. I need the `ItemLibrary` table to have a default query as shown. And either replace the `return Query()` that is part of the default table controller or merge it with it. This is what I need to do for the `GetAllItemLibraries` but I can't get it to work: ``` public class ItemLibraryController : TableController<ItemLibrary> { protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); MIIToolsContext context = new MIIToolsContext(); DomainManager = new EntityDomainManager<ItemLibrary>(context, Request, enableSoftDelete: true); } // GET tables/ItemLibrary public IQueryable<ItemLibrary> GetAllItemLibraries() { using (MIIToolsContext context = new MIIToolsContext()) { string sqlQueryString = "SELECT * FROM dbo.ItemSpecification WHERE Id IN (SELECT DISTINCT EquipmentItemID FROM dbo.SiteEquipment WHERE EquipmentSiteID = '8FA79274-C5CC-4610-9D6E-A7062D3CE966')"; string test = "SELECT TOP 10 * FROM dbo.ItemSpecification"; return context.ItemLibrary.SqlQuery(sqlQueryString).AsQueryable(); // return context.ItemLibrary.SqlQuery(test).AsQueryable(); } // possibly merge the SQL IQueryable with the default query? // Query.Union([sqlquery]) // default query // return Query(); } } ``` I could do the query in Linq and not SQL, but I have no idea how to reference the `SiteEquipment` table from the context of the `ItemLibrary` table controller. I need that to be the default query but still have it tack on any OData from a client. For those of you who don't know anything about Azure Mobile App Service and want to comment here is an example of the out of the box default table controller wrapper: ``` public class ExampleController : TableController<Example> { protected override void Initialize(HttpControllerContext controllerContext) { base.Initialize(controllerContext); MobileServiceContext context = new MobileServiceContext(); DomainManager = new EntityDomainManager<Example>(context, Request, enableSoftDelete: true); } // GET tables/Example public IQueryable<Example> GetAllExample() { return Query(); } // GET tables/Example/48D68C86-6EA6-4C25-AA33-223FC9A27959 public SingleResult<Example> GetExample(string id) { return Lookup(id); } // PATCH tables/Example/48D68C86-6EA6-4C25-AA33-223FC9A27959 public Task<Example> PatchExample(string id, Delta<Example> patch) { return UpdateAsync(id, patch); } // POST tables/Example public async Task<IHttpActionResult> PostExample(Example item) { Example current = await InsertAsync(item); return CreatedAtRoute("Tables", new { id = current.Id }, current); } // DELETE tables/Example/48D68C86-6EA6-4C25-AA33-223FC9A27959 public Task DeleteExample(string id) { return DeleteAsync(id); } } ```
2020/06/23
[ "https://Stackoverflow.com/questions/62525495", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9199404/" ]
I am working on a similar project and got the same error. I catched Exceptions and print the traceback ``` import traceback ... try: with youtube_dl.YoutubeDL(self.ydl_opts) as ydl: ydl.download([self.url]) except Exception as inst: print(inst) tb = traceback.format_exc() print(tb) pass ``` and I got this : ``` 'str' object has no attribute 'write' Traceback (most recent call last): File "/home/odrevet/.local/lib/python3.6/site-packages/youtube_dl/YoutubeDL.py", line 797, in extract_info ie_result = ie.extract(url) File "/home/odrevet/.local/lib/python3.6/site-packages/youtube_dl/extractor/common.py", line 530, in extract ie_result = self._real_extract(url) File "/home/odrevet/.local/lib/python3.6/site-packages/youtube_dl/extractor/generic.py", line 2277, in _real_extract % (url, url), expected=True) youtube_dl.utils.ExtractorError: 'qsd' is not a valid URL. Set --default-search "ytsearch" (or run youtube-dl "ytsearch:qsd" ) to search YouTube During handling of the above exception, another exception occurred: Traceback (most recent call last): File "src/main.py", line 81, in run download_retcode = ydl.download([self.url]) File "/home/odrevet/.local/lib/python3.6/site-packages/youtube_dl/YoutubeDL.py", line 2019, in download url, force_generic_extractor=self.params.get('force_generic_extractor', False)) File "/home/odrevet/.local/lib/python3.6/site-packages/youtube_dl/YoutubeDL.py", line 820, in extract_info self.report_error(compat_str(e), e.format_traceback()) File "/home/odrevet/.local/lib/python3.6/site-packages/youtube_dl/YoutubeDL.py", line 625, in report_error self.trouble(error_message, tb) File "/home/odrevet/.local/lib/python3.6/site-packages/youtube_dl/YoutubeDL.py", line 578, in trouble self.to_stderr(message) File "/home/odrevet/.local/lib/python3.6/site-packages/youtube_dl/YoutubeDL.py", line 527, in to_stderr self._write_string(output, self._err_file) File "/home/odrevet/.local/lib/python3.6/site-packages/youtube_dl/YoutubeDL.py", line 506, in _write_string write_string(s, out=out, encoding=self.params.get('encoding')) File "/home/odrevet/.local/lib/python3.6/site-packages/youtube_dl/utils.py", line 3180, in write_string out.buffer.write(byt) AttributeError: 'str' object has no attribute 'write' ``` By looking to the function's name in the stack, we can see that our error occure when ytdl try to report another error (in this case : "youtube\_dl.utils.ExtractorError: 'qsd' is not a valid URL", because I entered 'qsd' in my program instead of a valid url). By looking in YoutubeDl.py in the function to\_stderr we can see that out is supposed to be sys.stderr, and in utils.py in the function where the error occure : ``` def write_string(s, out=None, encoding=None): print(type(out)) # I added this line if out is None: out = sys.stderr assert type(s) == compat_str if sys.platform == 'win32' and encoding is None and hasattr(out, 'fileno'): if _windows_write_string(s, out): return if ('b' in getattr(out, 'mode', '') or sys.version_info[0] < 3): # Python 2 lies about mode of sys.stderr byt = s.encode(encoding or preferredencoding(), 'ignore') out.write(byt) elif hasattr(out, 'buffer'): enc = encoding or getattr(out, 'encoding', None) or preferredencoding() byt = s.encode(enc, 'ignore') out.buffer.write(byt) # Error on line 3180 else: out.write(s) out.flush() ``` stderr has a buffer attribute according to the hasattr elif check, the problem is how Kivy is handling the error stream. According to the print I added in write\_string, stderr is redefined as a <class 'kivy.logger.LogFile'> which do have a buffer attribute like the Stream it's supposed to be, but this attribute is a simple String. See <https://kivy.org/doc/stable/_modules/kivy/logger.html> ``` class LogFile(object): def __init__(self, channel, func): self.buffer = '' # <-- a str self.func = func self.channel = channel self.errors = '' ``` I don't known if it's possible to parameter kivy to use standard streams for stderr but I will check. Meanwhile catch the exception and print backtrace to at least have the original error before the "During handling of the above exception, another exception occurred" edit: you can redirect stderr to a file ``` sys.stderr = open('./stderr', 'w') ```
260,736
I do not have experience of Mathematics past a-level, so please excuse the incorrect terminology. I am trying to better understand the fundamentals of how a cubic bezier curve works. I am going by this (parametric?) formula... (I formatted, and labelled to make my point clear) ``` t = time along path r = 1-t a = start co-ordinate b = first handle c = second handle d = end co-ordinate a * r * r * r + b * r * r * t * 3 + c * r * t * t * 3 + d * t * t * t = value of x or y ``` As far as I understand it, the tension passes from t, to r as time passes, so that early points/handles become less influential over time, and late ones increase. I understand that - but what I don't understand is why the value 3 is used. As far as I can see, it would work equally well with any other arbitrary value. I expect that using another value would break the method of calculating points by tracing lines between the points at set intervals, like at `t = 0.25` for example, being able to make a line between ab and bc intersecting at their respective 25% marks, and finding the point at `t = 0.25` of the new line. So, what I want to understand, is the relationship between the number 3, and the ability to calculate the points along the path in said manner.
2012/12/17
[ "https://math.stackexchange.com/questions/260736", "https://math.stackexchange.com", "https://math.stackexchange.com/users/43036/" ]
The value 3 is a consequence of a different method to draw the curve, namely not by converting it to parameter form but rather by recursively refining it. That is, staring from four points $A,B,C,D$ you take successive mid points $E=\frac{A+B}2$, $F=\frac{B+C}2$, $G=\frac{C+D}2$, then midpoints of the midpoints $H=\frac{E+F}2$, $I=\frac{F+G}2$, finally $J=\frac{H+I}2$. Note that taking mid pints is a very simple operation with respect to the coordinates and may require much less precision than drawing the parametric curve. Now the crucial point is the following: The curve determined by the four points $A,B,C,D$ is replaced by two smaller pieces of curve, the first determined by $A,E,H,J$, the other by $J,I,G,D$. Several nice properties are obeyed by this replacement so that the rough shape of the curve can be "predicted": The curve passes through end points ($A$ and $D$ of the original curve, additionally $H$ for the refined curves), the tangents there point towards $B$ resp. $C$. Also, if the quadrangle $ABCD$ is convex, then the curve is contained inside it. Note that the refinement steps will sooner or later produce convex quadrangles and each refinement step from then on will give better and better containment estimates for the curve. Ultimately, it is possible to calculate what the curve described by the above procedure sould look like in parametric form and it turns out that the factor 3 you observed comes into play. In effect, this is the same $3$ as in the binomial formula $(a+b)^3=a^3+3a^2b+3ab^2+b^3$. (Which means that for quadratic Bezier curves you will find a factor of $2$ and for Bezier curves of degree $4$, the numbers $4$ and $6$ will occur etc.
104,060
I'm trying to install packages on GOOGLE COLAB, but I'm facing Import error, I can't import Sub module of my main module 'gym'. [![enter image description here](https://i.stack.imgur.com/Zqz2u.png)](https://i.stack.imgur.com/Zqz2u.png) I done the following things. First I cloned the git hub repository through git command (! git clone <https://github.com/zoraiz-ali/gym.git>) Then I add the directory using sys.path ``` import sys sys.path.append('/content/gym') ``` Code of my setup.py file is given below ``` from setuptools import setup setup( name="gym_robot", version="0.3", url="https://github.com/zoraiz-ali/gym.git", author="Zoraiz Ali", license="MIT", packages=["gym_robot", "gym_robot.envs", "gym_robot.envs.helper", ], include_package_data=True, install_requires=["gym", "numpy", "opencv-python", "pillow"] ) ``` The package works very well on my computer/s. So I'm not sure why I'm not able to use it on Colaboratory. Anyone know the solution please check this.
2021/11/12
[ "https://datascience.stackexchange.com/questions/104060", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/124813/" ]
I think this issue is caused by the fact that your module has the same name as another package, which is the [`gym`](https://pypi.org/project/gym/) package for reinforcement learning environments. This package is automatically installed in the google colab environment, so when you try to import `gym_robot` from `gym` it assumes you want to import it from the existing package instead of your own module. Since the package doesn't have this function/module it will give an import error. Try changing the name of your own module slightly so it doesn't interfere with the existing `gym` package.
26,095,595
Just started with Angular, and I have the following code: ``` <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js"></script> <link rel="stylesheet" href="css/bootstrap.css"> </head> <body ng-app> <p>This is your first angular expression {{1 +- 2}}</p> </body> </html> ``` running in this code in the browser gives me the o/p: ``` This is your first angular expression -1 ``` How come `-` is taking place instead of `+`. In fact I was expecting a error at runtime, but that doesn't. Even though the expression is changed to : ``` {{1 -+ 2}} ``` results in `-1`. `+` and `-` aren't having the same precedence? Edit: ----- Given the expression `{{1 -% 2}}` gives me an error: ``` Error: Syntax Error: Token '2' is an unexpected token at column 6 of the expression [1 -% 2] starting at [2]. at Error (<anonymous>) at throwError (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js:5913:11) at parser (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js:5907:5) at http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js:6470:29 at $interpolate (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js:4807:27) at addTextInterpolateDirective (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js:4436:27) at collectDirectives (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js:3933:11) at compileNodes (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js:3816:22) at compileNodes (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js:3824:15) at compileNodes (http://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js:3824:15) ``` This leaves to me the question, how come `+-` or `-+` is working fine.
2014/09/29
[ "https://Stackoverflow.com/questions/26095595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1500898/" ]
This: ``` 1 +- 2 ``` Is One plus Negative Two. Which is Negative One. It would be better written as `1 + -2`. This: ``` 1 -+ 2 ``` Is One minus the result of converting `2` to a Number (which is Two). This is also Negative One. It would be better written as `1 - +2` This ``` 1 -% 2 ``` Just doesn't make any sense.
741,913
I want to install phpize for PHP7 on Ubuntu 14.0.4 so I am running the following command: `sudo apt-get install php7.0-dev` But I am getting following errors: ``` E: Failed to fetch http://ppa.launchpad.net/ondrej/php-7.0/ubuntu/pool/main/p/php7.0/php7.0-common_7.0.3-5+deb.sury.org~trusty+1_all.deb 404 Not Found E: Failed to fetch http://ppa.launchpad.net/ondrej/php-7.0/ubuntu/pool/main/p/php7.0/php7.0-cli_7.0.3-5+deb.sury.org~trusty+1_amd64.deb 404 Not Found E: Failed to fetch http://ppa.launchpad.net/ondrej/php-7.0/ubuntu/pool/main/p/php-pear/php-pear_1.10.1+submodules+notgz-3+deb.sury.org~trusty+3_all.deb 404 Not Found E: Failed to fetch http://ppa.launchpad.net/ondrej/php-7.0/ubuntu/pool/main/p/php7.0/php7.0-dev_7.0.3-5+deb.sury.org~trusty+1_amd64.deb 404 Not Found E: Failed to fetch http://ppa.launchpad.net/ondrej/php-7.0/ubuntu/pool/main/d/dh-php/dh-php_0.6+deb.sury.org~trusty+1_all.deb 404 Not Found E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing? ``` Any ideas as to how can i fix these errors ?
2016/03/04
[ "https://askubuntu.com/questions/741913", "https://askubuntu.com", "https://askubuntu.com/users/479882/" ]
You are using an obsolete PPA: **ondrej/php-7.0** Use **ppa:ondrej/php** Instead First disable the obsolete PPA and reverts to official packages ``` sudo apt-get install python-software-properties sudo ppa-purge ppa:ondrej/php-7.0 ``` Then ``` sudo add-apt-repository ppa:ondrej/php sudo apt-get install php7.0-dev ```
21,009,631
Here is my code for my actionbar: ``` <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/actionBarNew" android:showAsAction="always" android:scaleType="fitXY" android:title="new" /> <item android:id="@+id/actionBarSave" android:showAsAction="always" android:scaleType="fitXY" android:title="save" /> <item android:id="@+id/actionBarLoad" android:showAsAction="always" android:scaleType="fitXY" android:title="load" /> <item android:id="@+id/actionBarDelete" android:showAsAction="always" android:scaleType="fitXY" android:title="delete" /> </menu> ``` Then in my **onCreate()** method, I add the switch widget like so: ``` ActionBar actionBar = getActionBar(); actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM, ActionBar.DISPLAY_SHOW_CUSTOM); actionBar.setCustomView(actionBarSwitch, new ActionBar.LayoutParams( ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, Gravity.CENTER_VERTICAL | Gravity.END)); actionBar.setTitle(title); actionBarSwitch.setText(sfx); actionBarSwitch.setTextColor(res.getColor(R.color.white)); actionBarSwitch.setChecked(soundOn); actionBarSwitch.setOnCheckedChangeListener(this); ``` Here is what it looks like at the moment: ![enter image description here](https://i.stack.imgur.com/FwhAb.jpg) As you can see, the switch widget on the left is covered up. It is supposed to say "SFX" on the left of it but it doesnt fit. Is there any way to keep the icon and all the other action bar icons visible? Maybe scale to fit or something? Any help is appreciated, thanks.
2014/01/09
[ "https://Stackoverflow.com/questions/21009631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2155605/" ]
> > Here is my code for my actionbar > > > I do not believe that `android:scaleType` is a recognized attribute for a `MenuItem`. > > Is there any way to keep the icon and all the other action bar icons visible? > > > [Use the split action bar](http://developer.android.com/guide/topics/ui/actionbar.html#SplitBar), to move your action bar items (NEW, etc.) to the bottom of the screen on narrow devices. > > Maybe scale to fit or something? > > > While you are welcome to attempt to use view properties to scale the size of your `Switch`, there is no guarantee that there is enough room to have a usable `Switch` when you're done. You do not have control over scaling of the regular action bar items.
44,718,744
``` package stringsplit; public class StringSplit { public static void main(String[] args) { String s = "hello world we are anonymous "; String[] s3 = s.split("\\s",2); for(String temp:s3){ System.out.println(temp); } } } ``` **O/P:** ``` hello world we are anonymous ``` The above code splits my string into two parts after 1 space character is encountered by compiler.I then introduced **'\\s+'** so as to split after 2 space characters to get **o/p:** ``` hello world we are anonymous ``` But it didn't work.Thanks for you guidance in advanced.
2017/06/23
[ "https://Stackoverflow.com/questions/44718744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6149509/" ]
According javadoc String [split(regex)](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)) and [split(regex, limit)](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)) work like expected. Depending on result you're trying to achieve you can use something of these below: ```java String s = "hello world we are anonymous"; String[] s1 = s.split("\\s",2); //result is ["Hello", " world we are anonymous"] String[] s2 = s.split("\\s+",2); //result is ["Hello", "world we are anonymous"] String[] s3 = s.split("\\s+",3); //result is ["Hello", "world", "we are anonymous"] String[] s4 = s.split("\\s+"); //result is ["Hello", "world", "we", "are", "anonymous"] ```
172,240
**Magento ver. 1.9.3.2** C:\xampp\htdocs\magento1\app\code\local\Maddy\Checkout\etc\config.xml ``` <?xml version="1.0"?> <config> <modules> <Maddy_Checkout> <version>0.0.1</version> </Maddy_Checkout> </modules> <global> <models> <maddy> <class>Maddy_Checkout_Model</class> </maddy> <events> <sales_order_place_after> <observers> <maddy_sendsms> <class>Maddy_Checkout_Model_Observer</class> <method>orderSms</method> <type>singleton</type> </maddy_sendsms> </observers> </sales_order_place_after> </events> </global> </config> ``` C:\xampp\htdocs\magento1\app\code\local\Maddy\Checkout\Model\Observer.php ``` <?php class Maddy_Checkout_Model_Observer { public function orderSms(Varien_Event_Observer $observer) { $incrementId = $observer->getEvent()->getOrder()->getIncrementId(); $custName = $observer->getEvent()->getOrder()->getCustomerFirstname(); $orderPrice = $observer->getEvent()->getOrder()->getGrandTotal(); $orderId = $observer->getEvent()->getOrder()->getId(); $order = $observer->getEvent()->getOrder() $mobile = trim($order->getShippingAddress()->getData('telephone')); echo "I am here"; die; /* I will write sms api here */ echo "Mobile" . $mobile; echo "<script>alert('Just to check')</script>"; } } ``` C:\xampp\htdocs\magento1\app\etc\modules\Maddy\_Checkout.xml ``` <?xml version="1.0"?> <config> <modules> <Maddy_Checkout> <active>true</active> <codePool>local</codePool> </Maddy_Checkout> </modules> </config> ``` When order is placed no alert is shown. UPDATE: if I use event based trigger I am not able to do add to cart. If I delete this module g then add cart is working.There is no log for this. **UPDATE:1.1** After creating some observers i am came to know that never echo any thing directly in observers , even dump in log to see the output. It will not break the functionality than.
2017/04/28
[ "https://magento.stackexchange.com/questions/172240", "https://magento.stackexchange.com", "https://magento.stackexchange.com/users/51834/" ]
Try below code app/etc/Modules/Maddy\_Checkout.xml ``` <?xml version="1.0"?> <config> <modules> <Maddy_Checkout> <active>true</active> <codePool>local</codePool> </Maddy_Checkout> </modules> </config> ``` app/code/local/Maddy/Checkout/etc/config.xml ``` <?xml version="1.0"?> <config> <modules> <Maddy_Checkout> <version>0.0.1</version> </Maddy_Checkout> </modules> <global> <models> <maddy> <class>Maddy_Checkout_Model</class> </maddy> </models> <events> <sales_order_place_after> <observers> <maddy_sendsms> <class>Maddy_Checkout_Model_Observer</class> <method>orderSms</method> <type>singleton</type> </maddy_sendsms> </observers> </sales_order_place_after> </events> </global> </config> ``` app/code/local/Maddy/Checkout/Model/Observer.php ``` <?php class Maddy_Checkout_Model_Observer { public function orderSms(Varien_Event_Observer $observer) { $order = $observer->getEvent()->getOrder(); echo $incrementId = $order->getIncrementId(); echo $custName = $order->getCustomerFirstname(); echo $orderPrice = $order->getGrandTotal(); echo $orderId = $order->getId(); echo $mobile = trim($order->getShippingAddress()->getData('telephone')); echo "I am here"; die; } } ```
36,421,291
I'm trying to reorder a 2D array with for loops. The first generateSong() method creates the array with random doubles and works fine. Then I have the simulateSong() method. Its purpose is to take the rows from the generateSong() array and reprint them as columns, starting with the bottom one. ``` import java.util.concurrent.ThreadLocalRandom; public class Guitar { private int strings; private int chords; private double[][] song; public Guitar(int mstrings, int mchords) { this.strings = mstrings; this.chords = mchords; song = new double[mstrings][mchords]; } public void generateSong() { for (int i = 0; i < song.length; i++) { for (int j = 0; j < song[i].length; j++) { song[i][j] = ThreadLocalRandom.current().nextDouble(27.5, 4186); System.out.printf(" %.2f",song[i][j]); } System.out.println(); } } public void simulateSong() throws InterruptedException { System.out.println("\nGuitar.simualateSong() "); for(int i = song.length-1; i >= 0; i--) { for(int j = song[i].length-1; j >= 0; j--) { song[i][j] = song[i][0]; System.out.printf(" %.2f",song[i][j]); } System.out.println(); } } } ``` The number of rows and columns are set by command line arguments in the main method. ``` public class Songwriter { public static void main(String[] args) throws InterruptedException { System.out.println("Guitar(): Generated new guitar with " + args[0] + " strings. Song length is " + args[1] + " chords."); String args0 = args[0]; int strings = Integer.parseInt(args0); String args1 = args[1]; int chords = Integer.parseInt(args1); Guitar guitarObj1 = new Guitar(strings, chords); guitarObj1.generateSong(); guitarObj1.simulateSong(); } } ``` So ultimately what I'm trying to do is make it so that the rows originally read left to right are now read as columns from top to bottom. Here's the intended output with 3 rows and 4 columns set as command line arguments. ``` Guitar(): Generated new guitar with 3 strings. Song length is 4 chords. 2538.83 2269.30 1128.09 3419.77 2356.74 2530.88 2466.83 3025.77 3898.32 3804.22 3613.94 337.93 Guitar.simualateSong() 3898.32 2356.74 2538.83 3804.22 2530.88 2269.30 3613.94 2466.83 1128.09 337.93 3025.77 3419.77 ``` And with the code that I currently have this is the output I'm getting. ``` Guitar.simualateSong() 3898.32 3898.32 3898.32 3898.32 2356.74 2356.74 2356.74 2356.74 2538.83 2538.83 2538.83 2538.83 ``` I know that the only problem(s) lie in the for loops of the simulateSong() method. As you can see my output is close, but no cigar.
2016/04/05
[ "https://Stackoverflow.com/questions/36421291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6159040/" ]
if i understand you right it should be something like this... ``` public void simulateSong() { System.out.println("\nGuitar.simualateSong() "); for (int i = 0; i < chords; i++) { for (int j = 0; j < strings; j++) { System.out.printf(" %.2f", song[j][i]); } System.out.println(); } } ``` generateSong makes something like > > A1 A2 A3 A4 > > B1 B2 B3 B4 > > C1 C2 C3 C4 > > > simulateSong makes something like > > A1 B1 C1 > > A2 B2 C2 > > A3 B3 C3 > > A4 B4 C4 > > >
330,826
In a book the following sentence is told about probability density function at point $a$: "it is a measure of how likely it is that the random variable will be near $a$." What is the meaning of this ?
2013/03/15
[ "https://math.stackexchange.com/questions/330826", "https://math.stackexchange.com", "https://math.stackexchange.com/users/-1/" ]
It is not a meaningful sentence. For a continuous random variable, the value of the probability density function (pdf) at a point tells us nothing about the probability that the random variable lies near that point. This is because the random variable is continuous, so the probability that it evaluates to any given point is of measure zero. What is meaningful is to talk about the *integral* of the pdf near the point $a$, as this yields a probability. So a much better sentence would be: "The definite integral of the probability density function over a small neighbourhood of the point $a$ is a measure of how likely it is that the random variable will be near $a$"
53,392,453
Suppose I have two tables as Table1 & Table2 and the data are as below: Table1 ``` Id __ id1 id2 id3 id4 id5 ``` Table2 ``` Id rank -- --- Id1 1 Id2 2 ``` Now, I want to make a orcale SQL query which returns as below: ``` Id rank -- --- Id1 1 Id2 2 Id3 0 Id4 0 Id5 0 ``` I have made following SQL but it does not return desired result. ``` SELECT TAB1.ID,(SELECT CASE WHEN TAB2.RANK IS NULL THEN TAB2.RANK ELSE 0 END FROM TABLE2 TAB2 WHERE TAB2.ID=TAB1.ID) as RANK FROM TABLE1 TAB1; ``` It returns as below: ``` Id rank -- --- Id1 1 Id2 2 Id3 null Id4 null Id5 null ```
2018/11/20
[ "https://Stackoverflow.com/questions/53392453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147857/" ]
Should be a simple left join: ``` SELECT tab1.id, coalesce(tab2.rank,0) as rank FROM tab1 LEFT JOIN tab2 ON tab1.id = tab2.id ```
959,511
I want instal Ubuntu on my notebook, Will Ubuntu Desktop 16.04.3 LTS work perfectly on; AMD C-60 1GHz processor 1 GB RAM 30 GB HDD I know the recommendation system requirements I just want to know Ubuntu will work properly or not with this spech?? Please Answer :)
2017/09/26
[ "https://askubuntu.com/questions/959511", "https://askubuntu.com", "https://askubuntu.com/users/741015/" ]
According to [Wikipedia](https://en.wikipedia.org/wiki/Python_Imaging_Library) Pillow is packaged as *python-pil* and *python3-pil* in Ubuntu 13.04 and later. To install the Python Imaging Library in Ubuntu 16.04 and later (and also in Ubuntu 14.04), open the terminal and type: ``` sudo apt install python-pil # for python 2.X ``` and/or... ``` sudo apt install python3-pil # for python 3.X including python3.6 ``` And if the imageTk import doesn't work, just do this: ``` sudo apt install python3-pil.imagetk ```
34,921,748
I've read similar threads but wasn't able to find a solution to my issue. When I start my project, I first saved it in a folder with blank space in its name (let name it "My Project") Lets also simplify the path through my project as a simple folder : "My path" (yes, there was blank spaces in the hierarchy). I used to have issues while building my project, especially with the Library search path in Build settings, regularly coming back with xcode updates or/and duplication of project for keeping a historical. To solved that, I've replaced all the blank spaces with underscores. So now my project's folder name is "My\_Project" and the path "My\_path". These changes have also been performed in the Build Settings of my project. But today, I have an error I can't get rid of. When I build my project, every file compile perfectly, but during the "copying" process, I get this kind of error. ``` /!\Copy AFNetworking ...in /Users/admin/Desktop/My_path/My Project/Product-name/Sub Folder CpResource /Users/admin/Desktop/My_path/My\ Project/Product-name/Sub\ Folder/AFNetworking /Users/admin/Library/Developer/Xcode/DerivedData/Product-name-gkplyeugxcxhijajdvpxutaodxmz/Build/Products/Release-iphoneos/Product-name.app/AFNetworking cd /Users/admin/Desktop/My_path/My_Project/Product-name export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" builtin-copy -exclude .DS_Store -exclude CVS -exclude .svn -exclude .git -exclude .hg -strip-debug-symbols -strip-tool /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/strip -resolve-src-symlinks /Users/admin/Desktop/My_path/My\ Project/Product-name/Sub\ Folder/AFNetworking /Users/admin/Library/Developer/Xcode/DerivedData/Product-name-gkplyeugxcxhijajdvpxutaodxmz/Build/Products/Release-iphoneos/Product-name.app ------------------------------------- error: /Users/admin/Desktop/My_path/My Project/Product-name/Sub Folder/AFNetworking: No such file or directory ``` I don't find in my target's Build Settings any field where blank spaces haven't been replaced by underscores. Any help appreciated. (I'm using Xcode 7.2, OS X El Capitan 10.11.2)
2016/01/21
[ "https://Stackoverflow.com/questions/34921748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2291363/" ]
I finally find somewhat by chance [an answer](https://stackoverflow.com/a/6191534/2291363) to my problem. I've opened the .xcodeproj file in finder, and then edit `project.pbxproj`. In this file, I've founded a line : ``` 84635D6F1C22F90100C55AB2 /* AFNetworking */ = {isa = PBXFileReference; lastKnownFileType = folder; name = AFNetworking; path = "/Users/admin/Desktop/My_path/My Project/Product-name/Sub Folder/AFNetworking"; sourceTree = "<absolute>"; }; ``` And retyping it properly made the trick.
5,847
Okay, I'm very confused now. A [question of mine from 2 years ago](https://softwareengineering.stackexchange.com/questions/43838/do-you-own-your-tools) with multiple upvoted answers and upvoted to ten was just closed as not constructive. I'm assuming that someone stumbled across it and voted to close putting it in the review queue. If anything maybe it should be locked, but there were good answers to the questions and it proposed something for people to think about. It relates directly to programming so I'm just curious, what's not constructive about the question?
2013/04/17
[ "https://softwareengineering.meta.stackexchange.com/questions/5847", "https://softwareengineering.meta.stackexchange.com", "https://softwareengineering.meta.stackexchange.com/users/13181/" ]
I went on a search for "what do you think" last night after seeing a few "what do you think" questions get asked, or answered and closed - this was one (of many) that I found. Many times new users attempt to [use old open questions as examples for why their question should be remain open](https://meta.stackoverflow.com/tags/broken-windows/info "respective tag wiki at MSO"). Closing old questions that don't fit the current quality standards helps limit this avenue of misunderstanding about the site scope. Often new users will find an "what do you think" question and answer it. These questions, because of their age, votes, and views will cause it to immediately jump to the top of the hot questions, which attracts more answers of questionable merit. These new answers to "what do you think" are often quite poor and garner downvotes resulting in a poor new user experience answering questions on P.SE. Locking is not available to most people, and is actually a stronger action than closing as it also prevents comments and votes (and new answers as closing does). Closing does not mean deletion. As I understand it, having answers (and upvoted answers) will prevent such automated cleanups (of negative voted, unanswered questions). --- There seems to be some misgivings about the questions... My close vote spree included: * [What do Java developers think of Scala?](https://softwareengineering.stackexchange.com/questions/25509/what-do-java-developers-think-of-scala) * [What do you think of the F# language?](https://softwareengineering.stackexchange.com/questions/3066/what-do-you-think-of-the-f-language) * [What do you think of the Joel Test?](https://softwareengineering.stackexchange.com/questions/2776/what-do-you-think-about-the-joel-test) * [What do you think of this book “JavaScript Programmer's Reference”](https://softwareengineering.stackexchange.com/questions/73967/what-do-you-think-of-this-book-javascript-programmers-reference) * [What do you think about the fork of Redmine : ChiliProject](https://softwareengineering.stackexchange.com/questions/64477/what-do-you-think-about-the-fork-of-redmine-chiliproject) * [What do you think would be a perfect testing tool for waterfall model?](https://softwareengineering.stackexchange.com/questions/45345/what-do-you-think-would-be-a-perfect-testing-tool-for-waterfall-model) * [What do you think about design by contract?](https://softwareengineering.stackexchange.com/questions/1158/what-do-you-think-about-design-by-contract) * [What do you think of this generator syntax?](https://softwareengineering.stackexchange.com/questions/41277/what-do-you-think-of-this-generator-syntax) * [What do you use string reversal for?](https://softwareengineering.stackexchange.com/questions/24691/what-do-you-use-string-reversal-for) * [what do you do to keep learning?](https://softwareengineering.stackexchange.com/questions/45803/what-do-you-do-to-keep-learning) * [What skills do you think a performance engineer should have?](https://softwareengineering.stackexchange.com/questions/59292/what-skills-do-you-think-a-performance-engineer-should-have) * [Licenses that prevent usage in weapons](https://softwareengineering.stackexchange.com/questions/66983/licenses-that-prevent-usage-in-weapons) * [Will enterprise software development kill my dreams?](https://softwareengineering.stackexchange.com/questions/94256/will-enterprise-software-development-kill-my-dreams) * [Should I include C private tutoring experience on my CV ( resume )?](https://softwareengineering.stackexchange.com/questions/57953/should-i-include-c-private-tutoring-experience-on-my-cv-resume) * [Do you own your tools?](https://softwareengineering.stackexchange.com/questions/43838/do-you-own-your-tools) * [Legality/Ethics of crawling a site to basically copy its database?](https://softwareengineering.stackexchange.com/questions/98111/legality-ethics-of-crawling-a-site-to-basically-copy-its-database) * [What to do with bad source code?](https://softwareengineering.stackexchange.com/questions/29671/what-to-do-with-bad-source-code) * [Punishing users for insecure passwords](https://softwareengineering.stackexchange.com/questions/92199/punishing-users-for-insecure-passwords) If people feel that my votes on any of these in error, please help me understand where they were the mistake was made. My skill set at rewriting old questions is not the greatest, and I would welcome any help in reformulating these questions into ones that can be reopened.
24,100,111
I have a string `p9909abc0221-` and `p9909abc0221` I have written regular expression to match the user input and validating it .The String may or may not contain '-' spcial character in last . Using the below code ``` return (str !== undefined && str.match('^(P|p)[0-9]{4}(ABC|abc)[0-9]{4}[/-]$')); ``` I think I am doing wrong for '-' special character . Any help would be great
2014/06/07
[ "https://Stackoverflow.com/questions/24100111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1328323/" ]
Some problems here: * regexes are not strings, use `/.../`, not `'...'` * instead of `(ABC|abc)` just make the pattern case-insensitive (unless you want to disallow `Abc`) * `[\-]` is just the same as `-` * `\d` is a shortcut for `[0-9]` That is, ``` return (str !== undefined && str.match(/^p\d{4}abc\d{4}-?$/i)); ``` or ``` return (str !== undefined && str.match(/^[Pp]\d{4}(ABC|abc)\d{4}-?$/)); ```
42,273,062
I have a root dialog, a LuisDialog, from which I am calling some child dialogs, as follows ``` [LuisModel("8869ccea-7c5f-4cce-8639-64bbc7ecd62b", "c5835534ed7746449356c62dcdf48fde")] [Serializable] public class DefaultDialog : LuisDialog<object> { [LuisIntent("showIncidents")] public async Task ShowIncidents(IDialogContext context, IAwaitable<IMessageActivity> _message, LuisResult result) { var message = await _message; await context.Forward(new ShowIncident(), ResumeAfter,message,CancellationToken.None); } [LuisIntent("CreateIncident")] public async Task CreateIncident(IDialogContext context, LuisResult result) { //context.Call(new CreateIncident(), ResumeAfter); context.Call(new CreateIncident(), ResumeAfter); } ``` When I call the "ShowIncident()" dialiog, i'd like to forward the LuisResult rather than message, because I need the entities from the LuisResult in the child dialog. So i tried calling the child dialog with the following code: ``` await context.Forward(new ShowIncident(), ResumeAfter,result,CancellationToken.None); ``` I tried implementing my "ShowIncident" dialog as follows: ``` [Serializable] public class ShowIncident : IDialog<object> { public async Task StartAsync(IDialogContext context) { context.Wait(MessageReceivedAsync); } public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<LuisResult> _result) { var result = await _result; // Get and post Incidents Incidents incidents = await ServiceNow.GetIncidentsAsync(); await context.PostAsync(incidents.toText()); } } ``` This throws an error, which I assume is because `IAwaitable<LuisResult>` has to be `IAwaitable<IMessageActivity>`. I realize I could use several workarounds, like positing the entities as a message or using a public static class to define the incidents. But what would be the 'proper way'?
2017/02/16
[ "https://Stackoverflow.com/questions/42273062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7236528/" ]
Add a constructor to `ShowIncident` ``` public class ShowIncident : IDialog<object> { private LuisResult _luisResult; public ShowIncident(LuisResult luisResult) { _luisResult = _luisResult; } public async Task MessageReceivedAsync(IDialogContext context, IAwaitable<IMessageActivity> activity) { //.... ``` and call it like this context.Call(new `CreateIncident(result), ResumeAfter)`;
5,247,138
I'm using inline editing in my grid , I have some cases which i want to change the value of a cell inside a column. I'm changing it with setCell ,and it works good. my problem is that after the change the cell losts it's edit mode while all other cells of the row are in edit mode. I want to keep the cell in edit mode after i changed it. for now what i did is saved the row and then selected it again and made in in edit mode - but i don't think it is a good solution - Is there a way to keep in edit mode while changin it? Thank's In Advance.
2011/03/09
[ "https://Stackoverflow.com/questions/5247138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/590586/" ]
If you need to implement the behavior of dependency cells which are all in the editing mode you have to modify the cell contain manually with respect of [jQuery.html](http://api.jquery.com/html/) function for example. If the name of the column which you want to modify has the name "description", and you use 'blur' event on another "code" column then you can do about the following ``` editoptions: { dataEvents: [ { type: 'blur', fn: function(e) { var newCodeValue = $(e.target).val(); // get the information from any source about the // description of based on the new code value // and construct full new HTML contain of the "description" // cell. It should include "<input>", "<select>" or // some another input elements. Let us you save the result // in the variable descriptionEditHtml then you can use // populate descriptionEditHtml in the "description" edit cell if ($(e.target).is('.FormElement')) { // form editing var form = $(e.target).closest('form.FormGrid'); $("#description.FormElement",form[0]).html(descriptionEditHtml); } else { // inline editing var row = $(e.target).closest('tr.jqgrow'); var rowId = row.attr('id'); $("#"+rowId+"_description",row[0]).html(descriptionEditHtml); } } } ] } ``` The code will work for both inline and form editing. The working example of dependent `<select>` elements you can find [here](http://www.ok-soft-gmbh.com/jqGrid/DependendSelects3.htm).
71,299,993
So there is this e-commerce page <https://www.jooraccess.com/r/products?token=feba69103f6c9789270a1412954cf250> and there are hundreds of products, and for each product there is a slider with images (or slideshow or whatever you call it). I just need to scrape all the images from the page. I understand how to grab first images in each slider, I just can't figure out how to scrape the rest of the images in each slider. I have inspected the element and noticed that each time I change the image in the slider, this part ``` <div data-position="4" class="PhotoBreadcrumb_active__2T6z2 PhotoBreadcrumb_dot__2PbsQ"></div> ``` moves down these positions (in the example below image#4 is selected) ``` <div class="PhotoBreadcrumb_breadcrumbContainer__2cALf" data-testid="breadcrumbContainer"> <div data-position="0" class="PhotoBreadcrumb_dot__2PbsQ"></div> <div data-position="1" class="PhotoBreadcrumb_dot__2PbsQ"></div> <div data-position="2" class="PhotoBreadcrumb_dot__2PbsQ"></div> <div data-position="3" class="PhotoBreadcrumb_dot__2PbsQ"></div> <div data-position="4" class="PhotoBreadcrumb_active__2T6z2 PhotoBreadcrumb_dot__2PbsQ"></div> <div data-position="5" class="PhotoBreadcrumb_dot__2PbsQ"></div> </div> ```
2022/02/28
[ "https://Stackoverflow.com/questions/71299993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9878172/" ]
To scrape all the values of the *`src`* attributes from the first slide you need to: * Click on each slide inducing [WebDriverWait](https://stackoverflow.com/a/59130336/7429447) for the [*element\_to\_be\_clickable()*](https://stackoverflow.com/a/54194511/7429447) * Collect the value of each *`src`* attribute inducing [WebDriverWait](https://stackoverflow.com/a/52607451/7429447) for the [*visibility\_of\_element\_located()*](https://stackoverflow.com/a/50474905/7429447) * You can use the following [locator strategies](https://stackoverflow.com/a/48376890/7429447): ``` driver.get("https://www.jooraccess.com/r/products?token=feba69103f6c9789270a1412954cf250") print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@class, 'Grid_Row__2R-IV') and contains(@class, 'Grid_left')]/div//img"))).get_attribute("src")) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@class, 'Grid_Row__2R-IV') and contains(@class, 'Grid_left')]/div//div[@data-position='1']"))).click() print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@class, 'Grid_Row__2R-IV') and contains(@class, 'Grid_left')]/div//img"))).get_attribute("src")) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@class, 'Grid_Row__2R-IV') and contains(@class, 'Grid_left')]/div//div[@data-position='2']"))).click() print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@class, 'Grid_Row__2R-IV') and contains(@class, 'Grid_left')]/div//img"))).get_attribute("src")) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@class, 'Grid_Row__2R-IV') and contains(@class, 'Grid_left')]/div//div[@data-position='3']"))).click() print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@class, 'Grid_Row__2R-IV') and contains(@class, 'Grid_left')]/div//img"))).get_attribute("src")) WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[contains(@class, 'Grid_Row__2R-IV') and contains(@class, 'Grid_left')]/div//div[@data-position='3']"))).click() print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@class, 'Grid_Row__2R-IV') and contains(@class, 'Grid_left')]/div//img"))).get_attribute("src")) ``` * Console Output: ``` https://cdn.jooraccess.com/img/uploads/accounts/678917/images/Sundays_NYC_3202%20(1).jpg https://cdn.jooraccess.com/img/uploads/accounts/678917/images/Sundays_NYC_3207.jpg https://cdn.jooraccess.com/img/uploads/accounts/678917/images/Maya%20dress_Floral03.jpg https://cdn.jooraccess.com/img/uploads/accounts/678917/images/Maya%20dress_Floral04.jpg https://cdn.jooraccess.com/img/uploads/accounts/678917/images/Maya%20dress_Floral05.jpg ```
57,331,680
I use TextInputEditText and kotlin. I try to change hint programaticaly. But it changed just in box. Add when move-up when i wrote something - upper hint not showing. I use this code in onCreate: ``` editTextChooseDate.hint = "Please choose the Date" ``` and later I check if editTextChooseDate has some test and try to change hint by: ``` editTextChooseDate.hint = "Selected Date" ``` There is editTextChooseDate in xml: ``` <com.google.android.material.textfield.TextInputLayout android:id="@+id/layoutEditTextChooseDate" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"> <com.google.android.material.textfield.TextInputEditText android:id="@+id/editTextChooseDate" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="" android:maxLines="1"/> </com.google.android.material.textfield.TextInputLayout> ``` I expected to change upper-hint programaticaly.
2019/08/02
[ "https://Stackoverflow.com/questions/57331680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8487757/" ]
You should set second `hint` to `layoutEditTextChooseDate` instead of `editTextChooseDate`. Because "upper-hint" as you called it, is a part of parent container `TextInputLayout`.
2,727,417
``` foreach(textbox t in this.controls) { t.text=" "; } ``` I want to clear all the textboxes in my page at one time. I am getting an error: > > Unable to cast object of type 'System.Web.UI.LiteralControl' to type > 'System.Web.UI.WebControls.TextBox'. > > >
2010/04/28
[ "https://Stackoverflow.com/questions/2727417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327568/" ]
The error is because your controls collection doesn't only contain text boxes. Try this instead. ``` foreach (Control c in this.Controls) { TextBox t = c as TextBox; if (t != null) { t.text=" "; } } ```
167,439
**Update:** Thanks for the suggestions guys. After further research, I’ve reformulated the question here: [Python/editline on OS X: £ sign seems to be bound to ed-prev-word](https://stackoverflow.com/questions/217020/pythoneditline-on-os-x-163-sign-seems-to-be-bound-to-ed-prev-word) On Mac OS X I can’t enter a pound sterling sign (£) into the Python interactive shell. * Mac OS X 10.5.5 * Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) * European keyboard (£ is shift-3) When I type “£” (i.e. press shift-3) at an empty Python shell, nothing appears. If I’ve already typed some characters, e.g. ``` >>> 1234567890 1234567890 1234567890 ``` ... then pressing shift-3 will make the cursor position itself after the most recent space, or the start of the line if there are no spaces left between the cursor and the start of the line. In a normal bash shell, pressing shift-3 types a “£” as expected. Any idea how I can type a literal “£” in the Python interactive shell?
2008/10/03
[ "https://Stackoverflow.com/questions/167439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20578/" ]
Not the best solution, but you could type: ``` pound = u'\u00A3' ``` Then you have it in a variable you can use in the rest of your session.
154,347
I live in Iran and I have bought this Qatar Airways flight from Tehran (Iran) to Vienna for February 29. As far as I know, to this moment the flight is not cancelled for health concerns regarding Coronavirus. Although I don't know of any way to make sure about that. So I might have to go to airport and see what is going on. And I don't want to cancel the flight, since I should be there in Vienna for my job starting March 1. But, in case the flight is not cancelled by the airline, I don't know what is going to happen to me at the airports. Some people say that they might put me in quarantine at Qatar airport or at Vienna airport, maybe for 14 days. Has anyone have any view or experience regarding such conditions? I am kind of panicked and overwhelmed by thoughts and concerns.
2020/02/26
[ "https://travel.stackexchange.com/questions/154347", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/91828/" ]
As suggested in comments there are three tariff levels in Sevilla but they apply for different sorts of journey as well as for different times. 1 is for urban, 2 for inter-urban and 3 for airport. <https://teletaxisevilla.es/tarifas/> It is in Spanish I am afraid but perhaps on-line translation tools may help here.
61,723,364
I've just started teaching myself Keras and I'm building trivial challenges to solve. I have managed to get off the ground and have managed to train a few simple models. However, there is a strange situation where a model trains well if I apply a simple linear transformation to the inputs but not otherwise. Here is the code that I'm using. One of these learns and the other doesn't. The aim of the model is to learn to figure out if someone is an adult given the year and month of birth. ``` from random import random import numpy as np from keras.models import Sequential from keras.layers import Dense X = [[1980 + int(39*random()), int(12*random())] for _ in range(0, 5000)] y = [1 if (12 * (2020 - x[0]) + (5 - x[1])) > 216 else 0 for x in X] # X = [[12 * (2020 -x[0]) + (5 - x[1])] for x in X] X = np.array(X) y = np.array(y) model = Sequential() layer = Dense(1, input_dim=2, kernel_initializer='random_normal', activation='sigmoid') model.add(layer) model.compile(loss='binary_crossentropy', optimizer='adam') model.fit(X, y, epochs=1000, batch_size=100) ``` Now this model does not seem to learn at all. The loss remains stuck at around 0.68 throughout. Things don't improve even if I rescale the inputs using: ``` X = [[x[0] / 1000.0, x[1] / 12.0] for x in X] ``` However, if I uncomment the line in the code above and change the input dimension of the layer to 1, the model converges very nicely. Shouldn't the current model converge as well. I can't see what I'm doing wrong here. As a clarification, the input here is basically the year and month of birth. We're assuming that we are checking if a person is an adult in May, 2020. -- Edit: I seem to have found the answer, thanks to @catalina's point about "variety". Since the input variables were all integers, there were only a few actual examples for the system to learn from. For a gradient to be defined nicely, you'd need more points on the surface being learned. So, in this case, if I change the relevant part of my code to the following: ``` X = [[1980 + int(39*random()), int(12*random())] for _ in range(0, 5000)] # adding random noise to create "variety" X = [[x[0] + random(), x[1] + random()] for x in X] y = [1 if (12 * (2020 - x[0]) + (5 - x[1])) > 216 else 0 for x in X] # approximately centering the inputs X = [[x[0] - 2002, x[1] - 6] for x in X] ``` The model converges beautifully. I'm still a little unclear why the centering was necessary (without it, it does not converge). I suspect that is because the gradient would be far too flat at the point where the weights start out, making it hard to find a direction to move in. P.S. - I absolutely get that this is not the right use-case for an NN. But my attempt right now is to understand the underlying mechanics to the point where everything I do flows from first principles. For example, the fact that x[1] is "noise" and should be dropped altogether, as suggested by a member, turns out to be not correct in this context.
2020/05/11
[ "https://Stackoverflow.com/questions/61723364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13515556/" ]
There are many issues, like the capacity of the network being too small, hard thresholding to make a really hard loss surface, etc. But, the main point I found was the highly skewed inputs for the first case. `X = [[1980 + int(39*random()), int(12*random())] for _ in range(0, 5000)]` The two values in the input are extremely skewed, one being more than 150 times than the other one. There are other fixes to make the network converge but the most simple one being, just re-scaling the inputs. For example, the following input also converges easily. `X = [[1980 + int(39*random()), 1000 + int(12*random())] for _ in range(0, 5000)]` The only thing I changed was the range of the input. Update: After your comment, I just plotted the data and realized your x[1](https://i.stack.imgur.com/bM9fP.png) is pure noise to the data which is completely destroying the predictions. ``` plt.plot(X[:100,0]) plt.plot(X[:100,1]) plt.plot(y[:100]) plt.legend(['x0', 'x1', 'y']) plt.show() ``` A person's age has nothing to do with the month of birth, as you can see in the graph, the month is completely adding pure noise to the predictions. If a person is an adult or not only depends on the birth year, the birth month would be a complete noise to the model, for such a simple model, it has no way to eliminate that noise hence such poor performance. **But, if you increase your network capacity with proper scaling you can technically make the model memorize the samples.** [![enter image description here](https://i.stack.imgur.com/bM9fP.png)](https://i.stack.imgur.com/bM9fP.png) Just to give some basic idea, ``` cnt = 0 idx = 0 for x in X: if x[1] == 1: print(x) print(y[idx]) cnt += 1 if cnt == 100: break idx += 1 ``` ``` [1987, 1] 1 [1986, 1] 1 [2001, 1] 1 [1983, 1] 1 [2011, 1] 0 [2003, 1] 0 [1990, 1] 1 [2016, 1] 0 [1980, 1] 1 [2002, 1] 1 [1987, 1] 1 [1996, 1] 1 [1997, 1] 1 [1984, 1] 1 [2005, 1] 0 [2016, 1] 0 [1987, 1] 1 [1984, 1] 1 [1986, 1] 1 [1990, 1] 1 [1983, 1] 1 [2006, 1] 0 [2018, 1] 0 [2012, 1] 0 [1992, 1] 1 [1992, 1] 1 [2012, 1] 0 [2013, 1] 0 [1988, 1] 1 [2014, 1] 0 [1992, 1] 1 [2018, 1] 0 [2013, 1] 0 [2006, 1] 0 [1984, 1] 1 [1992, 1] 1 [2003, 1] 0 [1991, 1] 1 [1993, 1] 1 [2001, 1] 1 [2015, 1] 0 [2013, 1] 0 [1997, 1] 1 [2000, 1] 1 [2011, 1] 0 [2000, 1] 1 [1987, 1] 1 [1985, 1] 1 [1983, 1] 1 [1999, 1] 1 [2015, 1] 0 [2018, 1] 0 [1996, 1] 1 [1987, 1] 1 [1997, 1] 1 [2015, 1] 0 [1982, 1] 1 [1995, 1] 1 [2016, 1] 0 [1986, 1] 1 [2009, 1] 0 [2009, 1] 0 [2007, 1] 0 [2009, 1] 0 [2013, 1] 0 [1998, 1] 1 [1994, 1] 1 [2011, 1] 0 [1997, 1] 1 [2004, 1] 0 [2015, 1] 0 [2015, 1] 0 [1983, 1] 1 [1984, 1] 1 [2014, 1] 0 [1988, 1] 1 [2008, 1] 0 [2010, 1] 0 [2009, 1] 0 [2004, 1] 0 [2002, 1] 1 [1991, 1] 1 [2001, 1] 1 [1982, 1] 1 [2011, 1] 0 [2002, 1] 1 [2013, 1] 0 [2001, 1] 1 [2000, 1] 1 [1998, 1] 1 [1999, 1] 1 [2017, 1] 0 [2001, 1] 1 [1981, 1] 1 [1994, 1] 1 [2000, 1] 1 [2011, 1] 0 [1988, 1] 1 [1982, 1] 1 ``` As you can see, it's pretty clear, even though the month is 1 for all of those data, only the year makes the label 1 or 0. the month has absolutely no effect on the data, it's useless. If month is high the label is 0 and vice-versa.
5,674,274
I want to return a list of ProductDetailViewModel from the first select but nothing I do seems to work. What is the proper way to combine theese two selects? ``` var test = (from pc in db.PartnerCoupons from coup in db.Coupons where pc.CouponID == coup.CouponID && pc.PartnerCampaignID == partCamp.PartnerCampaignID && coup.CategoryID == id select pc).ToList(); var partnerCoupons = from pc in test .Select(s => new ProductDetailViewModel(s)) .ToList() select pc; return View("List", partnerCoupons); ``` Just to be clear, this works I just want to get rid of the "partnercoupons"-select. /Mike
2011/04/15
[ "https://Stackoverflow.com/questions/5674274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/161980/" ]
`pattern.matcher(input)` always creates a new matcher, so you'd need to call `matches()` again. Try: ``` Matcher m = responseCodePattern.matcher(firstHeader); m.matches(); m.groupCount(); m.group(0); //must call matches() first ... ```
27,501,763
Why this not working browsers except IE? ``` var head = jQuery("#frame1").contents().find("head"); var css = '<style type="text/css">' + '.container{background:blue}; ' + '</style>'; jQuery(head).append(css); }); ```
2014/12/16
[ "https://Stackoverflow.com/questions/27501763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3927335/" ]
I'm assuming that the iframe is on the same domain, as otherwise it wouldn't be working in IE. Your problem is one of timing. You need to wait for the iframe to load, before you can apply your styles to it. The way you do that is: ``` $('#frame1').load(function() { // Code to execute once iframe is loaded }); ``` Once we know that it is loaded, we can apply any styles, thus: ``` var head = jQuery("#frame1").contents().find("head"); var css = '<style type="text/css">' + '.container{background:blue}; ' + '</style>'; $(head).append(css); ``` Although, you can shorten it to: ``` $('#frame1').load(function() { var css = '<style type="text/css">.container{background:blue};</style>'; $('#frame1').contents().find("head").append(css); }); ``` This works for me in Firefox and Chrome (on a server stack - not locally, due to security restrictions).
43,969,836
[![enter image description here](https://i.stack.imgur.com/3EYZr.png)](https://i.stack.imgur.com/3EYZr.png) ``` <form action='upload.php' method='post' enctype="multipart/form-data"> <input type='text' required="required" name='activityName' placeholder="Name of the activity..."><br><br> <input type='date' required="required" name='date'><br><br> <input type='file' required="required" name='file'><br><br> <button type='submit' name='submit'>Upload</button> </form> <?php $ps = $pdo->query("SELECT * FROM activities"); echo "<br>"; echo "<table>"; while($row = $ps->fetch(PDO::FETCH_BOTH)){ echo "<tr>"; echo "<td>";?> <img src="<?php echo $row['image'];?>" height="100" width="100"> <?php echo "</td>"; echo "<td>"; echo $row['name']; echo "</td>"; echo "</table>"; } ?> ``` The following code is what I'm using to upload to the database.. ``` <?php include 'dbh.php'; if (isset($_POST['submit'])){ $file = $_FILES['file']; $fileName = $_FILES['file']['name']; $fileTmp = $_FILES['file']['tmp_name']; $fileSize = $_FILES['file']['size']; $fileError = $_FILES['file']['error']; $fileType = $_FILES['file']['type']; $activityName = $_POST['activityName']; $activityDate = $_POST['date']; $fileExt = explode('.', $fileName); $fileActualExt = strtolower(end($fileExt)); $allow = array('jpeg', 'jpg', 'png'); if (in_array($fileActualExt, $allow)){ if($fileError === 0){ if ($fileSize < 1000000){ $fileNewName = uniqid('', true) . '.' . $fileActualExt; $fileDestination = '/home/bh03te/public_html/webproject/uploads/' . $fileNewName; move_uploaded_file($fileTmp, $fileDestination); $sql = "INSERT INTO activities (name, date, image) VALUES ('$activityName', $activityDate, '$fileNewName')"; $result = $pdo->query($sql); header("Location: activities.php?uploadsuccess"); } else{ echo "This file is too large"; } } else{ echo "There was an error uploading this file"; } } else{ echo "You cannot upload files of this type!"; } } ``` This is all the code I do have for it and don't see why it isn't working. Do I need to have the data type in the database as something specific? It is currently just VARCHAR. I don't know if it would make a difference or not. All the names from the database and everything is correct as images do upload but they just don't echo out correctly. It only outputs a broken image.
2017/05/14
[ "https://Stackoverflow.com/questions/43969836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7230950/" ]
I'm supposing your file is already uploading correctly, and I see you are not saving the entire path of the image on the database, therefore you also need to write it down in the `src` attribute of the image before the name of the file (with its extension). Either do it when printing: ``` // I am deleting everything up to public_html because I suppose that's the DOCUMENT_ROOT, so that's not web accessible <img src="/webproject/uploads/<?php echo $row['image'];?>" height="100" width="100"> ``` Or when inserting into the database: ``` // I am deleting everything up to public_html because I suppose that's the DOCUMENT_ROOT, so that's not web accessible $path = '/webproject/uploads/'.$fileNewName; $sql = "INSERT INTO activities (name, date, image) VALUES ('$activityName', $activityDate, '$path')"; ```
35,247,350
I'm trying to understand Spotify's login/authorization process. I was following a tutorial and ended up with this code. When I try to login I get this error: -canOpenURL: failed for URL: "spotify-action://" - error: "(null)" I checked the repo and saw that I needed to add spotify-action and spotify to Info.plist under LSApplicationQueriesSchemes. However after doing this I am still getting the above error. ``` class SpotifyLoginViewController: UIViewController, SPTAuthViewDelegate{ let kclientID = " my client id" let kcallbackURL = "my callback" @IBAction func loginSpotify(sender: AnyObject){ SPTAuth.defaultInstance().clientID = kclientID SPTAuth.defaultInstance().redirectURL = NSURL(string: kcallbackURL) SPTAuth.defaultInstance().requestedScopes = [SPTAuthStreamingScope] SPTAuth.defaultInstance().sessionUserDefaultsKey = "SpotifySession" //SPTAuth.defaultInstance().tokenSwapURL = NSURL(string: ktokenSwapURL) //you will not need this initially, unless you want to refresh tokens // SPTAuth.defaultInstance().tokenRefreshURL = NSURL(string: ktokenRefreshServiceURL)//you will not need this unless you want to refresh tokens let spotifyAuthViewController = SPTAuthViewController.authenticationViewController() spotifyAuthViewController.delegate = self spotifyAuthViewController.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext spotifyAuthViewController.definesPresentationContext = true presentViewController(spotifyAuthViewController, animated: false, completion: nil) } func authenticationViewController(authenticationViewController: SPTAuthViewController!, didLoginWithSession session: SPTSession!) { print("Logged In") } func authenticationViewController(authenticationViewController: SPTAuthViewController!, didFailToLogin error: NSError!) { print("Failed to Log In") print(error) authenticationViewController.clearCookies(nil) } func authenticationViewControllerDidCancelLogin(authenticationViewController: SPTAuthViewController!) { print("User Canceled Log In") authenticationViewController.clearCookies(nil) } } ```
2016/02/06
[ "https://Stackoverflow.com/questions/35247350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2620913/" ]
If the Spotify app isn't installed on your device. so you can not open the Spotify Original app with the URL "spotify-action://". You can login with the web browser. It will open the spotify.com and after authentication, it will redirects to the redirect url (app link ). You have to change only one parameter. **sessionManager.initiateSession(with: scope, options: *.clientOnly*, presenting: self)** That param is options. Please change this to ***.default***. So it will open the safari browser to login the spotify account. I hope this will be help.
47,713
How can I have underlined links with `hyperref`? That means how to configure `hyperref` not to change the color of the printout but use underlined active links which are completely transparent in print. The condition for an answer to be qualified would be not to make code changes in a local copy of the `hyperref` macros, working for linebraking/hyphenation of links in dvi/PS as well as PDF output, configuration for different dvi-drivers (e.g. `pstricks.con`). Options to specify underline color, linewidth, relative position/offset to baseline are a plus but functional not essential.
2012/03/12
[ "https://tex.stackexchange.com/questions/47713", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/12538/" ]
You can try this: ``` \documentclass{article} \usepackage[colorlinks=false, allbordercolors={0 0 0}, pdfborderstyle={/S/U/W 1}]{hyperref} \begin{document} \url{blub.blub.blub} \end{document} ```
48,845,912
I am trying to upload a video with java to an api of Microsoft(Video Indexer API) using a request Http Post and it's work with Postman But when i do this in java it's not work This is my code : ``` public static void main(String[] args) { CloseableHttpClient httpclient = HttpClients.createDefault(); try { URIBuilder builder = new URIBuilder("https://videobreakdown.azure-api.net/Breakdowns/Api/Partner/Breakdowns?name=film2&privacy=Public"); URI uri = builder.build(); HttpPost httpPost = new HttpPost(uri); httpPost.setHeader("Content-Type", "multipart/form-data"); httpPost.setHeader("Ocp-Apim-Subscription-Key", "19b9d647b7e649b38ec9dbb472b6d668"); MultipartEntityBuilder multipart = MultipartEntityBuilder.create(); File f = new File("src/main/resources/film2.mov"); multipart.addBinaryBody("film2",new FileInputStream(f)); HttpEntity entityMultipart = multipart.build(); httpPost.setEntity(entityMultipart); CloseableHttpResponse response = httpclient.execute(httpPost); HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println(EntityUtils.toString(entity)); } } ``` And this is the error: ``` {"ErrorType":"INVALID_INPUT","Message":"Content is not multipart."} ``` And for Postman this is a screen for all the parameter that i have to put on the Http Request [Screen for all the params on postman](https://i.stack.imgur.com/s8BFi.png) And for the header: [header](https://i.stack.imgur.com/xNlQH.png)
2018/02/17
[ "https://Stackoverflow.com/questions/48845912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8689469/" ]
And just for the fun of it... here's a simpler version: ``` <script> function evenNumbers2(minNumber, maxNumber){ var output = ""; for (var i = minNumber; i <= maxNumber; i++) { if (i % 2 == 0) { output += ", " + i; } } return output.substring(2,999); } console.log('evenNumbers2(4,13) returns: ' + evenNumbers2(4, 13)); console.log('evenNumbers2(3,10) returns: ' + evenNumbers2(3, 10)); console.log('evenNumbers2(8,21) returns: ' + evenNumbers2(8, 21)); </script> ```
5,725,997
How to show the version number in Java control panel?
2011/04/20
[ "https://Stackoverflow.com/questions/5725997", "https://Stackoverflow.com", "https://Stackoverflow.com/users/716509/" ]
> > How to show the version number in Java control panel? > > > System.out.println([System.getProperty("java.version")](http://pscode.org/prop/?prop=java.versionformat=TSV)); --- Or, for more complete information, see properties java.version, java.vm.version, java.specification.version & java.runtime.version. Sandboxed --------- Sandboxed values for properties [java.version, java.vm.version, java.specification.version & java.runtime.version](http://pscode.org/prop/?prop=java.version%2Cjava.vm.version%2Cjava.specification.version%2Cjava.runtime.version). ``` Name Value java.version 1.6.0_24 java.vm.version 19.1-b02 java.specification.version 1.6 java.runtime.version unknown ``` Trusted ------- Trusted values for properties [java.version, java.vm.version, java.specification.version & java.runtime.version](http://pscode.org/prop/?prop=java.version%2Cjava.vm.version%2Cjava.specification.version%2Cjava.runtime.version). ``` Name Value java.version 1.6.0_24 java.vm.version 19.1-b02 java.specification.version 1.6 java.runtime.version 1.6.0_24-b07 ```
40,343,865
I have the following aggregate query: ``` db.radars.aggregate([ { $group: { _id: '$locationId', count: {$sum: 1} }, }, { $match: { loggedAt: { $gte: new Date('2014-01-01T00:00:00Z'), $lte: new Date('2016-12-31T00:00:00Z') } } } ]); ``` I definitely have data matching the criteria: [![enter image description here](https://i.stack.imgur.com/RtVpv.png)](https://i.stack.imgur.com/RtVpv.png) But I get nothing: [![enter image description here](https://i.stack.imgur.com/oiiRK.png)](https://i.stack.imgur.com/oiiRK.png) Does anyone know why this might be happening?
2016/10/31
[ "https://Stackoverflow.com/questions/40343865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83897/" ]
After the `$group`, the pipeline will contain docs with just the fields defined in the `$group`: `_id` and `count` so there's no `loggedAt` field to match against. So, depending on the output you're looking for, reorder your pipeline to do the `$match` first or add an accumulator for `loggedAt` to your `$group` so its still available. For example: ``` db.radars.aggregate([ { $group: { _id: '$locationId', count: {$sum: 1}, loggedAt: {$push: '$loggedAt'} }, }, { $match: { loggedAt: { $elemMatch: { $gte: new Date('2014-01-01T00:00:00Z'), $lte: new Date('2016-12-31T00:00:00Z') } } } } ]); ```
11,859,479
I'm trying to implement a search on my android application using a search bar widget in the action bar. I am following <http://developer.android.com/guide/topics/search/search-dialog.html> <http://developer.android.com/guide/topics/ui/actionbar.html#ActionView> tutorials to get this done. I have two activities involved in searching. SearchBar activity has the action bar and AcceptSearch is my searchable activity. Even though I declared which activity was the searchable activity, the query is not being sent over to AcceptSearch and the activity is not launched. I configured the search bar such that a search bar hint appears when the widget is empty, but the hint never appears either. Here is my code. **SearchBar** ``` public class SearchBar extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.search_bar); } @Override public boolean onCreateOptionsMenu(Menu menu) { //Inflate the options menu from XML MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); // Get the SearchView and set the searchable configuration SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(false); return true; } ``` **AcceptSearch** ``` public class AcceptSearch extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); //Get the intent, verify the action and get the query Intent intent = getIntent(); if(Intent.ACTION_SEARCH.equals(intent.getAction())) { String query = intent.getStringExtra(SearchManager.QUERY); //Start the search doMySearch(); } } ``` **Searchable.xml** ``` <?xml version="1.0" encoding="utf-8"?> <searchable xmlns:android="http://schemas.android.com/apk/res/android" android:label="@string/app_label" android:hint="@string/search_hint"> </searchable> ``` **options\_menu** ``` <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:title="Help" android:id="@+id/menu_help" android:showAsAction="always" /> <item android:title="Categories" android:id="@+id/menu_cats" android:showAsAction="always" /> <item android:id="@+id/menu_search" android:title="Search with Searchlet" android:icon="@drawable/ic_action_search" android:showAsAction="ifRoom|collapseActionView" android:actionViewClass="android.widget.SearchView"/> </menu> ``` **Manifest** ``` <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.searchlet" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="11" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".SplashScreenActivity" android:label="@string/title_activity_splash_screen" android:screenOrientation="portrait" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".AcceptSearch"> <intent-filter> <action android:name="android.intent.action.SEARCH" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable"/> </activity> <activity android:name=".SearchBar" android:label="@string/app_name"> <intent-filter> <action android:name="com.example.searchlet.CLEARSCREEN" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity> </application> </manifest> ``` I beleive thats all the needed information to recreate the situation. Thank you all in advance. I apprecicate.
2012/08/08
[ "https://Stackoverflow.com/questions/11859479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1191132/" ]
I had a similar problem. I was following [grokking's tutorial](http://www.grokkingandroid.com/android-tutorial-adding-search-to-your-apps/) and the activity never opened. I tried the Indrek's solutions I that works for me. You should be sure that you have the right meta-data under the right parent. The meta-data ``` <meta-data android:name="android.app.default_searchable" android:value=".NameSearchActivity" /> ``` should be under application. The follow meta-data ``` <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" /> ``` should be under the search activity parameter inside AndroidManifest.xml. In the search Activity I did what it say in the tutorial linked before for managing the activity stack. I hope that this solution works for everyone with the same problem.
1,483,741
Let $x = 0.2154154\overline{154}$ , I have to prove that it is a rational number just by writing it as a fraction with the proper steps. I note that the repeating part, $154$, is composed by 3 digits. Thus, using a trick that I have learnt, I can write an equation of this type: $$1000x = ?$$ I am not sure about what goes on the right side of the equation because of this $0.2$ I mean, if, for instance, the number was $x = 0.154$ periodic, I would write the equation as: $1000x = 154 + x$ and solve for $x$ I have tried various attempts, re-writing $0$, $2$ as $\frac{1}{5}$, but I don't get the number which equals our $x$.
2015/10/16
[ "https://math.stackexchange.com/questions/1483741", "https://math.stackexchange.com", "https://math.stackexchange.com/users/279872/" ]
**First Method** What you basically do in this method is find a multiple of $x$ that will get rid of the repeating part when you subtract it from x itself. (HINT: $10x$, $100x$, it all depends on the number of digits in the repeating part.) $$x=0.2154154154...$$ $$10x=2.154154154...$$ $$10000x = 2154.154154...$$ $$10000x - 10x = 9990x = 2154 - 2 = 2152$$ $$x = \frac{2152}{9990}$$ Note we picked $10000x$ here because in the expression of $10x$, the repeating part has three digits. --- **Second Method** $$2.154154154 = 2 + 0.154 + 0.000154 + 0.000000154 + ...$$ $$= 2 + 0.154 + 0.154(0.001) + 0.154(0.001)^2 + 0.154(0.001)^3 + ...$$ $$2 + \frac{0.154}{(1-0.001)} = 2 + \frac{0.154}{0.999} = \frac{2.152}{0.999}$$ $$= \frac{2152}{999}$$ Thus $$2.\overline{154} = \frac{2152}{999}$$ Since the original number is $0.2\overline{154}$, the fractional form is: $$ \frac{2152}{9990}$$
17,794,266
Here is what I am currently doing, it works but it's a little cumbersome: ``` x = np.matrix([[1, 1], [2, -3]]) xmax = x.flat[abs(x).argmax()] ```
2013/07/22
[ "https://Stackoverflow.com/questions/17794266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/562222/" ]
The value you're looking for has to be either `x.max()` or `x.min()` so you could do ``` max(x.min(), x.max(), key=abs) ``` which is similar to aestrivex's solution but perhaps more readable? Note this will return the minimum in the case where `x.min()` and `x.max()` have the same absolute value e.g. `-5` and `5`. If you have a preference just order the inputs to `max` accordingly.
20,183,393
I am a beginner and I know I'm making a rookie mistake. I have the following code in my actionePerformed part of my JApplet. the if statement within the for loop is supposed to search for the matching name in array s[] (t6 is a JtextArea) and assign the value of int m to int n, so i can retireve all the information of s[i]. problem is that my n is always 0 not matter what!!! What am I doing worng? ``` if (e.getSource() == b7) { for(int m=0; m>i ; m++){ if(t6.getText().equals(s[m].getName())){ n=m; } } String text1 = ""; text1 += s[n].getName().toString() + ", average=" + s[n].getAvgMark() + ", " + s[n].getProgramName().toString() + ", " + s[n].getDegree()+ ", " + s[n].getUni1() +"-"+ s[n].getStatus0() +", "+ s[n].getUni2()+"-"+ s[n].getStatus1() + ", " + s[n].getUni3()+"-"+ s[n].getStatus2()+"\n"; ta2.setText(text1); } ```
2013/11/25
[ "https://Stackoverflow.com/questions/20183393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3023624/" ]
I bet you problem is that you you start `int n = 0`. Look at your loop ``` for(int m=0; m>i ; m++){ ``` Th only way this will not be an infinite loop is if `i` is 0 or less. Which I'll assume it is do to you not getting an infinite loop. And since you're not getting an `ArrayIndexOutOfBoundsException` I'll assume that `i` is 0 and not a negative. Therefore for(int m=0; m>i ; m++){ states that continue the loop if `m` is greater than `0`, which it never is. So your array index will only be `0` once. It never loops. Even if you `i++`, `m` will NEVER be greater than `i` because they start evenly and would be incremented evenly. **Just a hunch** Maybe you want this ``` for(int m = 0; m < s.length ; m++){ // iterates [size of the s array] times ```
22,524,492
I have seen in magento mysql install or upgrade script where they are adding column by using : ``` $installer->getTable('catalog/eav_attribute'), 'tooltip', array( 'type' => Varien_Db_Ddl_Table::TYPE_TEXT, 'nullable' => true, 'comment' => 'Tooltip' ) ``` I Want to know what is Varien\_Db\_Ddl\_Table::TYPE\_TEXT? If I want to add the tooltip column manually in mysql table then what should I use in type section? Is it only '**TEXT**'?
2014/03/20
[ "https://Stackoverflow.com/questions/22524492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2637953/" ]
`Varien_Db_Ddl_Table::TYPE_TEXT` is nothing but the type on of the column just like `char, varchar,int,tinyint,etc.,` you use anyone type in the following. ``` const TYPE_BOOLEAN = 'boolean'; const TYPE_SMALLINT = 'smallint'; const TYPE_INTEGER = 'integer'; const TYPE_BIGINT = 'bigint'; const TYPE_FLOAT = 'float'; const TYPE_NUMERIC = 'numeric'; const TYPE_DECIMAL = 'decimal'; const TYPE_DATE = 'date'; const TYPE_TIMESTAMP = 'timestamp'; // Capable to support date-time from 1970 + auto-triggers in some RDBMS const TYPE_DATETIME = 'datetime'; // Capable to support long date-time before 1970 const TYPE_TEXT = 'text'; const TYPE_BLOB = 'blob'; // Used for back compatibility, when query param can't use statement options const TYPE_VARBINARY = 'varbinary'; // A real blob, stored as binary inside DB // Deprecated column types, support is left only in MySQL adapter. const TYPE_TINYINT = 'tinyint'; // Internally converted to TYPE_SMALLINT const TYPE_CHAR = 'char'; // Internally converted to TYPE_TEXT const TYPE_VARCHAR = 'varchar'; // Internally converted to TYPE_TEXT const TYPE_LONGVARCHAR = 'longvarchar'; // Internally converted to TYPE_TEXT const TYPE_CLOB = 'cblob'; // Internally converted to TYPE_TEXT const TYPE_DOUBLE = 'double'; // Internally converted to TYPE_FLOAT const TYPE_REAL = 'real'; // Internally converted to TYPE_FLOAT const TYPE_TIME = 'time'; // Internally converted to TYPE_TIMESTAMP const TYPE_BINARY = 'binary'; // Internally converted to TYPE_BLOB const TYPE_LONGVARBINARY = 'longvarbinary'; // Internally converted to TYPE_BLOB ``` to get more information refer `lib\Varien\Db\Ddl\Table.php`
570,920
I’d like to see the status bar only after the prefix key has been sent. I’d like the bar to disappear again as soon as I’ve sent the intended command. I’d imagine it to work like this: 1. press `C-b` (send prefix) 2. *status bar appears* 3. press `c` (for example) 4. *status bar disappears* & *new window is created* Do you have any suggestions about how to approach this? Thank you!
2020/03/03
[ "https://unix.stackexchange.com/questions/570920", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/398378/" ]
This is difficult to do simply. It is easy to make it appear when you press the prefix, just unset the prefix option and bind a key instead: ``` set -g prefix None bind -n C-b set status on \; switchc -Tprefix ``` The problem is persuading it to turn off when a key is pressed, because there is no hook for "any command happened". You could change other key bindings to turn it off, so `c` becomes: ``` bind c set status off \; new-window ``` But that would be a pain to do for every key. Alternatively, you could just make it turn off after a second or so regardless, with something like: ``` set -g prefix None bind -n C-b set status on \; run -b "sleep 1; tmux set -t'#{session_id}' status off" \; switchc -Tprefix ``` But that may be annoying if you want to do multiple commands one after another. Although you could probably script something more sophisticated than this - perhaps update the time C-b is pressed in a user option and only turn the status off again if it has been long enough. If you must have it turn off as soon as the next key is pressed, you are left with either changing every other key binding, or modifying tmux to fire a hook you can use.
54,105,646
I have a table with a field LastChange which is of type `smalldatetime`. When I sort by ascending order on this field, I get the following: [![enter image description here](https://i.stack.imgur.com/mWSKE.png)](https://i.stack.imgur.com/mWSKE.png) I have created an entity corresponding to this in Entity Framework. The type of the `LastChange` field is `DateTime`. When I execute the same sort operation like this: ``` teams.OrderBy(x => x.LastChange).Select(x => x.TeamID) ``` I get the following result: ``` [0]: 158 [1]: 161 [2]: 159 [3]: 160 [4]: 165 [5]: 163 [6]: 166 [7]: 167 [8]: 168 [9]: 169 [10]: 170 [11]: 171 [12]: 1172 [13]: 162 [14]: 164 [15]: 172 ``` Why are the 2 results different? Is it because the `LastChange` values are the same for multiple records? Or has this got something to do with the `smalldatetime` type?
2019/01/09
[ "https://Stackoverflow.com/questions/54105646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4520453/" ]
This is because the LastChange field is exactly the same for several rows. Try these: ``` SELECT * FROM YourTable ORDER BY LastChange, TeamID; teams.OrderBy(x => x.LastChange).ThenBy(x => x.TeamID).Select(x => x.TeamID) ``` In both places and you will obtain exactly the same results. If you don't specify the order for second field SQL will show a random result (for fields not specified), normally is the same but can be totally different.
11,781,296
In the tutorial [Rubymonk](http://rubymonk.com/learning/books/1/chapters/6-objects/lessons/35-introduction-to-objects) says : "In Ruby, just like in real life, our world is filled with objects. Everything is an object - integers, characters, text, arrays - everything." But && and || are operators, operators are objects too ? how check ? this is not going against the philosophy of ruby "All is a object" ?
2012/08/02
[ "https://Stackoverflow.com/questions/11781296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/430059/" ]
### The `&&` and `||` Tokens are Operators The `&&` and `||` tokens are not objects, they are operators defined by Ruby's parser. You can dig through the source code to find the actual definitions and implementation details, if you're interested. To get you started, here's a regular expression match to get you started in reviewing the source: ``` $ fgrep -n '%token tANDOP tOROP' ruby-1.9.3-p194/ext/ripper/ripper.y 719:%token tANDOP tOROP /* && and || */ ```
24,577
LSTM can be used to generate text, can they be used to fix corrupted text files? Say that my original was: ``` Alice was beginning to get very tired of sitting by her sister on the bank, and of having nothing to do ``` Now it has become: ``` Alice0004 XGFT was beginning to get 900io ALPHA very tired 00New York 333 of siing XXXYYY by her siter on THIS IS 898 the bank, and of &*& HHH GTY DOG AND CAT having nothing to do. ``` Basically, a lot of crap was added (some meaningless words but also meaningful words, and some letters may have been erased). Is there any way LSTM would be able to fix this? (Maybe by cleaning some beforehand and then let LSTM do the rest)
2017/11/10
[ "https://datascience.stackexchange.com/questions/24577", "https://datascience.stackexchange.com", "https://datascience.stackexchange.com/users/13736/" ]
You should use a Seq2Seq (which uses LSTM/GRU/RNNs) architecture for the task of cleaning text. The encoder network would take in the "noisy" sequence and the decoder would generate the "cleaned" sequence. Seq2Seq models is often used for Neural Machine Translation (NMT). The next thing is you will need a very large data set. Fortunately this shouldn't be too hard to generate noise injections (of real words, symbols, fake words, letter omissions etc) into sequences of text. A good guide for a similar task is in the following post. The implementation uses Keras and has all of the code. <https://towardsdatascience.com/how-to-create-data-products-that-are-magical-using-sequence-to-sequence-models-703f86a231f8>
63,366,161
**PS : For requirements for this project use Javascript or Jquery, i can't use CSS.** I need to extract images from image and display in div using javascript and html. I try using this image : [![enter image description here](https://i.stack.imgur.com/3YWPU.png)](https://i.stack.imgur.com/3YWPU.png) **For information this image is just for test and base in solution i will adapt in real world image project.** I want to get this 2 images and display in my div using img dom in my HTML. [![enter image description here](https://i.stack.imgur.com/XzryE.png)](https://i.stack.imgur.com/XzryE.png) [![enter image description here](https://i.stack.imgur.com/wb01R.png)](https://i.stack.imgur.com/wb01R.png) For this purpose i try to adapt this work `http://jsfiddle.net/yn1tworg/6/` to work for me. But without success. Anyone have a idea how to resolve this issue, or `jsfiddle.net` work plz share with me and thanks.
2020/08/11
[ "https://Stackoverflow.com/questions/63366161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5308487/" ]
Use CSS and just play with `background-position` until the image is what you need to be. ```css #box{ width: 120px; height: 120px; background-color: #ff0000; background-image: url(https://i.stack.imgur.com/3YWPU.png); background-position: 280px -260px; } ``` ```html <div id='box'></div> ```
27,271,871
I have two divs with the total height of the viewport and a button for scrolling from one to another with ScrollTo jquery plugin. The problem is that I want to prevent the posibility of manual scroll. I want that when someone scrolls with mouse down, the browser scroll automatically to the second view, and when I scroll to top gets the previous view. I don't know if I'm explaining well, here an example: <http://orangina.eu/heritage> Try to scroll in this webpage, this is what I need. Thanks!
2014/12/03
[ "https://Stackoverflow.com/questions/27271871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4189043/" ]
Correct me if I'm wrong but it looks to me like you're trying to disable the browsers default scrolling behaviour, attach events to scroll up and scroll down and scroll up or down to the height of the page's height. The way I would do this is disable the browser's default scrolling behaviour with `overflow:hidden` to the body and html. Then you can bind the jQuery "mousewheel" and "DOMMouseScroll" to the div checking for "event.originalEvent.detail > 0" or "e.originalEvent.wheelDelta < 0" for down scrolling or else for scrolling up. Finally add your function call inside the if or else depending on the downscroll or upscroll. I can write the code if you want but it might help you more if you try this yourself.
15,239,337
For the purpose of this question I am not interested in big-O calculations; as I understand, it is used to compare relatively between algorithms, whereas I want to have an estimation of absolute time taken to run an algorithm. For example, I am using a vision algorithm that carries out approximately 2 million calculations/frame. The program runs on a core-i7 desktop. Then, how long will it take? To compute this time duration, which cpu operation should I take as a worst case calculation (\*,/,+,.. on floating point numbers, or something else)?
2013/03/06
[ "https://Stackoverflow.com/questions/15239337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1033713/" ]
Using `layout-large`, `layout-xlarge` is no longer recommended. Google says to target tablets using sw\* layouts. eg To target 7 inch tablets, put the layout in `layout-sw600dp`. For 10 inch tablets, put them in `layout-720dp`. The only exception is when targeting buggy devices such as the original galaxy tab running android 2.x, due to a bug in layout resolution you'll need to create a folder called `layout-xlarge-land` and place the layout there. Additionally, don't just have high res images and dump them in hdpi. Properly scale your images and put them in mdpi, hdpi, xhdpi etc. Most of the time, this will result in a much faster load time for the app, and a smaller APK size because you're not bundling "high resolution images" and making the framework scale the image on request. Having unoptimized images in your package will also have consequences with memory usage, as bitmaps are stored on the java heap.
2,488
Does anybody have any idea of what are Steven Erikson's plans towards works set in the Malazan world? Can we expect more of Ganeos and others? Also, I believe that Erikson and Esslemont have a pact about not interfering with each other, is that true?
2011/03/16
[ "https://scifi.stackexchange.com/questions/2488", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/947/" ]
From a [forum discussion following a signing tour](http://www.sffworld.com/forums/showthread.php?t=20236) (so second hand info) > > Steven Erikson confirmed that he has > signed up for 6 more Malazan novels > for Bantam. They will not be direct > continuations of the Malazan Book of > the Fallen, but will be two somewhat > self-contained trilogies, one of which > will be the backstory of Anomander > Rake. He also confirmed that the two > new trilogies will be released at a > more leisurely pace than the MBF, as > the one-book-per-year pace is too much > to keep up indefinitely. > > > He also confirmed that there are 6 > more Bauchelain and Korbal Broach > novellas to come, to bring the total > to 9. > > > Added in with the 10 volumes of the > MBF itself and Esslemont's planned 6 > novels, that brings the total to 22 > novels, 9 novellas and 1 companion > volume set in this world. > > >