pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
15,491,442 | 0 | <p>First things first, the CoffeeScript compiler already has a <code>join</code> command: </p> <blockquote> <pre><code>-j, --join [FILE] </code></pre> <p>Before compiling, concatenate all scripts together in the order they were passed, and write them into the specified file. Useful for building large projects.</p> </blockquote> <p>Secondly, instead of using <code>$(document).ready(function () { ...} )</code>, you can just pass the function directly to the <code>$()</code> - <code>$(function () { ... });</code></p> <p>For your actual problem, there are a few ways you could do it.</p> <h2>Option 1:</h2> <p>Compile the .coffee files using the <code>-b / --bare</code> option, and then manually concatenate a file containing <code>$(function() {</code> and the start and <code>});</code> at the end (but that's pretty gross).</p> <h2>Options 2:</h2> <p>Use something like <code>exports = window ? this</code> to get the global object, and assign the functionality you wish to run in the jQuery load function to that global object, eg:</p> <pre><code>FooModule = do -> class Foo constructor: (@blah) -> init = -> blah = new Foo('bar') init: init exports = window ? this exports.Foo = FooModule </code></pre> <p>You could then have another file that contains something like the following:</p> <pre><code>$(-> Foo.init() ) </code></pre> <p>Hope one of those options is good?</p> |
7,936,970 | 0 | <p>If you can display at most one set of topicdetails at a time, have one div set to position 0,0 with <code>display</code>=<code>none</code>. Whenever you need it to show, set the location appropriately (get it from the mousover/hover DOM element, or whatever you use to trigger the event that displays it), and load/set the content. On remove, just set the display to none (you can ignore the content since it will be replace by new content next time it appears).</p> |
32,507,690 | 0 | OSX codesign for a specific macho binary <p>I have a simple C code that i can gcc on my OS X. (I'm using El Capitan beta.) I know there are many guides for signing apps in Xcode. But I just want to codesign for this specific macho binary.</p> <p>Is there any way to do it? Also, do i have to have an apple developer account to codesign this program? I'm not planning to release the binary to anyone. I'm just studying OSX stuff. </p> <p>Thanks!</p> |
28,232,187 | 0 | <p>First, create examples for all these cases, and order them correctly by their intended priority:</p> <pre><code>status date -------------- past_due d1 past_due d2 open d1 open d2 paid d2 paid d1 future ? draft d2 draft d1 </code></pre> <p>Then, assign numbers so that <code>ORDER BY status2, date2</code> would work correctly. (If we assume that dates are numbers, <code>-d2</code> is smaller than <code>-d1</code>, i.e., negating them reverses the sort direction.)</p> <pre><code>status date status2 date2 ------------------------------ past_due d1 1 d1 past_due d2 1 d2 open d1 2 d1 open d2 2 d2 paid d2 3 -d2 paid d1 3 -d1 future ? 4 ? draft d2 5 -d2 draft d1 5 -d1 </code></pre> <p>Then use <a href="http://www.sqlite.org/lang_expr.html#case" rel="nofollow">CASE expressions</a> to map the status values to these numbers, and to modify the dates accordingly. (<a href="http://www.sqlite.org/lang_datefunc.html" rel="nofollow">julianday()</a> returns a number if the date values are in a supported format; the actual meaning of Julian days does not matter as long as they compare correctly to each other.)</p> <pre><code>SELECT customer_id, customer_version, startDate, status FROM invoices WHERE customer_id = 123 AND customer_version = '321' ORDER BY CASE status WHEN 'past_due' THEN 1 WHEN 'open' THEN 2 WHEN 'paid' THEN 3 WHEN 'future' THEN 4 WHEN 'draft' THEN 5 END, CASE WHEN status IN ('past_due', 'open', 'future') THEN julianday(startDate) -- earliest date first ELSE -julianday(startDate) -- latest date first END LIMIT 1 </code></pre> <p>The <code>LIMIT 1</code> then returns only the first of these sorted rows (if any has been found).</p> |
16,738,910 | 0 | <p>In addition to cellEditor it is necessary to do the cellRenderer to paint the combobox in the cell, look at this:</p> <pre><code> public void example(){ TableColumn tmpColum =table.getColumnModel().getColumn(1); String[] DATA = { "Data 1", "Data 2", "Data 3", "Data 4" }; JComboBox comboBox = new JComboBox(DATA); DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox); tmpColum.setCellEditor(defaultCellEditor); tmpColum.setCellRenderer(new CheckBoxCellRenderer(comboBox)); table.repaint(); } /** Custom class for adding elements in the JComboBox. */ class CheckBoxCellRenderer implements TableCellRenderer { JComboBox combo; public CheckBoxCellRenderer(JComboBox comboBox) { this.combo = new JComboBox(); for (int i=0; i<comboBox.getItemCount(); i++){ combo.addItem(comboBox.getItemAt(i)); } } public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) { combo.setSelectedItem(value); return combo; } } </code></pre> |
17,431,610 | 0 | DictionaryEntry to user object <p>I have a custom user object class appuser</p> <pre><code> public class appuser { public Int32 ID { get; set; } public Int32 ipamuserID { get; set; } public Int32 appID { get; set; } public Int32 roleID { get; set; } public Int16 departmenttypeID { get; set; } public generaluse.historycrumb recordcrumb { get; set; } public appuser() { } public appuser(DataRow dr) { ID = Convert.ToInt32(dr["AppUserID"].ToString()); ipamuserID = Convert.ToInt32(dr["IpamUserID"].ToString()); appID = Convert.ToInt32(dr["AppID"].ToString()); roleID = Convert.ToInt32(dr["AppRoleID"].ToString()); departmenttypeID = Convert.ToInt16(dr["AppDepartmentTypeID"].ToString()); recordcrumb = new generaluse.historycrumb(dr); } public void appuserfill(DictionaryEntry de, ref appuser _au) { //Search for key in appuser given by de and set appuser property to de.value } } </code></pre> <p>How do I set the property within the appuser object that is passed as the key in the DictionaryEntry without knowing what the key initially is?</p> <p>for example: de.key = ipamuserID, dynamically find the property within _au and set the value = de.value?</p> |
34,672,529 | 0 | Algorithmic complexity of Data.Hashtable <p>I am attempting to write a function that utilizes hashes (for an implementation of A*).</p> <p>After a little bit of research, I have found that the defacto standard is <code>Data.Map</code>.</p> <p>However, when reading the API documentation, I found that: <code>O(log n). Find the value at a key.</code></p> <p><a href="https://downloads.haskell.org/~ghc/6.12.2/docs/html/libraries/containers-0.3.0.0/Data-Map.html">https://downloads.haskell.org/~ghc/6.12.2/docs/html/libraries/containers-0.3.0.0/Data-Map.html</a></p> <p>In fact the documentation generally suggests big O times significantly inferior to the O(1) of a standard Hash.</p> <p>So then I found <code>Data.HashTable</code>. <a href="https://hackage.haskell.org/package/base-4.2.0.2/docs/Data-HashTable.html">https://hackage.haskell.org/package/base-4.2.0.2/docs/Data-HashTable.html</a> This documentation does not mention big O directly, leading me to believe that it probably fulfills my expectations.</p> <p>I have several questions: 1) Is that correct? Is O(lookupInDataHashTable) = O(1)? 2) Why would I ever want to use <code>Data.Map</code> given its inefficiency? 3) Is there a better library for my data structure needs?</p> |
17,020,545 | 0 | Doctrine 2 Postgresql stock procedure mapping <p>i 'd like to associate to a doctrine entity a postgresql stock procedure (which returns a table as result) instead of a table</p> <p>Ex : the procedure Get_Uuser(sexe, age) search all the users for the selected parameters et returns a collection of user_id (names user_id_rech for exemple).</p> <p>In pgsql, I can use this stock procedure as a table : </p> <p>select user_name from User left join Get_User('H', 45) where User.user_id = user_id_rech</p> <p>The stock procedure is used like a table here.</p> <p>I don't think that doctrine 2 allows to map a stock procedure, but I'd like that someone can confirm that to me.</p> <p>Thanks</p> |
12,379,448 | 0 | <p>Concider using the fitting layout manager that will help you expand the way you want to when you add the components</p> <p><a href="http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html">http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html</a></p> <p>I think you are looking for the GridLayout and possibly use FlowLayout JPanels inside so that they dont expand, but this will depend on what you want to insert.</p> |
14,319,708 | 0 | <p>Implementing the control is exactly the same as implementing it in pure ASP.NET - no difference.</p> <p>To include it in Sitefinity, you have to register it in the toolbox. Here is the documentation for this: <a href="http://www.sitefinity.com/documentation/documentationarticles/adding-controls-to-the-toolbox" rel="nofollow">http://www.sitefinity.com/documentation/documentationarticles/adding-controls-to-the-toolbox</a></p> <p>Once that's done, you can create a page in Sitefinity and put your custom control on it using drag and drop. Here's a video showing how: <a href="http://www.youtube.com/watch?v=LZ4VHGKQsrg" rel="nofollow">http://www.youtube.com/watch?v=LZ4VHGKQsrg</a></p> |
1,571,395 | 0 | htm vs html which one should be preferred? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/1163738/htm-vs-html">.htm vs .html</a> </p> </blockquote> <p>I have seen many static webpages having two variants of file extensions, which one is preferred and why there are two?</p> |
30,683,719 | 0 | Android - Activity uses or overrides a deprecated API <p>I have literally created a brand new Android Project on the latest Android Studio. The first thing I did was to add the `Realm' library to the project by adding the following to the gradle file:</p> <pre><code>compile 'io.realm:realm-android:0.80.3' </code></pre> <p>If I try to compile, I get the following error:</p> <pre><code>Note: C:\....\MainActivity.java uses or overrides a deprecated API. </code></pre> <blockquote> <p>Origin 2: C:\Users\Usmaan.gradle\caches\modules-2\files-2.1\io.realm\realm-android\0.80.3\7979d05ba7b919c53766bf98e31aaf0e9feb0590\realm-android-0.80.3.jar Error:duplicate files during packaging of APK C:...\app\build\outputs\apk\app-debug-unaligned.apk Path in archive: META-INF/services/javax.annotation.processing.Processor Origin 1: C:\Users\Usmaan.gradle\caches\modules-2\files-2.1\com.jakewharton\butterknife\6.1.0\63735f48b82bcd24cdd33821342428252eb1ca5a\butterknife-6.1.0.jar You can ignore those files in your build.gradle: android {<br> packagingOptions { exclude 'META-INF/services/javax.annotation.processing.Processor' } Error:Execution failed for task ':app:packageDebug'.</p> <blockquote> <p>Duplicate files copied in APK META-INF/services/javax.annotation.processing.Processor File 1: C:\Users\Usmaan.gradle\caches\modules-2\files-2.1\com.jakewharton\butterknife\6.1.0\63735f48b82bcd24cdd33821342428252eb1ca5a\butterknife-6.1.0.jar File 2: C:\Users\Usmaan.gradle\caches\modules-2\files-2.1\io.realm\realm-android\0.80.3\7979d05ba7b919c53766bf98e31aaf0e9feb0590\realm-android-0.80.3.jar }</p> </blockquote> </blockquote> <p>Any ideas?</p> |
29,559,289 | 0 | <p>I can't simulate this, but after read your code I assume this code will work.. First add marker as your pin property:</p> <pre><code>self.mapPin = function (name, lat, lon, text) { this.name = ko.observable(name); this.lat = ko.observable(lat); this.lon = ko.observable(lon); this.text = ko.observable(text); this.marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lon), map: map, animation: google.maps.Animation.DROP }); // removed for clarity }; </code></pre> <p>then set pin marker visibility while filtering your pins</p> <pre><code>self.filterPins = ko.computed(function () { var search = self.query().toLowerCase(); return ko.utils.arrayFilter(self.pins(), function (pin) { var match = pin.name().toLowerCase().indexOf(search) >= 0; pin.marker.setVisible(match); // maps API hide call return match; }); }); </code></pre> <p><a href="https://developers.google.com/maps/documentation/javascript/reference#Marker" rel="nofollow">Google Maps Marker Documentation</a></p> |
30,978,896 | 0 | <p>please try closing the classloader before you 'unload' it.</p> <pre><code>public void unloadJarAndClass() throws IOException { dukeClassLoader.close(); /* all object must be collected in order to reload jar */ jarFile = null; dukeClassLoader = null; classToLoad = null; // System.gc(); don't do this unless you're really // sure you have to ! } </code></pre> <p>I would recommend not calling System.gc() explicitly ! (see <a href="http://stackoverflow.com/questions/2414105/why-is-it-bad-practice-to-call-system-gc">Why is it bad practice to call System.gc()?</a> for example)</p> |
26,158,808 | 0 | <p>This error is caused by a product without ID. Check that all your *.product files specify an ID on the Overview tab of the Product Configuration Editor.</p> |
22,905,119 | 0 | create image of application and store to database <p>I have create a application in c#. What my problem was when user try to edit something new to database via this application, it will not save to main table in database directly, but will store on another table, and waiting for another user to approve it.</p> <p>In this case, if user try to edit, I wish to save the application image and store to the table, and when another user come and approve it, it can show different before edit and after edit, this is much convenience for user to view and make decision.</p> <p>I have search through internet, but I can not find a good solution to solve this problem, anyone can help please.</p> |
2,161,403 | 0 | <p>Looking at the documentation for <a href="http://developer.android.com/intl/fr/reference/android/media/MediaRecorder.AudioSource.html" rel="nofollow noreferrer"><code>MediaRecorder.AudioSource</code></a> I would say that this should be possible using the <a href="http://developer.android.com/intl/fr/reference/android/media/MediaRecorder.AudioSource.html#VOICE_DOWNLINK" rel="nofollow noreferrer"><code>VOICE_DOWNLINK</code> source</a>.</p> <pre><code>MediaRecorder recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_DOWNLINK); </code></pre> |
23,107,989 | 0 | How to Construct the Email To activity in SharePoint 2013 Workflow <p>I am using SharePoint 2013 SP1 and I am having a problem constructing the Email Activity To attribute. </p> <p>Here's where I am at. I have a created a custom workflow and custom association and initiation form using SharePoint 2013.</p> <p>My Assn. form is fine. I pass in the people Editor control (Active Directory group name ie. SharePointApprovers) value to my workflow just fine.</p> <p>Now on my Init form I use the passed in value from people picker and display a list of users and email addresses from the people picker group. The list of users and email addresses are listed in a table with a check box to the left of each row. I am using JQuery, Knockout and MVC web service to retrieve the values from the group.</p> <p>All is well.</p> <p>Now my users pick who they want to send the email to. Let's say they pick two users! This means my variable is like this (<code>[email protected];[email protected]</code>).</p> <blockquote> <p>When the user clicks the submit button, I have <code>JSOM</code> code which starts the workflow and sends in the 2 users email addresses as an argument to the workflow. Note: I tried sending my two emails as a array and failed but if I send it in as a string it works. The variable is called strUsers.</p> </blockquote> <p>Since the argument is a string and Email Activity To attribute requires an array, I use the <code>BuildCollection<String></code> Activity to convert my string strUsers to an array. I think this worked, as when I added a WriteToHistory Activity to <strong>my workflow my result in workflow history</strong> is as follows... <code>"The value is [email protected];[email protected]"</code>.</p> <p>I then configure the email Activity and set to To property to my BuildActivity variable (recipients). As this is an array.</p> <p>When I deploy my Visual Studio 2013 solution, and attach my workflow to a publishing page, I am getting this error after I submit the Init form.</p> <blockquote> <p>An unhandled exception occurred during the execution of workflow instance. System.ArgumentNullException.</p> </blockquote> <p>Does anyone know of an example of how to set up the Email To collection value.</p> <p>PS I have looked at this <a href="http://blogs.msdn.com/b/officeapps/archive/2013/09/18/step-by-step-sending-email-messages-from-a-workflow-in-an-app-for-sharepoint-2013.aspx" rel="nofollow">link</a> but it is only passing in one variable. In my case I have a string of emails. I need to pass in an array to the Email To property.</p> |
22,568,824 | 0 | <p>You are targeting a class called div instead of the tag. Remove the leading dot and you should be fine.</p> |
11,159,314 | 0 | <p>If the response is between 199 and 300 ( >= 200 and < 300 ) or equal to 304 and the responseText can be successfully converted to the dataType that you provide (text by default), it is considered a successful request.</p> <p>For example, if you return JSON and you get a 200 response status but it fails, it is more than likely a JSON parser problem meaning your JSON is not valid.</p> <p>If you are returning HTML or XML and it fails with a 200 response status, the responsetext couldn't be converted to HTML or XML respectively (commonly happens in IE with invalid html/xml)</p> |
18,550,614 | 0 | <p>Something along the lines of this, however you will have to do more checks to see if the socket is still alive or not, etc.</p> <pre><code>var net = require('net'); var sockets = {}; var server = net.createServer(function(c) { //'connection' listener var name = generate_name_from_con(c); console.log('server connected'); sockets[name] = c; c.on('end', function() { delete sockets[n]; console.log('server disconnected'); }); c.write('hello\r\n'); c.pipe(c); }); server.listen(8124, function() { //'listening' listener console.log('server bound'); }); app.get('/msg/:theMsg', function (req, res) { res.setHeader('Content-Type', 'application/json'); if(socketName in sockets) sockets[socketName].write(req.params.theMsg); }); </code></pre> |
40,401,338 | 0 | Sequelize: Query an association table <p>I have trouble querying an association table using sequelize. I have 3 tables: User, Roles and UserRoles. A user can have many roles.</p> <p>I am trying to query in UserRoles (which stores userID and roleID ).</p> <pre><code>var User = sequelize.define('User', { // }, { classMethods: { associate: function(models) { User.belongsToMany(models.Role, { through: 'UserRole' }); var Role = sequelize.define('Role', { // }, { classMethods: { associate: function(models) { Role.belongsToMany(models.User, { through: 'UserRole' }); } } }); </code></pre> <p>I suspect the problem is with UserRole Model defition.</p> <pre><code>var UserRole = sequelize.define('UserRole', { // }, { associate: function(models) { UserRole.belongsTo(models.User, { foreignKey: 'UserId', foreignKeyConstraint: true, targetKey: 'id' }); UserRole.belongsTo(models.Role, { foreignKey: 'RoleId', foreignKeyConstraint: true, targetKey: 'id' }); } db.UserRole.findAll({ //Returns empty }) </code></pre> |
10,260,250 | 0 | <p>According to Net::HTTP doc you can do </p> <pre><code>res = Net::HTTP.post_form("example.com/index.html", 'q' => 'ruby', 'max' => '50') puts res.body </code></pre> <p>see <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html#method-c-post_form" rel="nofollow">http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html#method-c-post_form</a></p> |
15,416,342 | 0 | Unknown extern method T System.Nullable`1::get_Value() <p>I've run into a problem with my dot42 C# project:</p> <pre><code>Unknown extern method T System.Nullable`1::get_Value() at System.Void NokiaStyleProfiles.AddDialogue::btnAdd_Click(System.Object,System.EventArgs) (c:\Users\STO\Documents\Visual Studio 2012\Projects\NokiaStyleProfiles\NokiaStyleProfiles\AddDialogue.cs, position 86,13) </code></pre> <p>Code that's causing that problem:</p> <pre><code>int hourStart = timePickerStart.CurrentHour.Value; (timePicker.CurrentHour is an int?) </code></pre> <p><code>(int)</code>, <code>.Value</code> and <code>.GetValueOrDefault()</code>, as expected, produce the same result : this error.</p> <p>How can i fix it?</p> |
6,214,666 | 0 | <p><a href="https://github.com/harrah/xsbt/tree/0.9" rel="nofollow"><strong>SBT 0.9.x</strong></a>:</p> <pre><code>(sourceDirectories in Test) := Seq(new File("src/test/scala/unit"), new File("src/test/scala/functional")) </code></pre> <p><strong>SBT 0.7.x</strong>:</p> <pre><code>override def testSourceRoots = ("src" / "test") +++ "scala" +++ ("unit" / "functional") </code></pre> |
35,177,226 | 0 | <p>The problem is here:</p> <pre><code>***Variables*** ... ${headers}= Create Dictionary Cache-Control no-cache </code></pre> <p>You cannot call keywords like <code>create dictionary</code> in the variables table. The above code is setting <code>${headers}</code> to be the <em>string</em> <code>"Create Dictionary Cache-Control no-cache"</code>.</p> <p>Starting with version 9 of robot framework there is direct support for dictionaries using an ampersand rather than dollar sign for variables. You can specify values using <code><key>=<value></code> syntax. For example:</p> <pre><code>*** Variables *** &{headers} Cache-Control=no-cache </code></pre> |
33,513,140 | 0 | <p>In the project window of your IDE click on the options menu(small gear icon) and disable the "Flatten Packages" option. This will make things more straight forward.</p> <p>From there you can simply right click on the ui package and select <code>new -> package</code> to create your <code>actvt2</code> package.</p> |
24,573,963 | 0 | Move Constructor - invalid type for defaulted constructor VS 2013 <p>I was reading regarding move constructor and I did this code in VS 2013...</p> <pre><code>class Student { unique_ptr<string> pName_; public: Student(string name) : pName_(new string(name)) { } ~Student() { } Student(Student&&) = default; // Here I get the error. void printStudentName(void) { cout << *pName_ << endl; } }; int main(void) { vector<Student> persons; Student p = Student("Nishith"); persons.push_back(std::move(p)); persons.front().printStudentName(); return 0; } </code></pre> <p>I get the "<code>Student::Student(Student&& )</code> : is not a special member function which can be defaulted" when I tried to compile it...</p> <p>Can anyone explain me why I am getting this error?</p> |
15,213,955 | 0 | What is the intersection of two languages with different alphabets? <p>I did some googling on this and nothing really definitive popped up.</p> <p>Let's say I have two languages A and B.</p> <p>A = { w is a subset of {a,b,c}* such that the second to the last character of w is b }</p> <p>B = { w is a subset of {b,d}* such that the last character is b }</p> <p>How would one define this? I think the alphabet would be the union of both, making it {a,b,c,d} but aside from that, I wouldn't know how to make a DFA of this.</p> <p>If anyone could shed some light on this, that would be great.</p> |
5,912,697 | 0 | <p>A better way to solve this issue, in my opinion, would be to edit your ~/.profile or /etc/bashrc and add the line:</p> <pre><code>export ARCHFLAGS="-arch i386 -arch x86_64" </code></pre> <p>Will save messing around with any future installations (I've just had to do this for installing lots of Perl modules in CPAN)!</p> |
2,600,840 | 0 | <p>A new window is generally prompted by a target attribute on the A tag:</p> <pre><code><a href="#" target="_blank">linktext</a> </code></pre> <p>FF can supress/override this behaviour in it's preferences.</p> |
30,041,096 | 0 | c++ pass by reference safely and compile time checking on size <pre><code>SpiDeviceDriver::SPI_Error SpiDeviceDriver::SPI_ReadBytes( quint32 size_, QVector<quint8>& rxData_ ) { //Get data and fill QVector<quint8> with data } </code></pre> <p>I'm trying to call a class function (from another class) and pass in a <code>QVector</code>, then fill it with data.</p> <ol> <li><p>I prefer to just pass in the <code>QVector</code> alone (without the <code>quint32</code> size parameter) and then figure out the size from that and fill it with data according to its size. However, if the passed in <code>QVector</code> is size 0, I'd either have to assume it is meant to be size 1, creating a new spot for the data, or throw/handle the error at run-time, which i'd rather not do. Compile time error checking would be much better. Is there a better way to do this?</p></li> <li><p>I guess you could pass in a <code>quint32 size_</code> parameter, then forget what the size of the <code>QVector</code> is and force the resizing to be that size. This seems awkward as well</p></li> </ol> <p><strong>Note:</strong> I've been instructed by my boss to make every function return an <code>enum</code> error code, so just using a <code>size_</code> and creating a vector, then returning that data is not an option.</p> |
24,877,080 | 0 | <p>you just want a scatter plot of points with x and y coordinates and a colour representing a third variable?</p> <p>this is what scatter is for, just use:</p> <pre><code>import matplotlib.pyplot as plt plt.scatter(x, y, c=z, cmap='jet') </code></pre> <p>you can give it any other colormap, all possibilities are shown here: <a href="http://matplotlib.org/examples/color/colormaps_reference.html" rel="nofollow">http://matplotlib.org/examples/color/colormaps_reference.html</a></p> <p>here a small example:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x = numpy.random.normal(0, 2, 100) y = numpy.random.normal(0, 2, 100) r = np.sqrt(x**2 + y**2) plt.scatter(x, y, c=r, cmap='jet') </code></pre> <p>this would give you 100 2d-gaussian distributed points with colors depending on the distance to (0,0)</p> |
33,296,848 | 0 | <p>You can try to override:</p> <pre><code>- (void) setSelectedSegmentIndex:(NSInteger)toValue </code></pre> |
39,873,396 | 0 | <p>In my opinion, the best way to do this is to simply use the Firebase Realtime Database:</p> <p>1) Add Firebase support to your app</p> <p>2) Select 'Anonymous authentication' so that the user doesn't have to signup or even know what you're doing. This is guaranteed to link to the currently authenticated user account and so will work across devices.</p> <p>3) Use the Realtime Database API to set a value for 'installed_date'. At launch time, simply retrieve this value and use this.</p> <p>I've done the same and it works great. I was able to test this across uninstall / re-installs and the value in the realtime database remains the same. This way your trial period works across multiple user devices. You can even version your install_date so that the app 'resets' the Trial date for each new major release.</p> |
2,063,352 | 0 | Caliburn and datatemplates in Silverlight 3 <p>Does anyone know if the same functionality for displaying views depending on object/viewmodel is applicable to Silverlight 3?</p> <p>Like this:</p> <pre><code><Application.Resources> <DataTemplate DataType="{x:Type vm:CustomerViewModel}"> <view:CustomerView /> </DataTemplate> </code></pre> <p></p> <pre><code><ContentControl Content="{Binding Path=CurrentView}"/> public class RootViewModel : BaseViewModel </code></pre> <p>{</p> <pre><code>private BaseViewModel _currentView; public BaseViewModel CurrentView { get { return _currentView; } set { _currentView = value; RaisePropertyChanged("CurrentView"); } } public void ShowCustomer() { CurrentView = IoC.Resolve<Customerviewmodel>(); } </code></pre> <p>}</p> <p>Sorry about the formatting. Can't seem to get it right...</p> <p>/Johan</p> |
7,613,396 | 0 | <p>In Visual Studio 2010, you now can apply a transformation to your web.config depending on the build configuration.</p> <p>When creating a web.config, you can expand the file in the solution explorer, and you will see two files:</p> <ol> <li>Web.Debug.Config </li> <li>Web.Release.Config</li> </ol> <p>They contains transformation code that can be used to:</p> <ul> <li>Change the connection string</li> <li>Remove debugging trace and settings</li> <li>Register error pages</li> </ul> <p><a href="http://msdn.microsoft.com/en-us/library/dd465326%28VS.100%29.aspx" rel="nofollow">link</a></p> |
38,499,744 | 0 | <p>Solution for this was to install <a href="https://msdn.microsoft.com/en-us/goglobal/bb964665.aspx" rel="nofollow">Microsoft Keyboard Layout Creator</a> Then to modify selected Keyboard layout and switch these characters.</p> |
7,411,418 | 0 | <p>If you only needs config file and not necessarily XML, take a look on <a href="http://www.boost.org/doc/libs/1_47_0/doc/html/program_options.html" rel="nofollow">Boost Program Options</a></p> <p>It is simple and easy to use. It use the format of .ini file.</p> <p>Example of .ini file:</p> <pre><code>[info] name=something x=0 y=0 </code></pre> |
38,225,875 | 0 | <p>My apologies, I am able to set user metadata through <a href="https://github.com/softlayer/softlayer-java" rel="nofollow">SoftLayer API Client for Java</a>, here a java script, try this and let me know if you continue having issues please. Make sure to use master branch from the client.</p> <p>Script:</p> <pre><code>package com.softlayer.api.VirtualGuest; import com.softlayer.api.ApiClient; import com.softlayer.api.RestApiClient; import com.softlayer.api.service.virtual.Guest; import java.util.ArrayList; import java.util.List; /** * This script sets the data that will be written to the configuration drive. * * Important Manual Page: * http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/setUserMetadata * * @license <http://sldn.softlayer.com/article/License> * @authon SoftLayer Technologies, Inc. <[email protected]> * @version 0.2.2 (master branch) */ public class SetUserMetadata { /** * This is the constructor, is used to set user metadata */ public SetUserMetadata() { // Declare your SoftLayer username and apiKey String username = "set me"; String apiKey = "set me"; // Create client ApiClient client = new RestApiClient().withCredentials(username, apiKey); Guest.Service guestService = Guest.service(client, new Long(206659875)); // Setting the medatada String metadataTest = "test1RcvRcv"; List<String> metadata = new ArrayList<String>(); metadata.add(metadataTest); try { boolean result = guestService.setUserMetadata(metadata); } catch (Exception e) { System.out.println("Error: " + e); } } /** * This is the main method which makes use of SetUserMetadata method. * * @param args * @return Nothing */ public static void main(String[] args) { new SetUserMetadata(); } } </code></pre> <p><strong>References:</strong></p> <ul> <li><a href="http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/setUserMetadata" rel="nofollow">SoftLayer_Virtual_Guest::setUserMetadata</a></li> </ul> |
10,109,579 | 0 | <p>Already found a solution, 2 classes need to be modified:</p> <p>class Doctrine_Query, change preQuery method:</p> <pre><code>public function preQuery() { $doctrine_manager = Doctrine_Manager::getInstance(); if ($this->getType() == Doctrine_Query::SELECT) { $this->_conn = $doctrine_manager->getConnection('slave'); } else { $this->_conn = $doctrine_manager->getConnection('master'); } } </code></pre> <p>class Doctrine_Record, update method save:</p> <pre><code>public function save(Doctrine_Connection $conn = null) { if ($conn === null) { $conn = Doctrine_Manager::getInstance()->getConnection('master'); } parent::save($conn); } </code></pre> |
31,969,526 | 0 | <p>To find the solution, I set up a virtual environment with seven Redis servers running simultaneously. They were set with sequential port numbers, with the default Redis port (6379) instance being the master. I configured two instances to be slaves to Instance_6379, and configured two more slaves each for Instance_6380 and Instance_6381, respectively. I then checked the <code>redis-cli info</code> output of each, taking note of the <code>connected_slaves</code> metric.</p> <p>Here is what I found: Masters will only report those slaves that are DIRECTLY CONNECTED to them. Slaves of slaves will NOT count towards the total number of slaves connected to the master.</p> <p>In the example image referenced in the question, the leftmost Redis server would have only two <code>connected_slaves</code> and each of its children would also show two <code>connected_slaves</code>.</p> <p>I hope this answer will be of use to someone.</p> |
24,169,795 | 1 | How to pass function parameters with parameter names to an external program in R? <p>For example,</p> <pre><code>passpara = function(pa, pb, pc) { # pa is not passed do1(pa) # pb and pc are passed # passed == "--pb pb_value --pc pc_value" # getpass is something I am trying to figure out passed = getpass(pb, pc) system(paste("cmd", passed)) } </code></pre> <p>To be specific, calling <code>passpara</code> like this:</p> <pre><code>passpara(pa="dummy", pb="full-iso", pc="always") </code></pre> <p>should be equivalent to call this command in shell:</p> <pre><code>cmd --pb full-iso --pc always </code></pre> <p>What would the function <code>getpass</code> look like in this case?</p> <p>I also think the <code>system</code> function is inconvenient sometimes, since it receive a string and you have to delimit arguments manually, is there something similar to python's <code>subprocess.call()</code> in R? In python you can do <code>subprocess.call(["cmd", parameter1, parameter2, parameter3])</code>, and it will delimit the args automatically, this is very handy if the args are strings that contain white spaces.</p> |
18,012,404 | 0 | <p>Try to use this example</p> <pre><code>$(function(){ $('#structure').click(function(){ $('#div1').html($('<div>', {'text' : 'structure'})); }); $('#style').click(function(){ $('#div1').html($('<div>', {'text' : 'style'})); }); }); </code></pre> <p>Update</p> <pre><code>$(function(){ // load default div to div 1 $('#div1').append($('#default')); $('#structure').click(function(){ // load some div to div 1 $('#div1').append($('#divForStructure')); }); $('#style').click(function(){ // load some div to div 1 $('#div1').append($('#divForStyle')); }); }); </code></pre> |
614,407 | 0 | <p>have you tried to clean/rebuild UnitTest++ library projects (if it is build form sources)?</p> |
32,590,195 | 1 | Django development server inaccessible from the internet <p>I'm running a Django development server with</p> <pre><code>python manage.py runserver 0.0.0.0:8000 </code></pre> <p>It is perfectly accessible from the local machine, but not from the outer world. Windows 8.1, Python 3.4.3, Django 1.8.4.</p> <p>I've tried a different port (7500, 50001) and allowing the port explicitly at Windows Firewall (through Inbound Rules). I've also run the server on a different machine (AWS EC2) with the port allowed there, same result. </p> <p>Netstat says that the program is listening on the specified port, so theoretically it should be working. My machine is also in the ALLOWED HOSTS list in settings.py. </p> <p>I know the development server is not safe enough to be used in production, but I'm doing a small short-term thing that isn't worth bothering with proper deployment. So, any ideas what can be the problem?</p> |
7,649,802 | 0 | <p><code>is_numeric</code> checks more:</p> <blockquote> <p>Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.</p> </blockquote> |
9,381,345 | 0 | <p>What you are referring to is called subdomains. Have a look here for more information on them: <a href="http://en.wikipedia.org/wiki/Subdomain" rel="nofollow">http://en.wikipedia.org/wiki/Subdomain</a> </p> |
25,928,517 | 0 | <p>You may need to add ng-model also to your directive to bind the selected value to controller scope.</p> <p>This might be what your are looking at:</p> <pre><code> app.directive('locselect', function () { function link(scope, element, attrs) { scope.ngModel = scope.defaultItem; console.log(scope.items); } var select = { restrict: 'E', templateUrl: 'prp-select.html', replace: true, scope: { items: "=" } } return select; }); </code></pre> <p>and your directive's template (app/search-filters/prp-select.html) should be </p> <pre><code><select ng-options="item as item.full_name for item in items"> <option value="">Select State...</option> </select> </code></pre> <p>and this is how you would want to use - </p> <pre><code><locselect ng-model="modSelectedState" items="states"></locselect> </code></pre> <p>Check the <a href="http://plnkr.co/edit/XhbwhIBmmuKbkqFlWyRM?p=preview" rel="nofollow">plunkr here</a></p> |
30,289,858 | 0 | Is it possible to pull/push my local MYSQL db to the heroku postgresql db? <p>I need to pull the heroku db to my local and also push my db to the heroku remote. Locally I have MYSQL and in heroku it is Postgresql. I found lot ways suggested in internet but none seems to be working and most of them are very old and things have changed.</p> <p>Things tried:</p> <hr> <p><code>heroku db:push</code> - didnt work</p> <pre><code>$ heroku db:push ! `db:push` is not a heroku command. ! Perhaps you meant `pg:push`. ! See `heroku help` for a list of available commands. </code></pre> <p><code>heroku pg:push</code> : Here am not sure how to mention the source database (and i dont have a local db password)</p> <pre><code>$ heroku pg:push mysql://root:@localhost/app_development --app myapp Usage: heroku pg:push <SOURCE_DATABASE> <REMOTE_TARGET_DATABASE> push from SOURCE_DATABASE to REMOTE_TARGET_DATABASE REMOTE_TARGET_DATABASE must be empty. SOURCE_DATABASE must be either the name of a database existing on your localhost or the fully qualified URL of a remote database. </code></pre> <hr> <p>Info:</p> <hr> <pre><code>$ heroku version heroku-toolbelt/3.37.0 (x86_64-linux) ruby/2.2.1 You have no installed plugins. </code></pre> <p>OS : Ubuntu 14.04</p> <pre><code>$ heroku pg:info --app myapp === DATABASE_URL Plan: Hobby-dev Status: Available Connections: 1/20 PG Version: 9.4.1 Created: 2015-05-16 07:05 UTC Data Size: 6.7 MB Tables: 6 Rows: 0/10000 (In compliance) Fork/Follow: Unsupported Rollback: Unsupported </code></pre> |
20,084,919 | 0 | <pre><code>$return_value = $driver->wait()->until($expectedCondition) </code></pre> |
26,904,714 | 0 | swt add widgets towards right in formLayout <p>Here is my code:</p> <pre><code>Composite outer = new Composite(parent, SWT.BORDER); outer.setBackground(new Color(null, 207, 255, 206)); // Green FormLayout formLayout = new FormLayout(); formLayout.marginHeight = 5; formLayout.marginWidth = 5; formLayout.spacing = 5; outer.setLayout(formLayout); //TOP Composite Top = new Composite(outer, SWT.BORDER); Top.setLayout(new GridLayout()); Top.setBackground(new Color(null, 232, 223, 255)); // Blue FormData fData = new FormData(); fData.top = new FormAttachment(0); fData.left = new FormAttachment(0); fData.right = new FormAttachment(100); // Locks on 10% of the view fData.bottom = new FormAttachment(20); Top.setLayoutData(fData); //BOTTOM Composite Bottom = new Composite(outer, SWT.BORDER); Bottom.setLayout(fillLayout); Bottom.setBackground(new Color(null, 255, 235, 223)); // Orange fData = new FormData(); fData.top = new FormAttachment(20); fData.left = new FormAttachment(0); fData.right = new FormAttachment(100); fData.bottom = new FormAttachment(100); Bottom.setLayoutData(fData); </code></pre> <p>I just wanted to add widgets for example label images to the right of the "TOP" composite layout. Since i am new to swt, am facing difficulty to align all the label to right of it. How could i achieve this ?</p> |
37,147,998 | 0 | PHP mysql returns null, hard coded SQL query works <p>I'm having an issue in which I'm unable to get my database query within a PHP program to work. The query works fine within the program if it is hard coded, but it fails otherwise and passes back no results. I have echo'd the two results and am given a different string length, but the string I am given is identical (strings gotten via var_dump). I'm at my wit's end; I'm not really sure what is the issue with the query. I have tried several different fixes which I found for similar problems, but none of them have worked. I trim the posted input and also have the variable double quoted as opposed to single quoted so that the reference executes. I really just have no clue what's wrong. Here is the code that's relevant to this project: AJAX call to php class:</p> <pre><code>chlorinator = ($('#chlorinator').val()).concat(' GS').trim(); $.ajax( { type: "POST", url: "gravity.php", data: "chlorinator="+chlorinator, cache: false, beforeSend: function () { $('#results').html('<img src="loader.gif" alt="" width="24" height="24">'); }, success: function(html) { $("#results").html( html ); }}); </code></pre> <p>And here is the relevant php code:</p> <pre><code><?php include 'connection.php'; $chlorinator = trim( mysqli_real_escape_string ($dbhandle,$_POST["chlorinator"])); $query = 'SELECT chlorinators.model_name, equipment.name, equipment.cutsheet_url, chlorinators.pump_specific, equipment.file_name FROM chlorinators INNER JOIN chlorinator_equipment ON chlorinators.chlorinator_index = chlorinator_equipment.chlorinator_index INNER JOIN equipment ON chlorinator_equipment.equipment_index = equipment.equipment_index WHERE chlorinators.model_name= "' . $chlorinator . '"'; echo "The value of the combined string is:<br> "; var_dump($query); echo '<br><br>'; echo "The value of the hard-coded string is:<br> "; $query = 'SELECT chlorinators.model_name, equipment.name, equipment.cutsheet_url, chlorinators.pump_specific, equipment.file_name FROM chlorinators INNER JOIN chlorinator_equipment ON chlorinators.chlorinator_index = chlorinator_equipment.chlorinator_index INNER JOIN equipment ON chlorinator_equipment.equipment_index = equipment.equipment_index WHERE chlorinators.model_name= "2075 GS"'; var_dump($query); echo '<br><br>'; if ($result = $dbhandle->query($query)) {?> <br><br><?php var_dump($result->fetch_assoc()); printf("<p style='font-family:sans-serif; text-align: center;'>The components of the %s are listed below</p><table id='form' name='pump' style='margin: auto; padding: auto'>", $_POST["chlorinator"]); while($row = $result->fetch_assoc()) { printf ("<div><tr><td>%s</td><td><a href='%s' download>Download</a></td></tr>", $row["name"],$row["cutsheet_url"]); } printf('</table>'); } ?> </code></pre> <p>For this particular example I'm using the value '2075 GS' as the chlorinator value. It is generally passed via change on a selection box, so the values are hard coded and correct. The output of this specific example is:</p> <blockquote> <p>string(403) "SELECT chlorinators.model_name, equipment.name, equipment.cutsheet_url, chlorinators.pump_specific, equipment.file_name FROM chlorinators INNER JOIN chlorinator_equipment ON chlorinators.chlorinator_index = chlorinator_equipment.chlorinator_index INNER JOIN equipment ON chlorinator_equipment.equipment_index = equipment.equipment_index WHERE chlorinators.model_name= "2075 GS""</p> <p>string(404) "SELECT chlorinators.model_name, equipment.name, equipment.cutsheet_url, chlorinators.pump_specific, equipment.file_name FROM chlorinators INNER JOIN chlorinator_equipment ON chlorinators.chlorinator_index = chlorinator_equipment.chlorinator_index INNER JOIN equipment ON chlorinator_equipment.equipment_index = equipment.equipment_index WHERE chlorinators.model_name= "2075 GS""</p> </blockquote> <p>I don't see any difference between the two outputs; any idea as to where the one character difference is and how I can eliminate it so that my query will properly work? Any help is greatly appreciated.</p> |
35,951,605 | 0 | Swift xcode two errors: load controller is not allowed and autoresize not equal to views window <p>EDIT: If you need me to post more class programs just let me know in the comments.</p> <p>Screenshot of what I'm trying to create: <a href="http://i.stack.imgur.com/dmuFw.png" rel="nofollow">enter image description here</a></p> <p>NOTE: There's no need to look at the code below if you decide to run the project because all the classes I posted below are inside the dropbox zipped project file.</p> <p>Each of the squares on the bottom selects a different color and there's an invisible square that selects the type of shape off to the right of the green one. After the user selects one of these shapes, the user will be able to draw in a certain part of the screen.</p> <p>Entire project: <a href="https://www.dropbox.com/s/rhj641yku230f3v/SwiftXcodeProejctTwoErrors6767.zip?dl=0" rel="nofollow">https://www.dropbox.com/s/rhj641yku230f3v/SwiftXcodeProejctTwoErrors6767.zip?dl=0</a></p> <p>If you run the project, create an account, then click sign in, then click one of the rows, then click on one of the colored boxes (red and green squares) the app will crash and get the following error message:</p> <pre><code>2016-03-11 17:06:43.580 finalProject2[11487:1058358] <UIView: 0x7faba1677710; frame = (0 0; 414 736); autoresize = W+H; gestureRecognizers = <NSArray: 0x7faba1658d90>; layer = <CALayer: 0x7faba16563f0>>'s window is not equal to <finalProject2.RowTableViewController: 0x7faba165a3c0>'s view's window! File slot 1 File slot 2 File slot 3 File slot 4 File slot 5 File slot 6 File slot 7 File slot 8 File slot 9 File slot 10 File slot 11 File slot 12 2016-03-11 17:06:44.746 finalProject2[11487:1058358] Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<UIAlertController: 0x7faba16b7d60>) </code></pre> <p>MainProject scene class:</p> <pre><code>import UIKit weak var FirstFileNameTextField: UILabel! enum ShapeType: String { case Line = "Line" case Ellipse = "Ellipse" case Rectangle = "Rectangle" case FilledEllipse = "Filled Ellipse" case FilledRectangle = "Filled Rectangle" case Scribble = "Scribble" } let shapes: [ShapeType] = [ .Line, .Ellipse, .Rectangle, .FilledEllipse, .FilledRectangle, .Scribble ] class MainProjectScene: UIViewController { var row: Row? @IBAction func PressedSaveAs(sender: UIButton) //this is the save as function that I would like to know how to change { //1. Create the alert controller. var alert = UIAlertController(title: "Name/rename your file:", message: "Enter a filename to name/rename and save your file", preferredStyle: .Alert) //2. Add the text field. You can configure it however you need. alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in textField.text = "Your file name" }) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in let textField = alert.textFields![0] as UITextField print("Text field: \(textField.text)") // rows.cell.textLabel?.text = textField.text CurrentFileName = textField.text! rows[IndexPath.row].FileName = textField.text! rows[IndexPath.row].UserText = self.TextUserScrollEdit.text! })) // 4. Present the alert. self.presentViewController(alert, animated: true, completion: nil) // rows[indexPath.row].FileName = rows.cell.textLabel?.text // rows[i] = textField.text // if let detailViewController = segue.destinationViewController as? MainProjectScene { // if let cell = sender as? UITableViewCell { // if let indexPath = self.tableView.indexPathForCell(cell) { // detailViewController.row = rows[indexPath.row] } override func viewWillAppear(animated: Bool) { if let r = row { row!.FileName = r.FileName row!.QuartzImage = r.QuartzImage row!.UserText = r.UserText rows[IndexPath.row].UserText = self.TextUserScrollEdit.text! } } override func viewDidLoad() { super.viewDidLoad() TextUserScrollEdit.text = rows[IndexPath.row].UserText // FacebookButton.addTarget(self, action: "didTapFacebook", forControlEvents: .TouchUpInside) } @IBOutlet weak var TextUserScrollEdit: UITextView! @IBOutlet weak var NewFileButton: UIButton! @IBOutlet weak var TwoDQuartzButton: UIButton! @IBOutlet weak var YouTubeButton: UIButton! @IBOutlet weak var TwitterButton: UIButton! @IBOutlet weak var OpenFileButton: UIButton! @IBOutlet weak var SnapChatButton: UIButton! @IBOutlet weak var FacebookButton: UIButton! @IBAction func PressedTwoDQuartzButton(sender: UIButton) { } @IBAction func PressedSnapchatButton(sender: UIButton){ UIApplication.sharedApplication().openURL(NSURL(string: "https://www.snapchat.com/")!) } @IBAction func PressedYouTubeButton(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "https://www.youtube.com/")!) } @IBOutlet weak var InstagramButton: UIButton! @IBAction func PressedFacebookButton(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "http://www.facebook.com")!) } @IBAction func PressedInstagramButton(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "https://www.instagram.com/")!) } @IBAction func PressedTwitterButton(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "https://twitter.com/")!) } @IBOutlet weak var SaveAsButton: UIButton! // @IBOutlet weak var shapeButton: ShapeButton! @IBOutlet weak var canvas: CanvasView! @IBOutlet var colorButtons: [UIButton]! @IBOutlet weak var shapeButton: ShapeButton! @IBAction func selectColor(sender: UIButton) { UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: CGFloat(0.25), initialSpringVelocity: CGFloat(0.25), options: UIViewAnimationOptions.CurveEaseInOut, animations: { for button in self.colorButtons { button.frame.origin.y = self.view.bounds.height - 58 } sender.frame.origin.y -= 20 }, completion: nil) canvas.color = sender.backgroundColor! shapeButton.color = sender.backgroundColor! } @IBAction func selectShape(sender: ShapeButton) { let title = "Select Shape" let alertController = UIAlertController(title: title, message: nil, preferredStyle: .ActionSheet) for shape in shapes { let action = UIAlertAction(title: shape.rawValue, style: .Default) { action in sender.shape = shape self.canvas.shape = shape } alertController.addAction(action) } presentViewController(alertController, animated: true, completion: nil) } } </code></pre> <p>ShapeButton class:</p> <pre><code>import UIKit class ShapeButton: UIButton { let shapes: [ShapeType] = [ .Line, .Ellipse, .Rectangle, .FilledEllipse, .FilledRectangle, .Scribble ] var shape: ShapeType = .Line { didSet { setNeedsDisplay() } } var color: UIColor = UIColor.blueColor() { didSet { setNeedsDisplay() } } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextSetFillColorWithColor(context, color.CGColor) CGContextSetLineWidth(context, 2) let x1: CGFloat = 5 let y1: CGFloat = 5 let x2: CGFloat = frame.width - 5 let y2: CGFloat = frame.height - 5 let rect = CGRect(x: x1, y: y1 + 5, width: frame.width - 10, height: frame.height - 20) switch shape { case .Line: CGContextMoveToPoint(context, x1, y1) CGContextAddLineToPoint(context, x2, y2) CGContextStrokePath(context) case .Ellipse: CGContextStrokeEllipseInRect(context, rect) case .Rectangle: CGContextStrokeRect(context, rect) case .FilledEllipse: CGContextFillEllipseInRect(context, rect) case .FilledRectangle: CGContextFillRect(context, rect) case .Scribble: CGContextMoveToPoint(context, x1, y1) CGContextAddCurveToPoint(context, x1 + 80, y1 - 10, // the 1st control point x2 - 80, y2 + 10, // the 2nd control point x2, y2) // the end point CGContextStrokePath(context) } } } </code></pre> <p>Canvas view class:</p> <pre><code>import UIKit /* This program is for Xcode 6.3 and Swift 1.2 */ class CanvasView: UIView { var shape: ShapeType = .Line var color: UIColor = UIColor.blueColor() var first :CGPoint = CGPointZero var last :CGPoint = CGPointZero var points: [CGPoint] = [] // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextSetFillColorWithColor(context, color.CGColor) let rect = CGRect(x: first.x, y: first.y, width: last.x - first.x, height: last.y - first.y) switch shape { case .Line: CGContextMoveToPoint(context, first.x, first.y) CGContextAddLineToPoint(context, last.x, last.y) CGContextStrokePath(context) case .Ellipse: CGContextStrokeEllipseInRect(context, rect) case .Rectangle: CGContextStrokeRect(context, rect) case .FilledEllipse: CGContextFillEllipseInRect(context, rect) case .FilledRectangle: CGContextFillRect(context, rect) case .Scribble: CGContextMoveToPoint(context, first.x, first.y) for p in points { CGContextAddLineToPoint(context, p.x, p.y) } CGContextStrokePath(context) } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { first = touch.locationInView(self) last = first points.removeAll(keepCapacity: true) if shape == .Scribble { points.append(first) } setNeedsDisplay() } } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { last = touch.locationInView(self) if shape == .Scribble { points.append(last) } setNeedsDisplay() } } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if let touch = touches.first { last = touch.locationInView(self) if shape == .Scribble { points.append(last) } setNeedsDisplay() } } override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { } } </code></pre> |
30,077,156 | 0 | <p>Try this code</p> <pre><code>var trArray = []; $('#tbPermission tr').each(function () { var tr =$(this).text(); //get current tr's text var tdArray = []; $(this).find('td').each(function () { var td = $(this).text(); //get current td's text var items = {}; //create an empty object items[tr] = td; // add elements to object tdArray.push(items); //push the object to array }); }); </code></pre> <p>Here, I just created an empty object, filled object with references of tr and td, the added that object to the final array.</p> <p>adding a working <a href="https://jsfiddle.net/kp89fd74/" rel="nofollow">jsfiddle</a></p> |
37,700,393 | 0 | Using Draft.js with Reagent <p>Does anyone have any luck adapting Draft.js for Reagent? There's pretty heavy editing issues if Draft.js is imported right away via <code>reagent/adapt-react-class</code>. Cursor jumps, disappearing symbols when you're typing, <code>onChange</code> calls with incorrect <code>EditorState</code>, you name it.</p> <p>People are reporting problems like this in clojurians/reagent Slack channel, but it seems there's no solution so far.</p> <p>Any help would be greatly appreciated.</p> |
4,432,210 | 0 | <p>Appears to function as design.</p> |
22,284,644 | 0 | <p>I got it to compile just fine with MinGW using the following script:</p> <pre><code>del *.o winurl.exe windres winurl.rc winurlres.o gcc -c winurl.c gcc -o winurl.exe winurl.o winurlres.o C:\MinGW\lib\libgdi32.a -mwindows strip winurl.exe del *.o </code></pre> |
30,128,784 | 0 | <p>You will want to call gapi.auth.init. See the docs here: <a href="https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauthinit" rel="nofollow">https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauthinit</a></p> <blockquote> <p>Initializes the authorization feature. Call this when the client loads to prevent popup blockers from blocking the auth window on gapi.auth.authorize calls.</p> </blockquote> |
40,739,479 | 0 | <p>Okay, @Arnold I'm not sure that I fully understand your question, but in case it helps, you could use the <code>background-size</code> and <code>background-repeat</code> properties, for example:</p> <pre><code><div style="background-image: url('file.png'); background-size: x% y%; background-repeat: repeat-x;"> </code></pre> <p>Where x and y are percentages that represent the width and the height, respectively. So if you have an image that is portrait (taller than it is wide), set y to 100% and x to a percentage evenly divisible by 100% that best represents the aspect ratio (so something like 10, 20, 25, 33.3, 50%). This way, your image will repeat evenly along the x-axis, but won't need to on the y because it's taking up 100% of the element height.</p> <p>(Conversely, if the image is landscape (wider than it is tall), x would be 100% and y would be divisible by 100 and use <code>repeat-y</code> instead of <code>repeat-x</code>.)</p> <p>This might take some tinkering and depends on whether the image is something that will look ok with its aspect ratio being off somewhat. It may or may not be the solution you need, but I figured it's worth a shot.</p> |
37,391,424 | 0 | <p>Use something similar:</p> <pre><code>if (pass1.value && pass2.value && pass1.value == pass2.value) { pass2.style.backgroundColor = goodColor; message.style.color = goodColor; message.innerHTML = "Passwords Match!" $("#submit").prop("disabled", false); } else { pass2.style.backgroundColor = badColor; message.style.color = badColor; message.innerHTML = "Passwords Do Not Match!" $("#submit").prop("disabled", true); } </code></pre> <p>I added two length checks (if value is <code>""</code> it is evaluated as false), and added the <code>#prop()</code> call to enable the button, when the two strings match.</p> |
6,478,410 | 0 | <p>If I have not wrongly misinterpreted your question, then here is what you want to do - </p> <ul> <li>Extract a .tgz file which may have more .tgz files within it that needs further extraction (and so on..) </li> <li>While extracting, you need to be careful that you are not replacing an already existing directory in the folder.</li> </ul> <p>If I have correctly interpreted your problem, then...<br> Here is what my code does - </p> <ul> <li>Extracts every .tgz file (recursively) in a separate folder with the same name as the .tgz file (without its extension) in the same directory.</li> <li>While extracting, it makes sure that it is not overwriting/replacing any already existing files/folder.</li> </ul> <p>So if this is the directory structure of the .tgz file - </p> <pre><code>parent/ xyz.tgz/ a b c d.tgz/ x y z a.tgz/ # note if I extract this directly, it will replace/overwrite contents of the folder 'a' m n o p </code></pre> <p>After extraction, the directory structure will be - </p> <pre><code>parent/ xyz.tgz xyz/ a b c d/ x y z a 1/ # it extracts 'a.tgz' to the folder 'a 1' as folder 'a' already exists in the same folder. m n o p </code></pre> <p>Although I have provided plenty of documentation in my code below, I would just brief out the structure of my program. Here are the functions I have defined - </p> <pre><code>FileExtension --> returns the extension of a file AppropriateFolderName --> helps in preventing overwriting/replacing of already existing folders (how? you will see it in the program) Extract --> extracts a .tgz file (safely) WalkTreeAndExtract - walks down a directory (passed as parameter) and extracts all .tgz files(recursively) on the way down. </code></pre> <p>I cannot suggest changes to what you have done, as my approach is a bit different. I have used <code>extractall</code> method of the <code>tarfile</code> module instead of the bit complicated <code>extract</code> method as you have done. (Just have glance at this - <a href="http://docs.python.org/library/tarfile.html#tarfile.TarFile.extractall" rel="nofollow">http://docs.python.org/library/tarfile.html#tarfile.TarFile.extractall</a> and read the warning associated with using <code>extractall</code> method. I don`t think we will be having any such problem in general, but just keep that in mind.)</p> <p>So here is the code that worked for me -<br> (I tried it for <code>.tar</code> files nested 5 levels deep (ie <code>.tar</code> within <code>.tar</code> within <code>.tar</code> ... 5 times), but it should work for any depth* and also for <code>.tgz</code> files.)</p> <pre><code># extracting_nested_tars.py import os import re import tarfile file_extensions = ('tar', 'tgz') # Edit this according to the archive types you want to extract. Keep in # mind that these should be extractable by the tarfile module. def FileExtension(file_name): """Return the file extension of file 'file' should be a string. It can be either the full path of the file or just its name (or any string as long it contains the file extension.) Examples: input (file) --> 'abc.tar' return value --> 'tar' """ match = re.compile(r"^.*[.](?P<ext>\w+)$", re.VERBOSE|re.IGNORECASE).match(file_name) if match: # if match != None: ext = match.group('ext') return ext else: return '' # there is no file extension to file_name def AppropriateFolderName(folder_name, parent_fullpath): """Return a folder name such that it can be safely created in parent_fullpath without replacing any existing folder in it. Check if a folder named folder_name exists in parent_fullpath. If no, return folder_name (without changing, because it can be safely created without replacing any already existing folder). If yes, append an appropriate number to the folder_name such that this new folder_name can be safely created in the folder parent_fullpath. Examples: folder_name = 'untitled folder' return value = 'untitled folder' (if no such folder already exists in parent_fullpath.) folder_name = 'untitled folder' return value = 'untitled folder 1' (if a folder named 'untitled folder' already exists but no folder named 'untitled folder 1' exists in parent_fullpath.) folder_name = 'untitled folder' return value = 'untitled folder 2' (if folders named 'untitled folder' and 'untitled folder 1' both already exist but no folder named 'untitled folder 2' exists in parent_fullpath.) """ if os.path.exists(os.path.join(parent_fullpath,folder_name)): match = re.compile(r'^(?P<name>.*)[ ](?P<num>\d+)$').match(folder_name) if match: # if match != None: name = match.group('name') number = match.group('num') new_folder_name = '%s %d' %(name, int(number)+1) return AppropriateFolderName(new_folder_name, parent_fullpath) # Recursively call itself so that it can be check whether a # folder named new_folder_name already exists in parent_fullpath # or not. else: new_folder_name = '%s 1' %folder_name return AppropriateFolderName(new_folder_name, parent_fullpath) # Recursively call itself so that it can be check whether a # folder named new_folder_name already exists in parent_fullpath # or not. else: return folder_name def Extract(tarfile_fullpath, delete_tar_file=True): """Extract the tarfile_fullpath to an appropriate* folder of the same name as the tar file (without an extension) and return the path of this folder. If delete_tar_file is True, it will delete the tar file after its extraction; if False, it won`t. Default value is True as you would normally want to delete the (nested) tar files after extraction. Pass a False, if you don`t want to delete the tar file (after its extraction) you are passing. """ tarfile_name = os.path.basename(tarfile_fullpath) parent_dir = os.path.dirname(tarfile_fullpath) extract_folder_name = AppropriateFolderName(tarfile_name[:\ -1*len(FileExtension(tarfile_name))-1], parent_dir) # (the slicing is to remove the extension (.tar) from the file name.) # Get a folder name (from the function AppropriateFolderName) # in which the contents of the tar file can be extracted, # so that it doesn't replace an already existing folder. extract_folder_fullpath = os.path.join(parent_dir, extract_folder_name) # The full path to this new folder. try: tar = tarfile.open(tarfile_fullpath) tar.extractall(extract_folder_fullpath) tar.close() if delete_tar_file: os.remove(tarfile_fullpath) return extract_folder_name except Exception as e: # Exceptions can occur while opening a damaged tar file. print 'Error occured while extracting %s\n'\ 'Reason: %s' %(tarfile_fullpath, e) return def WalkTreeAndExtract(parent_dir): """Recursively descend the directory tree rooted at parent_dir and extract each tar file on the way down (recursively). """ try: dir_contents = os.listdir(parent_dir) except OSError as e: # Exception can occur if trying to open some folder whose # permissions this program does not have. print 'Error occured. Could not open folder %s\n'\ 'Reason: %s' %(parent_dir, e) return for content in dir_contents: content_fullpath = os.path.join(parent_dir, content) if os.path.isdir(content_fullpath): # If content is a folder, walk it down completely. WalkTreeAndExtract(content_fullpath) elif os.path.isfile(content_fullpath): # If content is a file, check if it is a tar file. # If so, extract its contents to a new folder. if FileExtension(content_fullpath) in file_extensions: extract_folder_name = Extract(content_fullpath) if extract_folder_name: # if extract_folder_name != None: dir_contents.append(extract_folder_name) # Append the newly extracted folder to dir_contents # so that it can be later searched for more tar files # to extract. else: # Unknown file type. print 'Skipping %s. <Neither file nor folder>' % content_fullpath if __name__ == '__main__': tarfile_fullpath = 'fullpath_path_of_your_tarfile' # pass the path of your tar file here. extract_folder_name = Extract(tarfile_fullpath, False) # tarfile_fullpath is extracted to extract_folder_name. Now descend # down its directory structure and extract all other tar files # (recursively). extract_folder_fullpath = os.path.join(os.path.dirname(tarfile_fullpath), extract_folder_name) WalkTreeAndExtract(extract_folder_fullpath) # If you want to extract all tar files in a dir, just execute the above # line and nothing else. </code></pre> <p>I have not added a command line interface to it. I guess you can add it if you find it useful.</p> <p>Here is a slightly better version of the above program -<br> <a href="http://guanidene.blogspot.com/2011/06/nested-tar-archives-extractor.html" rel="nofollow">http://guanidene.blogspot.com/2011/06/nested-tar-archives-extractor.html</a></p> |
39,453,810 | 0 | <p>Have you added this to your manifest?</p> <pre><code><manifest ... > <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> ... </manifest> </code></pre> <p>Also, to be sure you have enable the location update in your phone setting, you can prompt the user to enable it <a href="https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi" rel="nofollow"><strong>using this method</strong></a></p> |
8,625,308 | 0 | <pre><code>var months = new Array("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"); var ddSplit = '12/23/2011'.split('/'); //date is mm/dd/yyyy format alert(ddSplit[1]+'-'+months[ddSplit[0]-1] + '-' + ddSplit[2]) </code></pre> |
18,072,451 | 0 | How to get id from selecting its value in spinner? <p>I want to get the id of the value selected in the spinner who's value is derived from Sqlite.</p> <p>My table in Sqlite is </p> <p>CITY_ID CITY_NAME <BR></p> <p>8 BOMBAY <BR> 9 NEW DELHI <BR> 10 MADRAS <BR> 11 CALCUTTA <BR> 12 BANGLORE <BR> 13 AHMEDABAD <BR> 14 JAIPUR <BR> 15 CHANDIGARH <BR> 16 SIMLA <BR> 17 LUCKNOW <BR> 18 PATNA <BR> 19 BHOPAL <BR> 20 NAGPUR <BR></p> <p>My Database Connector code is</p> <pre><code>public List<String> getCity(){ List<String> labels = new ArrayList<String>(); String selectQuery = "SELECT CITY_ID, CITY_NAME FROM city_list"; Log.d("Destination Country Query", selectQuery); SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { labels.add(cursor.getString(1)); } while (cursor.moveToNext()); } cursor.close(); db.close(); return labels; } </code></pre> <p>My implementation is </p> <pre><code>city = (Spinner) findViewById(R.id.city); loadCityData(); private void loadCityData() { DatabaseConnector db = new DatabaseConnector(getApplicationContext()); List<String> lables = db.getCity(); ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, lables); dataAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); city.setAdapter(dataAdapter); } </code></pre> <p>Now by selecting the City in the spinner. I want to get the id from the SQlite table.</p> <p>Can some one guide me to achieve this.</p> <p>Thanks in advance.</p> <p>Regards, Dinesh</p> |
9,145,911 | 0 | <p>You probably want to move your whiteLine subview initialization to <code>initWithStyle:reusedIdentifier:</code> Currently you set up the alpha before it gets instantiated. Also, you're creating a new view every time drawRect: is called, which definitely is a no-no as well.</p> <p>I'm not currently at the compiler, but something like this should solve your issue:</p> <p>Note that I also added the autorelease call to your whiteLine subview (I assume it is a retained property). You may want to consider using ARC if you're not comfortable with Cocoa Memory Management. Otherwise I suggest re-reading <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html" rel="nofollow">Apple's Memory Management</a> guide and possibly excellent <a href="http://google-styleguide.googlecode.com/svn/trunk/objcguide.xml" rel="nofollow">Google Objective-C Code Style Guide</a></p> <p>In BaseCell.m:</p> <pre><code>- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)identifier { self = [super initWithStyle:style reuseIdentifier:identifier]; if (self) { self.whiteLine = [[[UIView alloc] initWithFrame:CGRectMake(0.0, self.frame.size.height-1.0, self.frame.size.width, 1.0)] autorelease]; self.whiteLine.backgroundColor = [UIColor whiteColor]; [self addSubview:self.whiteLine]; } return self; } - (void)dealloc { self.whiteLine = nil; [super dealloc]; } - (void)rowIsOdd:(BOOL)isOdd { self.whiteLine.alpha = (isOdd ? 0.7 : 0.3); } </code></pre> |
14,363,994 | 0 | Android debuggable=false causing jQuery.ajax POST to fail in Cordova/Phonegap Eclipse project <p>I have an Android app built in Eclipse which uses Cordova 2.0.0. When built and loaded onto the phone using the Eclipse debugger the app works fine, but when I set android:debuggable="false" in the AndroidManifest file the jQuery.ajax() POST fails. I get nothing to tell me the failure reason in the LogCat trace.</p> <p>Here's the jQuery.ajax call:</p> <pre><code>jQuery.ajax({ url: that.endpoint, data: that.data, dataType: "json", type: "POST", contentType: "application/json", success: successHandler, error: errorHandler, timeout: serviceTimeout }); </code></pre> <p>When android:debuggable="true" it works fine and goes to the success handler, but when it android:debuggable="false" it goes to the failureHandler, with only textStatus set to "error" and nothing else to indicate why it failed. When it fails it appears that the post doesn't happen because I can see that it doesn't hit the webservice I am trying to call.</p> <p>Does anyone have any ideas why the debuggable flag might be affecting my application in this way? </p> <p>What else other than the logging level would the "debuggable" flag affect?</p> <p>Any hints or pointers would be greatly appreciated.</p> <p>Cheers</p> |
22,050,293 | 0 | <p>You're very close actually:</p> <pre><code>columns.Bound(property => property.neatProperty).Width(38).EditorTemplateName("neatPropertyDropDownList").Title("NeatProperty") </code></pre> <p>And then in a separate view called "neatPropertyDropDownList.cshtml"</p> <pre><code>@using System.Collections; @(Html.Kendo().DropDownList() .Name("NeatProperty") .DataTextField("Value") .DataValueField("Text") .BindTo("don't forget to bind!") ) </code></pre> |
32,644,740 | 0 | <p>If you want to generate a view with multiple model objects then you need to create a ViewModel comprising properties that are needed from those models. And then reference the view with this ViewModel.</p> <pre><code>public class Model1 { public string prop11 { get; set; } public string prop12 { get; set; } } public class Model2 { public string prop21 { get; set; } public string prop22 { get; set; } } public class ViewModel { public List<Model1> model1 { get; set; } public List<Model2> model2 { get; set; } } </code></pre> <p>Then generate the view referencing the viewmodel that will get the properties from both models.</p> <p>controller action that will be hit from that view:</p> <pre><code>public ActionResult Test(ModelView modelView) // you can access the viewmodel properties </code></pre> |
34,349,524 | 0 | getting error no implicit conversion of sequel <p>how to do below query in ruby sequel </p> <pre><code>table1.column1 = concat('a' + table2.column2 + 'b') </code></pre> <p>without 'a' </p> <pre><code>sequel.qualify(:table1, :column1) = concat(sequel.qualify(:table2, :column2) + 'b') </code></pre> <p>wokring properly.when adding 'a' also getting </p> <blockquote> <p>TypeError: no implicit conversion of Sequel::SQL::StringExpression into String /root/test/test.rb:13:in `+'</p> </blockquote> |
814,891 | 0 | <p>So one could make a custom control but for my app it isn't really worth the trouble.</p> <p>What I did was to create a DataGrid, made it resemble a ListView but with its own flare. I did this because the DataGrid already has a buttoncontrol built in to its cells.</p> <p>Yes I know, kind of fugly "hack", but it works like a charm! :)</p> <p>Props to Shay Erlichmen who led me into thinking outsite my ListBox. See what I did there? ;)</p> |
27,519,683 | 0 | <p>The <code>input[type=file]</code> is a native browser object and can't be changed within.</p> <p>What you can try and do is create a custom wrapper.</p> |
10,398,362 | 0 | Membership system <p>can anyone suggest a good membership structure?</p> <p>For example, user paid for 1 month membership, starting 1.2.2012 ending 1.3.2012.</p> <p>When and where is the best way to check if user is still a member or not?</p> <p>Users are ranked with numbers in database (1-regular 2-member 3-moderator). </p> |
13,918,646 | 0 | presentRenderbuffer using memory? <p>I have simple drawing code like the following - repeated calls to draw several objects, followed by one call to glBindRenderbufferOES and one call to presentRenderbuffer - </p> <p>Objects draw fine, BUT - the call to presentRenderBuffer allocates a good amount of memory with each call </p> <p>I've generated and bound frame and render buffers - once - then never really do anything with them after that - </p> <p>Should I be clearing my buffers after each call to presentRenderBuffer? Or is there some other way to give back memory after calling?</p> <pre><code>// these four calls made for each object Loop over objects glVertexPointer(3, GL_FLOAT, 0, ... glTexCoordPointer(2, GL_FLOAT, ... glNormalPointer(GL_FLOAT, 0, ... glDrawArrays(GL_TRIANGLES, 0,... // then, one-time call to these glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer); [context presentRenderbuffer:GL_RENDERBUFFER_OES]; </code></pre> |
11,895,514 | 0 | <p>you need to add this <code>"$(SDKROOT)/usr/include/libxml2"</code> in your <code>header search paths</code> and it will solve your problem!</p> |
15,336,162 | 0 | Shared_Ptr eates the performance of my application <p>I'm on Ubuntu, and I'm working on a computer vision application (optical flow), and I'm doing some profiling on the code using valgrind. After profiling, I found that the shared_ptr is taking 74% of the application. Kindly find the attached code that where the shared_ptr is used. I'm looking for an optimization for that. Besides that, also sprintf takes so much time, and the openMP threads also eats a lot. I'm really wondering about sprinft, and openMP cost...</p> <pre><code> int main(int argc, char *argv[]) { //QApplication a(argc, argv); omp_set_dynamic( 0 ); omp_set_num_threads( 4 ); double t1, t2; // ------------- Initialization: Frames. -------------- // Load first image char imFName[1024]; sprintf( imFName, "%s/img_%08i.png", imPath.c_str(), imIndex ); ifstream fileExists( imFName ); if (!fileExists) { printf("First image %s/img_%08i.png could not be loaded!", imPath.c_str(), imIndex); return -1; } QImagePtr prevImg; QImagePtr curImg( new QImage( QString(imFName) ) ); } </code></pre> |
17,220,286 | 0 | <p>It would be pretty easy to have an external system (simple .Net app) that collects the new tickets and "synchronizes" them to CRM with a tool like Scribe/CozyRoc. </p> <p>I'm not sure if this type of "system-to-system" integration would permit standard licensing however. I have heard of Microsoft give very good deals on ESS CALs and/or granting permitted use for similar situations.</p> |
36,987,550 | 0 | How to Clear all the list view items of a Static Custom list view in android? <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>package com.donateblood.blooddonation; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; /** * Created by YouCaf Iqbal on 4/6/2016. */ public class MainGUI extends AppCompatActivity { public static ArrayList<DonorPerson> Donors = new ArrayList<DonorPerson>(); @InjectView(R.id.findppl) Button _findButton; GPSTracker gps; String bloodgroup=null; private double latitude; private double longitude; DB db; String test=""; DBCursor cursor; DBCollection collection; Database dataobj = new Database(); ArrayList allPPLlat = new ArrayList(); ArrayList allPPLlong = new ArrayList(); ArrayList allPPLNumbers = new ArrayList(); ArrayList allPPLNames = new ArrayList(); ArrayList allPPLImages = new ArrayList(); ArrayList allPPLEmails = new ArrayList(); ArrayList SelectedPPLlat = new ArrayList(); ArrayList SelectedPPLlong = new ArrayList(); public Spinner mySpinner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.maingui); ButterKnife.inject(this); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Spinner spinner =(Spinner) findViewById(R.id.spinner); String[] list = getResources().getStringArray(R.array.blood_type); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,list); spinner.setAdapter(adapter); _findButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getCurrentLatLong(); dbAsync thrd = new dbAsync(); thrd.execute(); } //distance=Distance(lablat, lablong, curlat, curlong); }); } public void getCurrentLatLong(){ gps = new GPSTracker(MainGUI.this); if (gps.canGetLocation()) { latitude = gps.getLatitude(); longitude = gps.getLongitude(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId()==android.R.id.home){ finish(); } return super.onOptionsItemSelected(item); } public class dbAsync extends AsyncTask<Void,Void,Void>{ private ProgressDialog pDialog; @Override protected Void doInBackground(Void... voids) { getOtherLatLong(); return null; } @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainGUI.this); pDialog.setMessage("Searching people nearby..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); pDialog.dismiss(); Intent intent = new Intent(getApplicationContext(), PeopleList.class); startActivity(intent); // Toast.makeText(getBaseContext(), "Near by latitudes "+SelectedPPLlat, Toast.LENGTH_LONG).show(); // Toast.makeText(getBaseContext(), "Near by longitudes "+SelectedPPLlong, Toast.LENGTH_LONG).show(); } } public void getOtherLatLong() { db = dataobj.getconnection(); collection = db.getCollection("UserDetails"); //mySpinner=(Spinner) findViewById(R.id.spinner); //bloodgroup = mySpinner.getSelectedItem().toString(); // BasicDBObject whereQuery = new BasicDBObject(); //whereQuery.put("employeeId", 5); cursor = collection.find(); while (cursor.hasNext()) { DBObject doc = cursor.next(); // Lats longs used in the next for Loop for calculation distances allPPLlat.add(doc.get("lat")); allPPLlong.add(doc.get("long")); // All these other arraylists are used to store object of a donor person allPPLNumbers.add(doc.get("number").toString()); allPPLNames.add(doc.get("Name").toString()); allPPLImages.add(doc.get("image").toString()); allPPLEmails.add(doc.get("email").toString()); } for(int i =0;i<allPPLlat.size();i++){ double Dist= Distance((double)allPPLlat.get(i),(double)allPPLlong.get(i),latitude,longitude); Dist=Dist/1000; if(Dist<20){ Donors.add(new DonorPerson(""+allPPLNames.get(i)+"", ""+allPPLEmails.get(i)+"" ,""+allPPLNumbers.get(i)+"" ,""+allPPLImages.get(i)+"")); } } } public double Distance(double lat1, double lon1, double lat2, double lon2) { double R = 6371.0; // km double dLat = (lat2 - lat1) * Math.PI / 180.0; double dLon = (lon2 - lon1) * Math.PI / 180.0; lat1 = lat1 * Math.PI / 180.0; lat2 = lat2 * Math.PI / 180.0; double a = Math.sin(dLat / 2.0) * Math.sin(dLat / 2.0) + Math.sin(dLon / 2.0) * Math.sin(dLon / 2.0) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); double d = R * c; return d * 1000; // return distance in m } }</code></pre> </div> </div> </p> <p>I have a static custom view called <code>Donors</code> declared in one of my classes called <code>MainGUI</code>. Whenever the list is displayed and I go back and reopen the list, the same list items appear twice. I know this happens because the list items are being added to the listview again when I display it without clearing all the data items shown before. What I want is a way to remove all the existing data items when I reopen the list, so that the items are not duplicated when i access it again.</p> <pre><code>public class PeopleList extends AppCompatActivity { @Override public void onBackPressed() { MainGUI.Donors.clear(); // Clear all the Donors after search // this.notifyDatasetChanged(); super.onBackPressed(); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.peoplelistview); getSupportActionBar().setDisplayHomeAsUpEnabled(true); populateListView(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId()==android.R.id.home){ // MainGUI.Donors.clear(); // Clear all the Donors after search finish(); } return super.onOptionsItemSelected(item); } private void populateListView() { ArrayAdapter<DonorPerson> adapter = new MyListAdapter(); ListView list = (ListView) findViewById(R.id.DonorsListView); list.setAdapter(adapter); } private class MyListAdapter extends ArrayAdapter<DonorPerson> { public MyListAdapter() { super(PeopleList.this, R.layout.singlelistitemview,MainGUI.Donors); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Make sure we have a view to work with (may have been given null) View itemView = convertView; if (itemView == null) { itemView = getLayoutInflater().inflate(R.layout.singlelistitemview, parent, false); } // Find the Donor to work with. DonorPerson currentPerson = MainGUI.Donors.get(position); //Set the Image of the Current Donor ImageView DonorImage = (ImageView)itemView.findViewById(R.id.image); //currentPerson.getImage(); byte[] decodedString = Base64.decode(currentPerson.getImage(), Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); DonorImage.setImageBitmap(decodedByte); //imageView.setImageResource(currentPerson.getIconID()); /* Fill the view ImageView imageView = (ImageView)itemView.findViewById(R.id.item_icon); imageView.setImageResource(currentCar.getIconID()); */ return itemView; } } } </code></pre> |
19,990,356 | 0 | how to parse multiple file names and get relevant information in C# asp aspx <p>I've been trying to figure out a way for the program to read all of the files from the path or zip file as input. Than read all of the file names inside of the input folder and split it so I can get information such as what is product id and chip name. Than store the pdf file in the correct db that matches with the product id and chip name. </p> <p>The product id would be KHSA1234C and chip name LK454154.</p> <p>Example File name: N3405-H-KAD_K-KHSA1234C-542164143_LK454154_GFK.pdf</p> <pre><code>public void btnUploadAttach_Click(object sender, EventArgs e) { string fName = this.FileUploadCFC.FileName; string path = @"C:\mydir\"; string result; result = Path.GetFileNameWithoutExtension(fName); Console.WriteLine("GetFileNameWithoutExtension('{0}') return '{1}'", fName, result); result = Path.GetFileName(path); Console.WriteLine("GetFileName('{0}') return '{1}'", path, result); string[] sSplitFileName = fName.ToUpper().Split("-".ToCharArray()); foreach (char file in fName) { try { result = sSplitFileName[0] + "_" + sSplitFileName[1] + "-" + sSplitFileName[2] + "_" + sSplitFileName[3] + "_" + sSplitFileName[4] + "_" + sSplitFileName[5] + "_" + sSplitFileName[6]; } catch { return; } } } </code></pre> <p>I don't know if I'm on the right track or not. Can someone help me? Thank you.</p> |
533,370 | 0 | <p><code>Thread.Abort</code> will close the thread, of course, as it will call Win32 <a href="http://msdn.microsoft.com/en-us/library/ms686717(VS.85).aspx" rel="nofollow noreferrer"><code>TerminateThread</code></a>.</p> <p>Outcome of this action will depend on how your <code>API</code> likes to be closed by <code>TerminateThread</code>.</p> <p>If your method is called somthing like <code>NuclearPlant.MoveRod()</code> or <code>Defibrillator.Shock()</code>, I'd rather wait these 30 seconds.</p> <p>This method gives no chance to the victim to do some cleanup:</p> <blockquote> <p><code>TerminateThread</code> is used to cause a thread to exit. When this occurs, <em>the target thread has no chance to execute any user-mode code</em>. DLLs attached to the thread are not notified that the thread is terminating. The system frees the thread's initial stack.</p> </blockquote> <p>As stated in <code>MSDN</code>:</p> <blockquote> <p><code>TerminateThread</code> is a dangerous function that should only be used in the most extreme cases. You should call <code>TerminateThread</code> only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, <code>TerminateThread</code> can result in the following problems:</p> <ul> <li>If the target thread owns a critical section, the critical section will not be released.</li> <li>If the target thread is allocating memory from the heap, the heap lock will not be released.</li> <li>If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.</li> <li>If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.</li> </ul> </blockquote> |
34,706,311 | 0 | why does every process(or any address space) has its own page table? <ol> <li><p>Why does every process (or any address space) have its own page table? </p> <ul> <li>I think that if we use a single page table for all processes, then a process can access the address apace of other processes so we need a separate page table for each process. This means the pages which actually belong to a particular process will be valid and all other pages which belong to some other's address space will be marked invalid. Am I correct? </li> <li>If yes, then why didn't we add one more field as "process ID" to the page table to distinguish the address space of every process?</li> <li>If not, why does every process (or any address space) have its own page table?</li> </ul></li> <li><p>How can multilevel paging reduce the size of the page table?</p> <ul> <li>Because we added some more page tables (in multilevel paging) as overhead, and the actual page table is also in main memory</li> </ul></li> <li><p>Suppose we did 3 levels of paging as 1 (closer to CPU)->2->3; so we have three page tables for each level. What information is included in each page table? I am worried about 3rd level page table which contains the actual frame number where data resides. Now which page tables are used by processes?</p> <ul> <li>All??? Then the 3rd level page table which contains the actual frames should be of the same size as the original page table (without multilevel) because it must have entries for all frames which are used by physical memory too.</li> </ul></li> </ol> |
6,544,387 | 0 | <p>I think you have to see Density Considerations for Preventing from Scaling.</p> <p>The easiest way to avoid pre-scaling is to <code>put the resource in a resource directory</code> with the nodpi configuration qualifier. For example:</p> <pre><code>res/drawable-nodpi/icon.png </code></pre> <p>When the system uses the icon.png bitmap from this folder, it does not scale it based on the current device density.</p> <p>From <a href="http://developer.android.com/guide/practices/screens_support.html#DensityConsiderations" rel="nofollow">http://developer.android.com/guide/practices/screens_support.html#DensityConsiderations</a></p> |
38,984,063 | 0 | <p>This is common phenomena occurring if the class frequencies are unbalanced, e.g. nearly all samples belong to one class. For examples if 80% of your samples belong to class "No", then classifier will often tend to predict "No" because such a trivial prediction reaches the highest overall accuracy on your train set. </p> <p>In general, when evaluating the performance of a binary classifier, you should not only look at the overall accuracy. You have to consider other metrics such as the ROC Curve, class accuracies, f1 scores and so on.</p> <p>In your case you can use sklearns <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html" rel="nofollow">classification report</a> to get a better feeling what your classifier is actually learning:</p> <pre><code>from sklearn.metrics import classification_report print(classification_report(y_test, model_1.predict(X_test))) print(classification_report(y_test, model_2.predict(X_test))) </code></pre> <p>It will print the precision, recall and accuracy for every class. </p> <p>There are three options on how to reach a better classification accuracy on your class "Yes"</p> <ul> <li>use sample weights, you can increase the importance of the samples of the "Yes" class thus forcing the classifier to predict "Yes" more often</li> <li>downsample the "No" class in the original X to reach more balanced class frequencies </li> <li>upsample the "Yes" class in the original X to reach more balanced class frequencies</li> </ul> |
15,005,825 | 0 | <p>How about putting the Direction and Type as members of the enum, something like this:</p> <pre><code>public enum State { ONE_STATE(Direction.LEFT, Type.BIG), SECOND_STATE(Direction.RIGHT, Type.SMALL); THIRD_STATE(Direction.UP, Type.SMALL); private Direction direction; private Type type; private State(Direction direction, Type type) { this.direction = direction; this.type = type; } public static State getState(Direction dir, Type type) { for (State state : values()) { if (state.direction == dir && state.type == type) { return state; } } return THIRD_STATE; } } </code></pre> <p>Note that this will not work if there is more than one different combination for each enum. In that case, you will need to use some sort of lookup table as suggested by another poster. For example, you could use a <code>Map<Pair<Direction, Type>, State></code>. (Java doesn't have a <code>Pair<T, U></code> class, but you can easily make one or find one in lots of different libraries.)</p> |
21,228,301 | 0 | <p>Another point is Elasticache is dynamic , you can decrease/increase the memory you use dynamically, or even close the cache(and save $$) if your performance indexes are in the green.</p> |
28,649,728 | 0 | Devexpress LookUpEdit - serach second column by value meber <p>I want to know it is posible to filters **LookUpEdit ** dropdown list by the column that corresponds to the ValueMember value. </p> <pre><code> LookUpEdit.DataSource = ds.Tables(0) LookUpEdit.ValueMember = ds.Tables(0).Columns("VALUE").Caption.ToString LookUpEdit.DisplayMember = ds.Tables(0).Columns("DISPLAYtext").Caption.ToString LookUpEdit.View.FocusedRowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle LookUpEdit.AllowFocused = True LookUpEdit.CloseUpKey = New KeyShortcut(Keys.Add) LookUpEdit.NullText = "" </code></pre> <p><strong>I using devexpress 14.2.3. and vb.net</strong></p> |
3,164,525 | 0 | <p>Also you can create something like:</p> <pre><code>public class JqGridJsonData { public int Total {get;set;} public int Page {get;set;} etc } </code></pre> <p>And serialize this to json with Json.NET <a href="http://james.newtonking.com/pages/json-net.aspx" rel="nofollow noreferrer">http://james.newtonking.com/pages/json-net.aspx</a></p> |
10,360,986 | 0 | Classes C++. Multiple inheritance <p>I have a question about multiple inheritance. I have class A. Class A has several inheritors, for instance B,C,D.</p> <p>Class X is inheritor of classes B,C,D How can I pass parameters from the constructor of class X to the constructor of class A? </p> |
31,862,922 | 0 | <p>The same as option #1 from @zessx, but without overriding CSS. This one also aligns labels to the right to increase space between label-control pairs. Class "media" is there to add top margin without creating a custom class, but in general case it is better to have a custom one.</p> <pre><code><div class="form-horizontal"> <legend>Form legend</legend> <div class="media col-xs-12 col-sm-6 col-lg-3"> <label for="InputFieldA" class="control-label text-right col-xs-4">Field A</label> <div class="input-group col-xs-8"> <input type="text" class="form-control" id="InputFieldA" placeholder="InputFieldA"> </div> </div> <div class="media col-xs-12 col-sm-6 col-lg-3"> <label for="InputFieldB" class="control-label text-right col-xs-4">Field B</label> <div class="input-group col-xs-8"> <input type="text" class="form-control" id="InputFieldB" placeholder="InputFieldB"> </div> </div> <div class="media col-xs-12 col-sm-6 col-lg-3"> <label for="InputFieldC" class="control-label text-right col-xs-4">Field C</label> <div class="input-group col-xs-8"> <input type="text" class="form-control" id="InputFieldC" placeholder="InputFieldC"> </div> </div> <div class="media col-xs-12 col-sm-6 col-lg-3"> <button type="submit" class="btn btn-default col-xs-8 col-xs-offset-4">Submit Button</button> </div> </div> </code></pre> <p><a href="http://www.bootply.com/UnBZXGwjcj" rel="nofollow">Bootply</a></p> |
20,753,449 | 0 | <p>To do this, you could e.g. use a <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html" rel="nofollow">bool</a>-query with a <code>should</code> to weigh in a <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-span-first-query.html" rel="nofollow">span_first</a>-query which in turn has a <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-span-multi-term-query.html" rel="nofollow">span_multi</a></p> <p>Here is a runnable example you can play with: <a href="https://www.found.no/play/gist/8107157" rel="nofollow">https://www.found.no/play/gist/8107157</a></p> <pre><code>#!/bin/bash export ELASTICSEARCH_ENDPOINT="http://localhost:9200" # Index documents curl -XPOST "$ELASTICSEARCH_ENDPOINT/_bulk?refresh=true" -d ' {"index":{"_index":"play","_type":"type"}} {"title":"Female"} {"index":{"_index":"play","_type":"type"}} {"title":"Female specimen"} {"index":{"_index":"play","_type":"type"}} {"title":"Microscopic examination of specimen from female"} ' # Do searches # This will match all documents. curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d ' { "query": { "prefix": { "title": { "prefix": "femal" } } } } ' # This matches only the two first documents. curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d ' { "query": { "span_first": { "end": 1, "match": { "span_multi": { "match": { "prefix": { "title": { "prefix": "femal" } } } } } } } } ' # This matches all, but prefers the one's with a prefix match. # It's sufficient that either of these match, but prefer that both matches. curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d ' { "query": { "bool": { "should": [ { "span_first": { "end": 1, "match": { "span_multi": { "match": { "prefix": { "title": { "prefix": "femal" } } } } } } }, { "match": { "title": { "query": "femal" } } } ] } } } ' </code></pre> |
22,882,580 | 0 | Put date range to array <p>I have two JQuery datepicker on my page, I want to put all the days between the two dates to an array.</p> <p>How Can I work it out? Here is my snippet:</p> <pre><code>function mennyi() { var dtFrom = document.getElementById('arrival').value; var dtTo = document.getElementById('departure').value; var dt1 = new Date(dtFrom); var dt2 = new Date(dtTo); var diff = dt2.getDate() - dt1.getDate(); var days = diff; alert(dtTo); document.getElementById("nights").innerHTML = days + " nights"; { $('#arrival').datepicker({ dateFormat: 'dd-mm-yy' }).val(); $('#departure').datepicker({ dateFormat: 'dd-mm-yy' }).val(); var start = new Date(document.getElementById('arrival').value), end = new Date(document.getElementById('departure').value), currentDate = new Date(start), between = [] ; while (end > currentDate) { between.push(new Date(currentDate)); currentDate.setDate(currentDate.getDate() + 1); } $('#lista').html(between.join('<br> '));}; return false; } function isNumeric(val) { var ret = parseInt(val); }; </code></pre> <p>Now it works, but the thing is how can I change the date format, before I put the string into the array? </p> |
24,572,646 | 0 | <p>Just a thought(hadn't tried practically)</p> <pre><code>SELECT * FROM TABLE_NAME having max(na) = na GROUP BY nm_mp </code></pre> <p>If it works or doesn't work, do tell me. Its for all category.</p> <p>For just that two category, try this.</p> <pre><code>SELECT * FROM TABLE_NAME WHERE nm_mp IN('matematika', 'bahasa inggris') having max(na) = na GROUP BY nm_mp </code></pre> |
2,452,414 | 0 | http handlers not working on web server but works on localhost <p>i have a couple of xml files in my asp.net web application that i don't want anyone to access other than my server side code. this is what i tried..</p> <pre><code><add verb="*" path="*.xml" type="System.Web.HttpForbiddenHandler" /> </code></pre> <p>i wrote this inside the <b><httpHandlers></b></p> <p>it works well on the localhost but not in the server... the server without any hesitation displays the xml file... i have no idea how to proceed... </p> <p>thanks in advance..:)</p> <p><b>Update</b>: the server has IIS6, windows server 2003</p> |
15,525,673 | 0 | <p>The code sample you provided will not work. You need to return the new size or pass in the reference to the form object.</p> <pre><code> public void SetFormProperties(Form form){ fprm.Size = new Size(20,20); } SetFormPropertoes(form); </code></pre> <p>OR</p> <pre><code> public Size GetFormSize(){ return new Size(20,20); } from.Size = GetFormSize(); </code></pre> |
18,833,771 | 0 | <p>"android:process" and "android:taskAffinity" allows you to have different processes and affinities within the same package (application). </p> <p>"android:multiprocess" simply means if you want to allow the activity to have a different process-id. This only works within the same app, not when the activity is started from a different a different package. </p> <p>What are you exactly trying to do? If you want to share the same context and private files, you should use sharedUserId instead (you have to sign them using the same certificate as well). </p> |
1,299,551 | 0 | <p>The other answers here are similar but ...</p> <pre><code>Sub DiplayData(rst) Response.Write rst.Source End Sub DisplayData rs1 </code></pre> <p>Note <code>Sub</code> not <code>Function</code> since no value is returned. Also where you call a procedure as statement rather than as a function whose value you are assigning to a variable, do not enclose the parameters in ( ).</p> |
19,191,449 | 0 | iOS FBDialog crashes after clicking on Post <p>I am trying to create a share dialog to post on Facebook the user action. To do that I use this code:</p> <pre><code>id<FBGraphObject> fbObject = [FBGraphObject openGraphObjectForPostWithType:@"namespace:action" title:@"Titolo" image:imageURL url:URL description:@"descrizione"]; id<FBOpenGraphAction> action = (id<FBOpenGraphAction>)[FBGraphObject graphObject]; [action setObject:fbObject forKey:@"samplename"]; [FBDialogs presentShareDialogWithOpenGraphAction:action actionType:@"namespace:action" previewPropertyName:@"samplename" handler:^(FBAppCall *call, NSDictionary *results, NSError *error) { if(error) { NSLog(@"Error: %@", error.description); } else { NSLog(@"Success"); } }]; </code></pre> <p>The fbdialog is correctly displayed, but when I click on "Post" to complete the posting, the progress bar on facebook stops and I am redirected again to my app, so it fails the posting.</p> <p>Everything works fine by posting with the Graph API Explorer but I am not able to do that from the app.</p> |
40,170,934 | 0 | jqueryUI datepicker not showing within ng-if directive of angularjs <p>I have a sample <a href="https://jsfiddle.net/mpsbhat/qx9sxo8w/4/" rel="nofollow">here</a> where date picker is defined as </p> <pre><code><div ng-if="show_d"> <input id="date2" type="text" ng-model="date2"> </div> </code></pre> <p>which is not fires the datepicker if that field is put inside <code>ng-if</code> directive.</p> |
18,166,021 | 0 | <p>If it's just a single input, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.prompt" rel="nofollow">the built-in prompt()</a> method.</p> <p>Otherwise, you would have to <a href="http://stackoverflow.com/questions/6265574/popup-form-using-html-javascript-css">pop up your own form</a>.</p> |
12,156,550 | 0 | <p>if i'd understood your correctly, python example:</p> <pre><code>>>> a=[1,2,3,4,5,6,7,8,9,0] >>> >>> >>> len_a = len(a) >>> b = [1] >>> if len(set(a) - set(b)) < len_a: ... print 'this integer exists in set' ... this integer exists in set >>> </code></pre> <p>math base: <a href="http://en.wikipedia.org/wiki/Euler_diagram" rel="nofollow">http://en.wikipedia.org/wiki/Euler_diagram</a></p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.