text
stringlengths
64
81.1k
meta
dict
Q: MetaMap java.lang.OutOfMemoryError: Java heap space We keep encountering a java.lang.OutOfMemoryError: Java heap space error when running MetaMap (with Java API and UIMA wrapper). Unfortunately, the logs are not very informative, so we don't know which file it's puking on. In the past, we've had issues with MetaMap creating huge circular annotations when it's encountered the pipe (|) symbol. However, the file set we're using (MIMIC notes) don't contain any pipe symbols. Are there other characters that may be exhibiting similar behavior to the pipe symbol? We could increase system RAM to circumvent the heap space issue (it's actually not able to use the maximum set heap, which is set to 6 GB, since system RAM is limited), but we would prefer to know what is causing the issue, especially since then the output file size is more manageable. * EDIT * Just to clarify: We have increased memory resources for the JVM and that does help to actually push the data through (this was tested on a local VM). The problem MetaMap has is that it creates enormous circular annotations that eat up the JVM resources (and on our current system, the OS RAM is not optimal). As noted in my comment below, we preprocess the files to strip them of any characters that throw errors. The heap space error is kind of annoying though, since unlike for other errors we've encounter (e.g., spaces surrounding a lone period, as in text . text), these just throw a parsing error with the text that threw the error. In the case of the pipe symbol, we found it by increasing RAM (on the VM we were initially testing this on) and then looking at the annotations in the UIMA viewer. We were able to identify the problematic files, since the output file size of the XMI with circular annotations is enormous. We are running some tests on the VM again to see if we can identify the issue, but if anyone has MetaMap experience to help us identify any problem characters or character sequences, that would be desirable. * EDIT 2 * Memory should not be an issue. We are running the app using export JAVA_TOOL_OPTIONS='-Xms2G -Xmx6G -XX:MinHeapFreeRatio=25 -XX:+UseG1GC' there is a fundamental issue with circular annotations we are trying to resolve. This is gobbling up resources and puking. A: The solution was two fold: There is a UIMA JVM environment variable that needed to be set, as export UIMA_JVM_OPTS="-Xms128M -Xmx5g" And secondly, there is a MetaMap switch that reduces the recursion depth for creating annotations (which goes in the MetaMapApiAE.xml config file): <configurationParameterSettings> ... previous settings omitted ... <nameValuePair> <name>metamap_options</name> <value> <string>--prune 30</string> </value> </nameValuePair> </configurationParameterSettings>
{ "pile_set_name": "StackExchange" }
Q: Make WMS layer background transparent in Leaflet I have inserted the following layer from a GeoServer WMS in the following Leaflet map : var nexrad = new L.TileLayer.WMS("URL", { layers: 'Wrecks:WrecksGreaterNorthSea', format: 'image/png', transparent: true }); but the background is not transparent. I have tried to set it by modifying the tiff image with QGIS creating a transparency band but it does not work. I have a second WMS layer in the map but I do not have this problem with this one. Could you help me solve this issue, please? A: The problem is not in the code, but on the image itself. The Geotiff has 3 bands, and the nodata value is set to 0 Band 1 Block=508x8 Type=Byte, ColorInterp=Red NoData Value=0Band 2 Block=508x8 Type=Byte, ColorInterp=Green NoData Value=0 Band 3 Block=508x8 Type=Byte, ColorInterp=Blue NoData Value=0 However inspecting the image in QGIS, it seems that the background has the values of 255,255,255 (white). The Geotiff has no way of "knowing" these values represent a "no value", unless you tell it. You can set the no-value to 255, either using GDAL or the GDAL wrapper inside QGIS (Raster->Conversion->Translate). Something like this: gdal_translate -a_nodata 255 WrecksGreaterNorthSea.tif output.tif The resultant image will effectively show a transparent background where there is no data I have no way of testing if the rendered image works in Geoserver, but here is an example using the L.ImageOverlay directive, where transparency works out of the box:
{ "pile_set_name": "StackExchange" }
Q: POST request using QWebView request Hi I'm working with pyqt4 and what I want to do is to craft an arbitrary POST request by using the QtWebKit request of my QWebPage/QWebView. By looking extensively around my understanding is that I have to subclass networkaccessmanager by overriding the createRequest() method. I saw an example that allowed to use the fourth parameter of createRequest to extract the data of a POST request (see code below) being sent, but my question is how can I set that same data variable of createRequest to send a custom POST data, like "query=myvalue"? Apparently data is a QIODevice variable: I tried a lot of different ways to set it, but can't get it to work and always end up with python complaining it's an unexpected value. Am I missing something here? Anybody care to share a working code sample? import sys from PySide.QtCore import * from PySide.QtGui import QApplication from PySide.QtWebKit import QWebView, QWebPage from PySide.QtNetwork import QNetworkAccessManager html = ''' <html> <body> <form action="http://www.google.com" method="post"><input type="text" name="test" /><input type="submit" value="submit"/></form> </body> </html> ''' class Browser(object): def __init__(self): self.network_manager = QNetworkAccessManager() self.network_manager.createRequest = self._create_request self.web_page = QWebPage() self.web_page.setNetworkAccessManager(self.network_manager) self.web_view = QWebView() self.web_view.setPage(self.web_page) self.html_data = None def _create_request(self, operation, request, data): # data contains all the post data that is being added to the request # so you can look into it here print data.readAll() reply = QNetworkAccessManager.createRequest(self.network_manager, operation, request, data) return reply if __name__ == '__main__': app = QApplication(sys.argv) browser = Browser() frame = browser.web_page.mainFrame() browser.web_view.setHtml(html) browser.web_view.show() app.exec_() A: The code you posted is from one of my answers, so I feel obligated to answer this question too :) from PySide.QtCore import QByteArray, QUrl from PySide.QtGui import QApplication from PySide.QtWebKit import QWebView, QWebPage from PySide.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply class Browser(object): def __init__(self): self.network_manager = QNetworkAccessManager() self.network_manager.createRequest = self._create_request self.network_manager.finished.connect(self._request_finished) self.web_page = QWebPage() self.web_page.setNetworkAccessManager(self.network_manager) self.web_view = QWebView() self.web_view.setPage(self.web_page) def _create_request(self, operation, request, data): print data.readAll() reply = QNetworkAccessManager.createRequest(self.network_manager, operation, request, data) return reply def _request_finished(self, reply): if not reply.error() == QNetworkReply.NoError: # request probably failed print reply.error() print reply.errorString() def _make_request(self, url): request = QNetworkRequest() request.setUrl(QUrl(url)) return request def _urlencode_post_data(self, post_data): post_params = QUrl() for (key, value) in post_data.items(): post_params.addQueryItem(key, unicode(value)) return post_params.encodedQuery() def perform(self, url, method='GET', post_data=dict()): request = self._make_request(url) if method == 'GET': self.web_view.load(request) else: encoded_data = self._urlencode_post_data(post_data) request.setRawHeader('Content-Type', QByteArray('application/x-www-form-urlencoded')) self.web_view.load(request, QNetworkAccessManager.PostOperation, encoded_data) if __name__ == '__main__': app = QApplication([]) browser = Browser() browser.perform('http://www.python.org', 'POST', {'test': 'value', 'anothername': 'gfdgfd'}) app.exec_()
{ "pile_set_name": "StackExchange" }
Q: Interleaving vector elements with corresponding lists to create new vector of vectors I have data in the following format: [["i1" "i2"] ['("A" "B" "C" "D") '("red" "blue" "green" "yellow")]] I want to transform this to get a new data structure: [["column" "value"] ["i1" "A"] ["i1" "B"] ["i1" "C"] ["i1" "D"] ["i2" "red"] ["i2" "blue"] ["i2" "green"] ["i2" "yellow"]] Any help with this difficult problem would be great. My attempts to far have involved using nested "for" statements, but I cannot get the resulting vectors in the same level as the header vector, despite many attempts to convert the results. I have also used "interleave" and "repeat" on the value for column, but that too creates lists at the wrong level. A: There are some fun answers here. I will just add that conceptually, I think this is a good place for for. For each item in the first vector, you want to pair it with items from the corresponding lists in the second vector. (defn convert [[cols vals]] (vec (cons ["column" "value"] ;; turn the list into a vector. (for [i (range (count cols)) ;; i <- index over columns j (nth vals i)] ;; j <- items from the ith list [(nth cols i) j])))) ;; [col val] user=>(convert data) This is easily modified to handle more vectors of values: (defn convert [[cols & vals]] (cons ["column" "value"] (mapcat #(for [i (range (count cols)) j (nth % i)] [(nth cols i) j]) vals)))
{ "pile_set_name": "StackExchange" }
Q: React Leaflet Collision I am using map without any label of town. I am putting the labels, i need these labels appear and dissapear on zoom in/out. When zoom out appear only big towns when zoom in appear all towns. Is there fuctionality for this in existing react-leaflet? Also i am trying make plugin for Leaflet.LayerGroup.Collision, I tried overriding LayerGroup from react-leaflet import React, { PropTypes } from 'react'; import { MapLayer } from 'react-leaflet'; import { layerGroup } from 'leaflet'; import './leaflet-layergroup-collision'; export default class LayerGroupCollision extends MapLayer { static childContextTypes = { layerContainer: PropTypes.shape({ addLayer: PropTypes.func.isRequired, removeLayer: PropTypes.func.isRequired, }) } getChildContext() { return { layerContainer: this.leafletElement, } } createLeafletElement() { return layerGroup(this.getOptions()).collision({margin:5}); } } But i am getting error Uncaught TypeError: (0 , _leaflet.layerGroup)(...).collision is not a function Any help how implement this or any alternative idea? A: layerGroup should be with capital L, LayerGroup import { LayerGroup } from 'leaflet'; or an alternative try: import L from 'leaflet'; and then L.LayerGroup(this.getOptions()).collision({margin:5});
{ "pile_set_name": "StackExchange" }
Q: Drawing sound bars around a canvas circle I have the following which draws the frequency of an audio clip as soundbars: const drawSinewave = function() { requestAnimationFrame(drawSinewave); analyser.getByteFrequencyData(sinewaveDataArray); canvasCtx.fillStyle = 'white'; canvasCtx.fillRect(0, 0, canvas.width, canvas.height); canvasCtx.lineWidth = 2; canvasCtx.strokeStyle = "#40a9ff"; canvasCtx.beginPath(); const sliceWidth = canvas.width * 1.0 / analyser.fftSize; let x = 0; var barWidth = (canvas.width / analyser.fftSize) * 2.5; var barHeight; for(let i = 0; i < analyser.fftSize; i++) { barHeight = sinewaveDataArray[i]; canvasCtx.fillStyle = 'rgb(' + (barHeight+100) + ',50,50)'; canvasCtx.fillRect(x,canvas.height-barHeight/2,barWidth,barHeight); x += barWidth + 1; } canvasCtx.lineTo(canvas.width, canvas.height / 2); canvasCtx.stroke(); }; It looks like this: However I would like to draw that around a circle, so like the bars come out like rays from a circle border. I have failed to figure this out. Could someone assist me? A: A simple method is to draw one bar on its side, offset from the center of the circle. before you draw the bar rotate the current transform to the correct position for the bar. The example uses some random test data as I could not be bothered setting up an analyser const steps = 100; const testData = []; const ctx = canvas.getContext("2d"); const centerX = canvas.width / 2; const centerY = canvas.height / 2; const innerRadius = Math.min(canvas.width, canvas.height) / 2 * (3/4); const outerRadius = Math.min(canvas.width, canvas.height) / 2 - 20; const barHeight = outerRadius - innerRadius; const angStep = (Math.PI * 2) / steps; const barWidth = (innerRadius * Math.PI * 2 / steps) * 0.9; const barWidthHalf= barWidth * 0.5; const startAngle = -Math.PI / 2; // 12 oclock requestAnimationFrame(drawBars) function drawBars() { const color = h => 'rgb(' + (100+h*150) + ',' + (50+h*100) + ',' + (100+h*40) + ')'; //analyser.getByteFrequencyData(sinewaveDataArray); //const steps = analyser.fftSize; animateTestData(); ctx.fillStyle = 'white'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.lineWidth = 2; ctx.strokeStyle = "#40a9ff"; ctx.beginPath(); ctx.arc(centerX, centerY, innerRadius - 4, 0, Math.PI * 2); ctx.stroke(); for(let i = 0; i < steps; i++) { const h = testData[i]; const ang = i * angStep + startAngle; const xAx = Math.cos(ang); // direction of x axis const xAy = Math.sin(ang); ctx.setTransform(xAx, xAy, -xAy, xAx, centerX, centerY); ctx.fillStyle = color(h); ctx.fillRect(innerRadius, -barWidthHalf, h * barHeight, barWidth); } ctx.setTransform(1,0,0,1,0,0); // reset the transform; requestAnimationFrame(drawBars); }; for(let i = 0; i < steps; i ++) { testData.push(Math.random()) } var sOffset = 0; function animateTestData() { var i = 0, t, phase = Math.sin(sOffset/ 10) * 100; while(i < steps) { var t = testData[i]; t += (Math.random() - 0.5) * 0.01; t += Math.sin(i * 0.6 + phase + sOffset) * 0.03 t += Math.sin(i * 0.1 + sOffset * 2) * 0.07 testData[i++] = t <= 0 ? 0 : t >= 1 ? 1 : t; } sOffset += 0.1; } <canvas id = "canvas" width = "600" height = "600"></canvas>
{ "pile_set_name": "StackExchange" }
Q: windows mobile: Check if network is available How do I check if the internet is available on a windows mobile 6.5+ device? Thanks. A: Something like this. In essence, this is from the MSDN Tips and Tricks webcast of January 12, 2005. It's slightly rewritten to fit my own standards and completely untested, but you get the idea. Use as you please. enum ConnectionStatus { Offline, OnlineTargetNotFound, OnlineTargetFound, } ConnectionStatus GetConnectionStatus(String url) { try { // // If the device is set to loopback, then no connection exists. // String hostName = System.Net.Dns.GetHostName(); System.Net.IPHostEntry host = System.Net.Dns.GetHostByName(hostName); String ipAddress = host.AddressList.ToString(); if(ipAddress == System.Net.IPAddress.Parse("127.0.0.1").ToString()) { return ConnectionStatus.Offline; } // // Now we know we're online. Use a web request and check // for a response to see if the target can be found or not. // N.B. There are blocking calls here. // System.Net.WebResponse webResponse = null; try { System.Net.WebRequest webRequest = System.Net.WebRequest.Create(url); webRequest.Timeout = 10000; webResponse = webRequest.GetResponse(); return ConnectionStatus.OnlineTargetFound; } catch(Exception) { return ConnectionStatus.OnlineTargetNotFound; } } catch(Exception) { return ConnectionStatus.Offline; } }
{ "pile_set_name": "StackExchange" }
Q: What is causing this error about string? #include <iostream> #include <string> int main(void) { using std::cout; using std::cin; using std::string; string name; int n1, n2; cout << "What is your name ?\n"; cin >> name; cout << "Hello " << name.c_str() <<"!\n" << "Please give me two number separated by space\n"; cin >> n1 >> n2; cout << "Sum of " << n1 << " + " << n2 << " is " << n1 + n2 << "\n"; return 0; } My console input/output looks like this: What is your name ? John Titor Hello John! Please give me two number separated by space Sum of 0 + 1961462997 is 1961462997 It doesn't print the full name, only "John", and it doesn't even ask me about puting two numbers. A: You should use std::getline to get a string with spaces. std::cin separates the strings by spaces. getline(cin, name); In addition, you can print a std::string by std::cout without .c_str(): cout << name;
{ "pile_set_name": "StackExchange" }
Q: Pros and cons for different lambda expression syntax in view helper call I'm writing a view helper based on the ideas about partial requests from this blog post: http://blog.codeville.net/2008/10/14/partial-requests-in-aspnet-mvc/ In the controller action I prepare a widget by running: AddWidget<Someontroller>(x => x.OtherActionName(new List<int>())); Then in my view I can run the action and render the view output by doing some form of: Html.RenderWidget... And here comes my question, what compiler checked syntax would you choose from the following to use in the view: Html.RenderWidget<SomeController, List<int>>(x => x.OtherActionName); Html.RenderWidget<SomeController>(x => x.OtherActionName(null)); Html.RenderWidget<SomeController>(x => x.OtherActionName(It.IsAny<List<int>>); Can anyone name some pros and cons? Or is it better to go with strings as the original Partial Request implementation does? PS. Don't take the naming of It.IsAny> to litteraly, I just thought it was best described using the Moq naming. A: Using the strings is significantly faster than using so-called strongly typed helpers (really; it's like 10 times faster), unless you implement some kind of caching for your Expression parsing. Note, though, that MVC 2 may have something along these lines RSN. So one option, if you can, is to just wait and see what's in the next preview drop. At the very least, you'll want to look like the rest of MVC, and the MVC team may end up doing your work for you. ("So called" because under the covers they're going to end up as strings in a RouteValueDictionary anyway.)
{ "pile_set_name": "StackExchange" }
Q: jQuery custom order for .each() I am successfully using .each() to fade in some blocks one after the other. As expected it starts at the first element and moves on to the next in order. Is there any way to control the order of .each()? Instead of 1,2,3,4 and so on I'd like, for example, 1,2,5,9,6,3,4,7,8. $(window).load(function() { $(".blocks").each(function(i) { $(this).delay((i + 1) * 500).fadeIn(500); }); }); A: In a direct answer to your question, .each() iterates the items of a jQuery object in the order the items are in the jQuery internal array. There is no way to control the order that .each() uses other than changing the order in the array that it's iterating. Since you don't disclose how the desired order would be determined algorithmically, your options are: Sort the array before .each() is called Manually create the desired order before the .each() call Some other piece of code that orders the array appropriately before the .each() call In the very specific instance of your code snippet, you could solve it differently without reordering .each() or reordering the array by creating a lookup table that would look up the desired delay value for a given array index. $(window).load(function() { var delayLookup = {1:1,2:2,5:3,9:4,6:5,3:6,4:7,7:8,8:9}; $(".blocks").each(function(i) { var delayTime = delayLookup[i] || i; $(this).delay(delayTime * 500).fadeIn(500); }); });
{ "pile_set_name": "StackExchange" }
Q: "Unregister" vs "Deregister" The concept of "undoing a registration" is widely used in my line of work. While most dictionaries define unregister as the proper verb for it, several widely used and highly considered sources also use the verb deregister. Do both verbs exist? Are they synonyms? Is there a slight difference in their meaning? A: This is a question that used to plague me for ages, until I finally sat down and thought it through. As a programmer, I see both used a lot, and often interchangeably. For me, I like to think of the question by beginning with another question: What is the 'not registered' state called? Let's assume you're a programmer, but keep in mind this is applies anywhere. When you have a variable which represents some item that can be registered, what do you call the function to discover if it is registered? In all likelihood, you'll call it 'isRegistered()'. So in that sense, you make the problem into a boolean. i.e. is it registered, or is it NOT registered. Then, from that logic, I believe your options simply become: isRegistered() - false if the object is 'unregistered' - i.e. 'not registered' false == isRegistered(). registerSomething() - It has now moved from 'not registered' to 'registered'. deregisterSomething() - It has now moved from 'registered' to 'not registered'. i.e. 'unregistered'. This is why it's convention in programming to call an object that hasn't been 'initialised' as 'uninitialised', not 'deinitialised'. This implies it was never initialised to begin with, so its initial state is 'uninitialised'. If its initial state was called 'deinitialised' it would give the false impression that it was previously initialised. The bottom line for me is that you should define a convention for its use in your particular context, and stick to it. The above convention is what I now use throughout my code. Urgh... Here is all of that in a single line ;) state=unregistered -> 'register' -> state=registered -> 'deregister' -> state=unregistered. -- Shane A: Here's a look at usage during the last 20 years: As evidenced, unregister received a substantial boost shortly after the dot-com boom/bust of the late 90s, while deregister usage has been more or less the same throughout. It's worth noting that neither word is defined by any major dictionary, although some lesser dictionaries include the two. (Of course, placement in a dictionary does not mean a word is "real" or not - a word can exist anywhere - but it does indicate whether or not the word enjoys popular usage and if it has standardized spellings.) Additionally, both the un- and de- prefixes can be defined as a reversal of action. Despite the similarities, I'd go with popular usage and use unregister. A: Generally speaking, the de- and un- prefixes have different usages. Un- more usually negates an adjective: unkind, unfair, etc. On the other hand, de- is a verb prefix, that denotes the action of removing some thing or state. Hence: unleaded petrol/gasoline (because lead doesn't occur in petrol until it's added) but decaffeinated coffee (because the caffeine has been taken out). However, when an adjective is from a verb, usage often slips from this, and we end up with un- prefixing a new verb. So the adjective unregistered gives rise to the verb to unregister, although deregister would be more in line with convention. By this convention, unregistered should mean not registered (whether through active deregistration or never having been registered in the first place) and there should be no verb to unregister. Deregistered should mean actively removed from the register. (The verb to undo is I think the most notable exception to the conventional norm.)
{ "pile_set_name": "StackExchange" }
Q: Missing display option in dashlet I am not able to see any display option in civiCRM 4.6.10 Version of Joomla to show report on dashlet in bar/pie format under access tab in report instance. Please help from where i can activate the bar/pie option. I am getting tabular report when i check option Available for Dashboard? Users with appropriate permissions can add this report to their dashboard. A: The option you're looking for isn't under the Access tab. It's below all the tab data. See the attached screenshot. Note that most reports do NOT offer the ability to view a chart - make sure your report does! If you'd like to test, use the "Contribution Summary" report, which supports charts. After you've changed the view, press the "Update Report" button, and on the dashboard, press "Refresh Dashboard Data" and you should be in business.
{ "pile_set_name": "StackExchange" }
Q: AS3 Separating Arrays for different items I have a function that creates a new value inside an associative array. var array:Array = new Array(new Array()); var i : int = 0; function personVelgLand(evt:MouseEvent) { for(i = 0; i < personListe.dataProvider.length; i++) { if(txtPersonVelg.text == personListe.dataProvider.getItemAt(i).label) { personListe.dataProvider.getItemAt(i).reise = array; personListe.dataProvider.getItemAt(i).reise.push(landListe.selectedItem.land); } } } What happens is that the 'array' array which becomes 'personListe.dataProvider.getItemAt(i).reise' applies to every item in the list. I want it so that each time the function runs that the .reise only applies to the item chosen and not all of them. EDIT: I did this: personListe.dataProvider.getItemAt(i).reise = new Array(array); And now they are not the same but now each item in the list can not have multiple .reise values... EDIT 2: dataProvider is nothing it would work just as fine without it. .reise is created in the function I originally posted it creates .reise in the object getItemAt(i). personListe is a list which the users add their own items to by the use of a input textfield. It is given by this function: function regPerson(evt:MouseEvent) { regPersoner.push(txtRegPerson.text); personListe.addItem({label:regPersoner}); regPersoner = new Array(); txtRegPerson.text = ""; } EDIT 3 : The user can register names which turn in to labels in a list. There is also list with 3 countries, Spain, Portugal and England. The user can then register a country to a person they select. Thats when I want to create the .reise inside the "name" items in the first list which contains the countries they have selected. I want every name to be able to select multiple countries which then will be created in the element .reise inside the item that holds their name. This would be easy if I could use strings. But later I plan to have the user type in a country and then something that would show every user that have selected that country. That is why the countries need to be stored as arrays inside the "name" items.. A: You should first create a class for the User data that you are modelling. You already know all the properties. The user can register names The user can then register a country to a person they select. able to select multiple countries Such a class could look like this: package { public class User { private var _name:String; private var _countries:Array; public function User(name:String) { _name = name; _countries = []; } public function get name():String { return _name; } public function get countries():Array { return _countries; } public function set countries(value:Array):void { _countries = value; } } } Now create a DataProvider, fill it with objects of that class and use it for the list as described here: import fl.controls.List; import fl.data.DataProvider; var users:List = new List(); users.dataProvider = new DataProvider([ new User("David"), new User("Colleen"), new User("Sharon"), new User("Ronnie"), new User("James")]); addChild(users); users.move(150, 150); In order to get a label from a User object, define a labelFunction import fl.controls.List; import fl.data.DataProvider; var users:List = new List(); users.labelFunction = userLabelFunction; function userLabelFunction(item:Object):String { return item.name; } users.dataProvider = new DataProvider([ new User("David"), new User("Colleen"), new User("Sharon"), new User("Ronnie"), new User("James")]); addChild(users); users.move(150,150); This way you do not have to add a label property that you don't want in your class. Selecting a name means selecting a user. The list of countries associated to the name should show up in a second List. The DataProvider of that List remains constant, a list of all the available countries. import fl.controls.List; import fl.data.DataProvider; // list of users var users:List = new List(); addChild(users); users.move(150,150); users.labelFunction = userLabelFunction; function userLabelFunction(item:Object):String { return item.name; } users.dataProvider = new DataProvider([ new User("David"), new User("Colleen"), new User("Sharon"), new User("Ronnie"), new User("James")]); // lsit of countries var countries:List = new List(); addChild(countries); countries.move(550,150); // adjut position as desired countries.dataProvider = new DataProvider([ {label:"a"}, {label:"b"}, {label:"c"}, {label:"d"}, {label:"e"}, {label:"f"}]); Now all you have to do is to wire it all up. If a user is selected, select his countries in the countries list. If a country is selected, add that to the currently selected users list of countries. That could look somethign like this: users.addEventLsitener(Event.CHANGE, onUserSelected); function onUserSelected(e:Event):void { countries.selectedItems = users.selectedItem.countries; } countries.addEventLsitener(Event.CHANGE, onCountrySelected); function onCountrySelected(e:Event):void { users.selectedItem.countries = countries.selectedItems; } The full code could look like this. I did not test this, but you get the idea. // list of users var users:List = new List(); addChild(users); users.move(150,150); users.labelFunction = userLabelFunction; function userLabelFunction(item:Object):String { return item.name; } users.dataProvider = new DataProvider([ new User("David"), new User("Colleen"), new User("Sharon"), new User("Ronnie"), new User("James")]); // list of countries var countries:List = new List(); addChild(countries); countries.move(550,150); // adjut position as desired countries.dataProvider = new DataProvider([ {label:"a"}, {label:"b"}, {label:"c"}, {label:"d"}, {label:"e"}, {label:"f"}]); // events users.addEventLsitener(Event.CHANGE, onUserSelected); function onUserSelected(e:Event):void { countries.selectedItems = users.selectedItem.countries; } countries.addEventLsitener(Event.CHANGE, onCountrySelected); function onCountrySelected(e:Event):void { users.selectedItem.countries = countries.selectedItems; } From what I understand this seems to work except for the fact that the names are already provided when the program starts. What I want is that the user adds the name themselves while the program is running. You can add new items with the methods provided by the DataProvider class, like addItem() for example. Just add new User objects.
{ "pile_set_name": "StackExchange" }
Q: Datastore Location with Google App Engine / Java How can I customize the location of the datastore file while working with GAE/J. The option --datastore_path doesn't seem to work with GAE/J. And if it is possible, what option do I use in the maven-gae-plugin. A: I assume you mean while running the dev app server locally. Try the --generated_dir option with <sdk>/bin/dev_appserver.sh: --generated_dir=dir Set the directory where generated files are created. The generated files include the local datastore file.
{ "pile_set_name": "StackExchange" }
Q: Get public page statuses using Facebook Graph API without Access Token I'm trying to use the Facebook Graph API to get the latest status from a public page, let's say http://www.facebook.com/microsoft According to http://developers.facebook.com/tools/explorer/?method=GET&path=microsoft%2Fstatuses - I need an access token. As the Microsoft page is 'public', is this definitely the case? Is there no way for me to access these public status' without an access token? If this is the case, how is the correct method of creating an access token for my website? I have an App ID, however all of the examples at http://developers.facebook.com/docs/authentication/ describe handling user login. I simply want to get the latest status update on the Microsoft page and display it on my site. A: This is by design. Once it was possible to fetch the latest status from a public page without access token. That was changed in order to block unidentified anonymous access to the API. You can get an access token for the application (if you don't have a Facebook application set for your website - you should create it) with the following call using graph API: https://graph.facebook.com/oauth/access_token? client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET& grant_type=client_credentials This is called App Access Token. Then you proceed with the actual API call using the app access token from above. hope this helps A: You can use AppID and Secret key to get the public posts/feed of any page. This way you don't need to get the access-token. Call it like below. https://graph.facebook.com/PAGE-ID/feed?access_token=APP-ID|APP-SECRET And to get posts. https://graph.facebook.com/PAGE-ID/posts?access_token=APP-ID|APP-SECRET A: It's no more possible to use Facebook Graph API without access token for reading public page statuses, what is called Page Public Content Access in Facebook API permissions. Access token even is not enough. You have to use appsecret_proof along with the access token in order to validate that you are the legitimate user. https://developers.facebook.com/blog/post/v2/2018/12/10/verification-for-individual-developers/. If you are individual developer, you have access to three pages of the data (limited), unless you own a business app.
{ "pile_set_name": "StackExchange" }
Q: Unable to vertically align JLabel with JCheckBox as if single JCheckBox with GroupLayout Sometimes I need the label for a checkbox to be to the left of the checkbox not the right so instead of using JCheckBox checkbox = new JCheckBox("label",false); I do: JCheckBox checkbox = new JCheckBox("",false); JLabel label = new JLabel("label"); GroupLayout.ParallelGroup vp1 = layout.createBaselineGroup(false, false); vp1.addComponent(checkbox); vp1.addComponent(label); (I am using GroupLayout) but they are not vertically aligned correctly, I've also tried =layout.createParallelGroup(GroupLayout.Alignment.CENTER); which doesn't look bad but still appears different to using a single checkbox and various other options, is it possible to get the same alignment ? A: you may use the function setHorizontalTextPosition(int textPosition) with the int value SwingConstants.RIGHT etc
{ "pile_set_name": "StackExchange" }
Q: Adding Excel Sheets to End of Workbook I am trying to add excel worksheets to the end of a workbook, reserving the first sheet for a summary. import win32com.client Excel = win32com.client.DispatchEx('Excel.Application') Book = Excel.Workbooks.Add() Excel.Visible = True Book.Worksheets(3).Delete() Book.Worksheets(2).Delete() Sheet = Book.Worksheets(1) Sheet.Name = "Summary" Book.Worksheets.Add(After=Sheet) Sheet = Book.Worksheets(2) Sheet.Name = "Data1" This code adds the new sheet to the left, despite using After=Sheet, and when I modify the sheet named "Data1", it overwrites the sheet named "Summary". This is similar to this problem: Adding sheets to end of workbook in Excel (normal method not working?) but the given solutions don't work for me. A: Try using this by adding Before = None: add = Book.Sheets.Add(Before = None , After = Book.Sheets(book.Sheets.count)) add.Name = "Data1"
{ "pile_set_name": "StackExchange" }
Q: iOS Accessibility - Voice over repeating the same UI elements again in a loop I am new to accessibility, I have a simple table view which has a custom cell with some labels and text field, I have also set the order of elements to be read by self.contentView.accessibilityElements in awake from nib method. But when I run the app in voice over mode, some elements are repeated multiple times in a loop this happen when i swap 2 fingers from bottom to top , How can i stop this or is this a expected behaviour ?. override func awakeFromNib() { super.awakeFromNib() // Initialization code self.contentView.accessibilityElements = [headerlabel, Okbutton, nameTextField] } A: The code below works and reads everything below the cell as well, after a 2 finger swipe up. self.accessibilityElements = [headerLabel, okButton, nameTextField]
{ "pile_set_name": "StackExchange" }
Q: Emacs - installation in Vista I haven't used emacs but have heard about its features and really want to try it out. So can someone post the procedure how to install it in win vista. And the links to download its setup and stuffs so that i can get it setup on my lap? A: Your best bet is probably using EmacsW32 which is nicely integrated into Windows and comes with a proper Windows installer. A: Quick answer: The GNU Emacs FAQ for Windows
{ "pile_set_name": "StackExchange" }
Q: Bash Grep exact search I am trying to find an exact word in a file. The word is myServer and the file contents in which I am trying to find it are: This is myServer and it is cool This is myServer-test and it is cool Here're the results of my various attempts to do this: grep '^myServer$' test-file.txt grep -Fx myServer test-file.txt --> no results grep -w myServer test-file.txt grep -w myServer test-file.txt grep '\<myServer\>' test-file.txt grep '\bmyServer\b' test-file.txt --> This is myServer and it is cool This is myServer-test and it is cool Am I missing some switch here? Many Thanks. A: Try grep with word boundaries: grep '\<myServer\>' test-file.txt EDIT: Looks like you don't want to treat hyphen as word boundary. Use grep like this for that purpose: grep -E '\<myServer\>([^-]|$)' test-file.txt
{ "pile_set_name": "StackExchange" }
Q: Calling Awaitable Methods in Property Accessor [Windows Store Apps/Metro Apps] I have a custom class (to simplify stuff, I have stripped down the codes): public class AlbumItem { public StorageFile AlbumThumbnail { get; set;} } When I bind this to a ListView: <ListView.ItemTemplate> <DataTemplate> <Grid Height="100" Background="#FFabe372"> <Grid.ColumnDefinitions> <ColumnDefinition Width="80" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Image Source="{Binding AlbumSource}" Margin="10" Stretch="Uniform"></Image> <TextBlock Margin="20 5" Grid.Column="1" Style="{StaticResource AlbumListViewItemStyle}" Text="{Binding AlbumDisplayText}"></TextBlock> </Grid> </DataTemplate> </ListView.ItemTemplate> The Image's source is set to AlbumSource, as I have thought to implement AlbumSource as a Get-only property: public class AlbumItem { public StorageFile AlbumThumbnail { get; set;} public BitmapImage AlbumSource { get { BitmapImage bmp = new BitmapImage(); bmp.SetSource(await AlbumThumbnail.OpenReadAsync()); return bmp; } } } As expected I can't use the await keyword in the accessor method, at the same time I cannot declare a property stub as an async method. Can somebody point me in the correct direction? I may be trying a Converter later. Thanks! A: IMHO property accessors should always return almost immediately. Long running operations should not execute inside a property accessor as this can have significant perfromance impacts because of the widely held assumption that an accessor is basically a variable read operation (i.e. properties can be accessed a lot, in loops, not cached for subsequent access etc). I'd do something like this: private async Task SetAlbumSourceAsync() { bmp = new BitmapImage(); var source = await AlbumThumbnail.OpenReadAsync(); bmp.SetSource(source); RaisePropertyChanged("AlbumSource"); } BitmapImage bmp; public BitmapImage AlbumSource { get { if (bmp == null) // might need a better sync mechanism to prevent reentrancy but you get the idea SetAlbumSourceAsync(); return bmp; } }
{ "pile_set_name": "StackExchange" }
Q: How to increase the average Itemlevel My char is a level 34 Whitemage and had an average itemlevel of 22. After failed healing Titan in story mode I realised that my heal and my MP are to low to deal with the damage Titan is dealing to my mates. I checked the market and bought a new staff, belt and shoes. After these changes my itemlevel increased to 25. Now I equiped the best items I was able to find there but my average itemlevel is still 9 levels lower than my character level... I read about level 50 endgame chars with an average itemlevel of 80 and I know it's because of the crystal tower raids, etc. But isn't there a way to get a higher average itemlevel than the character level in midgame? Click here for my Lodestone link. Thank you in advance! A: Nope, I'm afraid there's no way to increase your item level beyond your level. Not while levelling, anyways. Every bit of equipment prior to level 50 has an item level that matches rather closely with its required level. Only once you hit max level does that open up into higher item levels.
{ "pile_set_name": "StackExchange" }
Q: Show Image at selected position and hide all other previous images in recycler view I'm displaying a list and I want to show the selected item by setting the visibility of an image view to visible but I'm having an issue keep tracking of the previous position. How Can I show the image view at selected position and hiding all the images at other positions after the user selects some element? What I mean is that I've a layout with text views and images. What I want is that when I click on a position suppose 2. Then the image at that position should be visible and all other images should be hidden. Let's assume I've selected another position like 3 now I want to hide the image and index 2 and show the image at index 3. holder.tvId.setText(String.valueOf(model.getId())); holder.tvName.setText(model.getName()); if(model.getName().equals("Current Location")){ holder.tvAddress.setText(model.getAddress()); }else{ holder.tvAddress.setText(model.getUserEnteredAddress()); } holder.tvCityName.setText(model.getCity()); A: Well, in order to achieve what you expect. From what I can think of is you need to hide all the image then show only the image that you clicked First, add a new getter & setter in your Model public class Model { ... boolean isVisible = true; public String getIsVisible() { return isVisible; } public void setIsVisible(boolean isVisible) { this.isVisible = isVisible; } } Then, in your onBindViewHolder function in your adapter, handle it like this @Override public void onBindViewHolder(ViewHolder holder, int position) { ... if (!model.getIsVisible()) { ivMyImage.visibility = View.INVISIBLE; } holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { for (Model model : models) { model.setIsVisible(false); } model.setIsVisible(true); ivMyImage.visibility = View.VISIBLE; notifyDataSetChanged(); } });
{ "pile_set_name": "StackExchange" }
Q: angularjs ag-grid does not show row data I am using ag-grid to return 1 row of data from a server. The data is returning from the server and it is set in the grid but the data is not displaying. This is my grid: $scope.lastResultGridOptions = { rowData: $scope.jobResult, suppressCellSelection: true, suppressSorting: true, enableFilter: true, enableColResize: true, angularCompileRows: true, angularCompileHeaders: true, suppressMenuHide: true, columnDefs: [{ field: 'StartDate', filter: 'text', headerName: 'Start Date', cellClass: 'wrap-text', minWidth: 10 }, { field: 'EndDate', filter: 'text', headerName: 'End Date', cellClass: 'wrap-text', minWidth: 40 }, { field: 'IsSuccess', filter: 'text', headerName: 'Result Status', cellClass: 'wrap-text', minWidth: 40 }, { field: 'DateCompleted', filter: 'text', headerName: 'Date Completed', cellClass: 'wrap-text', minWidth: 40 }] }; This function is called during initialization: $scope.refreshLastResultGrid = function () { jobResult.paged().$promise.then(function (results) { $scope.jobResult = results; $scope.lastResultGridOptions.rowData = $scope.jobResult; if ($scope.lastResultGridOptions.api) { $scope.lastResultGridOptions.api.setRowData(); $scope.lastResultGridOptions.api.sizeColumnsToFit(); } }, function (error) { $scope.messageModalVariables = { messageTitle: 'Error Refreshing Job Result', messageDisplay: 'API Error. Could not retrieve job results.', messageType: 'Error', okIsHidden: false, yesNoIsHidden: true }; $scope.openMessageModal($scope.messageModalVariables); }); }; $scope.refreshLastResultGrid(); This is the service call to the server that returns the row: angular.module('vAnalyzeApp.services') .factory('JobResult', function($resource, configSettings) { var jobresult = $resource(configSettings.apiServiceUrl + 'api/v1/jobresult', {}, { 'paged': { method: 'GET', isArray: false, transformResponse: function(data, headers) { var count = headers('Count'); return { count: angular.fromJson(count), results: angular.fromJson(data) }; } } }); return jobresult; }); I debug in the refreshLastResultGrid function and the results come back from the server and are set to the $scope.lastResultGridOptions.rowData. The setRowData() function is completed without error but the data is not shown on the grid. Here is a screen shot of the grid: Why is the data not displaying in the grid? UPDATE The result object is: public class JobParameterDto { public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public string SourceDB { get; set; } public string TargetDB { get; set; } public Nullable<DateTime> DateCompleted { get; set; } public Nullable<bool> IsSuccess { get; set; } } When I view the result object this is the correct data returned: StartDate: '01/01/2016T00:00:00' EndDate: '11/01/2016T00:00:00' TargetDB: 'MainDB' SourceDB: 'WrhDB' IsSuccess: null DateCompleted: null A: you should use api.setRowData to set grid rows. Make sure results.data is an Array - ag-grid expect rowData to be an Array. ... jobResult.paged().$promise.then(function (results) { $scope.jobResult = results instanceof Array?results:[results]; if ($scope.lastResultGridOptions.api) { $scope.lastResultGridOptions.api.setRowData($scope.jobResult); $scope.lastResultGridOptions.api.refreshView(); $scope.lastResultGridOptions.api.sizeColumnsToFit(); } }, function (error){ ...
{ "pile_set_name": "StackExchange" }
Q: Are there any different endings to Emily Is Away? I've played the game a few different ways, and so far have not had a lot of variation in the ending. Frankly, I'm starting to believe it's little more than a "friend-zone simulator". Is there any way to bring the game to a conclusion that's substantially different, particularly with regards to the Player/Emily relationship? A: I have played the game several times and searched for several different playthroughs on YouTube. As far as I can tell, there is no other way the game can end: the player's relationship with Emily is always in tatters by the time the two of them leave university. The form of this disintegration changes with each ending: for example, in one ending, Emily says that she's back together with Brad and the player can no longer talk to her; in another ending, Emily says that she can't talk to the player because she has homework to do. Yet it will always happen. There is no happy ending to this game, no matter what you do.
{ "pile_set_name": "StackExchange" }
Q: Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget In my application when I try to launch it Force Closed and the error pointing the line "setContentView(R.layout.Menu);" of the layout. And in the XML file it show the "OutOfMemoryError" image view in my layout. I am realy confused. Please guide me for further move. Edited: My application uses database, and at the very first time it parse some XML data and insert into the Sqlite database. My Outofmemory problem occurs only at the first time. Second time it works fine. I tried System.gc(). Is there any prob on that. This is my Log: E/dalvikvm-heap(2712): 105376-byte external allocation too large for this process. VM won't let us allocate 105376 bytes FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.Test/com.Test.Menu}: android.view.InflateException: Binary XML file line #13: Error inflating class <unknown> at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663) at android.app.ActivityThread.access$1500(ActivityThread.java:117) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:130) at android.app.ActivityThread.main(ActivityThread.java:3683) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:507) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) at dalvik.system.NativeStart.main(Native Method) Caused by: android.view.InflateException: Binary XML file line #13: Error inflating class <unknown> at android.view.LayoutInflater.createView(LayoutInflater.java:518) at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568) at android.view.LayoutInflater.rInflate(LayoutInflater.java:623) at android.view.LayoutInflater.rInflate(LayoutInflater.java:626) at android.view.LayoutInflater.inflate(LayoutInflater.java:408) at android.view.LayoutInflater.inflate(LayoutInflater.java:320) at android.view.LayoutInflater.inflate(LayoutInflater.java:276) at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207) at android.app.Activity.setContentView(Activity.java:1657) at com.Test.Menu.onCreate(Menu.java:32) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) ... 11 more Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Constructor.constructNative(Native Method) at java.lang.reflect.Constructor.newInstance(Constructor.java:415) at android.view.LayoutInflater.createView(LayoutInflater.java:505) ... 23 more Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method) at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:460) at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:336) at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:697) at android.content.res.Resources.loadDrawable(Resources.java:1709) at android.content.res.TypedArray.getDrawable(TypedArray.java:601) at android.widget.ImageView.<init>(ImageView.java:118) at android.widget.ImageView.<init>(ImageView.java:108) This is my XML code: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <RelativeLayout android:id="@+id/RL_Title" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="8" android:onClick="onTitleClick" > <ImageView android:id="@+id/Img_Title_bg" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="center" android:src="@drawable/title_bg" /> <Button android:id="@+id/Btn_Title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginRight="5dp" android:background="@drawable/title_al" android:drawableRight="@drawable/pro" android:gravity="center" android:onClick="onTitleClick" /> </RelativeLayout> <RelativeLayout android:id="@+id/RL_MainMenu" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:onClick="onDoNothing"> <ImageView android:id="@+id/ImageView01" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="4" android:src="@drawable/main_bg" android:scaleType="centerCrop"/> <ImageView android:id="@+id/Img_logo" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="4" android:scaleType="center" android:src="@drawable/logo_al" /> <LinearLayout android:id="@+id/LI_Menu" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/RL_ExtraOption" android:layout_alignTop="@+id/Img_logo" android:layout_margin="2dp" android:orientation="vertical" > <ImageButton android:id="@+id/Img_Buyer" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="1dp" android:layout_weight="1" android:background="@drawable/bt_blink" android:onClick="Nextclick" android:scaleType="fitCenter" android:soundEffectsEnabled="true" android:src="@drawable/buyer_icon" /> <ImageButton android:id="@+id/Img_Seller" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="1dp" android:layout_weight="1" android:background="@drawable/bt_blink" android:onClick="Nextclick" android:scaleType="fitCenter" android:src="@drawable/seller_icon" /> <ImageButton android:id="@+id/Img_Lender" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="1dp" android:layout_weight="1" android:background="@drawable/bt_blink" android:onClick="Nextclick" android:scaleType="fitCenter" android:src="@drawable/lender_icon" /> <ImageButton android:id="@+id/Img_myTitleRep" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="1dp" android:layout_weight="1" android:background="@drawable/bt_blink" android:onClick="Nextclick" android:scaleType="fitCenter" android:src="@drawable/my_title_rep_icon_al" /> <ImageButton android:id="@+id/Img_Setup" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="1dp" android:layout_weight="1" android:background="@drawable/bt_blink" android:onClick="Nextclick" android:scaleType="fitCenter" android:src="@drawable/setup_icon" /> </LinearLayout> <RelativeLayout android:id="@+id/RL_ExtraOption" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:background="@drawable/main_bottom_bg" > <TextView android:id="@+id/txt_RepName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="10dp" android:textColor="@color/white" android:textSize="@dimen/font_size" /> <TableRow android:id="@+id/TR_ContactRep" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:gravity="center" > <Button android:id="@+id/Btn_ContactRep" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="3dp" android:background="@drawable/contact_rep_blink" android:onClick="ContactRep_Click" /> <Button android:id="@+id/Btn_MoreOption" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="5dp" android:background="@drawable/main_more_blink" android:onClick="onMoreClick" /> </TableRow> </RelativeLayout> <LinearLayout android:id="@+id/ln_Mainmore" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/dialog_bg" android:layout_alignParentBottom="true" android:visibility="gone"> <LinearLayout android:id="@+id/LinearLayout02" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="3" android:orientation="vertical" > </LinearLayout> <TableLayout android:id="@+id/TableLayout01" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:gravity="center" > <TableRow android:id="@+id/TableRow04" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="5dp" android:layout_marginTop="20dp" android:gravity="center" > <Button android:id="@+id/Btn_Rate" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:background="@drawable/property_blue_blink" android:onClick="onRate" android:singleLine="true" android:text="Rate/Testimonial" android:textColor="@color/white" android:textSize="@dimen/font_size" android:textStyle="bold" /> </TableRow> <TableRow android:id="@+id/TableRow01" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="5dp" android:gravity="center" > <Button android:id="@+id/btn_SubFeature" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:background="@drawable/property_blue_blink" android:onClick="onSubFeature" android:singleLine="true" android:text="Submit A Feature" android:textColor="@color/white" android:textSize="@dimen/font_size" android:textStyle="bold" /> </TableRow> <TableRow android:id="@+id/TableRow03" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="5dp" android:gravity="center" > <Button android:id="@+id/Btn_ReferFrnd" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:background="@drawable/property_blue_blink" android:onClick="onReferAFrnd" android:text="Refer A Friend" android:textColor="@color/white" android:textSize="@dimen/font_size" android:textStyle="bold" /> </TableRow> <TableRow android:id="@+id/TableRow02" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="5dp" android:gravity="center" > <Button android:id="@+id/Btn_cancel" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:background="@drawable/property_cancel_blink" android:onClick="onClose" android:text="Cancel" android:textColor="@color/black" android:textSize="@dimen/font_size" android:textStyle="bold" /> </TableRow> </TableLayout> <LinearLayout android:id="@+id/linearLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="3" android:orientation="vertical" > </LinearLayout> </LinearLayout> </RelativeLayout> A: I guess the problem is not in your layout; the problem is somewhere else in your code. And you are probably leaking context somewhere. Other probable reason is that you must be creating bulky multiple objects while parsing your XML (as you mentioned this occurs the first time when you parse XML). Though Java has auto garbage collection approach, but still you can not completely rely on it. It is a good practice to nullify your collection instance or clear your objects content when you don't need them any more. But still I have prepared a list of important points which you should remember while dealing with bitmaps on Android. 1) You can call recycle on each bitmap and set them to null. (bitmap.recycle() will release all the memory used by this bitmap, but it does not nullify the bitmap object). 2) You can also unbind the drawables associated with layouts when an activity is destroyed. Try the code given below and also have a look at this link link. private void unbindDrawables(View view) { if (view.getBackground() != null) { view.getBackground().setCallback(null); } if (view instanceof ViewGroup) { for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) { unbindDrawables(((ViewGroup) view).getChildAt(i)); } ((ViewGroup) view).removeAllViews(); } } // Call this method from onDestroy() void onDestroy() { super.onDestroy(); unbindDrawables(findViewById(R.id.RootView)); System.gc(); } 3) You can convert your hashmaps to WeakHashmaps, so that its memory would get released when the system runs low on memory. 4) You can scale/resize all your bitmaps. To scale bitmaps you can try something like this: BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 8; Bitmap preview_bitmap=BitmapFactory.decodeStream(is, null, options); This inSampleSize option reduces memory consumption. Here's a complete method. First it reads the image size without decoding the content itself. Then it finds the best inSampleSize value; it should be a power of 2. And finally the image is decoded. // Decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f){ try { // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f),null,o); // The new size we want to scale to final int REQUIRED_SIZE=70; // Find the correct scale value. It should be the power of 2. int scale=1; while(o.outWidth/scale/2 >= REQUIRED_SIZE && o.outHeight/scale/2 >= REQUIRED_SIZE) scale*=2; // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize=scale; return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); } catch (FileNotFoundException e) { } return null; } Have a look at this link.. 5) You can override onLowMemory() method in an activity which gets a call when entire system runs low on memory. You can release a few resources there. 6) You can make your objects SoftReference or Weakreference, so that they get released in a low-memory condition. A very common memory leak that I observed is due to the implementation of inner classes and implementing Handler in Activity. This links talks about the same in more detail. I hope this helps to eliminate your problem. A: This is a typical problem when using Android's ImageView with large images on older devices (even if the file size is only several Kbs). The native graphics library called skia that is used to decode the image allocates native memory based on the image's dimensions, so the file size does not influence this directly. Even if you omit the src-attribute in the XML layout definition to load the image yourself in your onCreate() method the same error will be triggered. The only way to get around this is to use an inSampleSize in BitmapFactory.decodeStream to perform downsampling directly during decoding (see Strange out of memory issue while loading an image to a Bitmap object for example). This itself raises the question of how to determine this scale factor. The best solution I found when handling large images is replacing the ImageView with a WebView and load some minimal HTML like this: webView.loadUrl("file:///android_res/raw/background.html"); where the content of raw/background.html might be something like this: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <style type="text/css"> body { margin: 0; } img { width: 100%; height: auto; display: block; } </style> </head> <body> <img src="file:///android_res/drawable/background.png" /> </body> The WebKit engine that is used in the WebView performs image loading in a much more efficient way, so that those memory allocation errors should be gone. You can even use different images for portrait and landscape by putting them in drawable-port and drawable-land. But then you have to call clearCache(false) on the WebView instance in your onDestroy() method because otherwise the image cached on the first load will always be used (disabling caching on the WebView instance does not work). A: After spending a lot of time on this problem I found the solution! All you need to do is ask for more memory. Place this code inside your android manifest under: <application>: Put: android:largeHeap="true" Worked great for me! Please note that this solution works only on API 11 and above. More info here.
{ "pile_set_name": "StackExchange" }
Q: Delete the first character of certan line in file in shell script Here I want to delete the first character of file of certain lines. For example: >cat file1.txt 10081551 10081599 10082234 10082259 20081134 20081159 30082232 10087721 From 3rd line to 7th line delete the first character sed command or any else and output will be: >cat file1.txt 10081551 10081599 0082234 0082259 0081134 0081159 0082232 10087721 A: sed -i '3,7s/.//' file1.txt sed -i.bak '3,7s/.//' file1.txt # to keep backup From 3rd to 7th line, replace the first character with nothing.
{ "pile_set_name": "StackExchange" }
Q: Arithmetic geometry from a bird's-eye view Is ist true that Arithmetic Geometry can roughly be separated into two areas: 1) Showing that motivic $L$-functions are automorphic. 2) Calculating special values of these $L$-functions. A: No, I think your suggested dichotomy misses too many vitally important results in arithmetic geometry. In particular, there are purely Diophantine questions (and answers) which are not informed by any automorphic/motivic considerations whatsoever. As a point of philosophy, you might want to speculate that some of these results will eventually have automorphic interpretations, but in many cases there is not even presently a conjectural relation. To give a specific example, I will go out on a limb and claim that the single greatest theorem in arithmetic geometry is Faltings' proof of the Mordell-Lang Conjecture (informally, I like to think of this as the Faltings-Vojta-Faltings theorem): if $A$ is an abelian variety over a number field $k$, and $\Gamma \subset A(\overline{k})$ is a subgroup such that $\dim_{\mathbb{Q}} \Gamma \otimes \mathbb{Q} < \infty$, Then for any closed subvariety $X \subset A$, there exists $n \in \mathbb{Z}^+$, $\gamma_1,\ldots,\gamma_n \in \Gamma$ and abelian subvarieties $B_1,\ldots,B_n$ of $A$ such that $\Gamma \cap X(\mathbb{C}) = \bigcup_{i=1}^n \gamma_i + (B_i(\mathbb{C}) \cap \Gamma)$. In particular, this reduces Faltings' earlier finiteness theorem (finiteness of $k$-rational points on a curve $X$ of genus at least $2$) to the Mordell-Weil theorem and recovers the Manin-Mumford conjecture (that a curve of genus at least $2$ embedded in its Jacobian contains only finitely many torsion points). Some good articles on the subject include: http://www.math.jussieu.fr/~hindry/abvarmodel.pdf http://www.msri.org/publications/books/Book39/files/mazur.pdf http://www-math.mit.edu/~poonen/papers/mlb.pdf (The last one gives a signficantly more general result!) If anyone can relate this seminal result to motivic/automorphic anything, I would be very interested to know.
{ "pile_set_name": "StackExchange" }
Q: Parsing a JSON file How can I parse a file of this kind: {"group":"1"}{"group":"2"}{"group":"3"} Usually I parse in this way: NSString *fileContent = [[NSString alloc] initWithContentsOfFile:reloadPath]; SBJsonParser *parser = [[SBJsonParser alloc] init]; NSDictionary *data = (NSDictionary *) [parser objectWithString:fileContent error:nil]; // getting the data from inside of "menu" //NSString *message = (NSString *) [data objectForKey:@"message"]; //NSString *name = (NSString *) [data objectForKey:@"name"]; NSArray *messagearray = [data objectForKey:@"message"]; NSArray *namearray = [data objectForKey:@"name"]; NSDictionary* Dictionary = [NSDictionary dictionaryWithObjects:messagearray forKeys:namearray]; ...objects of this king... {"message":["Besth"],"name":["thgh"]} ...but in the type I want to parse, which is the key and object?? By the way I want to retrieve a list like this: 1, 2, 3, ... A: This is not valid JSON. You can validate for example at: http://jsonlint.com You could rewrite it as valid JSON like so: { "some_groups": [ { "group": "1" }, { "group": "2" }, { "group": "3" } ] } Then you could extract the data by doing something like this: NSArray *groups = [data objectForKey:@"some_groups"]; for (NSDictionary *group in groups) { NSLog(@"group number: %@", [group valueForKey:@"group"]); }
{ "pile_set_name": "StackExchange" }
Q: How to repeat a single frame? I see a lot about repeating an animation sequence, but my issue is much simpler. I'm using the video editor to make a very simple video, just a slide show really. I have a video of a person giving a talk and I'm just overlaying a set of slides to illustrate her talk. I've got that working very well. The original video of the talk ends abruptly at the end of her last sentence. I'd like to fix that by extending the last frame for a few seconds and then fading to black. So my question is very simple, but I don't see it answered anywhere: How do I get the last frame of a video to repeat for a few seconds? ============================== I tried the technique suggested in the comment by @Edgel3D, but it didn't work. I'm saying that here so I can attach a picture of what happened: The video strip in channel 2 used to be the same length as the audio strip in channel 1 at 11,575 frames. I pulled out the end handle on channel 2, which seems to have expanded it to either 11,771 frames or 11,772, depending on which number in the image above I should believe. But when I play it, after frame 11,575 the video window goes to a black and grey checkerboard pattern. The last frame is not being repeated. Am I doing something wrong? A: In the original video's strip, there are two handles, one at each end. Simply pull the right side's end out with the mouse button. (Left button I think) Beware of any faulty or black frames that might be present at the end. These can be sliced off with SHIFT-K. Delete those. Once the very end frame is valid video pull the handle to the right and this will extend that last frame out for as many frames as you like. You can use this extension to fade the scene out to black by keyframing the strip's opacity. Take some abiance audio from another part, copy and lay that with the silent extension, fade that out over the same frames as your inserted fade to black. You can copy/paste the original audio strip, into a free strip and if I remember rightly, you might also be able to duplicate it with SH-D and simply drag the copy up to a free strip. Once the copy is established, it can be sliced up to extract whatever you want, lay it where it's needed.
{ "pile_set_name": "StackExchange" }
Q: HTML form is not redirecting I've written probably a dozen forms for this project but for some reason this ONE is not working. I can't discern any difference between it and any of my other forms. By not working, I mean the page does not redirect when the submit button is clicked. Also, the default value I try to put in the 'patient' field isn't appearing but that's not important. It's probably something really silly like an unbalanced tag or something but I just cannot find it. Can a pair of fresh eyes help me out? <form id='addBill' method='POST' action="/add_to_bill.php"> <table class='t' style='width:100%'> <tr> <td class='tt'><p>Patient ID</p></td> <td class='tt'><input disabled class='t' type="numeric" name="patient" value=<?php getP('id') ?>></td> <td class='tt'><p>Visit ID</p></td> <td class='tt'><input class='t' type="numeric" name="visit"></td> </tr> <tr> <td class='tt'><p>Invoice Number</p></td> <td class='tt'><input class='t' type="numeric" name="invoice"></td> <td class='tt'><p class='t'>Due Date: (format: e.g. <?php echo "'".date('Y-m-d')."'"; ?>)</p></td> <td class='tt'><input class='t' type="text" name="date" value=<?php echo "'".date('Y-m-d')."'"?>></td> </tr> <tr> <td class='tt'><input class='t' type="submit" value="Go"></td> </tr> </table> </form> A: based on the image of the code i noticed there is a form tag without the closed form tag. there are two form tag in it, one without closed form tag which is at most top of the code and another one is at bottom
{ "pile_set_name": "StackExchange" }
Q: Why is using steam to rotate a turbine more efficient? For example i have an exhaust pipe with very hot air from burning biofuel, and i have a turbine at the end of the exhaust that rotates and generates electricity. Why is it more efficient to use the heat to boil water then use the steam produced to rotate the turbines? As in why is more electricity generated by using steam to rotate the turbines as opposed to not using steam when burning the same amount of biofuel? A: The main reason is that a turbine requires a pressure drop to extract energy from the working fluid. The drop in temperature that is observed in a turbine is a result of the expansion of the fluid; the turbine doesn't have a way to extract the heat energy directly from the fluid. The total work done by the fluid is typically expressed as a change in enthalpy, which is the sum of internal energy (heat) and work done by expansion (pressure drop): $\Delta H = \Delta U + \Delta (PV)$. If the exhaust pressure of your combustor is not much higher than ambient pressure, then there won't be much of a pressure drop across the turbine and hence not much work will be done by the gas. The gas will exit the turbine at a relatively high temperature, indicating that it still has a lot of energy that wasn't extracted by the turbine. The solution to capturing this wasted energy is to instead take some of that heat energy and convert it to pressure energy by boiling water - now you have a high-pressure working fluid that's much more useful for driving a turbine. The turbine is now able to extract much more of the original heat energy in the form of pressure, hence higher efficiency. A: Heating water to make steam is not necessarily more efficient, but a lot more practical. What you describe is how internal combustion engines work, for example, so it's a valid concept. However, they do this in bursts and use liquid and carefully engineered fuel, which makes the implementation more practical. In a continuous system as you describe, the fuel is burned at high pressure. Consider the mechanical difficulty of adding more fuel into the system while sealing against that pressure. You also have to get the unburnt waste out somehow. While basic physics does not prevent what you describe, practical engineering does. It's simpler to burn the fuel at ambient pressure, and use the heat to make high pressure inside a specially designed pressure vessel. Put another way, it's a lot easier to get heat across a pressure seal than solids with somewhat unpredictable shapes and sizes. A: You are almost describing a gas turbine engine. These are used to generate electrical power, and also to power aircraft. But, in a gas turbine the output of the combustor is at high pressure, and that is used to turn a turbine. And, that is a different combustion cycle from a steam cycle.
{ "pile_set_name": "StackExchange" }
Q: How can I properly set the order of divs at different breakpoints? I am using Bootstrap and I want to achieve the following arrangement: The numbers indicate how I want these divs to be ordered IN A SINGLE COLUMN on mobile. The HTML I tried is here: <div class="col-xs-12"> <div class="flex-row"> <div class="col-md-6"> <div class="order-1"> <!-- TITLE SUBTITLE --> </div> <div class="order-md-3"> <!-- FILM META AND CONTENT --> </div> </div> <div class="col-md-6"> <div class="order-md-2"> <!-- FILM POSTER --> </div> <div class="order-md-4"> <!-- UNDER POSTER. --> </div> </div> </div> Can anyone tell me what I'm doing wrong here? A: The simplest solution (no extra CSS or duplicate markup) is to use "floats" in Bootstrap 4. Use the d-md-block class to "disable" the flexbox on larger screens, and then float-* to position the columns. On mobile, the columns will follow their natural order... <div class="row d-md-block d-flex"> <div class="col-md-6 float-left py-2"> <div class="border"> 1 </div> </div> <div class="col-md-6 float-right py-2"> <div class="border taller"> 2 FILM POSTER </div> </div> <div class="col-md-6 float-left py-2"> <div class="border taller"> 3 FILM META AND CONTENT </div> </div> <div class="col-md-6 float-left py-2"> <div class="border"> 4 </div> </div> </div> https://www.codeply.com/go/WnnCXNckAy
{ "pile_set_name": "StackExchange" }
Q: How can I build a comments page? How to build a page where visitors can add comments to the page? I know it's possible with a db, the question is - can I do it without a db? Perhaps by saving a new element to the existing .aspx file in the correct location (after the last comment inserted), how do I do it? Any other elegant idea how to implement this? The reason I don't use a db in this case is for simplicity and for fast loading of the page - am I right with my approach? A: I also suggest the use of a database, how ever some time we need to make something low cost, simple and fast for a small web site with not so many traffic. So this is what I suggest you. Appends your commends to a file with File.AppendText, and then include the file using this command, on the place you like to see this comments. <!--#include file="CommentsA.htm"--> Do not append your comments in the aspx file because this can cause recompile of your site. As I say again, this is a simple idea, for something fast and low cost. You need here to take care the attacks via javascript injection and the spam, nether you have the luxury to approve/reject messages. This is for sure the faster and easiest way - but you do not have control over the comments.
{ "pile_set_name": "StackExchange" }
Q: Where should user configuration files go? If I look at my home directory there are a large number of dot files. If I am creating a new program that needs a user configuration file, is there any guidance where to put it? I could imagine creating a new dot directory ~/.myProgramName or maybe I should add it to /.config or ~/.local. A: The .config directory is a newish development courtesy of XDG that seems, deservedly, to have won favour. Personally, I don't mind a dot directory of your own. A bunch of separate dot files (ala bash and various old school tools) in the toplevel of $HOME is a bit silly. Choosing a single dot file is a bad idea, because if in the future you realize maybe there are a couple more files that would be good to have, you have a possible backward compatibility issue, etc. So don't bother starting out that way. Use a directory, even if you are only going to have one file in it. A better place for that directory is still in ~/.config, unless you are very lazy, because of course you must first check to make sure it actually exists and create it if necessary (which is fine). Note you don't need a dot prefix if your directory is in the .config directory. So to summarize: use a directory, not a standalone file put that directory in $HOME/.config
{ "pile_set_name": "StackExchange" }
Q: Extract Millisecond data from SQL stored procedure I have looked for answers on this subject and I have posted in another forum but this seems to be the font of all knowledge. I am trying to pull data from a SQL Server 2000 database using PowerShell. The Powershell script calls a stored procedure, this then extracts the data and export-csv outs it to, well a CSV. The problem is that the datetime fields in the outputted data have lost their milliseconds. This happens when PowerShell extracts the data from the database into a temporary table. Here are the two bits of code. PowerShell script #VARIABLES $SqlQuery = "SAP_proc" #Connection Strings $Server = "server" $Database = "db_dab" #Output Files $OutputPath = "c:\Sapout.csv" #END OF VARIABLES #SQL Connection $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server=$Server;Database=$Database;Integrated Security=True" $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = "SAP_proc" $SqlCmd.Connection = $SqlConnection $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd $DataSet = New-Object System.Data.DataSet $DataOut = $SqlAdapter.Fill($DataSet) #$DataOut = $SqlAdapter.FillSchema($DataSet,[System.Data.SchemaType]::Source) #Data Manipulation $DataOut | Out-Null #Export Data to Hash Table $DataTable = $DataSet.Tables[0] #Export Has table to CSV $DataTable | Export-CSV -Delimiter "," -Encoding Unicode -Path $OutputPath -NoTypeInformation $SqlConnection.Close() Stored procedure ALTER proc [dbo].[SAP_proc] as DECLARE @return_value int DECLARE @starttime datetime DECLARE @endtime datetime SET @starttime = DATEADD (dd, -30, CURRENT_TIMESTAMP) SET @endtime = CURRENT_TIMESTAMP EXEC @return_value = [dbo].[sp_agent] @starttime ,@endtime SELECT 'Return Value' = @return_value Because the other stored procedure SP_agent is created by the software I can't edit it. Also I don't want to replicate the software defined stored procedure (with SELECT convert to varchar for datetime) in my command text string as it is a behemoth stored procedure. Any help would be massively useful. A: It's not a Powershell issue or a temp table issue. This is because your datetime column is converted to a string when you call export-csv using the default tostring method which doesn't include milliseconds. If you want milliseconds then specify it in the tostring method call: $a = get-date $a.ToString("d/M/yyyy hh:mm:ss.fff tt") #To to something similar with your export-csv of a datatable you can create an expression: $DataTable | select column1, column2, @{n=datecolumn;e={$_.datecolumn.ToString("d/M/yyyy hh:mm:ss.fff tt")}} | export-csv <rest of code> Edited 10/17/2012 It seems like you are having trouble with this still. So here's a complete script which I've tested outputs milliseconds. You'll need to change the variable section to your environment. I hope this helps: #VARIABLES $SqlQuery = "select 'test' as column1, 'milliseconds' as column2, getdate() as datecolumn" #Connection Strings $Server = "$env:computername\sql1" $Database = "tempdb" #Output Files $OutputPath = "./millisec.csv" #END OF VARIABLES #SQL Connection $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server=$Server;Database=$Database;Integrated Security=True" $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.CommandText = $SqlQuery $SqlCmd.Connection = $SqlConnection $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd $DataSet = New-Object System.Data.DataSet $DataOut = $SqlAdapter.Fill($DataSet) #$DataOut = $SqlAdapter.FillSchema($DataSet,[System.Data.SchemaType]::Source) #Data Manipulation $DataOut | Out-Null #Export Data to Hash Table $DataTable = $DataSet.Tables[0] #Export Has table to CSV #$DataTable | Export-CSV -Delimiter "," -Encoding Unicode -Path $OutputPath -NoTypeInformation $DataTable | select column1, column2, @{n='datecolumn';e={$_.datecolumn.ToString("M/d/yyyy hh:mm:ss.fff tt")}} | export-csv $OutputPath -NoTypeInformation -force $SqlConnection.Close() #Another code example with explanation. Added on 10/23/2012 #VARIABLES $SqlQuery = "select getdate() as datecolumn" #Connection Strings $Server = "$env:computername\sql1" $Database = "tempdb" $SqlConnection = New-Object System.Data.SqlClient.SqlConnection $SqlConnection.ConnectionString = "Server=$Server;Database=$Database;Integrated Security=True" $SqlConnection.Open() $SqlCmd = new-Object System.Data.SqlClient.SqlCommand($SqlQuery, $SqlConnection) $data = $SqlCmd.ExecuteScalar() $SqlConnection.Close() #Notice NO millisecond Write-Output $data #See $data is an object of type System.DateTime $data | gm #There's a property called millisecond #Millisecond Property int Millisecond {get;} #Although you don't "see" millisecond's on screen it's still there $data.Millisecond #Powershell uses a types and format rules to define how data is display on screen. You can see this by looking at #C:\Windows\System32\WindowsPowerShell\v1.0\types.ps1xml and searching for "DataTime". This file along with format file define how data is displayed #When you display datatime screen it's implicitly calling #Searching for datetime in types.ps1xml you'll find this line: #"{0} {1}" -f $this.ToLongDateString(), $this.ToLongTimeString() #for our example "{0} {1}" -f $data.ToLongDateString(), $data.ToLongTimeString() #So millisecond is still there, but if you want millisecond in your output to CSV, screen or file you'll need to call a ToString method with a date format. Here's an example: $data.ToString("M/d/yyyy hh:mm:ss.fff tt")
{ "pile_set_name": "StackExchange" }
Q: How do I get around this error in PowerShell? Exception setting "Rtf": "Error creating window handle." This has no issue with SQL. it's when creating the rtf object. I am connecting to a sql database and pulling information. Some of the information is html,rtf, and plain text. After about 10 mins of running I get this: Exception setting "Rtf": "Error creating window handle." At line:24 char:76 + ... Name System.Windows.Forms.RichTextBox; $rtf.Rtf = $convo.Body; $body ... + ~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], SetValueInvocationException + FullyQualifiedErrorId : ExceptionWhenSetting Has anyone else ran into this issue? Here is the script itself. #Who are you searching for? #Example User ID: [email protected] $Subject = "[email protected]" #Set the date to search from #Example date format: 2016-08-16. #Leave it blank if you don't want to search for just dates. $Date = "" #Blank array to store the conversation history $arr = @() #Lync Archive Server $SQLSvr = "ServerName Goes Here" #Lync Archive Database $Database = "LcsLog" #Get the UserId's $UserUri = Invoke-Sqlcmd -Query "Select UserUri,UserId From dbo.Users u;" -ServerInstance $SQLSvr -Database $Database #Build the Select Statement $select = "Select * from dbo.Users d left join dbo.Messages m on FromId = d.UserId or ToId = d.UserId Where d.UserUri = '$Subject' " if($Date) { $select = $select +"and m.MessageIdTime >= '$Date 00:00:01.550' order by m.MessageIdTime asc;" } else { $select = $select + "order by m.MessageIdTime asc;" } #Get the conversation history $ConvoData = Invoke-Sqlcmd -Query ($select) -ServerInstance $SQLSvr -Database $Database; #Loop through each conversation foreach($convo in $ConvoData) { #Loop through each user. foreach($user in $UserUri) { #Verify the FromId if($convo.FromId -eq $user.UserId) { $FromID = $user.UserUri } #Verify the ToId if($convo.ToId -eq $user.UserId) { $ToId = $user.UserUri } } #Parse the body for legible reading switch ($convo.ContentTypeId) { '1' {$html = New-Object -ComObject "HTMLFile"; $html.IHTMLDocument2_write($convo.Body);$body = $html.IHTMLDocument2_body.innerText; $html.close();} '2' {$rtf = New-Object -TypeName System.Windows.Forms.RichTextBox; $rtf.Rtf = $convo.Body; $body = $rtf.Text; $rtf.Clear();} '3' {$body = $convo.Body} } #Build the Message Output $obj = New-Object -TypeName psobject -Property @{User = $Subject; "Message Time" = $convo.MessageIdTime; From = $FromID; To = $ToId; Body = $body} #Add data to the array $arr += $obj } $arr | Select User,"Message Time",From,To,Body | Export-csv "$env:userprofile\desktop\$Subject - conversation report.csv" A: Not really an answer, but a recommendation that you should turn your parameters into a Param block. It would be more useful if you wanted to call the script from the command line or turn it into a function. Param ( # Parameter Subject [Parameter(Mandatory = $true, HelpMessage = 'Who are you searching for? e.g. User ID: [email protected]')] $Subject = '[email protected]', # Parameter Date [Parameter(HelpMessage = 'Set the date to search from. e.g. "2016-08-16"')] [String] $Date, # Parameter SQLSvr [Parameter(Mandatory = $true, HelpMessage = 'ServerName Goes Here')] $SQLSvr, # Parameter Database [Parameter(Mandatory = $true, HelpMessage = 'Lync Archive Database')] $Database = 'LcsLog' )
{ "pile_set_name": "StackExchange" }
Q: Should I use UIViewController or UIView? Making a custom tab bar/nav controller I am making an app that has both a bottom bar and a top bar (both are customized) and i want them to stay there the entire length of the app while the middle portion switches between views. But the kicker is at some points in the app, i want to have the top bar and bottom bar slide off the screen and be able to be dragged back on. What i was thinking was to have one main UIViewController with three UIViews (top bar, middle section, and bottom bar) each running code from their own respective files. Sort of like how a Tab bar works with a nav controller. or do i have that backwards? i dont really know... but any constructive advice helps =) Im fairly new to xcode and i've been trying to find a way for a few days now, so please dont be too harsh on me. Thanks! A: In general, we build one view controller for each 'screenful' of content. So the basic advice for you would be to make the app in a way where each 'section' is it's own view controller. This is especially important to the MVC paradigm, where your business logic should be in the viewControllers, not the views (just display and interaction logic there). If you had just one view controller, it would get convoluted FAST by trying to manage multiple sections. A good route may be this: Embed the whole hierarchy in a navigation controller, which gives you the top bar. Then make a custom view controller class which knows how to make your bottom bar, and have each section subclass that. The side effect is that the bottom bar will be uniquely created for each section VC. If that is not desirable for you, you can explore view controller 'containment'. It is basically a technique for building components like the navigation controller, which keep certain elements onscreen for a long time, while exchanging 'content' view controllers for a smaller portion of the screen. It's not the easiest thing to do, and should be considered carefully. However, if you really need to keep the same instance of something on screen while other view controllers come and go, it may be the right way to go. That said, consider the other idea first (each section manages it's own bottom bar). You can accomplish it in a way that promotes code re-use, etc.
{ "pile_set_name": "StackExchange" }
Q: Generate a 'Guru Meditation Error' on an Amiga Can anyone post some source code that, when compiled (if necessary) and run, will produce a 'Guru Meditation Error' on an Amiga. Assembler, C or ARexx will do. Thanks. A: Try the Alert() function of the exec.library: http://amigadev.elowar.com/read/ADCD_2.1/Includes_and_Autodocs_3._guide/node01E3.html For instance (in C): #include <exec/execbase.h> #include <exec/alerts.h> #include <clib/exec_protos.h> void main(void) { Alert(ACPU_InstErr); /* or use 0x80000004 if you don't have alerts.h */ /* might not return if it was a dead end (non-recoverable) alert */ }
{ "pile_set_name": "StackExchange" }
Q: Link my bitcoin address with multiple wallets I created a CoinBase bitcoin wallet address, can I share this address with Electrum desktop software instead of having different addresses and paying the transfer fees. Or is there another wallet like coinbase that has less fees and good security. Bear with me, I am new. A: I created a CoinBase bitcoin wallet address, can I share this address with Electrum desktop software instead of having different addresses and paying the transfer fees. No, because afaik Coinbase does not provide access to the private keys for this address, and so you will not be able to control this address from any other wallet software. In order to send a transaction from your Coinbase wallet, you will have to submit a request to Coinbase to initiate a transaction, and then their service will (hopefully) craft and publish the transaction for you. The point here is that you can contrast this custodial wallet model with a self-sovereign wallet model, in which the user is fully responsible for maintaining their own private keys (funds). (disclaimer: I have never used Coinbase, but it is my understanding they are a custodial service, and in that case the above is true). In order to spend some bitcoin, you need the private key for the bitcoin address in question. If you use some wallet software that is non-custodial, the software will create and manage these private keys for you in the background (a bitcoin address will be presented to you). If you so desire, you can import the keys to another wallet, so that you can spend your funds from one of several wallet instances. Many wallets these days are 'hierarchical deterministic' (HD) wallets, which will provide you with a 12 or 24 word 'seed phrase', this seed phrase can similarly be used to recreate an entire wallet on a separate device. However, in general, having multiple instances of the same wallet is not the most secure method of using Bitcoin, as you would now have a larger possible attack surface. If any one of your wallet instances is compromised, then your funds could be stolen. Additionally, entering private keys into software is a moment of vulnerability, as a keylogger could be present on your machine, waiting to grab any bitcoin private keys, etc. Many users will instead create several wallets, using various software and with varying levels of security between them. Maybe one wallet holds the majority of your funds in a super-secure manner, while another wallet is easily accessible through your mobiles phone, with a small amount of BTC on it for day-to-day spending, etc. If you use good wallet software and are cognizant of the mempool backlog, you can send non-time-sensitive bitcoin transactions for extremely cheap. If Coinbase is offering cheaper fees than what you would actually pay to miners otherwise, then that probably just means they are making money off your use of their service otherwise. Generally I would not recommend using them as your wallet, it is a better idea to educate yourself on how to use bitcoin to regain monetary sovereignty, not sacrifice it to some corporation.
{ "pile_set_name": "StackExchange" }
Q: Height of child layout not matching parent layout I have a basic layout here, but the LinearLayout inside ScrollView is not matching the parent height. <LinearLayout . . android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "vertical" . .> <EditText . ./> <Button . ./> <ScrollView android:layout_width = "match_parent" android:layout_height = "match_parent"> <LinearLayout android:id = "@+id/layoutWeb" android:layout_width = "match_parent" android:layout_height = "match_parent" android:orientation = "vertical"> <ListView android:id = "@+id/listWeb" android:layout_width = "match_parent" android:layout_height = "match_parent"> </ListView> </LinearLayout> </ScrollView> </LinearLayout> The ide suggests to change the linear layout's(id=layoutWeb) height to wrap_parent. I have selected the linear layout in the screenshot below, but its height is not matching the parent A: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:id="@+id/layoutWeb" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ListView android:id="@+id/listWeb" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout> try this code . for listview you dont need to take scrollview. its already scrollable
{ "pile_set_name": "StackExchange" }
Q: Way to synchronize two cores in simulation I have to build a dual-core processor simulator in C (it's actually a multilevel memory simulation, cache L1/L2, block substitution, etc). Thing is, I'm having a hard time figuring a way to synchronize the cores (which I'm programming as threads). Any ideas how I could do a global clock? Should I change from threads to child processes? Thanks in advance A: So many options here: since you might end-up supporting complex interactions with multiple threads, you might want to consider using a "virtual clock" with a message passing "bus". This way, you'll have more time to focus on the core functionality instead of debugging the synchonization logic... Using this technique, you can build a state-machine (see here) per "actor" thread (worst case) and worry less about mutexes/conditions. Once you've got this base, you'll be able to handle cases that show up mid-stream (e.g. "I forgot about this detail... no worries, just add a state here... don't have to re-shuffle my mutexes). Also, since doing simulation is all about "virtual time" (since you can't run real-time !), then having a base architecture based on a "virtual clock" abstracts the problem to an appropriate level.
{ "pile_set_name": "StackExchange" }
Q: Input command taking input as an int instead of a str in Python I am a beginner programing with Python 2.79. I am writing a program that "tokenizes" a mathematical formula, basically turning each number and operator into an item in a list. My problem is currently (because it is a semantic error i haven't been able to test the rest of the code yet) in my input command. I am asking the user to enter a mathematical equation. Python is interpreting this as an int. I tried making it into a string, and Python basically solved the formula, and ran the solution through my tokenize function My code is as follows: #Turn a math formula into tokens def token(s): #Strip out the white space s.replace(' ', '') token_list = [] i = 0 #Create tokens while i < len(s): #tokenize the operators if s[i] in '*/\^': token_list.append(s[i]) #Determine if operator of negation, and tokenize elif s[i] in '+-': if i > 0 and s[i - 1].isdigit() or s[i - 1] == ')': token_list.append(s[i]) else: num = s[i] i += 1 while i < len(s) and s[i].isdigit(): num += s[i] i += 1 token_list.append(num) elif s[i].isdigit(): num = '' while i < len(s) and s[i].isdigit(): num += s[i] i += 1 token_list.append(num) else: return [] return token_list def main(): s = str(input('Enter a math equation: ')) result = token(s) print(result) main() Any help would be appreciated I am looking to A: The reason Python is interpreting the user's input as an integer is because of the line input('Enter a math equation: '). Python interprets that as eval(raw_input(prompt)). The raw_input function creates a string from the user input, and eval evaluates that input -- so an input of 5+2 is considered "5+2" by raw_input, and eval evaluates that to be 7. Documentation
{ "pile_set_name": "StackExchange" }
Q: TFS hosted build controller to send email alerts Has anyone ever configured the: tfs.visualstudio.com "hosted build controller" to send emails when a build is started, failed, or completed? Note: this is not TFS - Team Foundation Server, it's the Team Foundation Services hosted by MS. I'd like to be able to send an alert so my testers know to take a break during the builds. A: You can setup team alerts using the Team Foundation Service. It is also available in Team Foundation Server for on-premises as well. I have a walkthrough available here: http://www.edsquared.com/2012/02/09/Creating+EMail+Alerts+For+Team+Members+In+TFS.aspx A: You need to set alerts in the project portal. Just click on the small cog on the upper right corner and click on the Alerts tab. There you can customize alerts for your project. By the way, you can do that inside Visual Studio as well, in the Team menu.
{ "pile_set_name": "StackExchange" }
Q: Expect script for rsync with quotation marks I want to rsync a folder to another machine. sshpass is not an option and certificates don't either. So I'm stuck with expect. So far, I have this bash script (minimized). read -p "Enter remote IP: " IP read -p "Enter remote user: " USER read -s -p "Enter remote password: " PASSWORD expect <<EOF set timeout -1 spawn rsync -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" \ -aHv --exclude=".*/" --delete ../.. ${USER}@${IP}:~/destination expect "password: " send "${PASSWORD}\n" expect eof EOF Problem is that rsync doesn't respect the "--exclude" option. In the stdout, I see: spawn rsync -e ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -aHv --exclude=".*/" --delete ../.. [email protected]:~/OberonHAP Somehow, the quotes around the -e option vanished, but exclude still has them. So I escape the quotes expect <<EOF set timeout -1 spawn rsync -e \"ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null\" \ -aHv --exclude=".*/" --delete ../.. ${USER}@${IP}:~/destination expect "password: " send "${PASSWORD}\n" expect eof EOF but now I get Missing trailing-" in remote-shell command. Note that the command itself works perfectly when typed directly into a Terminal. I've also tried different things, like 'EOF' heredoc and passing in the variables via environment, but always get error messages of different sorts :-) How do I have to escape the rsync command so that it works fine? A: Tcl's syntax (and hence Expect's syntax) is not the same as that of the shell. In particular, the quoting rules are different; you don't need to put double-quoting in the middle of a word as Tcl doesn't expand glob characters for you (you'd need to call glob explicitly if you wanted that). This means that your spawn command is actually best written as: spawn rsync -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" \ -aHv --exclude=.*/ --delete ../.. ${USER}@${IP}:~/destination # ☝☝☝☝☝☝ LOOK HERE!
{ "pile_set_name": "StackExchange" }
Q: Android EditText with multiple Lines automatic line break is it possible to have an EditText with multiple Lines which automatically makes a Line break after every 20th Character the user is typing in? Thanks in advange for your replys. A: In your XML file create the edittext like this, <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textMultiLine" > <requestFocus /> </EditText> A: You can implement TextWatcher interface and implement method afterTextChanged. The method will be invoked after text changed, so you can add the line breaks in it by yourself.
{ "pile_set_name": "StackExchange" }
Q: How to convert html blade that contains dynamic data from database to PDF in laravel? I'm trying to write code that converts html blade to PDF using tcpdf in laravel. This is the controller code which i use to convert: public function htmlToPDF() { $view=view('PdfDemo'); $html_content =$view->render(); PDF::SetTitle('Sample PDF'); PDF::AddPage(); PDF::writeHTML($html_content, true, false, true, false, ''); PDF::Output('SamplePDF.pdf'); } When I put static data on my view(PdfDemo) everything runs successfully, but the problem is when I put dynamic data with some variables in the blade as the following: <table> <?php $i=0?> @if(count($names)) @foreach($names as $n) <tr><td> <label>Name{{$i}}:</label>{{$n}}</td> <tr><td><hr></td></tr> <?php $index = $index+1; ?> @endforeach @endif </table> Here $names is the result of select statement in other function of controller, then I pass it to the blade like this: return view('PdfDemo',compact('names')); In this case the blade appear exactly as I want, but when I try to convert to PDF it shows error, $name not defined. A: Do like this: $view = View::make('PdfDemo',compact('names')); $contents = (string) $view; // or $contents = $view->render(); When you use View::make() it gets the HTML code of blade file as HTML content after adding dynamic variable's values.
{ "pile_set_name": "StackExchange" }
Q: Apache Felix shell with SSH I'm interested how I can use Apache Felix with SSH? I want to access Felix shell from remote computer using SSH. I know that there is a telnet support but it's too unsafe. Is there any solution? A: Yes, there is one, as described here (the guide is relative to eclipse's equinox but it doesn't matter) using a combination of gogo shell, apache mina sshd server and three equinox console bundles (core+ssh plugin+jaas plugin for ssh authentication) you will be able to connect to mina's ssh server and your commands related to OSGi will be executed by the gogo shell. You'll need these bundles: GoGo Shell: org.apache.felix.gogo.command.jar, org.apache.felix.gogo.runtime.jar, org.apache.felix.gogo.shell.jar Equinox console Bundles: org.eclipse.equinox.console.jar, org.eclipse.equinox.console.supportability.jar, org.eclipse.equinox.console.jaas.fragment.jar Apache Mina: org.apache.mina.core.jar, org.apache.sshd.core.jar And for logging slf4j-api.jar and a slf4j-api_impl.jar As described here, you will also need these properties in your Felix configuration file: osgi.console.enable.builtin=false osgi.console.ssh=<port> osgi.console.ssh.useDefaultSecureStorage=true The equinox JAAS bundle will search for a org.eclipse.equinox.console.authentication.config file, that will enable the login module: equinox_console { org.eclipse.equinox.console.jaas.SecureStorageLoginModule REQUIRED; }; I'm not quite sure where this will be searched using Felix (i'm not sure this is done in a standard OSGi way), but the conf directory is a good guess. The user equinox/equinox will already be present, other users can be created with the console commands provided. Edit: For the equinox console/supportability bundle you can get the Mars release from here expanding the section Add-on Bundles: org.eclipse.equinox.console_1.1.100.v20141023-1406.jar You'll also need the supportability bundle that you can get from here(the last version is from 2011).
{ "pile_set_name": "StackExchange" }
Q: Why this gives 0? fixed in 10.0.2. Why this gives 0? I am in shock, it should be Sinh[x]. FullSimplify[I InverseFourierTransform[FourierTransform[Cosh[t],t,w]/w,w,x]] A: As was noted by @DumpsterDoofus, the FT of cosh(x) does not exist. So in a sense this is GIGO. Whether FourierTransform should be able to detect this nonexistence is a question I will raise in house. So why does one get 0 for that transform? I have not checked in detail but will hazaed a guess that Integrate (called by FourierTransform under the hood) is dropping a divergent part of a result found via Slater convolution, and coming up with 0. Is this wrong? Possibly not. Here is a regularization for the exponential that converges, and from which a limit can be extracted. ii = Integrate[Exp[-m*x^2 + x + I*x*t], {x, -Infinity, Infinity}, Assumptions -> {m > 0, Element[t, Reals]}] (* Out[18]= (E^(-((-I + t)^2/(4 m))) Sqrt[\[Pi]])/Sqrt[m] *) Limit cannot handle the case of arbitrary real t so I'll pick a specific value. In[19]:= Limit[ii /. t -> 7/3, m -> 0] (* Out[19]= 0 *) So I don't think anything is really amiss, other than possibly that FourierTransform does not recognize this nonexistence. A: It is not hard to see where the 0 is coming from. It has to do with the FourierTransform part. By the time we get to the Inverse, it is too late. The damage has been done. f = TrigToExp[Cosh[t]] f1 = FourierTransform[f, t, w] Now Mathematica decided to give zero for each part of the above: FourierTransform[(1/2) ExpToTrig[Exp[-t]], t, w] (* 0 *) FourierTransform[(1/2) ExpToTrig[Exp[t]], t, w] (* 0 *) What this means, is that Mathematica thinks that FourierTransform[Cosh[t], t, w] is zero. And zero/w is zero. So the division by w here makes no difference. The InverseTransform of zero is zero. So the final result is zero. Now why does M think FourierTransform[(1/2) E^-t, t, w] is zero? That is the main question. Exp[t] is 2 sided exponential. Only way to get convergence is like this (from definition itself, but must use |t|) else it will not converge. Assuming[w > 0, Integrate[Exp[-Abs@t] Exp[-I w t], {t, -Infinity, Infinity}]] A: This has been fixed in V 10.0.2. It no longer returns 0. On windows 7, 64 bit: FullSimplify[I InverseFourierTransform[FourierTransform[Cosh[t], t, w]/w, w, x]]
{ "pile_set_name": "StackExchange" }
Q: ssh from parameter laravel I want to create a form like this. Host __________ user __________ pass __________ port _________ to connect the ssh via laravel. I see config in remote.php is 'connections' => [ 'production' => [ 'host' => '222.222.222.222', 'username' => 'root', 'password' => '', 'key' => '', 'keytext' => '', 'keyphrase' => '', 'agent' => '', 'timeout' => 10, ], ], but i don't want to force the config. I just want like SSH::connect('222.222.222.222','root','1234',22); How can do that? Sorry my english. A: This is the laravel way to set your config runtime! config(['remote.connections.production' => array( 'host' => '$host, 'username' => $un, 'password' => $pw, 'key' => '', 'keytext' => '', 'keyphrase' => '', 'agent' => '', 'timeout' => 10, )]);
{ "pile_set_name": "StackExchange" }
Q: How do I get the exit code from my subscript in main script - bash How do I get the exit code from my subscript in main script. In my script below when the subscript fails it exits from the main script as well. #!/bin/bash function reportError() { if [ $1 -ne 0 ]; then echo $2 exit $1 fi } #executing the subscript /data/utility/testFolder.sh #calling the function if there is any error then function would update the #audit table reportError $? "job is failed, please check the log for details" Subscript code - #!/bin/bash if [ -d "/data/myfolder/testfolder" ] then echo "ERROR: Directory does not exists" exit 1 else echo "INFO: Directory exists" exit 0 fi A: I checked your code and everything is fine except you made a mistake in the subscript condition. #!/bin/bash function reportError() { if [ $1 -ne 0 ]; then echo $2 exit $1 fi } #executing the subscript /data/utility/testFolder.sh #calling the function if there is any error then function would update the #audit table reportError $? "job is failed, please check the log for details" Child script: #!/bin/bash if [ ! -d "/data/myfolder/testfolder" ] # add "!". More details: man test then echo "ERROR: Directory does not exists" exit 1 else echo "INFO: Directory exists" exit 0 fi
{ "pile_set_name": "StackExchange" }
Q: Find Co-domain such that Function becomes always Continuous Assume that set $\mathbb{S}$ is co-domain to any function $\mathbb{F}$ and this function is always continuous for any domain which is subset real numbers. What can be $\mathbb S$ ? It is possible if $\mathbb S$ contains only one element but if it is very small interval, then is it possible for function to be always continuous ? If yes, then can we prove it using definition of continuity in terms of convergent sequences ? A: Note that the definition of continuity in terms of convergent sequences applies only to metric spaces. That being said: if $\Bbb S$ is any metric space containing at least two points, then there exists a discontinuous $\Bbb S$-valued function. If $\Bbb S$ contains any two points $s_1 \neq s_2$, then we can construct such a discontinuous function $f:[0,1] \to \Bbb S$ by defining $$ f(x) = \begin{cases} s_1 & x \neq 0\\ s_2 & x = 0 \end{cases} $$ Consider the sequence $x_n = 1/n$ with $n = 1,2,3,\dots$, which satisfies $x_n \to 0$. We note that $f(x_n) \to s_1$, but $f(0) = s_2$. So, $\lim_{n \to \infty}f(x_n) \neq f(\lim_{n \to \infty} x_n)$.
{ "pile_set_name": "StackExchange" }
Q: Target list items in primary ul but not nested ul I need to add css styles to parent list. I have one parent ul and children. I want to apply color to fruits, vegetables and flowers but not Apple, Banana, Orange. I want to do this using a CSS selector. ul:root>li { color: red; } <ul> <li>Fruits <ul> <li>Apple</li> <li>Banana</li> <li>Orange</li> </ul> </li> <li>Vegetables</li> <li>Flowers</li> </ul> A: You could simply add a class to the parent ul and then use the direct descendant selector to target only those li items. This is definitely going to change the colors for Apple or Orange but you can then reset the color on the sub ul items. Here's your updated demo. .parent-list > li { color: red; } .parent-list > li ul { color: initial; } <ul class="parent-list"> <li>Fruits <ul> <li>Apple</li> <li>Banana</li> <li>Orange</li> </ul> </li> <li>Vegetables</li> <li>Flowers</li> </ul>
{ "pile_set_name": "StackExchange" }
Q: Get an enumerable of all sub lists of an existing list I have a List<T> and I want to obtain all possible sub lists, e.g.: [A, B, C, D, E] => [[A], [A, B], [A, B, C], [A, B, C, D], [A, B, C, D, E]] Is there an easy way to do obtain this new enumerable with LINQ to Objects? EDIT 1: Note that I only want "prefix lists", not all possible permutations (i.e., the shown example result is already complete). EDIT 2: Note that I want to maintain the order of the elements as well. EDIT 3: Is there a way to obtain the enumerables in O(n) instead of O(n²), i.e., by iterating over the source only once instead of multiple times and returning some kind of view on the data instead of a new list each time? A: A very naive extension method: public static class Extensions { public static IEnumerable<IEnumerable<T>> GetOrderedSubEnumerables<T>( this IEnumerable<T> collection) { var builder = new List<T>(); foreach (var element in collection) { builder.Add(element); yield return builder; } } } Use: void Main() { var list = new List<string> { "A", "B", "C", "D", "E" }; Console.WriteLine(list.GetOrderedSubEnumerables()); } Result: Note this will return views of your data as you iterate the collection. But eventually, if you need to consume each permutation separately, you'll need to copy each List<T> over before yielding it back. In that case, this should do it: public static class Extensions { public static IEnumerable<IEnumerable<T>> GetOrderedSubEnumerables<T>( this IEnumerable<T> collection) { var builder = new List<T>(); foreach (var element in collection) { builder.Add(element); var local = new List<T>(builder); yield return local; } } }
{ "pile_set_name": "StackExchange" }
Q: How to put 4-seconds delay while changing the background image of a buttan in Android I have two buttons in my sample application and I want to change the background image of the buttons one after another with 4-seconds delay, So far i have developed the code, you can see it below, but it gets sleep my application and display nothing. Please somebody help me that I could do so. int m =0; int delay = 4; //Seconds while(m < 4) { // int i = (int) (Math.random() * num + 1); if(m==0) { button1.postDelayed(new Runnable() { public void run() { // TODO Auto-generated method stub button1.setBackgroundResource(R.drawable.buttonyellow); m++; } }, 1000*delay); } else if(m==1) { button2.postDelayed(new Runnable() { public void run() { // TODO Auto-generated method stub button2.setBackgroundResource(R.drawable.buttonyellow); m++; } }, 1000*delay); } if(m==2) { button1.postDelayed(new Runnable() { public void run() { // TODO Auto-generated method stub button1.setBackgroundResource(R.drawable.buttonblue); m++; } }, 1000*delay); } else if(m==3) { button2.postDelayed(new Runnable() { public void run() { // TODO Auto-generated method stub button2.setBackgroundResource(R.drawable.buttonblue); m++; } }, 1000*delay); } } A: int mark = 0; button2.postDelayed(new Runnable() { public void run() { switch(mark++){ case 0:button2.setBackgroundResource(R.drawable.buttonyellow); break; case 1:button2.setBackgroundResource(R.drawable.buttongreen); break; ..ect } if(mark==Max)mark=0; button2.postDelayed(this,4000); } }, 4000); Note, this will go on till the end of time, or when your app stops.
{ "pile_set_name": "StackExchange" }
Q: Do Hindu scriptures allow the use of weapons of mass destruction like the Brahmastra to annihilate the civilian population of a foreign country? In the Mahabharata, Krishna destroyed the city Kashi with his Sudarshana Chakra. Is the use of Brahmastras and other celestial Astras, akin to weapons of mass destruction, to destroy entire cities along with their civilian population prohibited or permitted by Hindu scripture? A: WMDs like Brahmāstra and Brahmaśira should never be fired on unarmed civilians or even enemy combatants who are no match for these weapons. Otherwise, it can set the whole universe (Earth?) on fire. Droṇa warns Arjuna about the dangers of Brahmaśira before bestowing it on him: Adi Parva (Sambhava Parva) Chapter 123 . . . A few days later, the best of those of the Angirasa lineage went with his students to the Ganga to bathe. When Drona entered the water, a powerful crocodile grabbed him by the thigh, as if sent by destiny itself. Though quite capable of saving himself, Drona told his students, "Kill the crocodile and quickly save me." Even before he had finished speaking, Bibhatsu let loose five sharp arrows that killed the crocodile under the water. The others were still standing around, looking confused. On seeing the Pandava’s swiftness in action, Drona was extremely pleased and decided that he was the best of his students. The crocodile was chopped into many pieces through Partha's arrows. It let go of the great-souled one's thigh and returned to the five elements. Bharadvaja's son told the great-souled maharatha, "O mighty-armed one! Receive this invincible and supreme weapon, named brahmashira, with the knowledge of releasing it and withdrawing it. You must never use it against human beings. If it is used against an enemy whose energy is inferior, it will burn up the entire universe. O son! It is said that there is nothing superior to this weapon in the three worlds. Therefore, preserve it carefully and listen to my words. O brave one! If a superhuman enemy ever fights with you, use this weapon to kill him in battle." With joined hands, Bibhatsu promised that he would do as he had been asked and received the supreme weapon. His preceptor again told him, "No man in the world will be a greater archer than you." [The Mahabharata: Volume 1, Bibek Debroy]
{ "pile_set_name": "StackExchange" }
Q: Python - Fast way to split positive integer into array of ones I have an array of shape (100000, 1) with each element in the array is a positive integer and not greater than 6. My goal is to convert each element into ones and place these ones in a new matrix of shape (100000, 6). For example, Input X = np.array([[6], [2], [1], ..., [5], [4], [3]]) # shape of X is (100000, 1) Output Y = np.array([[1, 1, 1, 1, 1, 1], [1, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [ ... ], [1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 0, 0], [1, 1, 1, 0, 0, 0]]) # shape of Y is (100000, 6) Is there any method that can achieve this without looping? Any help would be appreciated. A: One way using numpy.flip with cumsum: max_ = 6 np.flip(np.flip(np.eye(max_)[X.ravel()-1], 1).cumsum(1), 1) Output: array([[1., 1., 1., 1., 1., 1.], [1., 1., 0., 0., 0., 0.], [1., 0., 0., 0., 0., 0.], [1., 1., 1., 1., 1., 0.], [1., 1., 1., 1., 0., 0.], [1., 1., 1., 0., 0., 0.]]) Benchmark with 100k: x_large = np.random.randint(1, 7, 100000) max_ = 6 %timeit np.flip(np.flip(np.eye(max_)[x_large.ravel()-1], 1).cumsum(1), 1) # 6.71 ms ± 68.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
{ "pile_set_name": "StackExchange" }
Q: Is it possible to find the address of the end of an array with a reference to the n+1th element? I need to know when the pointer went through the whole array -> is on the first position behind it. Examplecode in c: unsigned int ar[10]; char *pointer = (char*) ar; while(pointer != (char*) &ar[10]){ *pointer++ = 0xff } Would this example work to set every element of the array to 0xffffffff? A: When working with raw binary, I'd recommend to use an unsigned character type such as uint8_t instead of char, since the latter has implementation-defined signedness. Then there are two special rules in C you can utilize: C11 6.3.2.3/7 When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object. Successive increments of the result, up to the size of the object, yield pointers to the remaining bytes of the object. This allows us to inspect or modify the raw binary contents of any type in C by using a character pointer. So you can indeed set every byte of the integer array to 0xFF using a character pointer. The other special rule is hidden inside how the additive operators work, since the [] operator is just syntactic sugar around + and dereference. C11 6.5.6/8, emphasis mine: If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. This allows us to check the address 1 int beyond the end of the array. However converting between a character type pointer and an int pointer creates misaligned pointers and that (at least in theory) invokes undefined behavior and possibly instruction traps. So you can't just cast the character pointer to an integer pointer and compare. So the completely correct way would be to increase the character pointer by sizeof(int) then set 4 bytes each lap in the loop. Meaning that the following is an well-defined (but cumbersome & hard-to-read) way of setting all bytes in the array: #include <stdio.h> #include <stdint.h> int main (void) { unsigned int arr[10]; for(uint8_t* i = (uint8_t*)arr; (unsigned int*)i != &arr[10]; i+=sizeof(unsigned int)) { i[0] = 0xFF; i[1] = 0xFF; i[2] = 0xFF; i[3] = 0xFF; } for(size_t i=0; i<10; i++) { printf("%X\n", arr[i]); } return 0; }
{ "pile_set_name": "StackExchange" }
Q: d3 draw a children element on top of a parent element and access parent element attributes I want to draw a rectangle for each data point, and also draw a dot on the center of each rectangle if certain value is true. Although I can draw another set of dots trivial way. But I want to access some attribute (e.g., x, y) of the (parent) rectangles while drawling the corresponding dots. I have illustrated in the attached image. Can you please help me her? Thanks. <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title> Icon </title> <script type="text/javascript" src="lib/d3/d3.v3.js"></script> </head> <body> <p id="icon"> <script> var dataset = [ {"id": 1, "selection": true}, {"id": 2, "selection": true}, {"id": 3, "selection": true}, {"id": 4, "selection": false}, {"id": 5, "selection": false}, {"id": 6, "selection": true}, {"id": 7, "selection": false}, {"id": 8, "selection": true} ]; var svg = d3.select("#icon") .append("svg") .attr("height", 200) .attr("width", 200); var x = 10, y = 10; svg.selectAll("rect") .data(dataset).enter() .append("rect") .attr("width", 10) .attr("height", 10) .attr("x", function(d, i) { return x = x + 12; }) .attr("y", function(d, i) { return y; }) .style("fill", "yellow") .style("stroke", "grey") .style("stroke-width", ".5px"); </script> </body> </html> A: You can use the same code as you did for the rectangles to append circles on top : http://jsfiddle.net/bh50q7Le/ Simply style the stroke using a function which returns "none" if the point is not a selection. Formatted code (I've also parameterized the size of the rectangle): var dataset = [ {"id": 1, "selection": true}, {"id": 2, "selection": true}, {"id": 3, "selection": true}, {"id": 4, "selection": false}, {"id": 5, "selection": false}, {"id": 6, "selection": true}, {"id": 7, "selection": false}, {"id": 8, "selection": true} ]; var rectsize = 30; var svg = d3.select("#icon") .append("svg") .attr("height", rectsize*dataset.length) .attr("width", rectsize*(dataset.length + 1)); svg.selectAll("rect") .data(dataset).enter() .append("rect") .attr("width", rectsize) .attr("height", rectsize) .attr("x", function(d, i) { return i*(rectsize + 2); }) .attr("y", function(d, i) { return rectsize; }) .style("fill", "yellow") .style("stroke", "grey") .style("stroke-width", ".5px"); svg.selectAll("circle") .data(dataset).enter() .append("circle") .attr("r", rectsize/4) .attr("cx", function(d, i) { return rectsize*0.5 + i*(rectsize + 2); }) .attr("cy", function(d, i) { return rectsize*1.5; }) // color if selected .style("stroke", function(d) { return d.selection ? "grey" : "none"}) .style("fill", "none") .style("stroke-width", "2px");
{ "pile_set_name": "StackExchange" }
Q: Avoid connection timeout when using multiple threads and connection pool I'm splitting up a readonly database operation into multiple chunks, (Each of which reads a subset of a very large amount of data, analyzes it and writes the results to a disk file). Each chunk performs a Select (into a datatable) on a new .net thread (using a delegate and BeginInvoke) There are more subsets of the data than there are available connections in the pool, so when I run out of connections, before the first one is released, subsequent connection requests are queued up... until the connection timeout expires, and then I get a timeout exception. How do I either, A) inhibit the timeout connection exception when the connections in the pool are all in use, or B) detect that they are all in use before I even ask for another one so I can wait until one is available before asking? A: Two solutions: A) Configure your connection pool with a timeout of several days. That will block the pending tasks until a connection is returned. Drawback: This won't work when a task hangs. B) Use a thread pool and a work queue. The thread pool must have the same size as the connection pool (i.e. one connection per thread). Put all the work in the queue and have the tasks fetch work items from the queue until the queue is empty. Pseudocode for solution B: public class Setup connPool = createConnectionPool(100); queue = createWorkQueue(); putAllWorkItemsInQueue(queue); for (int i=0; i<connPool.size(); i++) { t = new WorkerThread(queue) list.add(t); t.start(); } while (queue.size() != 0) { Thread.sleep(1000); } for (thread in list) { thread.interrupt(); } public class WorkerThread run() { while (true) { try { workUnit = queue.get(); // This blocks process(workUnit); } catch (InterruptedException e) { break; } } }
{ "pile_set_name": "StackExchange" }
Q: BadRequestError: Only ancestor queries are allowed inside transactions from google.appengine.ext import db class Parent(db.Model): app_id = db.StringProperty() class Child(db.Model): app_id = db.ReferenceProperty(Parent,collection_name='children') type = db.StringProperty() count = db.IntegerProperty() @db.transactional def increment_counter(app,childName): childA = Child.all().ancestor(app).filter('type =',childName).get() if childA is not None: obj = db.get(childA.key()) obj.count += 1 obj.put() else: childA = Child(app_id=app.key(),type=childName,count=0) childA.put() increment_counter(Parent.all().filter('app_id =',app_id).get().key(),childKey) This fails with the title error on the put() if childA is empty. In my head I want to attach a new child entity to the single Parent entity I'm working with in the transaction if it's not already present, otherwise do an increment. Why is this not regarded as an ancestor query and what should I be doing instead to get the effect I'm after? A: OK, seems after a time away from App Engine I confused the separate concepts of entity parent and ReferenceProperty. The correct code: class Parent(db.Model): app_id = db.StringProperty() class Child(db.Model): type = db.StringProperty() count = db.IntegerProperty() @db.transactional def increment_counter(app,childName): childA = Child.all().ancestor(app).filter('type =',childName).get() if childA is not None: obj = db.get(childA.key()) obj.count += 1 obj.put() else: childA = Child(parent=app,type=childName,count=0) childA.put() increment_counter(Parent.all().filter('app_id =',app_id).get().key(),childKey)
{ "pile_set_name": "StackExchange" }
Q: How does one enter women's restroom? On the Crew Deck of Normandy, we have the restrooms. Throughout the game thus far, I have been able enter men's restroom, but never women's (no hologrammatic lock on it). How do I enter women's? Is it openable at all at certain point in the game? I play a male Shepherd if that makes any difference. I am not a pervert or anything. Just curious about what's in that room. :-) A: One may only enter the bathroom appropriate for one's gender. If you're really curious you could start a character of the opposite gender, though you will likely be disappointed.
{ "pile_set_name": "StackExchange" }
Q: Select top statement ordering by non-unique column I have two sql queries select * from table1 ORDER BY column1 Select top 10 * from table1 ORDER by column1 Column1 is a non unique column and table1 does not have a primary key. When I run both queries, I'm getting the rows returning in different orders. I attribute this to the fact that the criterion for ranking (the Order By) is non unique. I'm wondering what method does a normal SELECT statement use to determine the output order of the rows in this case and what a select top statement would use. Is it just random? A: In the non-unique case, the output order of the rows should not be relied upon. Instead, impose the ordering you want (by including other columns in the ORDER BY)
{ "pile_set_name": "StackExchange" }
Q: How to Update a Many-Many Field in Django In my django app, my model looks like: class Tag(models.Model): title = models.CharField(max_length=50,) class Publication(models.Model): title = models.CharField(max_length=200,) tags = models.ManyToManyField(Tag, blank=True, related_name="publications", null=True) Let's say have 2 tags in my Tag table: "dogs" and "cats." Let's say my existing publication "Pets" has only the tag "dogs" on it. How can I add the existing "cats" tag to "Pets?" In the Django docs https://docs.djangoproject.com/en/dev/ref/models/instances/, I saw the following example for updating a db item: product.name = 'Name changed again' product.save(update_fields=['name']) But I don't see anything for updating a many-many field. How would I do this? A: # let publication be your existing Pets publication instance cats_tag, created = Tag.objects.get_or_create(title='cats') publication.tags.add(cats_tag)
{ "pile_set_name": "StackExchange" }
Q: How can I set signature to v2 by using AWS S3 C++ SDK I have to set the AWS S3 C++ SDK to using signature_v2,I know how to set it in PHP SDK,but I did't found the method in C++ SDK.Is anybody know ,thx! A: Signature Version 2 has been deprecated in favor of the more secure version 4. We don't support it, and the only reason it is supported in other sdks is for backwards compatibility. For Amazon S3, you can turn off body signing for v4. This is the default option for the S3 Client in the C++ SDK.
{ "pile_set_name": "StackExchange" }
Q: Option txt is overwrite drop-down arrow from select on google chrome I have a strange problem with select on chrome. I want to add a gradient background and I managed that but my problem now is how to make the option to not overwrite my select arrow. Maybe if I use pointer-events:auto; ??? If anyone can help I'll really appreciate. Tkank's. fiddle: http://jsfiddle.net/thirtydot/DCjYA/361/ A: try with : -webkit-padding-end: 10px; this will fix your problem.
{ "pile_set_name": "StackExchange" }
Q: Laravel 5 - stay logged in forever I wanted to put in the login page a checkbox "stay logged in". That should never end the session of the user unless the user logs out. I know that in app/config/session.php I have these variables: 'lifetime' => 60, 'expire_on_close' => false, But I wanted to maintain alive the session forever, and not be removed if the user close his navigator. Any ideas on how should I proceed? Thanks A: Laravel has a built-in feature to remember users, I'd strongly recommend using it. If you would like to provide "remember me" functionality in your application, you may pass a boolean value as the second argument to the attempt method, which will keep the user authenticated indefinitely, or until they manually logout. Of course, your users table must include the string remember_token column, which will be used to store the "remember me" token. if (Auth::attempt(['email' => $email, 'password' => $password], $remember)) { // The user is being remembered... } if you want to solve the problem manually, there is workaround for this: you have to set the expires date of your cookie to a date in the wide future, somewhat like 2050. this is technically not forever, but should usually be long enough.
{ "pile_set_name": "StackExchange" }
Q: Validation of String containing DateTime in a specific pattern I'm trying to do some validation to the params that a receive from a post in Nodejs. The body is something like: { "startDateTime": "2019-10-01 00:00:01", "endDateTime": "2019-10-01 23:59:59", "interval": "00:00:01" } So, i need to validate if startDateTime and endDateTime are in the pattern "yyyy-MM-dd hh:mm:ss", and interval in "hh:mm:ss" I try to use the moment package, but didn't work const testDate = moment(startDateTime, "yyyy-MM-dd hh:mm:ss", true).isValid() I'm passing StartDateTime = "2019-10-01 00:00:01" and testDate is getting assigned to false. Anyone could help? A: You're using the wrong Format. Try "YYYY-MM-DD HH:mm:ss" instead. To learn more about Moment.js Formats, take a look at its documentation. let response = { "startDateTime": "2019-10-01 00:00:01", "endDateTime": "2019-10-01 23:59:59", "interval": "00:00:01" }; const testDate = moment(response.startDateTime, "YYYY-MM-DD HH:mm:ss", true).isValid(); console.log(testDate); <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
{ "pile_set_name": "StackExchange" }
Q: why won't this Corona SDK code work for centering view based on touch point? Any suggestions re how to fix the code I have below to make it work? I want to be able to position the moveableGroup after a zoom in or out (i.e. click or double-click) such that the point clicked will be moved to the centre of the cross-hairs in the fixedGroup. I'm getting muddled up getting it right noting the use of group zoom, moves etc. display.setStatusBar( display.HiddenStatusBar ) system.setTapDelay( 0.3 ) local function moveableMapTouchListener( event ) local moveableView = event.target if event.phase == "began" then moveableView.markX = moveableView.x -- store x location of object moveableView.markY = moveableView.y -- store y location of object elseif event.phase == "moved" then local x = (event.x - event.xStart) + moveableView.markX local y = (event.y - event.yStart) + moveableView.markY moveableView.x, moveableView.y = x, y -- move object based on calculations above elseif event.phase == "ended" then end return true end local function moveableViewTapListener(event) local moveableView = event.target -- Calculate Scale Ratio local scaleRatio if event.numTaps == 1 then -- Single Tap scaleRatio = 0.8 elseif event.numTaps == 2 then scaleRatio = 1/0.8 end -- Note Pivot Point (where user clicked) and current Centre local pivotXLocal, pivotYLocal = event.target:contentToLocal( event.x, event.y ) local centreX, centreY = -moveableView.x, -moveableView.y -- Scale Image moveableView:scale(scaleRatio, scaleRatio) -- ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ -- Move to Centre Around Pivot Point *** HOW TO DO THIS ??? - THIS DOESN'T WORK *** local pivotXContent, pivotYContent = event.target:localToContent( pivotXLocal, pivotYLocal ) local zeroXContent, zeroYContent = event.target:localToContent( 0,0 ) moveableView.x, moveableView.y = pivotXContent - zeroXContent, pivotYContent - zeroYContent -- ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ return true end --------------------------------- -- Implementation --------------------------------- -- Moveable Group local moveableGroup = display.newGroup() local internalContents = display.newRect(moveableGroup, 50,80, 300,300) internalContents.strokeWidth = 3 internalContents:setFillColor ( 1, 0.5 ,1, 0.5 ) internalContents:setStrokeColor( 0, 0, 1, 1 ) -- Fixedup Group (with crosshairs) local mainFixedGroup = display.newGroup() local _w, _h = 0.8 * display.contentWidth, 0.8 * display.contentHeight local myRectangle = display.newRect(mainFixedGroup, 0, 0, _w, _h ) myRectangle.strokeWidth = 3 myRectangle:setFillColor ( 1, 0 ,0, 0 ) myRectangle:setStrokeColor( 0, 0, 1, 1 ) -- Cross Haris local crossHari1 = display.newLine(mainFixedGroup, -_w/2, -_h/2, _w/2, _h/2 ) crossHari1:setStrokeColor( 0, 0, 1, 1 ) crossHari1.strokeWidth = 1 local crossHari2 = display.newLine(mainFixedGroup, -_w/2, _h/2, _w/2, -_h/2 ) crossHari2:setStrokeColor( 0, 0, 1, 1 ) crossHari2.strokeWidth = 1 mainFixedGroup.x, mainFixedGroup.y = display.contentWidth/2, display.contentHeight/2 -- Insert Moveable Group into Fixed Group mainFixedGroup:insert(moveableGroup) moveableGroup.x = -50 moveableGroup.y = -50 -- Add Listeners (to move / scale the moveable Group) moveableGroup:addEventListener( "touch", moveableMapTouchListener ) moveableGroup:addEventListener( "tap", moveableViewTapListener) A: this seems to fix it: display.setStatusBar( display.HiddenStatusBar ) system.setTapDelay( 0.3 ) local function showPoint(parent, x, y) local myCircle = display.newCircle(parent, x,y, 8 ) myCircle:setFillColor( 0.5,0,1 ) myCircle.strokeWidth = 0 end local function moveableMapTouchListener( event ) local moveableView = event.target if event.phase == "began" then moveableView.markX = moveableView.x -- store x location of object moveableView.markY = moveableView.y -- store y location of object elseif event.phase == "moved" then local x = (event.x - event.xStart) + moveableView.markX local y = (event.y - event.yStart) + moveableView.markY moveableView.x, moveableView.y = x, y -- move object based on calculations above elseif event.phase == "ended" then end return true end local function moveableViewTapListener(event) local moveableView = event.target -- Calculate Scale Ratio local scaleRatio if event.numTaps == 1 then -- Single Tap scaleRatio = 0.8 elseif event.numTaps == 2 then scaleRatio = 1/0.8 end -- -- Note Pivot Point (where user clicked) and current Centre -- local pivotXLocal, pivotYLocal = event.target:contentToLocal( event.x, event.y ) -- local centreX, centreY = -moveableView.x, -moveableView.y -- Note Pivot Point (where user clicked) and current Centre local pivotXL, pivotYL = moveableView:contentToLocal( event.x, event.y ) local myCircle = display.newCircle(moveableView, pivotXL, pivotYL, 8 ) myCircle:setFillColor( 0.5,0,1 ) myCircle.strokeWidth = 0 -- Scale Image moveableView:scale(scaleRatio, scaleRatio) -- ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ local ox, oy = moveableView.parent:contentToLocal( display.contentWidth/2, display.contentHeight/2 ) local txc, tyc = moveableView:localToContent(myCircle.x, myCircle.y) local tx, ty = moveableView.parent:contentToLocal( txc, tyc) showPoint(moveableView.parent, ox, oy) local dx, dy = tx-ox, ty-oy moveableView.x, moveableView.y = moveableView.x - dx, moveableView.y - dy -- -- Move to Centre Around Pivot Point *** HOW TO DO THIS ??? - THIS DOESN'T WORK *** -- local pivotXContent, pivotYContent = event.target:localToContent( pivotXLocal, pivotYLocal ) -- local zeroXContent, zeroYContent = event.target:localToContent( 0,0 ) -- moveableView.x, moveableView.y = pivotXContent - zeroXContent, pivotYContent - zeroYContent -- ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ return true end --------------------------------- -- Implementation --------------------------------- -- Moveable Group local moveableGroup = display.newGroup() local internalContents = display.newRect(moveableGroup, 50,80, 300,300) internalContents.strokeWidth = 3 internalContents:setFillColor ( 1, 0.5 ,1, 0.5 ) internalContents:setStrokeColor( 0, 0, 1, 1 ) -- Fixedup Group (with crosshairs) local mainFixedGroup = display.newGroup() local _w, _h = 0.8 * display.contentWidth, 0.8 * display.contentHeight local myRectangle = display.newRect(mainFixedGroup, 0, 0, _w, _h ) myRectangle.strokeWidth = 3 myRectangle:setFillColor ( 1, 0 ,0, 0 ) myRectangle:setStrokeColor( 0, 0, 1, 1 ) -- Cross Haris local crossHari1 = display.newLine(mainFixedGroup, -_w/2, -_h/2, _w/2, _h/2 ) crossHari1:setStrokeColor( 0, 0, 1, 1 ) crossHari1.strokeWidth = 1 local crossHari2 = display.newLine(mainFixedGroup, -_w/2, _h/2, _w/2, -_h/2 ) crossHari2:setStrokeColor( 0, 0, 1, 1 ) crossHari2.strokeWidth = 1 mainFixedGroup.x, mainFixedGroup.y = display.contentWidth/2, display.contentHeight/2 -- Insert Moveable Group into Fixed Group mainFixedGroup:insert(moveableGroup) moveableGroup.x = -50 moveableGroup.y = -50 moveableGroup:rotate( 45 ) -- Add Listeners (to move / scale the moveable Group) moveableGroup:addEventListener( "touch", moveableMapTouchListener ) moveableGroup:addEventListener( "tap", moveableViewTapListener)
{ "pile_set_name": "StackExchange" }
Q: What is the Imperial Navy rank structure and where was it inspired from? In reading Thrawn he receives a few ranks which I found interesting. He is a commodore and ultimately a grand admiral. What was the rank structure in the Empire's navy? And what was the motivation/basis for this structure, particularly when I believe some of the ranks are different than existing ranks in most militaries? A: The (Legends) ranking system is described in The Essential Guide to Warfare by Del Rey (2012). The guide describes the difference between positions and line ranks as following: Position is an officer's current assignment to a specific ship of unit, as opposed to permanent rank. The positions of Warlord and High Admiral are essentially honorary, normally held by Grand Admirals and Moffs. Line rank is held by line officers, the men who command the bridge crew, captain ships, and hoist their flag over fleets. There are very few officers with permanent line ranks above senior captain (formally known as captain of the line). Out-of-universe, the inspiration seems to come from the military rank systems on Earth, with great influence of American and British systems. There are many similar rank names, with some fictional flavor added, of course. There is a good list of naval officer ranks in Wikipedia.
{ "pile_set_name": "StackExchange" }
Q: Speeding up sumproduct calculation I have an excel file that contains data from GIS that has just under 215k rows of data. Of this data there are 3 columns that are of interest to me: GRID_ID (roughly 18k unique values) Croptype (15 unique values) AREA (all unique values) Now I know I can get a summation table of this (the area for each combination of Grid_ID and Croptype) by using this formula in Cell C2. Whilst column A contains the unique GRID_ID's, in ascending order, and row 1 contains the Croptype's starting in column C. =Sumproduct((GRID_ID=$A2)*(Croptype=C$1)*AREA) Where in the formula the column names are replaced with the actual ranges of the data. Now this works fine for a smaller dataset, but for my set it is problematically slow. Would there be a more efficient way of going about calculating this problem? A: Use SUMIFS() =SUMIFS(AREA,GRID_ID,$A2,Croptype,C$1) Which should be quicker. But even too many of these will slow down the calcs. you may want vba to do the whole at once using variant arrays.
{ "pile_set_name": "StackExchange" }
Q: как открыть программу через python код в ubuntu Как из python-кода запустить нужную мне программу (например PyCharm) если программа была установлена через менеджер приложений ubuntu? A: Запустить ярлык из меню можно так gtk-launch jetbrains-datagrip Имя смотрите в папках /usr/share/applications/, ~/.local/share/applications, /usr/share/local/applications/.
{ "pile_set_name": "StackExchange" }
Q: C++ how to catch an exception? I am trying to catch pointer exception. My code looks like this. I am getting "Unhandled exception". What is it that I am doing wrong? Any help will be appreciated. #include <iostream> #include <exception> using namespace std; struct Node{ int data; Node* next; }; int list_length(struct Node* head){ try{ int i = 0; while (head->next){ head = head->next; i++; } return i + 1; } catch (exception& e){ cout << e.what() << endl; } }; int main(void){ struct Node *perr = nullptr; list_length(perr); return 0; } A: There is no C++ exception here. You just dereference null pointer, that is undefined behaviour, not exception. You should just check, that head is not nullptr before dereference it. Probably, you are using windows and windows exception is thrown. You can read here: How to catch the null pointer exception?
{ "pile_set_name": "StackExchange" }
Q: $|f(x)-f(1)|<k|x-1|$ Given the function : $f(x)=x^2+x|x-1|-1$ such that $x$ is a real number . Show that there is a $k\in \mathbb{R}$ for all $x\in \mathbb{R}$ such that: $|x-1|<1 \implies |f(x)-f(1)|<k|x-1|$ I tried cases of $x$ : If $x>1$ then $f(x)=(2x+1)(x-1)$ If $x<1$ then $f(x)=x-1$ And so the $k=2x+1$ ? And then conclude that for all positive $\varepsilon$ there is a positive $\alpha$ for all real $x$ Such that: $|x-1|\lt1 \implies |f(x)-f(1)|\lt\varepsilon$ A: If $x \in \mathbb{R}$, then $$ |f(x) - f(1)| = |x^{2}+x|x-1|-1| \leq |x-1|(|x| + |x+1|); $$ if $|x-1| < 1$, then $0 < x < 2$, so $$ |x-1|(|x| + |x+1|) < 5|x-1|; $$ take $k := 5$.
{ "pile_set_name": "StackExchange" }
Q: AES Cipher not picking up IV I am trying to use an IV with AES so that the encrypted text is unpredictable. However, the encrypted hex string is always the same. I have actually tried a few methods of attempting to add some randomness by passing some additional parameters to the cipher init call: 1) Manual IV generation byte[] iv = generateIv(); IvParameterSpec ivspec = new IvParameterSpec(iv); 2) Asking cipher to generate IV AlgorithmParameters params = cipher.getParameters(); params.getParameterSpec(IvParameterSpec.class); 3) Using a PBEParameterSpec byte[] encryptionSalt = generateSalt(); PBEParameterSpec pbeParamSpec = new PBEParameterSpec(encryptionSalt, 1000); All of these seem to have no influence on the encrypted text.... help!!! My code: package com.citc.testencryption; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class Main extends Activity { public static final int SALT_LENGTH = 20; public static final int PBE_ITERATION_COUNT = 1000; private static final String RANDOM_ALGORITHM = "SHA1PRNG"; private static final String PBE_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC"; private static final String CIPHER_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC"; private static final String TAG = Main.class.getSimpleName(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { String password = "password"; String plainText = "plaintext message to be encrypted"; // byte[] salt = generateSalt(); byte[] salt = "dfghjklpoiuytgftgyhj".getBytes(); Log.i(TAG, "Salt: " + salt.length + " " + HexEncoder.toHex(salt)); PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, PBE_ITERATION_COUNT); SecretKeyFactory keyFac = SecretKeyFactory.getInstance(PBE_ALGORITHM); SecretKey secretKey = keyFac.generateSecret(pbeKeySpec); byte[] key = secretKey.getEncoded(); Log.i(TAG, "Key: " + HexEncoder.toHex(key)); // PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, ITERATION_COUNT); Cipher encryptionCipher = Cipher.getInstance(CIPHER_ALGORITHM); // byte[] encryptionSalt = generateSalt(); // Log.i(TAG, "Encrypted Salt: " + encryptionSalt.length + " " + HexEncoder.toHex(encryptionSalt)); // PBEParameterSpec pbeParamSpec = new PBEParameterSpec(encryptionSalt, 1000); // byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); // Log.i(TAG, encryptionCipher.getParameters() + " "); byte[] iv = generateIv(); IvParameterSpec ivspec = new IvParameterSpec(iv); encryptionCipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec); byte[] encryptedText = encryptionCipher.doFinal(plainText.getBytes()); Log.i(TAG, "Encrypted: " + HexEncoder.toHex(encryptedText)); // <== Why is this always the same :( Cipher decryptionCipher = Cipher.getInstance(CIPHER_ALGORITHM); decryptionCipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec); byte[] decryptedText = decryptionCipher.doFinal(encryptedText); Log.i(TAG, "Decrypted: " + new String(decryptedText)); } catch (Exception e) { e.printStackTrace(); } } private byte[] generateSalt() throws NoSuchAlgorithmException { SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM); byte[] salt = new byte[SALT_LENGTH]; random.nextBytes(salt); return salt; } private byte[] generateIv() throws NoSuchAlgorithmException { SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM); byte[] iv = new byte[16]; random.nextBytes(iv); return iv; } } A: I changed the way I was generating the secret key... fixed now. package com.citc.testencryption; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import android.app.Activity; import android.os.Bundle; import android.util.Log; public class Main extends Activity { public static final int SALT_LENGTH = 20; public static final int PBE_ITERATION_COUNT = 1000; private static final String RANDOM_ALGORITHM = "SHA1PRNG"; private static final String PBE_ALGORITHM = "PBEWithSHA256And256BitAES-CBC-BC"; private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding"; private static final String TAG = Main.class.getSimpleName(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); try { String password = "password"; String plainText = "plaintext message to be encrypted"; // byte[] salt = generateSalt(); byte[] salt = "dfghjklpoiuytgftgyhj".getBytes(); Log.i(TAG, "Salt: " + salt.length + " " + HexEncoder.toHex(salt)); PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt, PBE_ITERATION_COUNT, 256); SecretKeyFactory factory = SecretKeyFactory.getInstance(PBE_ALGORITHM); SecretKey tmp = factory.generateSecret(pbeKeySpec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); byte[] key = secret.getEncoded(); Log.i(TAG, "Key: " + HexEncoder.toHex(key)); // PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, ITERATION_COUNT); Cipher encryptionCipher = Cipher.getInstance(CIPHER_ALGORITHM); // byte[] encryptionSalt = generateSalt(); // Log.i(TAG, "Encrypted Salt: " + encryptionSalt.length + " " + HexEncoder.toHex(encryptionSalt)); // PBEParameterSpec pbeParamSpec = new PBEParameterSpec(encryptionSalt, 1000); // byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); Log.i(TAG, encryptionCipher.getParameters() + " "); byte[] iv = generateIv(); IvParameterSpec ivspec = new IvParameterSpec(iv); encryptionCipher.init(Cipher.ENCRYPT_MODE, secret, ivspec); byte[] encryptedText = encryptionCipher.doFinal(plainText.getBytes()); Log.i(TAG, "Encrypted: " + HexEncoder.toHex(encryptedText)); Cipher decryptionCipher = Cipher.getInstance(CIPHER_ALGORITHM); decryptionCipher.init(Cipher.DECRYPT_MODE, secret, ivspec); byte[] decryptedText = decryptionCipher.doFinal(encryptedText); Log.i(TAG, "Decrypted: " + new String(decryptedText)); } catch (Exception e) { e.printStackTrace(); } } private byte[] generateSalt() throws NoSuchAlgorithmException { SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM); byte[] salt = new byte[SALT_LENGTH]; random.nextBytes(salt); return salt; } private byte[] generateIv() throws NoSuchAlgorithmException { SecureRandom random = SecureRandom.getInstance(RANDOM_ALGORITHM); byte[] iv = new byte[16]; random.nextBytes(iv); return iv; } }
{ "pile_set_name": "StackExchange" }
Q: Python 3 throws name 'InputLayer' is not defined when trying to add tensorflow input layer I've been trying to implement a simple network which takes images of varying sizes and colorizes them. I've been trying to use an input layer with this model, but it seems that python has "changed its mind" since I last worked on this project, and no longer recognises InputLayer I've checked my imports for malformed library names, and no errors have been thrown. What has changed since I ran this code last and what should I change about what I have now? For context, I'm using the newest version of tensorflow and all other libraries on python 3. I don't remember how I last ran this script, but it appears to have been on a legacy version of at least one of the libraries I'm using. My imports: from skimage import color import numpy as np import tensorflow as tf import tensorflow.keras.backend as K import matplotlib.pyplot as plt %matplotlib inline from keras.datasets import mnist from tensorflow.keras.layers import Dense, Flatten, MaxPooling2D, BatchNormalization,UpSampling2D,Conv2DTranspose,Add,AvgPool2D from keras.layers.convolutional import Conv2D from tensorflow.keras import Sequential from tensorflow.keras.models import Sequential, Model from tensorflow.keras.regularizers import l2 import sys !pip install opencv-python import cv2 from os.path import isfile, join The area causing errors: colormodel = Sequential() colormodel.add(InputLayer(input_shape=(None, None, 1))) If anything else is needed of me, please comment what I've left out I've revieved this error message when trying to load in the code block on jupyter notebook: NameError Traceback (most recent call last) <ipython-input-21-13604e43d8ef> in <module>() 1 colormodel = Sequential() ----> 2 colormodel.add(InputLayer(input_shape=(None, None, 1))) 3 colormodel.add(Conv2D(8, (3, 3), activation='relu', padding='same', strides=2)) 4 colormodel.add(Conv2D(8, (3, 3), activation='relu', padding='same')) 5 colormodel.add(Conv2D(16, (3, 3), activation='relu', padding='same')) NameError: name 'InputLayer' is not defined A: Add this in your import: from tensorflow.keras.layers import InputLayer
{ "pile_set_name": "StackExchange" }
Q: Fancybox script not working I have used Fancybox on multiple occasions and never run into this problem. I have included both jQuery and Fancybox files in the header, linked up the first order button the the page to open up an iframe in a Fancybox. However I cant seem to get it to work at all. It doesn't open an iframe and instead goes straight to the page I was trying to open inside the Fancybox iframe. Can somebody point out whatever blindingly obvious mistake I've made this horrible Monday morn? Testing server can be found here: http://www.designti.me/testing/flipstick/original.php A: The error message is: Uncaught TypeError: Object #<an Object> has no method 'fancybox' Which implies that fancybox hasn't loaded. Taking a close look at your source we see <script type="text/x-ecmascript" src="js/fancybox/jquery.fancybox-1.3.4.pack.js"></script> which you can see uses x-ecmascript rather than javascript. Change that and you should be fine.
{ "pile_set_name": "StackExchange" }
Q: Best practices OO Ok, let's see the following scenario: I have two classes. Schedule and Event. One Schedule has many events. It's simple. So, for get all Events, where I should leave the getAllEvents method?. Schedule Class or Event Class? Best practices? Thanks. A: If you'd like to get all events for a given schedule, define a method called getAllEvents() in the Schedule object. If you'd like to get all events - globally, across all schedules - I would encourage you to create an EventCollection object, and add all events to it - besides registering them in the respective Schedule.
{ "pile_set_name": "StackExchange" }
Q: Redirect stdout and stderr to file in Django with wsgi I'm trying to make django work with wsgi in a shared hosting, so I cannot access server logs, I'm trying to redirect the output to a file in my django.wsgi script, like this: saveout = sys.stdout log_out = open('out.log', 'w') sys.stdout = log_out but this is the error that I have (in the only error log that I can access) [Thu Oct 07 19:18:08 2010] [error] [client <ip>] File "/home/myuser/public_html/django.wsgi", line 9, in <module> [Thu Oct 07 19:18:08 2010] [error] [client <ip>] mod_wsgi (pid=30677): Exception occurred processing WSGI script '/home/myuser/public_html/django.wsgi'. and that is all the error I can get Line 9 is the one that tries to open file. I've tried creating previously the file, giving writing access to everyone, without the file previously created.. and nothing. In the app, I only get a 500 server error. Is there a proper way to get this output without access to apache logs? Edited: Using absolute paths, I can open files and write to them, but I get empty files unless I close the files in the end, is it necessary? Could I leave the files open?.. Regarding to the initial problem, even though I used exception handling, write a "finish ok" to file in the end of my script, then close the file, but still get the error: [Thu Oct 07 13:33:07 2010] [error] [client <ip>] mod_wsgi (pid=32541): Exception occurred processing WSGI script '/home/myuser/public_html/django.wsgi'. If I intentionally raise an error, it is logged in the file, so as i get "ok" I think the script worked fine but the result is still that message error... no clues A: You can't use relative pathnames like out.log in a WSGI application. WSGI doesn't specify where the working directory will be pointing and mod_wsgi doesn't set it unless specifically asked to in daemon mode. Use an absolute pathname based on your application's root. You can use os.path.dirname(__file__) to get the directory containing the current script/module if needed.
{ "pile_set_name": "StackExchange" }
Q: Streaming an mp4 through a php file progressively I'm working on a more secure streaming method for our video player. Because each file requires special token authentication and also only allows each token to be loaded once, I'm running MP4 through a php container. This works perfectly inside a HTML5 video tag and prevents users from easily downloading the source. I'm adapting some code from here <?php include('...'); //include site functions /* Here I connect to the database, and retrieve the location of the video which is returned as $video = "http://domain.tld/folder/file.mp4" This has been removed for this SO example. */ $file = $video; $fp = @fopen($file, 'rb'); $head = array_change_key_case(get_headers($file, TRUE)); $size = $head['content-length']; //$size = filesize($file); // File size $length = $size; // Content length $start = 0; // Start byte $end = $size - 1; // End byte header('Content-type: video/mp4'); //header("Accept-Ranges: 0-$length"); header("Accept-Ranges: bytes"); if (isset($_SERVER['HTTP_RANGE'])) { $c_start = $start; $c_end = $end; list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2); if (strpos($range, ',') !== false) { header('HTTP/1.1 416 Requested Range Not Satisfiable'); header("Content-Range: bytes $start-$end/$size"); exit; } if ($range == '-') { $c_start = $size - substr($range, 1); }else{ $range = explode('-', $range); $c_start = $range[0]; $c_end = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size; } $c_end = ($c_end > $end) ? $end : $c_end; if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) { header('HTTP/1.1 416 Requested Range Not Satisfiable'); header("Content-Range: bytes $start-$end/$size"); exit; } $start = $c_start; $end = $c_end; $length = $end - $start + 1; fseek($fp, $start); header('HTTP/1.1 206 Partial Content'); } header("Content-Range: bytes $start-$end/$size"); header("Content-Length: ".$length); $buffer = 1024 * 8; while(!feof($fp) && ($p = ftell($fp)) <= $end) { if ($p + $buffer > $end) { $buffer = $end - $p + 1; } set_time_limit(0); echo fread($fp, $buffer); flush(); } fclose($fp); exit(); ?> Problems now arise as I'd like to be able to seek into the video. Skipping to an area in the video which has not been loaded crashes the <video> tag (and chrome). I'd assume that since the HTML5 player is seeking in seconds and the PHP is loading in bytes, that this cannot be done. Which is why I'm asking here. What can I do (if anything) to allow progressive streaming? Is there a more appropriate container format I could use which would serve the same purpose? A: In addition to what dlopez said, I recommend to use 3rd-party solution for progressive download with seeking capabilities (AKA pseudo-streaming). You may take a look at the PD solutions listed in Wikipedia: https://en.wikipedia.org/wiki/Progressive_download Most of them can also prevent video hotlinking protection as well. A: I think that you have a conceptual failure. You are treating the mp4 file like if it were a "raw data file". I try to explain myself. Imagine that you have a text file, and you want to get the chars from position X. You can open the file, point the cursor to the correct position and then read byte by byte your text. This will work fine. But now image that you want to do the same but with a text processor file. Would you expect the same results? No, because you have a lot of metadata in the file that prevents you from doing that. Your problem is basically the same. You need to take in consideration the format of the file, managing the file with libraries designed for it, or doing by yourself. The other option will be to work with raw data files, but in the case of video files, these are going to be really big files. I hope that I helped you.
{ "pile_set_name": "StackExchange" }
Q: Regex to extract specific domain names in R I have thousands of URLs and I want to extract domain names. I am using the following regex to do this: http://|https://|www\\. This manages to extract domains like so: elpais.com veren.elpais.com canaris7.es vertele.eldiario.es eldiario.es The problem is that I want to only extract the domain -- that is, both vertele.eldiario.es and eldiario.es should give me eldiario.es. I have used urltools as well, but it doesn't seem to be doing the job. I need to extract the domain because I need to have a proper count of the specific domains in all URLs. I am interested in a regex that can extract TLDs ending in both .com and .es. A: This regular expression .*\\.(.*\\.(com|es)) used with sub to call the group (which is between parentheses) will do it. url <- c( "http://www.elpais.com", "http://www.veren.elpais.com", "http://www.canaris7.es", "http://www.vertele.eldiario.es", "http://www.eldiario.es" ) sub(".*\\.(.*\\.(com|es))", "\\1", url) [1] "elpais.com" "elpais.com" "canaris7.es" "eldiario.es" "eldiario.es" Edit following the comment from @Corion to another answer: If you are concerned about url having more complex suffixes, then you can use: .*\\.(.*\\.(com|es)).* url <- c( "http://www.elpais.com", "http://www.veren.elpais.com", "http://www.canaris7.es", "http://www.vertele.eldiario.es", "http://www.eldiario.es", "http://www.google.es.hk", "http://www.google.com.br" ) sub(".*\\.(.*\\.(com|es)).*", "\\1", url) [1] "elpais.com" "elpais.com" "canaris7.es" "eldiario.es" "eldiario.es" [6] "google.es" "google.com"
{ "pile_set_name": "StackExchange" }
Q: Django Model field read only for a MySql generated column I want to add a generated column to a MySql database and am looking for a way to be able to read that column from a a Django model object, but not have it ever try to write a value for that column on an insert/update and MySql will throw an error on that. I know that you can easily set a field to be readonly on a form for the admin site, but is there a way to set this at the model/field level? A: Another option would be to override the default manager to return a QuerySet that is always annotated with the value from that column: from django.db.models.expressions import RawSQL class MyManager(models.Manager): def get_queryset(self): return super().get_queryset().annotate( my_field=RawSQL('''"{table}"."myfield"'''.format( table=self.model._meta.db_table ), ()) ) then set objects = MyManager() in your model and whenever you fetch objects, they will be annotated with the field you want: instance = MyModel.objects.first() instance.my_field # value from db annotation
{ "pile_set_name": "StackExchange" }
Q: Select every other element of class using css3 Given an ul with a structure like this: <ul> <li class="product">...</li> <li class="product">...</li> <li class="product">...</li> <li class="product">...</li> <li class="spot">...</li> <li class="product">...</li> <li class="product">...</li> </ul> Is there any way using CSS3 to target every other occurance of a li with the class product. I've tried using both nth-of-child and nth-of-type in various configurations to no luck, both seem to target every other li element regardless of the class is has. A: Basically, you can't with plain CSS3. The nth-child selectors work on element selectors, not classes. So, li:nth-child(even) works, but .product:nth-child(even) does not. You will need jQuery to achieve this. A: This cannot be done with plain CSS (in any way that I yet know of), however a plain-JavaScript solution is pretty simple: var​ lis = document.querySelectorAll('li.product'); for (var i=0,len=lis.length;i<len;i++){ if (i%2 == 0){ lis[i].className = 'oddProduct'; } }​ JS Fiddle demo. jQuery could be used instead (as could, presumably, any other JavaScript library), but it's certainly not required.
{ "pile_set_name": "StackExchange" }
Q: Couldn't we use "du coup" in written French? I ever heard from my French teacher that "du coup" is used only for spoken usage, but I'm not sure about it. A: Du coup is widely used in written French, but you will find that some people follow the recommandation of the Académie Française of not using it as a synonym of donc and only use it in the sense of aussitôt. But as we can see in the example taken from Zola (below) the barrier between the two meanings is sometimes very thin. My point of view is that language is a living thing, it evolves and we find numerous instances of du coup used in the sense of donc in very good writings. Il y a autour de l'expression « du coup » une polémique qui se trouve résumée dans cet article de 2005 : «Du coup». Un vilain tic de langage © Le Télégramme Cet article reflète autant l'usage de l'expression à l'oral qu'à l'écrit. L'Académie Française recommande de ne garder l'usage de l'expression que dans son sens premier d'« aussitôt » et décourage l'emploi de « du coup » pour exprimer la conséquence : La locution adverbiale du coup a d’abord été employée au sens propre : Un poing le frappa et il tomba assommé du coup. Par la suite, on a pu l’utiliser pour introduire la conséquence d’un évènement : Un pneu a éclaté et du coup la voiture a dérapé. Mais, ainsi que le dit Le Bon Usage, il exprime « l’idée d’une cause agissant brusquement », et à sa valeur consécutive s’ajoute donc une valeur temporelle traduisant une quasi-simultanéité. Du coup est alors très proche d’aussitôt. On ne peut donc pas employer systématiquement du coup, ainsi qu’on l’entend souvent, en lieu et place de donc, de ce fait, ou par conséquent. On évitera également de faire de du coup un simple adverbe de discours sans sens particulier. Ce n'est ni la première, ni la dernière fois sans doute, que des puristes s'offusquent de l’évolution de la langue. L'usage nous montre que « du coup » est aussi présent dans la langue orale que dans la langue écrite, et dans des écrits dont le style ne saurait être qualifié de familier. L'air entrait par bouffées glaciales, tous deux s'emportaient, en soutenant chacun l'exactitude de ses renseignements, lorsque des cris et des larmes éclatèrent. C'était, dans son berceau, Estelle que le froid contrariait. Du coup, Maheu se réveilla. (Émile Zola, Germinal) les hasards d'une conversation avec sa mère l'amenèrent à en faire l'aveu, et le lièrent ainsi à une fantaisie de gosse, qu'il eût si facilement abandonnée, qu'il était du coup dans l'obligation de poursuivre. (Aragon, Les Beaux quartiers,1936, p. 239. Exemple du TLF, qui d'ailleurs ne qualifie pas l'expression de familière). Dans sa fonction verticale le signe renvoie à des entités moins vastes, plus concrétisée que le symbole – ce sont des universaux RÉIFIÉS, devenus OBJETS au sens fort du mot; or, relationnée dans une structure de signe, l'entité en question (le phénomène, ou le personnage) est, du coup, transcendentalisée, élevée au rang d'une unité théologique. (Julia Kristeva, Le Texte du Roman: Approche sémiologique d'une structure discursive transformationnelle) Ce profit est une meilleure compréhension des valeurs intrinsèques de l'œuvre, et, du coup, une interprétation plus poussée de ses rapports externes. (Guy Demerson, Louise Labé, les voix du lyrisme) Du coup le sublime retombe. L’aura qui entourait le sacrifice du père Goriot s’efface, et il ne reste plus de son sacrifice que l’image d’une servitude volontaire, d’une domesticité, quand le maître de la domus n’est plus qu’une sorte d’animal domestique, de « toutou » manipulé. ( Le sublime et le grotesque chez Balzac : l’exemple du « Père Goriot », par Pierre Brunel, paru dans une revue universitaire.) A: I have no idea why someone would say that, at least for its meaning (and I know of no others) of "as such, by the same token". It's a perfectly valid locution at most language levels. It's in the Trésor de la Langue Française and the Académie dictionaries, and covered in Grevisse (Bon Usage, 14th ed. §1006 f.) with no usage notes anywhere.
{ "pile_set_name": "StackExchange" }
Q: SQL Server : fix misspelled business names I'm looking for advice on how to tackle the issue of different spelling for the same name. I have a SQL Server database with company names, and there are some companies that are the same but the spelling is different. For example: Building Supplies pty Buidings Supplies pty Building Supplied l/d The problem is that there are no clear consistencies in the variation. Sometimes it's an extra 's', other times its an extra space. Unfortunately I don't have a lookup list, so I can't use Fuzzy LookUp. I need to create the clean list. Is there a method that people use to deal with this problem? p.s I tried searching for this problem but can't seem to find a similar thread Thanks A: You can use SOUNDEX() DIFFERENCE() for this purpose. DECLARE @SampleData TABLE(ID INT, BLD VARCHAR(50), SUP VARCHAR(50)) INSERT INTO @SampleData SELECT 1, 'Building','Supplies' UNION SELECT 2, 'Buidings','Supplies' UNION SELECT 3, 'Biulding','Supplied' UNION SELECT 4, 'Road','Contractor' UNION SELECT 5, 'Raod','Consractor' UNION SELECT 6, 'Highway','Supplies' SELECT *, DIFFERENCE('Building', BLD) AS DIF FROM @SampleData WHERE DIFFERENCE('Building', BLD) >= 3 Result ID BLD SUP DIF 1 Building Supplies 4 2 Buidings Supplies 3 3 Biulding Supplied 4 If this serves your purpose you can write an update query to update selected record accordingly.
{ "pile_set_name": "StackExchange" }
Q: how to use jquery auto-complete to load from mysql database What I want to do is to be able to load data from the database which will show up as an auto-complete text below the textbox. I'm using the ajax function in jquery to load data from the database. My problem now is how to put that data in the auto-suggest box. <html> <head> <script src="js/jq.js"></script> <link rel="stylesheet" href="css/otocomplete.css" type="text/css" /> <link rel="stylesheet" href="css/otocomplete.css" type="text/css" /> <script type="text/javascript" src="js/bigiframe.js"></script> <script type="text/javascript" src="js/otocomplete.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#example').keyup(function(){ var inpval = $('#example').val(); $.ajax({ type: 'POST', data: ({p : inpval}), url: 'query.php', success: function(data) { $("#yoh").autocomplete(data); } }); }); }); </script> </head> <body> text: <input id="example" /> <div id="yoh"></div> </body> </html> A: Are otocomplete.js/otocomplete.css the autocomplete plugin & its stylesheet? I'll assume that they are. Is there a reason you are putting the autocomplete inside of an ajax method? It works without it. <link rel="stylesheet" type="text/css" href="http://view.jquery.com/trunk/plugins/autocomplete/jquery.autocomplete.css"> <script src="http://view.jquery.com/trunk/plugins/autocomplete/jquery.autocomplete.js"></script> <script type="text/javascript"> $(document).ready(function() { $("#example").autocomplete("query.php", { width: 260, selectFirst: false }); }); </script> Your php file should output one result per line, like so: Gyr Falcon Lanner Falcon Red Falcon ... This is all lifted straight from http://view.jquery.com/trunk/plugins/autocomplete/demo/ but I tested it, so I know it will work. EDIT: I just read that the plugin's author no longer supports it, and recommends using jQuery UI's autocomplete. Personally, I'm not a big fan of jQuery UI, I just want the author's intent to be represented here. EDIT 2: I didn't realize that you're trying to do some kind of custom UI for the auto suggest. Feel free to ignore this.
{ "pile_set_name": "StackExchange" }
Q: Obtener día de la semana en numero del dia actual Esto me da como reultado: "Viernes" pero necesito el numero, osea 6, empezando desde el domingo. string dia = DateTime.Now.ToString("dddd"); Gracias A: Usa la propiedad DayOfWeek del objeto DateTime que es en este es es Now; Esta propiedad regresará un enum de tipo DayOfWeek, simplemente lo casteas a int y obtendrás el numero de dia de la semana. int diaSemana = (int)DateTime.Now.DayOfWeek;
{ "pile_set_name": "StackExchange" }
Q: Running a set returning function on all the rows in a postgres table and getting all the results back I have a PostgreSQL 9.1 database with a svn version of PostGIS 2.0. I have a set returning function from postgis (ST_DumpAsPolygon), which takes one row and returns many rows. I have a table of data and want to run the set returning function on each row of the input and return all the rows. However SELECT ST_DumpAsPolygon(rast) FROM mytable seems to return the values from only one row. Is there some way to get the set returning function to run on every row in the table, and collect all the results together, and return all those results? A: Actually, I think I made a mistake. An error in a previous step of a process led me to think there were things in there that weren't in the table, and hence I thought that the set returning function wasn't doing things. This should probably be closed.
{ "pile_set_name": "StackExchange" }
Q: jQuery validate on radio button click I have a contact form which asks whether one would like to be contacted via email or telephone. When you click on the email radio button, an email text-field appears. Same for clicking the telephone radio button. When I click on the email radio button for example and enter an invalid email, the invalid email error message appears on blur. Now when I click on telephone, the telephone text-field appears but the invalid email error message does not disappear. That's what I would like to happen. HTML (with Bootstrap) <div class="control-group"> <label class="control-label" for="How_would_you_like_to_be_contacted_">How would you like to be contacted?</label> <div class="controls"> <label class="radio"> <input id="contact_type_email" name="contact_type" type="radio" value="email" /> <label for="Email">Email</label> </label> <label class="radio"> <input id="contact_type_telephone" name="contact_type" type="radio" value="telephone" /> <label for="Telephone">Telephone</label> </label> </div> </div> <div class="control-group" id="email"> <label class="control-label" for="contact_email">Email</label> <div class="controls"> <input id="contact_email" name="contact[email]" size="30" type="text" /> </div> </div> <div class="control-group" id="telephone"> <label class="control-label" for="contact_telephone">Telephone</label> <div class="controls"> <input id="contact_telephone" name="contact[telephone]" placeholder="###-###-####" size="30" type="text" /> </div> </div> JavaScript $(document).ready(function() { $('#email').hide(); $('#telephone').hide(); $('#contact_type_email').click(function() { $('#email').show(); $('#telephone').hide(); $('#contact_telephone').val(''); }); $('#contact_type_telephone').click(function() { $('#telephone').show(); $('#email').hide(); $('#contact_email').val(''); }); $('#new_contact').validate({ rules: { 'contact[name]': { required: true }, 'contact[email]': { required: { depends: function(element){ return $("#contact_type_email").prop("checked"); } }, email: true }, 'contact[telephone]': { required: { depends: function(element) { return $("#contact_type_telephone").prop("checked"); } }, phoneUS: true } } errorPlacement: function(error, element) { error.appendTo("#error"); } } } A: From OP's comments: @Sparky, here's my jsFiddle: jsfiddle.net/mikeglaz/BmNWR. When I click on the email radio button, enter an invalid email address, then click on the telephone radio button, my invalid email error message is still there. – mikeglaz This is what I tried to show you in the last edit of my answer on your previous question. I cleaned up your logic a bit and added $('label').hide();... $('#contact_type_email').click(function () { $('#email').show(); $('#telephone').hide(); $('#contact_telephone').val(''); // <-- fixed this $('label[for="contact_telephone"]').hide(); // <-- added this }); $('#contact_type_telephone').click(function () { $('#telephone').show(); $('#email').hide(); $('#contact_email').val(''); $('label[for="contact_email"]').hide(); // <-- added this }); Modified jsFiddle Demo: http://jsfiddle.net/BmNWR/8/
{ "pile_set_name": "StackExchange" }
Q: HP ML150 G6 upgrading RAM/CPU beyond specs? I am being told that some limits on some HP servers can be crossed. Do any of you have any experience with that? A ML150/G6 is limited to 48GB RAM but I have been talking to a German company that guaranties me that this server will be able to be upgraded to 384GB RAM (using 32GB memory modules and 2 CPUs) http://www.compuram.de/en/memory,HP+%28-Compaq%29,Server,Proliant,ML150+G6.htm Can this really be true? The server that I have is using E5504 CPUs but will I be able to upgrade to any CPU that is using a LGA1366 socket? All from a low wattage L5640 all the way to the 6 core, high wattage versions like an X5650? (If cooling and power is adequate ofcause). Is there any limitation with powerregulators and chipset (Intel 5500). I am looking forward to any reply. Thanks in advance and best regards, - Morten Green Hermansen, Fanitas A: Now I have tried with 32GB (2x8GB + 4x4GB) register memory, using only one CPU (E5520). According to specs the limit is 24GB (6x4GB). The system has been running very stable for 4 months now. I still really want to see if 32GB modules gets accepted. :-)
{ "pile_set_name": "StackExchange" }
Q: How to implement and use the sub-modes feature from System.Console.CmdArgs I would like to create a kind of swiss-knife tool for a specific domain, and a "cabal" or "darcs" command-line interface looks perfect. Using the on-line tutorials I could implement a simple "hello, world" program. Then I implemented a more sophisticated solution with modes and all when well. But now, I would like to explore the "sub-modes" to have a good understanding of all the possibilities, and I'm stuck. I could not find any tutorial, example or detailed description of the feature. How to implement and use the submodes feature? I want to clarify that I understand modes, but it's really the submodes that are not clear to me. A: The cmdargs tutorial has examples for sub-modes. The documentation for the modes function is also clear. In fact, a Google search for "cmdargs modes" reveals quite a few more tutorials covering exactly this.
{ "pile_set_name": "StackExchange" }
Q: HQL Select Query How to select a row based on a unique column. In my table, Id is auto generated. I am using phone number to select the row which is unique in my table schema. Ex: Id Phone Name 1 2209897 abc 2 5436567 def Here, Id is primary key. Phone is unique. I am using phone to login. I donot want a list to be generated but a single row as output. @Repository public class CustomerDetailsDAOImpl implements CustomerDetailsDAO { @Autowired SessionFactory sessionFactory; @Override @Transactional public List<CustomerDetails> getCustomer(String customerPhone) { Session session = sessionFactory.openSession(); Query q = session.createQuery("from CustomerDetails where customerPhone =:p"); q.setParameter("p", customerPhone); List<CustomerDetails> customer = q.getResultList(); session.close(); return customer; } A: Use getSingleResult() instead of using getListResult().This Executes a SELECT query that returns a single untyped result. So whenever you expect a single record to be retrieved with unique type, should use getSingleResult(). @Repository public class CustomerDetailsDAOImpl implements CustomerDetailsDAO { @Autowired SessionFactory sessionFactory; @Override @Transactional public List<CustomerDetails> getCustomer(String customerPhone) { Session session = sessionFactory.openSession(); Query q = session.createQuery("from CustomerDetails where customerPhone =:p"); q.setParameter("p", customerPhone); CustomerDetails customer = q.getSingleResult(); session.close(); return customer; } Hope this helps :)
{ "pile_set_name": "StackExchange" }
Q: Tag Syn: Operating Systems Synonym request: operating-systems -> operating-system A: This is now complete. (we like to have answers on these so they don't show up as no answers..)
{ "pile_set_name": "StackExchange" }
Q: jquery image slider not sliding? The blueberry Image slider isnt sliding, here is the java script code please help me modify or add enough code so that it will work properly. I have linked the blueberry.css and jquery.blueberry.js files too btw. thank you - student of web development <meta charset="UTF-8"></meta> <title>Rose Street | Auto Repair</title> <meta name="viewport" content="width=device-width, initail-scale=1.0"></meta> <link rel="stylesheet" href="main.css"></link> <link rel="stylesheet" href="font-awesome.css"></link> <link rel="stylesheet" href="blueberry.css"></link> <link rel="stylesheet" href="style2.css"></link> <link rel="stylesheet" id="google-fonts-css" href="//fonts.googleapis.com/css?family=Open+Sans%3A400%2C400italic%2C300italic%2C300%2C600%2C600italic%7CLato%3A400%2C100%2C300%2C700&amp;ver=4.0.5" type="text/css" media="all"></link> <script src="https://apis.google.com/js/platform.js"> async defer></script> <script type="text/javascript" src="jquery-1.11.2.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"</script> <script src="jquery.blueberry.js"></script> <script> $(window).load(function() { $('.blueberry').blueberry(); }); </script> <script type="text/javascript"> function Scroll(){ var top = document.getElementById('header'); var ypos = window.pageYOffset; if(ypos < 700) { top.style.opacity = ".9"; top.style.height= "86px" }else{ top.style.opacity = ".5"; top.style.height= "100px" } } window.addEventListener("scroll",Scroll); </script> <script type="text/javascript"> $(function(){ $("#header").fadeToggle(1).delay(2000).fadeToggle(2000); $("#logo").fadeToggle(1).delay(2000).fadeToggle(2000); $("nav").fadeToggle(1).delay(2500).slideToggle(1000); }); </script> HTML: <div id="doc"> <div id="content"> <div class="blueberry"> <ul class="slides"> <li class="" style="display: inline;"> <img src="http://ultraimg.com/images/93ee8dce5462.jpg" alt="slide1"> </li> <li class="active" style="display: inline;"> <img src="http://ultraimg.com/images/85173643ed34.jpg" alt="slide2"> </li> <li class="" style="display: none;"> <img src="http://www.thehogring.com/wp-content/uploads/2012/11/The-Hog-Ring-Auto-Upholstery-Community-Auto-Trimmer-History-11.jpg" alt="slide3"> </li> <li class="" style="display: none;"> <img src="http://theoldmotor.com/wp-content/uploads/2013/11/Euclid1-600x351.jpg" alt="slide4"> </li> </ul> <ul class="pager"> <li class=""> <a href="#"><span>0</span></a> </li> <li class=""> <a href="#"><span>1</span></a> </li> <li class=""> <a href="#"><span>2</span></a> </li> <li class="active"> <a href="#"><span>3</span></a> </li> </ul> </div> </div> </div> A: I have some trouble understanding your problem. Your code seems to work pretty well //jQuery Blueberry Slider v0.4 BETA !function(e){e.fn.extend({blueberry:function(a){var i={interval:5e3,duration:500,lineheight:1,height:"auto",hoverpause:!1,pager:!0,nav:!0,keynav:!0},a=e.extend(i,a);return this.each(function(){var i=a,n=e(this),t=e(".slides li",n),u=e(".pager li",n),s=0,c=s+1,l=t.eq(s).find("img").height(),r=t.eq(s).find("img").width(),d=r/l,o=0,h=0;t.hide().eq(s).fadeIn(i.duration).addClass("active"),u.length?u.eq(s).addClass("active"):i.pager&&(n.append('<ul class="pager"></ul>'),t.each(function(a){e(".pager",n).append('<li><a href="#"><span>'+a+"</span></a></li>")}),u=e(".pager li",n),u.eq(s).addClass("active")),u&&e("a",u).click(function(){return clearTimeout(n.play),c=e(this).parent().index(),f(),!1});var f=function(){t.eq(s).fadeOut(i.duration).removeClass("active").end().eq(c).fadeIn(i.duration).addClass("active").queue(function(){p(),e(this).dequeue()}),u&&u.eq(s).removeClass("active").end().eq(c).addClass("active"),s=c,c=s>=t.length-1?0:s+1},p=function(){n.play=setTimeout(function(){f()},i.interval)};p(),i.hoverpause&&t.hover(function(){clearTimeout(n.play)},function(){p()});var v=function(){o=e(".slides",n).width(),h=Math.floor(o/d/i.lineheight)*i.lineheight,e(".slides",n).css({height:h})};v(),e(window).resize(function(){v()}),i.keynav&&e(document).keyup(function(e){switch(e.which){case 39:case 32:clearTimeout(n.play),f();break;case 37:clearTimeout(n.play),c=s-1,f()}})})}})}(jQuery); $(window).load(function() { $('.blueberry').blueberry(); }); /* * jQuery Blueberry Slider v0.4 BETA * http://marktyrrell.com/labs/blueberry/ * * Copyright (C) 2011, Mark Tyrrell <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ .blueberry { margin: 0 auto; } .blueberry .slides { display: block; position: relative; overflow: hidden; } .blueberry .slides li { position: absolute; top: 0; left: 0; overflow: hidden; } .blueberry .slides li img { display: block; width: 100%; max-width: none; } .blueberry .slides li.active { display: block; position: relative; } .blueberry .crop li img { width: auto; } .blueberry .pager { height: 40px; text-align: center; } .blueberry .pager li { display: inline-block; } .blueberry .pager li a, .blueberry .pager li a span { display: block; height: 4px; width: 4px; } .blueberry .pager li a { padding: 18px 8px; -webkit-border-radius: 6px; -moz-border-radius: 6px; -o-border-radius: 6px; -ms-border-radius: 6px; -khtml-border-radius: 6px; border-radius: 6px; } .blueberry .pager li a span { overflow: hidden; background: #c0c0c0; text-indent: -9999px; -webkit-border-radius: 2px; -moz-border-radius: 2px; -o-border-radius: 2px; -ms-border-radius: 2px; -khtml-border-radius: 2px; border-radius: 2px; } .blueberry .pager li.active a span { background: #404040; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" href="https://raw.githubusercontent.com/marktuk/Blueberry/master/blueberry.css"></link> <div id="doc"> <div id="content"> <div class="blueberry"> <ul class="slides"> <li class="" style="display: inline;"><img src="http://ultraimg.com/images/93ee8dce5462.jpg" alt="slide1"></li> <li class="active" style="display: inline;"><img src="http://ultraimg.com/images/85173643ed34.jpg" alt="slide2"></li> <li class="" style="display: none;"><img src="http://www.thehogring.com/wp-content/uploads/2012/11/The-Hog-Ring-Auto-Upholstery-Community-Auto-Trimmer-History-11.jpg" alt="slide3"></li> <li class="" style="display: none;"><img src="http://theoldmotor.com/wp-content/uploads/2013/11/Euclid1-600x351.jpg" alt="slide4"></li> </ul> <ul class="pager"> <li><a href="#"><span></span></a></li> <li><a href="#"><span></span></a></li> <li><a href="#"><span></span></a></li> <li><a href="#"><span></span></a></li> </ul> </div> </div> </div>
{ "pile_set_name": "StackExchange" }
Q: Find a sequence $\{a_n\}$ such that both $\sum {a_n}$ and $\sum{\frac{1}{n^2 a_n}}$ converge. Find a sequence $\{a_n\}$ such that both $\sum_1^\infty {a_n}$ and $\sum_1^\infty {\frac{1}{n^2 a_n}}$ converge. If no such sequence exists, prove that. Actually the question was for $\sum_1^\infty {n{a_n}}$ and $\sum_1^\infty {\frac{1}{n^2 a_n}}$. For this problem; If we suppose that both are convergent, then their multiply $\sum_1^\infty 1/n$ must be convergent and this is a contradiction. But for $\sum_1^\infty {a_n}$ and $\sum_1^\infty {\frac{1}{n^2 a_n}}$, if we multiply we get $\sum_1^\infty 1/n^2$ which is convergent. I tried to find a sequence such that both the series converge but I couldn't find any but also I couldn't prove that there is no such sequence exists. Edit. $a_n >0$ A: Perhaps a bit too trivial? $a_n=(-1)^n(1/n)$ A: The above answer shows that if the $a_n$s are allowed to change sign, then the sum may converge. However, if the $a_n$s are all positive, then by the Cauchy-Schwarz inequality, \begin{align*} \sum_{n=1}^k\frac{1}{n}&=\sum_{n= 1}^k\frac{\sqrt{a_n}}{\sqrt{n^2a_n}}\\ &\leq \left(\sum_{n =1}^ka_n\right)^{1/2}\left(\sum_{n= 1}^k\frac{1}{n^2a_n}\right)^{1/2} \end{align*} Since $\sum_{n=1}^k\frac{1}{n}\to\infty$ as $k\to\infty$, one of $\sum a_n$ and $\sum \frac{1}{n^2a_n}$ must diverge. A: The answer is yes, an example is $$a_n = \frac{(-1)^n}{n}$$ However, there is no such a sequence with positive terms. Indeed, if you suppsose that both $\sum a_n$ and $\sum\frac{1}{n^2a_n}$ are convergent and with positive terms, then you have by the AM-GM inequality $$\sum \frac{1}{n}=\sum \sqrt{a_n \cdot \frac{1}{n^2a_n}} \le \sum \frac{1}{2} \left(a_n + \frac{1}{n^2a_n} \right) < +\infty$$ which implies that the harmonic series is convergent: a contradiction.
{ "pile_set_name": "StackExchange" }
Q: Why are coproduct objects corepresentations of cartesian products, rather than representations of disjoint unions? One way we can define the product of two objects $A$ and $B$ in some category $\mathcal C$ is as a representation of the contravariant functor $(\to A) \times (\to B)$ in $[\mathcal C^{\mathrm{op}}, Set]$. The analogous definition of coproducts is as a corepresentation of the covariant functor $(A \to) \times (B \to)$ in $[\mathcal C, Set]$. Notably, AFAICT one can't get products by asking for a corepresentation of $(A \to) + (B \to)$, nor coproducts by asking for a representation of $(\to A) + (\to B)$, where here I'm using $+$ to denote coproducts. I find this asymmetry curious, and my main question is the title question. That question's a bit broad and vague, though. To be a bit more specific, aspects of this question that I'm particularly curious about include: What are these other objects? ((co)representations of $(A \to) + (B \to)$) Are they well-studied? Alternatively, are there good reasons to consider them boring and ignore them? Whence the asymmetry? It's almost as if $Set$ is insisting that $\times$ is "more primary" than $+$. Of course, $Set^{\mathrm{op}}$ will sing the opposite tune, but I still find the situation surprising. Is there a good intuition for why the "correct" way to ask for coproducts in arbitrary categories is equivalent to asking for a corepresentation of Set-theoretic products, rather than (say) a direct representation of Set-theoretic coproducts? Given a construction in $Set$ (such as a product or a coproduct or an exponential), what determines whether that construction in going to be "representable-ish" versus "corepresentable-ish"? We could of course just try both and see which one works and classify our constructions accordingly, but is there any way to look at products and coproducts in $Set$ and notice ab initio that products are going to be the "representy" ones and coproducts the "corepresenty" ones? (Alternatively, what are the keywords I should be searching to read up on this?) (lmn if I should expand on my notation more here. Note that I'm following the nlab's convention when distinguishing between representable functors and corepresentable functors, and that by eg $(\to A) \times (\to B)$ I mean $(X \mapsto \mathrm{Hom}_{\mathcal C}(X, A) \times \mathrm{Hom}_{\mathcal C}(X, B))$.) A: Suppose we had, for some objects $A$ and $B$, an object $C$ such that $(C,-)$ is naturally isomorphic to $(A,-)+(B,-)$. Then the category in which this happens cannot have a terminal object, since such an object, call it $T$, would have only one element in $(C,T)$ but two in $(A,T)+(B,T)$. More generally, any functor of the form $(C,-)$ preserves all the products that exist in your category. So $(A,-)+(B,-)$ would have to preserve products, and this leads to lots of problems since $(A,-)$ and $(B,-)$ individually also preserve products. More generally yet, you'll have a problem with preservation of limits. I'm not sure how far one can carry this line of reasoning, but it certainly prevents the existence of such representing objects $C$ in the categories that people usually want to work with. (At the moment, I can't think of any category where such $A,B,C$ exist, but that may be just a deficiency of my imagination.) A: Coproducts don't always look much like disjoint unions; consider the coproduct of groups, namely the free product. More formally, there's a condition called disjointness that coproducts can satisfy, and they don't always satisfy it. You can think of your definition as an attempt to formalize disjointness; unfortunately it doesn't work. You're asking for an object $D$ such that a morphism $f : C \to D$ is either a morphism $C \to A$ or a morphism $C \to B$. Unfortunately, even disjoint unions don't satisfy this property! You don't expect this kind of thing unless $C$ is connected in some sense (say, it is a connected topological space in $\text{Top}$ or a connected graph in $\text{Graph}$); in general some part of $C$ might map to $A$ and some other part can map to $B$. Nevertheless there is something to this idea; it's one way to try formalizing a sum type, namely a type whose terms are either terms of some type $A$ or some other type $B$. From this perspective it's not obvious that sum types have anything to do with coproducts; I wish I understood this better than I do. A definition that seems related to bridging this gap is the notion of an extensive category.
{ "pile_set_name": "StackExchange" }
Q: Find duplicate rows based on the first two columns from a data frame and add its third column I have two data frames df1 and df2 with three columns in each. I want to find the duplicate rows based on the first two columns and replace the third column of the duplicate entries in df1 with the sum of third columns in the corresponding duplicate entries simple exsample df1 col1 col2 col3 80.3 30.3 15 80.3 30.2 15 80.3 30.4 15 80.3 30 15 80.3 29.9 15 80.4 29.9 10 df2 col1 col2 col3 80.3 30.3 5 80.3 30.2 5 80.3 30.4 5 80.3 30 5 80.3 29.9 5 expected result 80.3 30.3 20 80.3 30.2 20 80.3 30.4 20 80.3 30 20 80.3 29.9 20 80.4 29.9 10 And how exactly i should introduce tolerance level of 0.01 in col1 and col2 for finding duplicates? A: Try this for no tolerance: pd.concat([df1, df2]).groupby(["col1", "col2"], as_index=False)["col3"].sum() col1 col2 col3 0 80.3 29.9 20 1 80.3 30.0 20 2 80.3 30.2 20 3 80.3 30.3 20 4 80.3 30.4 20 5 80.4 29.9 10 For tolerance see @jezrael answer. A: Solution with no tolerance is concat with aggregate sum: df = pd.concat([df1, df2]).groupby(['col1','col2'], as_index=False, sort=False).sum() print (df) col1 col2 col3 0 80.3 30.3 20 1 80.3 30.2 20 2 80.3 30.4 20 3 80.3 30.0 20 4 80.3 29.9 20 5 80.4 29.9 10 Solution with tolerance is more complicated with bining by cut: df2 = (pd.concat([df1, df2]) .assign(c1 = lambda x: pd.cut(x['col1'], np.arange(x['col1'].min(), x['col1'].max()+0.01, 0.02), right = False), c2 = lambda x: pd.cut(x['col2'], np.arange(x['col2'].min(), x['col2'].max()+0.01, 0.02), right = False)) .groupby(['c1','c2'], sort=False) .agg({'col1':'first', 'col2':'first', 'col3':'sum'}) .dropna() .reset_index(drop=True))
{ "pile_set_name": "StackExchange" }
Q: Bootstrap button width is wider than normal I have problem with bootstrap. At first there is problem with showing the first <section>, sometimes you must resize window and than first <section> appear. The second problem is with buttons in first <section>, look at search button please, why is it wider than normal? Here is my page: http://www.nibaru.com/core/mainpage.html Thanks. A: Second problem: Line 313 of theme-blues.css contains a declaration for .btn This has "min-width: 155px;" set. Removing that fixes the button.
{ "pile_set_name": "StackExchange" }
Q: trying to understand delegates this code won't compile c++ 11 I was watching this video https://www.youtube.com/watch?v=QMb4RRFrY-o and am trying to follow the examples but i can't get the code to compile. He supposedly copy and pasted the code from the link below but i also can't get it to compile. I'm using QT to compile with visual studio 2015 x64 and c++11 enabled. https://codereview.stackexchange.com/questions/14730/impossibly-fast-delegate-in-c11 Example 1 #include <iostream> #include <functional> #include "delegate.hpp" void fn1(){ std::cout << "Function one! \n"; } void fn2(){ std::cout << "Function two! \n"; } int main() { std::function<decltype (fn1)> func; delegate<decltype (fn1)> delg; func = delg = fn1; func(); delg(); func = delg = fn2; func(); delg(); } The code below is the delegate.hpp file. // This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef DELEGATE_HPP_INCLUDED #define DELEGATE_HPP_INCLUDED #include <type_traits> #include <functional> #include <memory> #include <cstddef> // ----- SYNOPSIS ----- namespace spec { template<size_t, size_t, typename, typename...> class pure; template<size_t, size_t, typename, typename...> class inplace_triv; template<size_t, size_t, typename, typename...> class inplace; } namespace detail { constexpr size_t default_capacity = sizeof(size_t) * 4; template<typename T> using default_alignment = std::alignment_of< std::function<T> >; } template< typename T, template<size_t, size_t, typename, typename...> class Spec = spec::inplace, size_t size = detail::default_capacity, size_t align = detail::default_alignment<T>::value > class delegate; // unspecified template< typename R, typename... Args, template<size_t, size_t, typename, typename...> class Spec, size_t size, size_t align > class delegate<R(Args...), Spec, size, align>; class empty_delegate_error : public std::bad_function_call { public: const char* what() const throw() { return "Empty delegate called"; } }; // ----- IMPLEMENTATION ----- namespace detail { template<typename R, typename... Args> static R empty_pure(Args...) { throw empty_delegate_error(); } template< typename R, typename S, typename... Args > static R empty_inplace(S&, Args&&... args) { return empty_pure<R, Args...>(std::forward<Args>(args)...); } template< typename T, typename R, typename... Args > using closure_decay = std::conditional< std::is_convertible<T, R(*)(Args...)>::value, R(*)(Args...), typename std::decay<T>::type >; template<typename T = void, typename...> struct pack_first { using type = std::remove_cv_t<T>; }; template<typename... Ts> using pack_first_t = typename pack_first<Ts...>::type; } namespace spec { // --- pure --- template<size_t, size_t, typename R, typename... Args> class pure { public: using invoke_ptr_t = R(*)(Args...); explicit pure() noexcept : invoke_ptr_{ detail::empty_pure<R, Args...> } {} template<typename T> explicit pure(T&& func_ptr) noexcept : invoke_ptr_{ func_ptr } { static_assert(std::is_convertible<T, invoke_ptr_t>::value, "object not convertible to pure function pointer!"); } pure(const pure&) noexcept = default; pure(pure&&) noexcept = default; pure& operator= (const pure&) noexcept = default; pure& operator= (pure&&) noexcept = default; ~pure() = default; R operator() (Args&&... args) const { return invoke_ptr_(std::forward<Args>(args)...); } bool empty() const noexcept { return invoke_ptr_ == static_cast<invoke_ptr_t>( detail::empty_pure<R, Args...>); } template<typename T> T* target() const noexcept { return static_cast<T*>(invoke_ptr_); } private: invoke_ptr_t invoke_ptr_; }; // --- inplace_triv --- template< size_t size, size_t align, typename R, typename... Args > class inplace_triv { public: using storage_t = std::aligned_storage_t<size, align>; using invoke_ptr_t = R(*)(storage_t&, Args&&...); explicit inplace_triv() noexcept : invoke_ptr_{ detail::empty_inplace<R, storage_t, Args...> } { new(&storage_)std::nullptr_t{ nullptr }; } template< typename T, typename C = typename detail::closure_decay<T, R, Args...>::type > explicit inplace_triv(T&& closure) : invoke_ptr_{ static_cast<invoke_ptr_t>( [](storage_t& storage, Args&&... args) -> R { return reinterpret_cast<C&>(storage)(std::forward<Args>(args)...); } )} { static_assert(sizeof(C) <= size, "inplace_triv delegate closure too large!"); static_assert(std::alignment_of<C>::value <= align, "inplace_triv delegate closure alignment too large"); static_assert(std::is_trivially_copyable<C>::value, "inplace_triv delegate closure not trivially copyable!"); static_assert(std::is_trivially_destructible<C>::value, "inplace_triv delegate closure not trivially destructible!"); new(&storage_)C{ std::forward<T>(closure) }; } inplace_triv(const inplace_triv&) noexcept = default; inplace_triv(inplace_triv&&) noexcept = default; inplace_triv& operator= (const inplace_triv&) noexcept = default; inplace_triv& operator= (inplace_triv&&) noexcept = default; ~inplace_triv() = default; R operator() (Args&&... args) const { return invoke_ptr_(storage_, std::forward<Args>(args)...); } bool empty() const noexcept { return reinterpret_cast<std::nullptr_t&>(storage_) == nullptr; } template<typename T> T* target() const noexcept { return reinterpret_cast<T*>(&storage_); } private: invoke_ptr_t invoke_ptr_; mutable storage_t storage_; }; // --- inplace --- template< size_t size, size_t align, typename R, typename... Args > class inplace { public: using storage_t = std::aligned_storage_t<size, align>; using invoke_ptr_t = R(*)(storage_t&, Args&&...); using copy_ptr_t = void(*)(storage_t&, storage_t&); using destructor_ptr_t = void(*)(storage_t&); explicit inplace() noexcept : invoke_ptr_{ detail::empty_inplace<R, storage_t, Args...> }, copy_ptr_{ copy_op<std::nullptr_t, storage_t>() }, destructor_ptr_{ nullptr } {} template< typename T, typename C = typename detail::closure_decay<T, R, Args...>::type > explicit inplace(T&& closure) noexcept : invoke_ptr_{ static_cast<invoke_ptr_t>( [](storage_t& storage, Args&&... args) -> R { return reinterpret_cast<C&>(storage)(std::forward<Args>(args)...); } ) }, copy_ptr_{ copy_op<C, storage_t>() }, destructor_ptr_{ static_cast<destructor_ptr_t>( [](storage_t& storage) noexcept -> void { reinterpret_cast<C&>(storage).~C(); } ) } { static_assert(sizeof(C) <= size, "inplace delegate closure too large"); static_assert(std::alignment_of<C>::value <= align, "inplace delegate closure alignment too large"); new(&storage_)C{ std::forward<T>(closure) }; } inplace(const inplace& other) : invoke_ptr_{ other.invoke_ptr_ }, copy_ptr_{ other.copy_ptr_ }, destructor_ptr_{ other.destructor_ptr_ } { copy_ptr_(storage_, other.storage_); } inplace(inplace&& other) : storage_ { std::move(other.storage_) }, invoke_ptr_{ other.invoke_ptr_ }, copy_ptr_{ other.copy_ptr_ }, destructor_ptr_{ other.destructor_ptr_ } { other.destructor_ptr_ = nullptr; } inplace& operator= (const inplace& other) { if (this != std::addressof(other)) { invoke_ptr_ = other.invoke_ptr_; copy_ptr_ = other.copy_ptr_; if (destructor_ptr_) destructor_ptr_(storage_); copy_ptr_(storage_, other.storage_); destructor_ptr_ = other.destructor_ptr_; } return *this; } inplace& operator= (inplace&& other) { if (this != std::addressof(other)) { if (destructor_ptr_) destructor_ptr_(storage_); storage_ = std::move(other.storage_); invoke_ptr_ = other.invoke_ptr_; copy_ptr_ = other.copy_ptr_; destructor_ptr_ = other.destructor_ptr_; other.destructor_ptr_ = nullptr; } return *this; } ~inplace() { if (destructor_ptr_) destructor_ptr_(storage_); } R operator() (Args&&... args) const { return invoke_ptr_(storage_, std::forward<Args>(args)...); } bool empty() const noexcept { return destructor_ptr_ == nullptr; } template<typename T> T* target() const noexcept { return reinterpret_cast<T*>(&storage_); } private: mutable storage_t storage_ {}; invoke_ptr_t invoke_ptr_; copy_ptr_t copy_ptr_; destructor_ptr_t destructor_ptr_; template< typename T, typename S, typename std::enable_if_t< std::is_copy_constructible<T>::value, int > = 0 > copy_ptr_t copy_op() { return [](S& dst, S& src) noexcept -> void { new(&dst)T{ reinterpret_cast<T&>(src) }; }; } template< typename T, typename S, typename std::enable_if_t< !std::is_copy_constructible<T>::value, int > = 0 > copy_ptr_t copy_op() { static_assert(std::is_copy_constructible<T>::value, "constructing delegate with move only type is invalid!"); } }; } // namespace spec template< typename R, typename... Args, template<size_t, size_t, typename, typename...> class Spec, size_t size, size_t align > class delegate<R(Args...), Spec, size, align> { public: using result_type = R; using storage_t = Spec<size, align, R, Args...>; explicit delegate() noexcept : storage_{} {} template< typename T, typename = std::enable_if_t< !std::is_same<std::decay_t<T>, delegate>::value> /*&& std::is_same< decltype(std::declval<T&>()(std::declval<Args>()...)), R >::value>*/ > delegate(T&& val) : storage_{ std::forward<T>(val) } {} // delegating constructors delegate(std::nullptr_t) noexcept : delegate() {} // construct with member function pointer // object pointer capture template<typename C> delegate(C* const object_ptr, R(C::* const method_ptr)(Args...)) noexcept : delegate( [object_ptr, method_ptr](Args&&... args) -> R { return (object_ptr->*method_ptr)(std::forward<Args>(args)...); }) {} template<typename C> delegate(C* const object_ptr, R(C::* const method_ptr)(Args...) const) noexcept : delegate( [object_ptr, method_ptr](Args&&... args) -> R { return (object_ptr->*method_ptr)(std::forward<Args>(args)...); }) {} // object reference capture template<typename C> delegate(C& object_ref, R(C::* const method_ptr)(Args...)) noexcept : delegate( [&object_ref, method_ptr](Args&&... args) -> R { return (object_ref.*method_ptr)(std::forward<Args>(args)...); }) {} template<typename C> delegate(C& object_ref, R(C::* const method_ptr)(Args...) const) noexcept : delegate( [&object_ref, method_ptr](Args&&... args) -> R { return (object_ref.*method_ptr)(std::forward<Args>(args)...); }) {} // object pointer as parameter template< typename C, typename... MemArgs, typename std::enable_if_t< std::is_same<detail::pack_first_t<Args...>, C*>::value, int> = 0 > delegate(R(C::* const method_ptr)(MemArgs...)) noexcept : delegate( [method_ptr](C* object_ptr, MemArgs... args) -> R { return (object_ptr->*method_ptr)(std::forward<MemArgs>(args)...); }) {} template< typename C, typename... MemArgs, typename std::enable_if_t< std::is_same<detail::pack_first_t<Args...>, C*>::value, int> = 0 > delegate(R(C::* const method_ptr)(MemArgs...) const) noexcept : delegate( [method_ptr](C* object_ptr, MemArgs... args) -> R { return (object_ptr->*method_ptr)(std::forward<MemArgs>(args)...); }) {} // object reference as parameter template< typename C, typename... MemArgs, typename std::enable_if_t< std::is_same<detail::pack_first_t<Args...>, C&>::value, int> = 0 > delegate(R(C::* const method_ptr)(MemArgs...)) noexcept : delegate( [method_ptr](C& object, MemArgs... args) -> R { return (object.*method_ptr)(std::forward<MemArgs>(args)...); }) {} template< typename C, typename... MemArgs, typename std::enable_if_t< std::is_same<detail::pack_first_t<Args...>, C&>::value, int> = 0 > delegate(R(C::* const method_ptr)(MemArgs...) const) noexcept : delegate( [method_ptr](C& object, MemArgs... args) -> R { return (object.*method_ptr)(std::forward<MemArgs>(args)...); }) {} // object copy as parameter template< typename C, typename... MemArgs, typename std::enable_if_t< std::is_same<detail::pack_first_t<Args...>, C>::value, int> = 0 > delegate(R(C::* const method_ptr)(MemArgs...)) noexcept : delegate( [method_ptr](C object, MemArgs... args) -> R { return (object.*method_ptr)(std::forward<MemArgs>(args)...); }) {} template< typename C, typename... MemArgs, typename std::enable_if_t< std::is_same<detail::pack_first_t<Args...>, C>::value, int> = 0 > delegate(R(C::* const method_ptr)(MemArgs...) const) noexcept : delegate( [method_ptr](C object, MemArgs... args) -> R { return (object.*method_ptr)(std::forward<MemArgs>(args)...); }) {} delegate(const delegate&) = default; delegate(delegate&&) = default; delegate& operator= (const delegate&) = default; delegate& operator= (delegate&&) = default; ~delegate() = default; R operator() (Args... args) const { return storage_(std::forward<Args>(args)...); } bool operator== (std::nullptr_t) const noexcept { return storage_.empty(); } bool operator!= (std::nullptr_t) const noexcept { return !storage_.empty(); } explicit operator bool() const noexcept { return !storage_.empty(); } void swap(delegate& other) { storage_t tmp = storage_; storage_ = other.storage_; other.storage_ = tmp; } void reset() { storage_t empty; storage_ = empty; } template<typename T> T* target() const noexcept { return storage_.template target<T>(); } template< typename T, typename D = std::shared_ptr<T>, typename std::enable_if_t<size >= sizeof(D), int> = 0 > static delegate make_packed(T&& closure) { D ptr = std::make_shared<T>(std::forward<T>(closure)); return [ptr](Args&&... args) -> R { return (*ptr)(std::forward<Args>(args)...); }; } template< typename T, typename D = std::shared_ptr<T>, typename std::enable_if_t<!(size >= sizeof(D)), int> = 0 > static delegate make_packed(T&&) { static_assert(size >= sizeof(D), "Cannot pack into delegate"); } private: storage_t storage_; }; #endif // DELEGATE_HPP_INCLUDED Error messages are cryptic to me any idea what it means? If somebody could explain what they mean would greatly appreciate it. 404: see reference to function template instantiation 'spec::inplace<32,8,R>::inplace<void(__cdecl &)(void),void(__cdecl *)(void)>(T) noexcept' being compiled with [ R=void, T=void (__cdecl &)(void) ] C2061: syntax error: identifier 'C' at line 253 C2061: syntax error: identifier 'C' at line 259 invalid operands to binary expression ('std::nullptr_t'(aka 'nullptr_t') and 'nullptr_t') at line 212 A: You're compiling with C++11 but the code you're using requires C++14. I get a ton of errors when I compile with C++11, but they go away when I use C++14. See here for an explanation of how to compile with C++14 in visual studio! Why won't the code compile with C++11? The file "delegates.hpp" uses a lot of stuff in the C++14 standard library that doesn't appear in C++11. For example, on line 76 of delegates.hpp, we see // C++14 (what's found in the file) using type = std::remove_cv_t<T>; In C++11, this would be // C++11 version using type = typename std::remove_cv<T>::type; There's a lot of code you'd have to change to get it to work in C++11, so I recommend just using C++14 instead.
{ "pile_set_name": "StackExchange" }
Q: Why can the state space of the 15 puzzle be divided into two separate parts? I am trying to understand the proof here of why the state space in 15 puzzle is divided into two separate parts, but the explanation is complicated for me. Could someone please explain it in simpler terms? I have been struggling with this for days :( A: Perhaps the simplest way to understand the proof is by the idea of a conserved quantity : find some quantity that can be derived from a configuration and show that every move preserves that quantity. A static version of the idea is found in the following old puzzle: Remove the northeast and southwest corner squares from a standard 8x8 checkerboard. Can the remaining 62 squares be tiled using 31 dominos? Here, the parity principle is simple: each domino takes up exactly one black and one white square on a checkerboard, so any shape that can be tiled by the dominos has to have exactly as many white squares as black. Since the 62-square shape has 32 squares of one color and 30 squares of the other, there's no way of tiling it. The conservation principle for the 15-puzzle is a bit more complicated, but it's fairly close to this: it's also a parity principle. Let's number the blank square '16' for the time being and imagine it being filled in; then we can talk about the state of the puzzle as a permutation of the numbers (1...16). Now, given an arbitrary permutation of the numbers (1...$n$), we can count how many pairs of numbers we have to swap to return all the numbers to their 'original place'. There are many different possible sets of swaps that can be made - for instance, if you have the permutation (3, 2, 1) you can get back to (1, 2, 3) by either swapping the first and third positions (3 with 1) or by swapping the first and second positions (3 with 2), then the second and third positions (3 with 1), then the first and second positions (1 with 2). (The minimum number of swaps that need to be made is called the number of inversions of the permutation, and it's an interesting quantity in its own right, but that's not important here). However you swap numbers around, though, the total number of swaps will either always be odd (like it is for (3, 2, 1)) or always be even; we call this number the parity of the permutation. Now, going back to the fifteen puzzle: every move is to swap the blank square (the one we've labeled as '16') with some other square, one unit away from the blank square's current position. This means that a swap always comes with a move of one square - so if you consider the quantity 'total number of swaps I have done' + 'moves the 16 is away from its home square', then this quantity will always be even. In particular, when the 16 is back at its home square (0 moves away) then the overall number of swaps that's been performed must be even. This means that the parity of the permutation of the numbers (1..16) corresponding to our resulting position is always even. But now imagine the position of the original puzzle where the 14 and 15 have exchanged places; the 16 is at home but there's been only one 'swap' made. Since this is an odd number of swaps rather then an even number, it can't possibly be reachable from the base configuration. There's one more minor catch: this shows that there are at least two categories that 15-puzzle positions can fall into, but it doesn't show that there are only two. For that, a slightly more complicated result is needed: namely, that any even permutation can be decomposed as a product of what are known as 3-cycles (i.e. swaps $a\rightarrow b\rightarrow c\rightarrow a$). I won't try to prove this here, but the simplest proofs work algorithmically - similar to how bubble sort shows that every permutation can be generated by swapping only adjacent elements. With this result in hand, though, it's easy to get any even permutation: we can get an arbitrary 3-cycle by moving our three elements into positions 11, 12, and 15 on the puzzle (with the blank square in position 16, of course), and then moving the blank square Up, Left, Down, Right - you can convince yourself that this motion cycles the three elements. Once we've done this, we just undo the same motions that got the three elements into those positions, leaving the final positions of all the other elements unchanged from their starting positions. This way of getting an arbitrary 3-cycle, along with the theorem allowing any even permutation to be expressed in terms of 3 cycles, then gives a way of getting every reachable (i.e., corresponding to an even permutation) position.
{ "pile_set_name": "StackExchange" }