id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
19,143,360
Python: Writing to and Reading from serial port
<p>I've read the documentation, but can't seem to find a straight answer on this. I have a list of all COM Ports in use by Modems connected to the computer. From this list, I try to open it, send it a command, and if it says anything back, add it to another list. I'm not entirely sure I'm using pyserial's read and write functions properly. </p> <pre><code>i=0 for modem in PortList: for port in modem: try: ser = serial.Serial(port, 9600, timeout=1) ser.close() ser.open() ser.write("ati") time.sleep(3) print ser.read(64) if ser.read(64) is not '': print port except serial.SerialException: continue i+=1 </code></pre> <p>I'm not getting anything out of ser.read(). I'm always getting blank strings.</p>
19,143,704
2
9
null
2013-10-02 17:44:29.133 UTC
1
2019-11-27 20:25:39.783 UTC
2013-10-02 17:53:11.547 UTC
null
2,816,588
null
2,816,588
null
1
8
python|serial-port|pyserial
140,618
<p><code>ser.read(64)</code> should be <code>ser.read(size=64)</code>; ser.read uses keyword arguments, not positional.</p> <p>Also, you're reading from the port twice; what you probably want to do is this:</p> <pre><code>i=0 for modem in PortList: for port in modem: try: ser = serial.Serial(port, 9600, timeout=1) ser.close() ser.open() ser.write("ati") time.sleep(3) read_val = ser.read(size=64) print read_val if read_val is not '': print port except serial.SerialException: continue i+=1 </code></pre>
8,911,230
What is the function of an asterisk before a function name?
<p>I've been confused with what I see on most C programs that has unfamiliar function declaration for me.</p> <pre><code>void *func_name(void *param){ ... } </code></pre> <p>What does <code>*</code> imply for the function? My understanding about (<code>*</code>) in a variable type is that it creates a pointer to another variable thus it can be able to track what address at which the latter variable is stored in the memory. But in this case of a function, I don't know what this <code>*</code> asterisk implies.</p>
8,911,253
4
6
null
2012-01-18 13:49:57.437 UTC
24
2016-09-22 12:33:35.763 UTC
2016-09-22 12:33:35.763 UTC
null
560,648
null
969,645
null
1
77
c|function|pointers
47,718
<p>The asterisk belongs to the return type, and not to the function name, i.e.:</p> <pre><code>void* func_name(void *param) { . . . . . } </code></pre> <p>It means that the function returns a void <em>pointer</em>.</p>
21,969,851
What is the difference between File.ReadLines() and File.ReadAllLines()?
<p>I have query regarding File.ReadLines() and File.ReadAllLines().what is difference between them. i have text file where it contains data in row-wise.<code>File.ReadAllLines()</code> return array and using <code>File.ReadLines().ToArray();</code> will also i can get same result.So is there any performance difference related to these methods?</p> <pre><code>string[] lines = File.ReadLines("C:\\mytxt.txt").ToArray(); </code></pre> <p>Or</p> <pre><code>string[] lines = File.ReadAllLines("C:\\mytxt.txt"); </code></pre>
21,970,035
3
4
null
2014-02-23 14:58:58.287 UTC
7
2018-06-18 09:44:01.767 UTC
2016-08-15 22:31:18.47 UTC
null
3,769
null
1,118,932
null
1
57
c#|readline|file.readalllines
61,329
<blockquote> <p>is there any performance difference related to these methods?</p> </blockquote> <p><strong>YES</strong> there is a difference </p> <p><code>File.ReadAllLines()</code> method reads the whole file at a time and returns the string[] array, so it takes time while working with large size of files and not recommended as user has to wait untill the whole array is returned.</p> <p><code>File.ReadLines()</code> returns an <code>IEnumerable&lt;string&gt;</code> and it does not read the whole file at one go, so it is really a better option when working with large size files.</p> <p>From <a href="http://msdn.microsoft.com/en-us/library/dd383503%28v=vs.110%29.aspx" rel="noreferrer">MSDN</a>: </p> <blockquote> <p>The ReadLines and ReadAllLines methods differ as follows:</p> <p>When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.</p> </blockquote> <p>Example 1: <code>File.ReadAllLines()</code></p> <pre><code>string[] lines = File.ReadAllLines("C:\\mytxt.txt"); </code></pre> <p>Example 2: <code>File.ReadLines()</code></p> <pre><code>foreach (var line in File.ReadLines("C:\\mytxt.txt")) { //Do something } </code></pre>
10,902,959
How to hide or show a div
<p>I have on my Page_Load registered this</p> <pre><code> Page.ClientScript.RegisterStartupScript(this.GetType(), "clientscript", "document.getElementById('showdiv').style.visibility = 'hidden';", true); </code></pre> <p>But its not getting hidden... My div is as shown below</p> <pre><code>&lt;div id="showdiv"&gt; &lt;input class="button" type="button" value="OK" name="success_button" id="my button" onclick="javascript:window.close();" /&gt; &lt;/div&gt; </code></pre> <p>what am I doing wrong?. Thank you for your help</p>
10,903,791
8
2
null
2012-06-05 18:40:42.397 UTC
null
2017-07-31 15:09:56.043 UTC
2012-06-05 19:17:25.403 UTC
null
819,494
null
1,416,156
null
1
5
c#|javascript|asp.net
59,924
<p>I highly recommend doing this simple client side manipulation (show/hode rows controls, etc.) with JavaScript or even more easily with a .js library like jQuery. After you include the jQuery scripts in your application, this is all you need to do to have that DIV be hidden after the page has completed its initialization. </p> <p>Include this script section at the top of your page or in a referenced .js file if you already have one:</p> <pre><code>&lt;script type="text/javascript"&gt; //$(document).ready is used to define a function that is guaranteed to be called only after the DOM has been initialized. $(document).ready(function () { //Hide the div $('#showdiv').hide(); //conversely do the following to show it again if needed later //$('#showdiv').show(); }); &lt;/script&gt; </code></pre> <p>jQuery API documentation on this method:<br> <a href="http://api.jquery.com/hide/">http://api.jquery.com/hide/</a></p>
10,964,821
Exception caught but program keeps running
<p>I am working on my first Java project implementing a class called "HeartRates" which takes the user's date of birth and returns their max and target heart rate. Everything in the main test program works except for one thing, I can't figure out how to stop the rest of the code from printing after the exception is caught. </p> <p>I am not really sure about the entire portion of code where the exception is caught because it was copied and pasted from what the professor gave us. If anybody can tell me how to terminate the program after an error occurs, or print a custom error message and stop the program from executing further I would appreciate it.</p> <p>Here is the code:</p> <pre><code> import java.util.Scanner; import java.util.GregorianCalendar; import javax.swing.JOptionPane; public class HeartRatesTest { public static void main(String[] args) { HeartRates test= new HeartRates(); Scanner input = new Scanner( System.in ); GregorianCalendar gc = new GregorianCalendar(); gc.setLenient(false); JOptionPane.showMessageDialog(null, "Welcome to the Heart Rate Calculator");; test.setFirstName(JOptionPane.showInputDialog("Please enter your first name: \n")); test.setLastName(JOptionPane.showInputDialog("Please enter your last name: \n")); JOptionPane.showMessageDialog(null, "Now enter your date of birth in Month/Day/Year order (hit enter after each): \n"); try{ String num1= JOptionPane.showInputDialog("Month: \n"); int m= Integer.parseInt(num1); test.setMonth(m); gc.set(GregorianCalendar.MONTH, test.getMonth()); num1= JOptionPane.showInputDialog("Day: \n"); m= Integer.parseInt(num1); test.setDay(m); gc.set(GregorianCalendar.DATE, test.getDay()); num1= JOptionPane.showInputDialog("Year: \n"); m= Integer.parseInt(num1); test.setYear(m); gc.set(GregorianCalendar.YEAR, test.getYear()); gc.getTime(); // exception thrown here } catch (Exception e) { e.printStackTrace(); } String message="Information for "+test.getFirstName()+" "+test.getLastName()+": \n\n"+"DOB: "+ test.getMonth()+"/" +test.getDay()+ "/" +test.getYear()+ "\nAge: "+ test.getAge()+"\nMax Heart Rate: "+test.getMaxHR()+" BPM\nTarget Heart Rate(range): "+test.getTargetHRLow() +" - "+test.getTargetHRHigh()+" BPM"; JOptionPane.showMessageDialog(null, message); } </code></pre>
10,964,835
3
1
null
2012-06-09 21:47:42.6 UTC
3
2012-06-09 22:00:04.237 UTC
2012-06-09 22:00:04.237 UTC
null
369
null
1,383,628
null
1
14
java|exception-handling
57,921
<p>Not really sure why you want to terminate the application after the exception is caught - wouldn't it be better to fix whatever went wrong?</p> <p>In any case, in your catch block:</p> <pre><code>catch(Exception e) { e.printStackTrace(); //if you want it. //You could always just System.out.println("Exception occurred."); //Though the above is rather unspecific. System.exit(1); } </code></pre>
11,276,043
How to add a SearchWidget to the ActionBar?
<p>I'm trying to add a Search-ActionView to my application (as explained here <a href="http://developer.android.com/guide/topics/search/search-dialog.html#UsingSearchWidget" rel="noreferrer">http://developer.android.com/guide/topics/search/search-dialog.html#UsingSearchWidget</a>). Unfortunately I keep getting a NullPointerException and I'm having a hard time detecting what's actually going wrong.</p> <p>I created a searchable config and a searchable activity as shown on the android page. My menu .xml file looks like this:</p> <pre><code>&lt;menu xmlns:android="http://schemas.android.com/apk/res/android" &gt; ... &lt;item android:id="@+id/menu_item_search" android:actionViewClass="android.widget.SearchView" android:icon="@drawable/icon_search" android:showAsAction="always" android:title="@string/action_bar_button_search"&gt; &lt;/item&gt; &lt;/menu&gt; </code></pre> <p>This is the method where the Exception is thrown:</p> <pre><code>public boolean onCreateOptionsMenu( Menu menu ) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate( R.menu.action_bar, menu ); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.menu_item_search).getActionView(); // NullPointerException thrown here; searchView is null. searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(false); return super.onCreateOptionsMenu( menu ); } </code></pre> <p>Complete stack trace:</p> <pre><code>FATAL EXCEPTION: main java.lang.NullPointerException at com.example.activities.Test.onCreateOptionsMenu(Test.java:41) at android.app.Activity.onCreatePanelMenu(Activity.java:2444) at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:408) at com.android.internal.policy.impl.PhoneWindow.invalidatePanelMenu(PhoneWindow.java:759) at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:2997) at android.os.Handler.handleCallback(Handler.java:605) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4507) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557) at dalvik.system.NativeStart.main(Native Method) </code></pre>
11,276,285
7
5
null
2012-06-30 17:16:31.523 UTC
16
2016-09-03 09:45:39.797 UTC
2012-07-20 09:47:18.34 UTC
null
1,493,269
null
1,493,269
null
1
26
android|nullpointerexception|android-actionbar|searchview
48,686
<p>use this way as in <a href="http://www.edumobile.org/android/android-development/action-bar-search-view/" rel="noreferrer">link</a></p> <pre><code>public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.action_bar, menu); MenuItem searchItem = menu.findItem(R.id.menu_item_search); SearchView searchView = (SearchView) searchItem.getActionView(); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); if(null!=searchManager ) { searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); } searchView.setIconifiedByDefault(false); return true; } </code></pre>
11,138,939
How to trigger javascript on print event?
<p>Is it possible to trigger a javascript event when a user prints a page? I would like to remove a dependancy on a javascript library, when a user opts to print a page, as the library is great for screen but not for print.</p> <p>Any idea how to achieve this?</p>
15,713,060
5
5
null
2012-06-21 13:11:18.663 UTC
4
2022-05-17 14:14:57.18 UTC
2012-06-21 14:14:40.587 UTC
null
1,437,962
null
578,667
null
1
31
javascript|browser|printing
48,315
<p>For anyone stumbling upon this answer from Google, let me try to clear things up:</p> <p>As Ajay pointed out, there are two events which are fired for printing, but they are not well-supported; as far as I have read, they are only supported in Internet Explorer and Firefox (6+) browsers. Those events are window.onbeforeprint and window.onafterprint, which (as you'd expect) will fire before and after the print job. </p> <p>However, as pointed out in Joe's link (<a href="https://stackoverflow.com/a/9920784/578667">https://stackoverflow.com/a/9920784/578667</a>), that's not exactly how it is implemented in all cases. In most cases, both events fire before the dialog; in others, script execution might be halted during the print dialog, so both events may fire at the same time (after the dialog has been completed).</p> <p>For more information (and browser support) for these two events:</p> <p><a href="https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeprint" rel="noreferrer">https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeprint</a></p> <p><a href="https://developer.mozilla.org/en-US/docs/DOM/window.onafterprint" rel="noreferrer">https://developer.mozilla.org/en-US/docs/DOM/window.onafterprint</a></p> <p>The short answer: if you're hoping to interfere with the print flow, don't. If you're hoping to trigger code after printing, it's not going to work how you're wanting; expect poor browser support, and try to degrade gracefully.</p>
11,107,263
How compatible are different versions of glibc?
<p>Specifically:</p> <ol> <li><p>Is it assured somehow that all versions of glibc 2.x are binary compatible?</p></li> <li><p>If not, how can I run a binary (game) on my system which has been compiled for a different version? Can I install glibc in a different folder?</p></li> </ol> <p>My specific problem is the compatibility between glibc 2.14 (what I have) and 2.15 (what the game wants).</p> <p>I might also get a version for glibc 2.13 but I'm not sure if that will run on 2.14.</p>
11,108,336
3
0
null
2012-06-19 18:38:48.62 UTC
13
2020-12-11 12:20:32.587 UTC
2012-09-12 07:16:31.127 UTC
null
241,776
null
34,088
null
1
33
installation|shared-libraries|glibc|binary-compatibility
26,198
<p>In general, running binaries that were compiled for an older glibc version (e.g. 2.13) will run fine on a system with a newer glibc (e.g. 2.14, like your system).</p> <p>Running a binary that was built for a newer glibc (e.g. 2.15, like the one that fails) on a system with an older glibc will probably not work.</p> <p>In short, glibc is backward-compatible, not forward-compatible.</p>
12,785,638
Command for opening serial port in Windows 7
<p>Is there a Windows command for opening serial ports, say COM3 via the command prompt in Windows 7? For example:</p> <pre><code>OPEN "COM6" AS #1 </code></pre> <p>I cannot use pyserial or any other utilities that are not distributed with Windows 7.</p> <p><strong>Preferred solution</strong> <a href="https://stackoverflow.com/questions/19317679/opening-a-com-port-in-qbasic-on-windows-7/19860784">Opening a COM port in QBasic on Windows 7</a></p>
12,801,667
2
4
null
2012-10-08 16:26:30.253 UTC
4
2020-03-27 14:33:54.907 UTC
2018-08-03 12:42:39.853 UTC
null
3,826,372
null
181,783
null
1
10
windows|batch-file|cmd|windows-7|serial-port
71,189
<p>Maybe you can use the Powershell? It's included in Win7... </p> <p>code taken from here <a href="http://blogs.msdn.com/b/powershell/archive/2006/08/31/writing-and-reading-info-from-serial-ports.aspx" rel="noreferrer">http://blogs.msdn.com/b/powershell/archive/2006/08/31/writing-and-reading-info-from-serial-ports.aspx</a></p> <p><strong>Writing to a Serial Port</strong></p> <pre><code>PS&gt; [System.IO.Ports.SerialPort]::getportnames() COM3 PS&gt; $port= new-Object System.IO.Ports.SerialPort COM3,9600,None,8,one PS&gt; $port.open() PS&gt; $port.WriteLine("Hello world") PS&gt; $port.Close() </code></pre> <p><strong>Reading from a Serial Port</strong></p> <pre><code>PS&gt; $port= new-Object System.IO.Ports.SerialPort COM3,9600,None,8,one PS&gt; $port.Open() PS&gt; $port.ReadLine() </code></pre>
12,964,021
Script to install app in iOS Simulator
<p>I am trying to automate the process of building an app, running unit tests, and finally running UI tests. </p> <p>I am building the app via command line (xcodebuild -sdk iphonesimulator6.0) in some directory. </p> <p>How do I install this app to the iOS simulator via command line (in ~/Library/Application Support/iPhone Simulator//Applications)?</p> <p>I tried:</p> <pre><code>/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app/Contents/MacOS/iPhone\ Simulator -SimulateApplication MyApp.app/MyApp </code></pre> <p>but this opens a new finder window named "iOS Simulator could not find the application to simulate".</p>
12,982,349
2
0
null
2012-10-18 21:27:16.97 UTC
10
2016-10-06 17:02:07.467 UTC
2014-06-13 22:06:01.073 UTC
null
1,160,022
null
1,160,022
null
1
11
shell|command-line|ios-simulator
14,570
<p>I made a shell script which installs the app to the simulator.</p> <pre><code>#!/bin/sh # Pick a uuid for the app (or reuse existing one). if ! [ -f installApp.uuid ]; then uuidgen &gt; installApp.uuid fi UUID=$(cat installApp.uuid) #create supporting folders TOPDIR="$HOME/Library/Application Support/\ iPhone Simulator/6.0/Applications/$UUID/" mkdir -p "$TOPDIR" mkdir -p "$TOPDIR/Documents" mkdir -p "$TOPDIR/Library" mkdir -p "$TOPDIR/tmp" mkdir -p "$TOPDIR/$1.app" #copy all the app file to the simulators directory cp -r * "$TOPDIR/$1.app" </code></pre> <p>How to use this script to install the app:</p> <ol> <li><p>Change this line: </p> <pre><code>TOPDIR="$HOME/Library/Application Support/iPhone Simulator/6.0/Applications/$UUID/" </code></pre> <p>to reflect the version of iPhone Simulator you are using i.e. <code>6.0</code>/<code>7.1</code>. </p></li> <li><p>Save the script as <code>installApp.sh</code> in your <code>project_name.app/</code> folder.</p></li> <li><p>Open a terminal window and run <code>installApp</code> from the project directory. <ul> <li>So if I have my <code>project_name.app/</code> with a project inside. Type in the terminal:</p> <blockquote> <p>cd path/to/project_name.app/</li> <li>Then <code>./installApp</code> to install the app to the simulator.</li> </ul></p> </blockquote></li> </ol> <p>I got the idea from Jeffrey Scofield: <a href="http://psellos.com/2012/05/2012.05.iossim-command-line-2.html" rel="noreferrer">Run iOS Simulator from the Command Line</a></p> <hr> <p>For <strong>iOS8 and the new XCode</strong> Apple changed a few things and made it difficult to install apps via the command line. It is still possible to do:</p> <ol> <li><p>First you need to find the app directory (assuming you have installed apps): <code>find ~/Library/Developer/CoreSimulator/Devices -name '*.app'</code></p></li> <li><p>This will list all the paths that have a custom app installed. E.g. </p></li> </ol> <p><code>/34792D41-55A9-40F5-AAC5-16F742F1F3E4/data/Containers/Bundle/Application/4BA2A285-6902-45A8-9445-FC3E46601F51/YourApp.app</code></p> <ol start="3"> <li>There will be multiple UUID parent directories with the structure above. Each UUID corresponds to a simulator for a different device. Open the top directory and you will find a <code>device.plist</code> file. This file will contain the device it is simulating:</li> </ol> <blockquote> <pre><code>&lt;dict&gt; ... &lt;string&gt;34792D41-55A9-40F5-AAC5-16F742F1F3E4&lt;/string&gt; &lt;string&gt;com.apple.CoreSimulator.SimDeviceType.iPhone-6-Plus&lt;/string&gt; ... &lt;/dict&gt; </code></pre> </blockquote> <ol start="4"> <li>If you want to install your app for iPhone-6-Plus this is the directory you would do it in. Run the shell script above to install the app. Change the <code>TOPDIR</code> path to <code>$HOME/Library/Developer/CoreSimulator/Devices/{UUID for device}/data/Containers/Bundle/Applications/$UUID/</code></li> </ol>
12,678,833
C# - when to use public int virtual, and when to just use public int
<p>I am working through a tutorial 'Professional ASP.NET MVC 3' by J Galloway. In this tutorial, Jon shows us how to build the MVC music store.</p> <p>I am at the part where we are creating CS classes to model the data using EF code first.</p> <p>I <strong>all</strong> the examples in the book, <code>public virtual int property {get; set; }</code> is used with no explanation. The term virtual is stuffed EVERYWHERE.</p> <p>Elsewhere on the web, I have not seen the term virtual used with any kind of concistency whatsoever.</p> <p>Could anybody explain to me:</p> <ol> <li>The purpose of the term 'virtual' in this particular context</li> <li>Is using 'virtual' necessary?</li> <li>Why do some people use 'virtual' and others do not?</li> <li>Why do some people only use 'virtual' when defining foreign keys?</li> <li>What is the best practice use of the term 'virtual'?</li> </ol> <p>Many thanks in advance</p>
12,678,883
7
4
null
2012-10-01 18:24:25.767 UTC
10
2012-10-02 03:14:37.443 UTC
2012-10-01 19:29:22.033 UTC
null
1,137,379
null
1,239,122
null
1
23
c#|asp.net-mvc|asp.net-mvc-3|entity-framework
25,485
<p>In order to truly understand the <code>virtual</code> keyword you are going to want to read up on <a href="http://msdn.microsoft.com/en-us/library/ms173152.aspx">Polymorphism in general</a>:</p> <blockquote> <p>Polymorphism is often referred to as the third pillar of object-oriented programming, after encapsulation and inheritance. Polymorphism is a Greek word that means "many-shaped" and it has two distinct aspects:</p> <ol> <li><p>At run time, objects of a derived class may be treated as objects of a base class in places such as method parameters and collections or arrays. When this occurs, the object's declared type is no longer identical to its run-time type.</p></li> <li><p><em><strong>Base classes may define and implement virtual methods, and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object, and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed.</em></strong></p></li> </ol> </blockquote> <p>Once you understand these concepts better you might be able to determine whether or not the method you are creating from the book needs to be <code>virtual</code> or not.</p>
12,742,695
Use or not leading slash in value for @RequestMapping. Need official docs or point to Spring source?
<p>I involved in project where I found a mix of:</p> <pre> @RequestMapping(value = "events/..."); @RequestMapping(value = "/events/..."); </pre> <p>(with and without slash before method level annotation).</p> <p>I perform search:</p> <pre> site:http://static.springsource.org/spring/docs/3.1.x slash </pre> <p>and read these links:</p> <ul> <li><a href="http://forum.springsource.org/showthread.php?130753-Various-Spring-MVC-RequestMapping-configuration-questions" rel="nofollow noreferrer">http://forum.springsource.org/showthread.php?130753-Various-Spring-MVC-RequestMapping-configuration-questions</a></li> <li><a href="https://stackoverflow.com/questions/12712232/various-spring-mvc-requestmapping-configuration-questions">Various Spring MVC RequestMapping configuration questions</a></li> <li><a href="https://stackoverflow.com/questions/6984474/handling-of-pre-slash-in-requestmapping">Handling of pre-slash in @RequestMapping</a></li> <li><a href="https://www.rfc-editor.org/rfc/rfc6570" rel="nofollow noreferrer">https://www.rfc-editor.org/rfc/rfc6570</a></li> </ul> <p>But none of these sources answer why skipping slash allowed. Official Spring docs always shown examples with slashes...</p> <p>Need point to official docs or to Spring sources.</p>
12,744,010
1
0
null
2012-10-05 08:48:39.667 UTC
5
2012-10-05 10:08:53.677 UTC
2021-10-07 05:46:31.917 UTC
null
-1
null
173,149
null
1
33
java|spring|spring-mvc
7,483
<p>It does not matter: If the path does not start with an <code>/</code> then Spring (DefaultAnnotationHandlerMapping) will add it.</p> <p>See method <code>String[] determineUrlsForHandler(String beanName)</code> of Class <code>DefaultAnnotationHandlerMapping</code> line 122 (Spring 3.1.2) (that is for the class level)</p> <pre><code>String[] methodLevelPatterns = determineUrlsForHandlerMethods(handlerType, true); for (String typeLevelPattern : typeLevelPatterns) { if (!typeLevelPattern.startsWith("/")) { typeLevelPattern = "/" + typeLevelPattern; } </code></pre> <p>See method <code>String[] determineUrlsForHandler(Class&lt;?&gt; handlerType, final boolean hasTypeLevelMapping))</code> of Class <code>DefaultAnnotationHandlerMapping</code> line 182 (Spring 3.1.2) (that is for the method level)</p> <pre><code>String[] mappedPatterns = mapping.value(); if (mappedPatterns.length &gt; 0) { for (String mappedPattern : mappedPatterns) { if (!hasTypeLevelMapping &amp;&amp; !mappedPattern.startsWith("/")) { mappedPattern = "/" + mappedPattern; } </code></pre>
12,775,265
iOS 6 shouldAutorotate: is NOT being called
<p>I have been scouring the internet for a solution to this but am finding nothing. I am trying to make my iOS 5 app iOS 6 compatible. I cannot get the orientation stuff to work right. I am unable to detect when a rotation is about to happen. Here is the code I am trying:</p> <pre><code>- (BOOL)shouldAutorotate { return NO; } - (NSUInteger)supportedInterfaceOrientations { return UIInterfaceOrientationMaskPortrait; } // pre-iOS 6 support - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation { return (toInterfaceOrientation == UIInterfaceOrientationPortrait); } </code></pre> <p>The new supportedInterfaceOrientation: method gets called just fine. The shouldAutorotate method, however, will not fire. I need to do some image swapping on rotate, but I can't get any indication that a rotation is about to occur.</p> <p>Thanks in advance.</p>
12,790,798
9
2
null
2012-10-08 04:20:01.17 UTC
12
2019-04-23 12:00:52.403 UTC
2015-07-17 08:17:37.3 UTC
null
1,820,838
null
985,027
null
1
48
iphone|ios|cocoa-touch|rotation|ios6
48,851
<p>See if you are getting the following error when your App starts.</p> <blockquote> <p>Application windows are expected to have a root view controller at the end of application launch</p> </blockquote> <p>If so the way to fix it is by making the following change in the <code>AppDelegate.m</code> file (although there seem to be a number of answers how to fix this):</p> <pre class="lang-objective-c prettyprint-override"><code>// Replace [self.window addSubview:[navigationController view]]; //OLD // With [self.window setRootViewController:navigationController]; //NEW </code></pre> <p>After this <code>shouldAutoRotate</code> should be correctly called.</p>
30,678,712
FBSDK Login Error Code: 308 in Objective-C
<p>I keep getting </p> <blockquote> <p>"Error Domain=com.facebook.sdk.login Code=308 "The operation couldn’t be completed. (com.facebook.sdk.login error 308.)""</p> </blockquote> <p>upon trying to login with Facebook from my device.</p> <p>My code works on the simulator, but not on an actual device. Has anyone ran into this error code before? I'll be more than happy to share code upon request.</p>
33,883,052
18
5
null
2015-06-06 03:46:13.317 UTC
13
2018-12-19 03:42:59.567 UTC
2015-06-06 04:08:15.847 UTC
null
3,940,672
null
975,798
null
1
57
ios|facebook|parse-platform|facebook-sdk-4.0
38,183
<p>One solution, at least for me, is to not run on device via the Xcode debugger. If I run the app on device outside the debugger the Facebook login works fine. If I run the app in the sim via the debugger the Facebook login works fine.</p> <p>Only if I run the app on device via the Xcode debugger do I get the com.facebook.sdk.login error 308 every time.</p>
17,057,934
Wpf merged resource dictionary no being recognized from app.xaml
<p>I have a WPF .net 4.5 application where I am having trouble merging resource dictionaries.</p> <p>I have the exact same problem as <a href="https://stackoverflow.com/a/4166345/1923268">This SO question</a> and <a href="https://stackoverflow.com/a/4113594/1923268">This Question</a> but the accepted solution does not work for me. </p> <p>I have a resource dictionaries declared in my app.xaml as follows (simplified for clarity):</p> <pre><code>&lt;Application.Resources&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="Skin/ResourceLibrary.xaml" /&gt; &lt;ResourceDictionary Source="Skin/Brushes/ColorStyles.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;/ResourceDictionary&gt; &lt;/Application.Resources&gt; </code></pre> <p><strong>Problem:</strong> The app can "SEE" the ColorStyles dictonary when listed in app.xaml, but if I move/nest it inside the ResourceLibrary.xaml, then the ColorStyles.xaml are not "seen" by the app and errors about missing static resources appear.</p> <p>Here is how I create the ResourceLibrary.xaml dictionary (simplified):</p> <pre><code>&lt;ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;!-- BRUSHES AND COLORS --&gt; &lt;ResourceDictionary Source="Brushes/ColorStyles.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;/ResourceDictionary&gt; </code></pre> <p><strong>Reason for change:</strong> My current organization of my resource dictionaries is awful and I need to change it (as I am creating objects more than once). I wanted to have one resource dictionary in a "Skin" folder and then sub-folders for organizing the remaining style dictionaries which would all be merged in the ResourceLibrary.xaml file which in turn would be called in app.xaml.</p> <p><strong>What I tried:</strong> Yes I did try to use the solution from the link above:</p> <pre><code>&lt;Application.Resources&gt; &lt;ResourceDictionary&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="Skin/ResourceLibrary.xaml"/&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;!-- Dummy Style, anything you won't use goes --&gt; &lt;Style TargetType="{x:Type Rectangle}" /&gt; &lt;/ResourceDictionary&gt; &lt;/Application.Resources&gt; </code></pre> <p>but I get the following error on the dummy style line:</p> <blockquote> <p>Error 2 Property elements cannot be in the middle of an element's content. They must be before or after the content.</p> </blockquote> <p>Changing the code to the following got rid of the error above, thanks to lisp comment:</p> <pre><code>&lt;Application.Resources&gt; &lt;ResourceDictionary&gt; &lt;!--Global View Model Locator--&gt; &lt;vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" /&gt; &lt;!-- Dummy Style, anything you won't use goes --&gt; &lt;Style TargetType="{x:Type Rectangle}" /&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="Skin/ResourceLibrary.xaml"&gt;&lt;/ResourceDictionary&gt; &lt;ResourceDictionary Source="Skin/Brushes/ColorStyles.xaml" /&gt; &lt;ResourceDictionary Source="Skin/NamedStyles/AlertStyles.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;/ResourceDictionary&gt; &lt;/Application.Resources&gt; </code></pre> <p>but the Resource Library is still not being called.</p> <p>I also tried to change all the file paths to pack URI's, but that did not solve the problem either.</p> <p>I tried moving the resourceLibrary.xaml and the other resource dictionaries into a different class library project (using the same folder structure and files as above). I then used the following URI but I still am not able to access resources declared in the ResourceLibrary.xaml file.</p> <pre><code>&lt;ResourceDictionary Source="pack://application:,,,/FTC.Style;component/ResourceLibrary.xaml" /&gt; </code></pre> <p>But again, if I add each resource dictionary to the App.Xaml file, using the UIR format above, the resources are usable.</p> <p>The error is gone, but I am still unable to use resources that are a part of the merged dictionary in the ResourceLibrary.xaml file. I am inclined to agree with the comment of dowhilefor as to whether or not I should use this approach, but I want to figure this out because the most common solution to this problem (see links at top of this post) is not working and maybe this solution could help someone else. </p> <p><strong>Question:</strong> Why is the ResourceLibrary.xaml file being ignored?</p>
17,083,360
3
10
null
2013-06-12 04:57:50.733 UTC
12
2022-08-29 15:21:47.043 UTC
2018-03-27 15:56:48.347 UTC
null
102,937
null
1,854,382
null
1
25
.net|wpf|xaml|resourcedictionary
24,558
<p>I hava a big problem with MergedDictionaries and I believe that your problem is the same. I want my ResourceDictionaries to be properly organized, which means for me that there are for example seperate Buttons.xaml, TextBoxes.xaml, Colors.xaml and so on. I merge them in Theme.xaml, often all the Styles are in a seperate assembly (so that I could easily switch Themes). My ApplicationResources are as follows:</p> <pre><code>&lt;Application.Resources&gt; &lt;ResourceDictionary&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source="/DefaultTheme;component/Theme.xaml" /&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;Style TargetType="{x:Type Ellipse}"/&gt; &lt;/ResourceDictionary&gt; &lt;/Application.Resources&gt; </code></pre> <p>And every StaticResource in the .xamls defined in the main application assembly work, default styles work thanks to the dummy Style. <strong>What doesn't work are StaticResources between .xamls inside of Theme</strong>. If I define a Style in Buttons.xaml that uses a StaticResource from Colors.xaml, I get an error about StaticResources and UnsetValue. It works if I add Colors.xaml to Application MergedDictionaries.</p> <h2>Solution 0</h2> <p>Abandon organization. Put everything in one .xaml. I believe that is how the ResourceDictionaries were generally supposed to be used because of all the 'problems' with MergedDictionaries (for me this would be a nightmare).</p> <h2>Solution 1</h2> <p>Change all cross-xaml StaticResource references inside of theme to DynamicResource. It works but comes with a price as DynamicResources are 'heavier' than StaticResources.</p> <h2>Solution 2</h2> <p>In every Theme .xaml that uses StaticResources from another .xaml, add this another ResourceDictionary to MergedDictionaries. That means that Buttons.xaml, TextBoxes.xaml and others would have Colors.xaml in their MergedDictionaries. It will result in Colors ResourceDictionary being stored in memory in multiple copies. To avoid that you might want to look into <a href="http://wpftutorial.net/MergedDictionaryPerformance.html" rel="noreferrer">SharedResourceDictionary</a>.</p> <h2>Solution 3</h2> <p>By different ResourceDictionaries setup, different nestings I came up with a <em>theory</em>: </p> <blockquote> <p>If a StaticResource isn't found above in the same .xaml or in the MergedDictionaries of this ResourceDictionary, it is searched in <em>other top-level MergedDictionaries</em>.</p> </blockquote> <p>I would prefer to add to ApplicationResources only one .xaml, but I usually end up using <strong>two</strong>. You dont have to add to ApplicationResources every .xaml that you have in Theme, just - for example - Controls.xaml (with any kind of MergedDictionaries nesting, but no cross-references between Dictionaries of Controls.xaml are allowed) and Common.xaml which contains all common Resources of Controls. In case of Common.xaml nesting is also allowed, but no cross-references, there cannot be seperate Colors.xaml and Brushes.xaml that uses Colors as StaticResources - then you would have to have 3 .xamls added to Application MergedDictionaries.</p> <p>Now I always use the third solution, but I don't consider it perfect and still would like to know if there is a better way. I hope I correctly interpreted what you described as the same problem as mine.</p>
17,099,025
Determine whether doc is new or exists in mongoose Post middleware's 'save'?
<p>From <a href="http://mongoosejs.com/docs/middleware.html" rel="noreferrer">Mongoose JS</a> documentation:</p> <pre><code>schema.post('save', function (doc) { console.log('%s has been saved', doc._id); }) </code></pre> <p>Is there any way to determine whether this is the original save or the saving of an existing document (an update)? </p>
18,305,924
3
0
null
2013-06-13 23:45:09.713 UTC
9
2016-04-11 11:36:16.403 UTC
null
null
null
null
2,005,565
null
1
34
mongoose
20,107
<p><a href="https://github.com/LearnBoost/mongoose/issues/1474">@aheckmann reply at github </a></p> <pre><code>schema.pre('save', function (next) { this.wasNew = this.isNew; next(); }); schema.post('save', function () { if (this.wasNew) { // ... } }); </code></pre> <p><code>isNew</code> is an key used by mongoose internally. Saving that value to the document's <code>wasNew</code> in the pre save hook allows the post save hook to know whether this was an existing document or a newly created one. Additionally, the <code>wasNew</code> is not commited to the document unless you specifically add it to the schema.</p>
16,952,846
How to keep console window open
<p>When I run my program, the console window seems to run and close. How to keep it open so I can see the results? </p> <pre><code>class Program { public class StringAddString { public virtual void AddString() { var strings2 = new string[] { "1", "2", "3", "4", "5","6", "7", "8", "9"}; Console.WriteLine(strings2); Console.ReadLine(); } } static void Main(string[] args) { StringAddString s = new StringAddString(); } } </code></pre>
16,952,898
13
0
null
2013-06-06 02:35:36.977 UTC
4
2022-03-16 10:57:11.78 UTC
2014-03-14 19:29:21.02 UTC
null
41,956
null
1,929,393
null
1
45
c#|console-application
151,912
<p>You forgot calling your method:</p> <pre><code>static void Main(string[] args) { StringAddString s = new StringAddString(); s.AddString(); } </code></pre> <p>it should stop your console, but the result might not be what you expected, you should change your code a little bit:</p> <pre><code>Console.WriteLine(string.Join(",", strings2)); </code></pre>
4,779,188
How to use mmap to allocate a memory in heap?
<p>Just the question stated, how can I use <code>mmap()</code> to allocate a memory in heap? This is my only option because <code>malloc()</code> is not a reentrant function.</p>
4,779,245
2
4
null
2011-01-24 06:19:48.68 UTC
14
2021-11-16 16:50:21.567 UTC
2021-11-16 16:50:21.567 UTC
null
5,459,839
null
130,278
null
1
16
c|memory-management|heap-memory|mmap
26,251
<p>Why do you need reentrancy? The only time it's needed is for calling a function from a signal handler; otherwise, thread-safety is just as good. Both <code>malloc</code> and <code>mmap</code> are thread-safe. Neither is async-signal-safe per POSIX. In practice, <code>mmap</code> probably works fine from a signal handler, but the whole idea of allocating memory from a signal handler is a very bad idea.</p> <p>If you want to use <code>mmap</code> to allocate anonymous memory, you can use (not 100% portable but definitely best):</p> <pre><code>p = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); </code></pre> <p>The portable but ugly version is:</p> <pre><code>int fd = open("/dev/zero", O_RDWR); p = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0); close(fd); </code></pre> <p>Note that <code>MAP_FAILED</code>, not <code>NULL</code>, is the code for failure.</p>
4,175,188
Setting memory of Java programs that runs from Eclipse
<p>I'm running a Java application from Eclipse that need a lot of memory.</p> <p>Where can i put the <strike><code>-Xmms</code></strike><code>-xms</code> flag ?</p>
4,175,193
2
0
null
2010-11-13 23:01:53.45 UTC
1
2010-11-13 23:19:03.917 UTC
2010-11-13 23:19:03.917 UTC
null
449,071
null
449,071
null
1
20
java|eclipse|memory
40,832
<p>You can set the VM arguments for a specific run configuration:</p> <p><em>Run → Run Configurations... → Arguments Tab → VM arguments</em></p> <p>Btw, you may want to try <code>-Xms</code> instead of <code>-Xmms</code>.</p>
4,333,463
What does this strange Jersey warning mean?
<p>What does this warning mean in Jersey 1.4:</p> <pre><code>WARNING: A sub-resource method, public final java.lang.String com.XXX.render(), with URI template, "/", is treated as a resource method </code></pre> <p>This is how the method looks:</p> <pre><code>@GET @Produces(MediaType.APPLICATION_XML) @Path("/") public final String render() { return "test"; } </code></pre>
4,333,532
2
0
null
2010-12-02 09:31:33.42 UTC
1
2012-06-28 01:35:45.873 UTC
2012-06-28 01:35:45.873 UTC
null
-1
null
187,141
null
1
29
java|jersey
8,569
<p>Why do you need specify such path for method? @Get is enough to tell jersey that it is default method for entire class (I'm assuming that your class has some @Path("/MyRes") annotation).</p>
4,173,483
HTML Encoding Strings - ASP.NET Web Forms VS Razor View Engine
<p>I'm not quite sure how this works yet... trying to find documentation.</p> <p>In my existing app I've got two different ways of rendering strings in my View</p> <pre><code>&lt;%: model.something %&gt; &lt;!-- or --&gt; &lt;%= model.something %&gt; </code></pre> <p>The first one is html encoded, and the second one is not.</p> <p>Is there something similarly short in Razor? All I can find is this, which is the encoded version.</p> <pre class="lang-csharp prettyprint-override"><code>@model.something </code></pre>
5,259,479
2
0
null
2010-11-13 16:27:46.877 UTC
0
2012-04-09 13:50:37.27 UTC
2012-04-09 13:50:37.27 UTC
null
124,069
null
124,069
null
1
35
asp.net-mvc-3|razor|viewengine|html-encode
25,208
<p>I guess the best approach would be to use the Raw extension-method: <code>@Html.Raw(Model.Something)</code></p>
68,444,429
How can I distinguish between high- and low-performance cores/threads in C++?
<p>When talking about multi-threading, it often seems like threads are treated as equal - just the same as the main thread, but running next to it.</p> <p>On some new processors, however, such as the <a href="https://en.wikipedia.org/wiki/Apple_silicon#M_series" rel="nofollow noreferrer">Apple &quot;M&quot; series</a> and the upcoming Intel <a href="https://en.wikipedia.org/wiki/Alder_Lake_(microprocessor)" rel="nofollow noreferrer">Alder Lake</a> series not all threads are equally as performant as these chips feature separate high-performance cores and high-efficiency, slower cores.</p> <p>It’s not to say that there weren’t already things such as hyper-threading, but this seems to have a much larger performance implication.</p> <p>Is there a way to query <code>std::thread</code>‘s properties and enforce on which cores they’ll run in C++?</p>
68,448,721
5
9
null
2021-07-19 17:06:31.233 UTC
9
2021-10-18 20:38:39.723 UTC
2021-10-18 20:38:39.723 UTC
null
12,501,684
null
12,501,684
null
1
71
c++|multithreading|performance|intel|apple-m1
7,394
<blockquote> <p>How to distinguish between high- and low-performance cores/threads in C++?</p> </blockquote> <p>Please understand that &quot;thread&quot; is an abstraction of the hardware's capabilities and that something beyond your control (the OS, the kernel's scheduler) is responsible for creating and managing this abstraction. &quot;Importance&quot; and performance hints are part of that abstraction (typically presented in the form of a thread priority).</p> <p>Any attempt to break the &quot;thread&quot; abstraction (e.g. determine if the core is a low-performance or high-performance core) is misguided. E.g. OS could change your thread to a low performance core immediately after you find out that you were running on a high performance core, leading you to assume that you're on a high performance core when you are not.</p> <p>Even pinning your thread to a specific core (in the hope that it'll always be using a high-performance core) can/will backfire (cause you to get less work done because you've prevented yourself from using a &quot;faster than nothing&quot; low-performance core when high-performance core/s are busy doing other work).</p> <p>The biggest problem is that C++ creates a worse abstraction (<code>std::thread</code>) on top of the &quot;likely better&quot; abstraction provided by the OS. Specifically, there's no way to set, modify or obtain the thread priority using <code>std::thread</code>; so you're left without any control over the &quot;performance hints&quot; that are necessary (for the OS, scheduler) to make good &quot;load vs. performance vs. power management&quot; decisions.</p> <blockquote> <p>When talking about multi-threading, it often seems like threads are treated as equal</p> </blockquote> <p>Often people think we're still using time-sharing systems from the 1960s. Stop listening to these fools. <strong>Modern systems do not allow CPU time to be wasted on unimportant work while more important work waits. Effective use of thread priorities is a fundamental performance requirement.</strong> Everything else (&quot;load vs. performance vs. power management&quot; decisions) is, by necessity, beyond your control (on the other side of the &quot;thread&quot; abstraction you're using).</p>
9,938,008
Variance and Mean of Image
<p>I am calculating mean and variance of my original and stego image to compare them I am using grayscale BMP image for comaprison</p> <pre><code>image=imread("image name") M = mean(image(:)) V = var((image(:))) </code></pre> <p>Is this is correct way fo calculating mean/var in MATLAB? My Variance is getting more than mean..</p> <p>Any help appreciated..</p>
9,938,918
2
0
null
2012-03-30 06:28:05.717 UTC
4
2012-08-15 12:51:31.363 UTC
null
null
null
null
1,268,559
null
1
6
matlab
39,332
<p>These are indeed the correct way to calculate the mean and variance over all the pixels of your image.</p> <p>It is not impossible that your variance is larger than the mean as both are defined in the following way:</p> <pre><code>mean = sum(x)/length(x) variance = sum((x - mean(x)).^2)/(length(x) - 1); </code></pre> <p>For example, if you generate noise from a standard normal distribution with <code>randn(N,1)</code>, you will get <code>N</code> samples, and if you calculate the mean and variance, you will get approximately <code>0</code> and <code>1</code>. So there as well, your variance may well be larger than the mean.</p> <p>Both have a totally different meaning: the mean gives you an idea <strong>where</strong> your pixels are (i.e. are they white, black, 50% gray, ...). The mean will give you an idea of what pixel color to choose to summarize the color of the complete image. The variance gives you an idea how the pixel values are <strong>spread</strong>: e.g. if your mean pixel value is 50% gray, are most of the other pixels also 50% gray (small variance) or do you have 50 black pixels and 50 white pixels (large variance)? So you could also view it as a way to get an idea how well the mean summarizes the image (i.e. with zero variance, most of the information is captured by the mean).</p> <p><strong>edit:</strong> For the RMS value (Root Mean Square) of a signal, just do what the <a href="http://en.wikipedia.org/wiki/Root_mean_square" rel="noreferrer">definition</a> says. In most cases you want to remove the DC component (i.e. the mean) before calculating the RMS value.</p> <p><strong>edit 2:</strong> What I forgot to mention was: it also makes little sense to compare the numerical value of the variance with the mean from a physical point of view. The mean has the same dimension as your data (in case of pixels, think of intensity), while the variance has the dimension of your data squared (so intensity^2). The standard deviation (<code>std</code> in MATLAB), which is the square root of the variance on the other hand has the same dimension as the data, so there you could make some comparisons (it is another question whether you should do such comparison).</p>
9,932,072
Matplotlib table formatting
<p><img src="https://i.stack.imgur.com/XtUKQ.png" alt="enter image description here"> Can't seem to locate in the documentation how to <strong>increase the line-height</strong> of the cells, as the text itself is very cramped.</p> <p>Any help with code is appreciated! Table formatting doesn't seem to be well documented...</p> <pre><code> # Plot line width matplotlib.rc('lines', linewidth=3) ind = np.arange(len(overall)) fig = pyplot.figure() ax = fig.add_subplot(211) ax.set_title('Overall Rating of Experience') ax.set_ylabel('Score (0-100)') # Plot data on chart plot1 = ax.plot(ind, overall) plot2 = ax.plot(ind, svc_avg) plot3 = ax.plot(ind, benchmark) ax.yaxis.grid(True, which='major', ls='-', color='#9F9F9F') ax.set_ylim([min(overall + svc_avg + benchmark) - 3, 100]) ax.set_xlim([-.5,1.5]) ax.get_xaxis().set_ticks([]) ax.set_position([.25, .3, 0.7, 0.5]) colLabels = ['July', 'August'] rowLabels = ['Average', 'Service Average', 'Benchmark'] cellText = [overall, svc_avg, benchmark] the_table = ax.table(cellText=cellText, rowLoc='right', rowColours=colors, rowLabels=rowLabels, colWidths=[.5,.5], colLabels=colLabels, colLoc='center', loc='bottom') </code></pre> <p>EDIT: Thanks to Oz for the answer-- Looping through the properties of the table allows easy modification of the height property:</p> <pre><code> table_props = the_table.properties() table_cells = table_props['child_artists'] for cell in table_cells: cell.set_height(0.1) </code></pre>
9,947,184
2
1
null
2012-03-29 19:24:26.067 UTC
15
2017-09-14 18:34:07.35 UTC
2017-03-17 19:50:41.843 UTC
null
4,370,109
null
321,781
null
1
30
python|matplotlib
47,922
<p>The matplotlib documentation says </p> <blockquote> <p>Add a table to the current axes. Returns a matplotlib.table.Table instance. For finer grained control over tables, use the Table class and add it to the axes with add_table().</p> </blockquote> <p>You could do is the following, look at the properties of your table (it's and object belonging to that class Table):</p> <pre><code>print the_table.properties() # hint it's a dictionary do: type(the_table.properties() &lt;type 'dict'&gt; </code></pre> <p>edit that dictionary the way you see right, and the update your table, with:</p> <pre><code>the_table.update(giveHereYourDictionary) </code></pre> <p>Hint: if you work with IPython or interactive shell it's enough to do help(objectName), e.g. help(the_table) to see all the object's methods. This should, hopefully, work.</p> <p>OK, I'm adding here a walk through of how to to that kind of stuff. I admit, it's not trivial, but I am using matplotlib for 3.5 years now, so ...</p> <p>Do your code in IPython (I said it before, but I must emphasize again), it really helps to examine all the properties that objects have (type object name and then the key):</p> <pre><code>In [95]: prop=the_table.properties() In [96]: prop #This is a dictionary, it's not so trivial, but never the less one can understand how dictionaries work... Out[96]: {'agg_filter': None, 'alpha': None, 'animated': False, 'axes': &lt;matplotlib.axes.AxesSubplot at 0x9eba34c&gt;, 'celld': {(0, -1): &lt;matplotlib.table.Cell at 0xa0cf5ec&gt;, (0, 0): &lt;matplotlib.table.Cell at 0xa0c2d0c&gt;, (0, 1): &lt;matplotlib.table.Cell at 0xa0c2dec&gt;, (0, 2): &lt;matplotlib.table.Cell at 0xa0c2ecc&gt;, (1, -1): &lt;matplotlib.table.Cell at 0xa0cf72c&gt;, (1, 0): &lt;matplotlib.table.Cell at 0xa0c2fac&gt;, (1, 1): &lt;matplotlib.table.Cell at 0xa0cf08c&gt;, (1, 2): &lt;matplotlib.table.Cell at 0xa0cf18c&gt;, (2, -1): &lt;matplotlib.table.Cell at 0xa0cf84c&gt;, (2, 0): &lt;matplotlib.table.Cell at 0xa0cf28c&gt;, (2, 1): &lt;matplotlib.table.Cell at 0xa0cf3ac&gt;, (2, 2): &lt;matplotlib.table.Cell at 0xa0cf4cc&gt;}, 'child_artists': [&lt;matplotlib.table.Cell at 0xa0c2dec&gt;, &lt;matplotlib.table.Cell at 0xa0cf18c&gt;, &lt;matplotlib.table.Cell at 0xa0c2d0c&gt;, &lt;matplotlib.table.Cell at 0xa0cf84c&gt;, &lt;matplotlib.table.Cell at 0xa0cf3ac&gt;, &lt;matplotlib.table.Cell at 0xa0cf08c&gt;, &lt;matplotlib.table.Cell at 0xa0cf28c&gt;, &lt;matplotlib.table.Cell at 0xa0cf4cc&gt;, &lt;matplotlib.table.Cell at 0xa0cf5ec&gt;, &lt;matplotlib.table.Cell at 0xa0c2fac&gt;, &lt;matplotlib.table.Cell at 0xa0cf72c&gt;, &lt;matplotlib.table.Cell at 0xa0c2ecc&gt;], 'children': [&lt;matplotlib.table.Cell at 0xa0c2dec&gt;, &lt;matplotlib.table.Cell at 0xa0cf18c&gt;, ...snip snap ... &lt;matplotlib.table.Cell at 0xa0cf72c&gt;, &lt;matplotlib.table.Cell at 0xa0c2ecc&gt;], 'clip_box': TransformedBbox(Bbox(array([[ 0., 0.], [ 1., 1.]])), CompositeAffine2D(BboxTransformTo(Bbox(array([[ 0., 0.], [ 1., 1.]]))), BboxTransformTo(TransformedBbox(Bbox(array([[ 0.25, 0.3 ], [ 0.95, 0.8 ]])), BboxTransformTo(TransformedBbox(Bbox(array([[ 0., 0.], [ 8., 6.]])), Affine2D(array([[ 80., 0., 0.], [ 0., 80., 0.], [ 0., 0., 1.]])))))))), 'clip_on': True, 'clip_path': None, 'contains': None, 'figure': &lt;matplotlib.figure.Figure at 0x9eaf56c&gt;, 'gid': None, 'label': '', 'picker': None, 'rasterized': None, 'snap': None, 'transform': BboxTransformTo(TransformedBbox(Bbox(array([[ 0.25, 0.3 ], [ 0.95, 0.8 ]])), BboxTransformTo(TransformedBbox(Bbox(array([[ 0., 0.], [ 8., 6.]])), Affine2D(array([[ 80., 0., 0.], [ 0., 80., 0.], [ 0., 0., 1.]])))))), 'transformed_clip_path_and_affine': (None, None), 'url': None, 'visible': True, 'zorder': 0} # we now get all the cells ... [97]: cells = prop['child_artists'] In [98]: cells Out[98]: [&lt;matplotlib.table.Cell at 0xa0c2dec&gt;, &lt;matplotlib.table.Cell at 0xa0cf18c&gt;, ... snip snap... &lt;matplotlib.table.Cell at 0xa0cf72c&gt;, &lt;matplotlib.table.Cell at 0xa0c2ecc&gt;] In [99]:cell=cells[0] In [100]: cell # press tab here to see cell's attributes Display all 122 possibilities? (y or n) cell.PAD cell.add_callback ...snip snap ... cell.draw cell.eventson cell.figure ...snip snap ... In [100]: cell.set_h cell.set_hatch cell.set_height # this looks promising no? Hell, I love python ;-) wait, let's examine something first ... In [100]: cell.get_height() Out[100]: 0.055555555555555552 In [101]: cell.set_height(0.1) # we just 'doubled' the height... In [103]: pyplot.show() </code></pre> <p>and TA DA:</p> <p><img src="https://i.stack.imgur.com/W2xaG.png" alt="Table with modified height for one cell"></p> <p>Now, I challege you to change the height of all the cells, using a for loop. Should not be so hard. Would be nice to win that bounty ;-)</p>
10,204,471
Convert char array to a int number in C
<p>I want to convert a char array[] like:</p> <pre><code>char myarray[4] = {'-','1','2','3'}; //where the - means it is negative </code></pre> <p>So it should be the integer: -1234 using <strong>standard</strong> libaries in <strong>C</strong>. I could not find any elegant way to do that.</p> <p>I can append the '\0' for sure.</p>
10,204,663
5
5
null
2012-04-18 07:02:04.493 UTC
16
2020-07-02 20:57:57.01 UTC
2012-04-18 07:25:06.61 UTC
null
812,912
null
1,221,495
null
1
41
c|arrays|char|int
304,642
<p>I personally don't like <code>atoi</code> function. I would suggest <code>sscanf</code>:</p> <pre><code>char myarray[5] = {'-', '1', '2', '3', '\0'}; int i; sscanf(myarray, "%d", &amp;i); </code></pre> <p>It's very standard, it's in the <code>stdio.h</code> library :)</p> <p>And in my opinion, it allows you much more freedom than <code>atoi</code>, arbitrary formatting of your number-string, and probably also allows for non-number characters at the end.</p> <p><strong>EDIT</strong> I just found this wonderful <a href="https://stackoverflow.com/questions/3420629/convert-string-to-integer-sscanf-or-atoi">question</a> here on the site that explains and compares 3 different ways to do it - <code>atoi</code>, <code>sscanf</code> and <code>strtol</code>. Also, there is a nice more-detailed insight into <code>sscanf</code> (actually, the whole family of <code>*scanf</code> functions).</p> <p><strong>EDIT2</strong> Looks like it's not just me personally disliking the <code>atoi</code> function. Here's a <a href="https://stackoverflow.com/a/1488584/884412">link</a> to an answer explaining that the <code>atoi</code> function is deprecated and should not be used in newer code.</p>
9,718,117
Selecting first 10 records, then next 10, paging using Linq
<p>How select first 10 records, Then the next 10, Then the next 10, and so long as the array will not end.</p> <pre><code>Phrases = bannersPhrases.Select(x=&gt;x.Phrase).Take(10).ToArray() </code></pre> <p>How get the next 10 records?</p>
9,718,155
4
0
null
2012-03-15 10:44:45.063 UTC
16
2018-11-27 09:37:13.117 UTC
2012-11-28 00:31:05.97 UTC
null
815,724
null
1,266,349
null
1
42
c#|linq
109,344
<pre><code>var total = bannersPhrases.Select(p =&gt; p.Phrase).Count(); var pageSize = 10; // set your page size, which is number of records per page var page = 1; // set current page number, must be &gt;= 1 (ideally this value will be passed to this logic/function from outside) var skip = pageSize * (page-1); var canPage = skip &lt; total; if (!canPage) // do what you wish if you can page no further return; Phrases = bannersPhrases.Select(p =&gt; p.Phrase) .Skip(skip) .Take(pageSize) .ToArray(); </code></pre>
9,769,496
Celery Received unregistered task of type (run example)
<p>I'm trying to run <a href="http://ask.github.com/celery/getting-started/first-steps-with-celery.html#id3" rel="noreferrer">example</a> from Celery documentation.</p> <p>I run: <code>celeryd --loglevel=INFO</code></p> <pre><code>/usr/local/lib/python2.7/dist-packages/celery/loaders/default.py:64: NotConfigured: No 'celeryconfig' module found! Please make sure it exists and is available to Python. "is available to Python." % (configname, ))) [2012-03-19 04:26:34,899: WARNING/MainProcess] -------------- celery@ubuntu v2.5.1 ---- **** ----- --- * *** * -- [Configuration] -- * - **** --- . broker: amqp://guest@localhost:5672// - ** ---------- . loader: celery.loaders.default.Loader - ** ---------- . logfile: [stderr]@INFO - ** ---------- . concurrency: 4 - ** ---------- . events: OFF - *** --- * --- . beat: OFF -- ******* ---- --- ***** ----- [Queues] -------------- . celery: exchange:celery (direct) binding:celery </code></pre> <p>tasks.py:</p> <pre><code># -*- coding: utf-8 -*- from celery.task import task @task def add(x, y): return x + y </code></pre> <p>run_task.py:</p> <pre><code># -*- coding: utf-8 -*- from tasks import add result = add.delay(4, 4) print (result) print (result.ready()) print (result.get()) </code></pre> <p>In same folder celeryconfig.py:</p> <pre><code>CELERY_IMPORTS = ("tasks", ) CELERY_RESULT_BACKEND = "amqp" BROKER_URL = "amqp://guest:guest@localhost:5672//" CELERY_TASK_RESULT_EXPIRES = 300 </code></pre> <p>When I run "run_task.py":</p> <p>on python console</p> <pre><code>eb503f77-b5fc-44e2-ac0b-91ce6ddbf153 False </code></pre> <p>errors on celeryd server</p> <pre><code>[2012-03-19 04:34:14,913: ERROR/MainProcess] Received unregistered task of type 'tasks.add'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you are using relative imports? Please see http://bit.ly/gLye1c for more information. The full contents of the message body was: {'retries': 0, 'task': 'tasks.add', 'utc': False, 'args': (4, 4), 'expires': None, 'eta': None, 'kwargs': {}, 'id': '841bc21f-8124-436b-92f1-e3b62cafdfe7'} Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/celery/worker/consumer.py", line 444, in receive_message self.strategies[name](message, body, message.ack_log_error) KeyError: 'tasks.add' </code></pre> <p>Please explain what's the problem.</p>
9,769,705
40
3
null
2012-03-19 11:40:50.567 UTC
27
2022-07-06 14:53:57.557 UTC
2012-06-27 11:00:56.643 UTC
null
171,278
null
824,088
null
1
133
python|celery
136,813
<p>You can see the current list of registered tasks in the <code>celery.registry.TaskRegistry</code> class. Could be that your celeryconfig (in the current directory) is not in <code>PYTHONPATH</code> so celery can't find it and falls back to defaults. Simply specify it explicitly when starting celery.</p> <pre><code>celeryd --loglevel=INFO --settings=celeryconfig </code></pre> <p>You can also set <code>--loglevel=DEBUG</code> and you should probably see the problem immediately.</p>
9,841,623
Mockito : how to verify method was called on an object created within a method?
<p>I am new to Mockito.</p> <p>Given the class below, how can I use Mockito to verify that <code>someMethod</code> was invoked exactly once after <code>foo</code> was invoked?</p> <pre><code>public class Foo { public void foo(){ Bar bar = new Bar(); bar.someMethod(); } } </code></pre> <p>I would like to make the following verification call,</p> <pre><code>verify(bar, times(1)).someMethod(); </code></pre> <p>where <code>bar</code> is a mocked instance of <code>Bar</code>.</p>
9,841,929
8
3
null
2012-03-23 15:09:31.85 UTC
49
2022-03-10 09:34:59.05 UTC
null
null
null
null
584,862
null
1
435
java|unit-testing|junit|mockito
783,814
<p><a href="http://en.wikipedia.org/wiki/Dependency_injection" rel="noreferrer">Dependency Injection</a></p> <p>If you inject the Bar instance, or a factory that is used for creating the Bar instance (or one of the other 483 ways of doing this), you'd have the access necessary to do perform the test.</p> <p>Factory Example:</p> <p>Given a Foo class written like this:</p> <pre><code>public class Foo { private BarFactory barFactory; public Foo(BarFactory factory) { this.barFactory = factory; } public void foo() { Bar bar = this.barFactory.createBar(); bar.someMethod(); } } </code></pre> <p>in your test method you can inject a BarFactory like this:</p> <pre><code>@Test public void testDoFoo() { Bar bar = mock(Bar.class); BarFactory myFactory = new BarFactory() { public Bar createBar() { return bar;} }; Foo foo = new Foo(myFactory); foo.foo(); verify(bar, times(1)).someMethod(); } </code></pre> <p>Bonus: This is an example of how TDD(Test Driven Development) can drive the design of your code.</p>
63,241,719
Improve the speed of a JavaScript function
<p>I have a task I found on CodeWars and I managed to solve it, however, after submitting is says:</p> <blockquote> <p>Execution timed out: (12000 ms)</p> </blockquote> <p>When I try to test the function is passed, but I guess it is too slow. Before you condemn me for not finding the answer on my own. I don't really care about submitting that as a response, but I have no idea how to make it faster and that is why I am here. Here is the function:</p> <pre><code>const ls = [0, 1, 3, 6, 10] const partsSums = (ls) =&gt; { const sum = [] for(let i = 0, len = ls.length; i &lt; len + 1; i++) { let result = ls.slice(i).reduce( (accumulator, currentValue) =&gt; accumulator + currentValue, 0) sum.push(result) } return sum } </code></pre> <p>Here are the instructions:</p> <blockquote> <p>Let us consider this example (array written in general format):</p> <pre><code>ls = [0, 1, 3, 6, 10] </code></pre> <p>Its following parts:</p> <pre><code>ls = [0, 1, 3, 6, 10] ls = [1, 3, 6, 10] ls = [3, 6, 10] ls = [6, 10] ls = [10] ls = [] </code></pre> <p>The corresponding sums are (put together in a list): [20, 20, 19, 16, 10, 0]</p> <p>The function parts_sums (or its variants in other languages) will take as parameter a list ls and return a list of the sums of its parts as defined above.</p> </blockquote>
63,241,820
6
7
null
2020-08-04 07:02:16.79 UTC
2
2020-08-24 13:30:51.767 UTC
2020-08-04 18:49:00.867 UTC
null
1,048,572
null
13,108,189
null
1
29
javascript|arrays|function|sum
1,529
<p>For this kind of array maipulations, you better not use build in methods, like <code>slice</code> or <code>reduce</code>, because they are slow in comparison to a <code>for</code> loop, or any other looping approaches.</p> <p>This approach takes a sinlge loop and uses the index for getting a value of the given array and takes the last sum of the new array.</p> <p>Some speed tests on <a href="https://www.codewars.com/kata/sums-of-parts/train/javascript" rel="noreferrer">Codewars: Sums of Parts</a>:</p> <ul> <li><strong>5621 ms</strong> with sparse array <code>sum = []; sum[i] = 0;</code> (the first version of this answer),</li> <li><strong>3452 ms</strong> with <code>Array(i + 1).fill(0)</code> and without <code>sum[i] = 0;</code>,</li> <li><strong>1261 ms</strong> with <code>Array(i + 1)</code> and <code>sum[i] = 0;</code> (find below),</li> <li><strong>3733 ms</strong> with Icepickle's <a href="https://stackoverflow.com/a/63256004/1447675">first attempt</a>.</li> </ul> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const partsSums = (ls) =&gt; { let i = ls.length; const sum = Array(i + 1); sum[i] = 0; while (i--) sum[i] = sum[i + 1] + ls[i]; return sum; }, ls = [0, 1, 3, 6, 10]; console.log(...partsSums(ls));</code></pre> </div> </div> </p>
8,054,009
jQuery/JavaScript: Is it a date? (Validate whether is a date)
<p>I have datepicker, but I could not find a way to validate if the user's entry is a date or not AND if it follows the required format (<strong>format: yyyy-mm-dd</strong>) </p> <p>This is my datepicker:</p> <pre><code>$("input[name='date']").datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, numberOfMonths: 3, showButtonPanel: true}); </code></pre> <p>I looked on this solution, "<a href="https://stackoverflow.com/questions/2990610/how-to-validate">How to validate datepicker to forbid/reject certain dates?</a>". It looks simple enough, but it only checks whether it's a weekend. It does not checks it the user entered a date, a random number or a typo (1231....30-30-2011...30/30/2011...212-565-565...etc.).</p> <p>Please fiddle with my fiddle: <a href="http://jsfiddle.net/MDa4A/" rel="noreferrer">http://jsfiddle.net/MDa4A/</a></p> <p><br/><br/><br/><strong>Additional info (11-10-2011):</strong><br/> (Try these jsFiddles and type 0-0-0 or 0/0/0)</p> <p>I used your answers to come up with a solution. It works when I use the format <strong>"yy-mm-dd"</strong>: <a href="http://jsfiddle.net/LyEvQ/" rel="noreferrer">http://jsfiddle.net/LyEvQ/</a></p> <p>BUT it is totally useless when I use a different format <strong>(Ej.: "mm/dd/yy")</strong>: <a href="http://jsfiddle.net/LyEvQ/1/" rel="noreferrer">http://jsfiddle.net/LyEvQ/1/</a></p> <p>I need both to work. Can you please help</p>
8,054,052
3
2
null
2011-11-08 16:46:27.613 UTC
2
2017-02-23 05:16:55.123 UTC
2017-05-23 12:34:28.393 UTC
null
-1
null
931,377
null
1
20
javascript|jquery|validation|date|datepicker
83,002
<p>Something like this should work:</p> <pre><code>jQuery.validator.addMethod("customDateValidator", function(value, element) { try { jQuery.datepicker.parseDate("mm/dd/yyyy", value); return true; } catch(e) { return false; } }, "Please enter a valid date" ); $("input[name='date']").rules("add", { customDateValidator:true }); </code></pre>
7,933,596
Django dynamic model fields
<p>I'm working on a <strong>multi-tenanted</strong> application in which some users can define their own data fields (via the admin) to collect additional data in forms and report on the data. The latter bit makes JSONField not a great option, so instead I have the following solution:</p> <pre><code>class CustomDataField(models.Model): """ Abstract specification for arbitrary data fields. Not used for holding data itself, but metadata about the fields. """ site = models.ForeignKey(Site, default=settings.SITE_ID) name = models.CharField(max_length=64) class Meta: abstract = True class CustomDataValue(models.Model): """ Abstract specification for arbitrary data. """ value = models.CharField(max_length=1024) class Meta: abstract = True </code></pre> <p>Note how CustomDataField has a ForeignKey to Site - each Site will have a different set of custom data fields, but use the same database. Then the various concrete data fields can be defined as:</p> <pre><code>class UserCustomDataField(CustomDataField): pass class UserCustomDataValue(CustomDataValue): custom_field = models.ForeignKey(UserCustomDataField) user = models.ForeignKey(User, related_name='custom_data') class Meta: unique_together=(('user','custom_field'),) </code></pre> <p>This leads to the following use:</p> <pre><code>custom_field = UserCustomDataField.objects.create(name='zodiac', site=my_site) #probably created in the admin user = User.objects.create(username='foo') user_sign = UserCustomDataValue(custom_field=custom_field, user=user, data='Libra') user.custom_data.add(user_sign) #actually, what does this even do? </code></pre> <p>But this feels very clunky, particularly with the need to manually create the related data and associate it with the concrete model. Is there a better approach? </p> <p>Options that have been pre-emptively discarded:</p> <ul> <li>Custom SQL to modify tables on-the-fly. Partly because this won't scale and partly because it's too much of a hack.</li> <li>Schema-less solutions like NoSQL. I have nothing against them, but they're still not a good fit. Ultimately this data <strong>is</strong> typed, and the possibility exists of using a third-party reporting application.</li> <li>JSONField, as listed above, as it's not going to work well with queries.</li> </ul>
7,934,577
3
1
null
2011-10-28 18:58:20.063 UTC
159
2015-12-10 04:52:04.307 UTC
2011-12-21 20:39:40.673 UTC
null
497,056
null
402,605
null
1
176
python|django|dynamic|django-models|django-custom-manager
83,972
<p><strong><em>As of today, there are four available approaches, two of them requiring a certain storage backend:</em></strong></p> <ol> <li><p><strong><a href="https://github.com/mvpdev/django-eav" rel="noreferrer">Django-eav</a></strong> (the original package is no longer mantained but has some <strong><a href="https://github.com/mvpdev/django-eav/network" rel="noreferrer">thriving forks</a></strong>) </p> <p>This solution is based on <a href="https://en.wikipedia.org/wiki/Entity-attribute-value_model" rel="noreferrer">Entity Attribute Value</a> data model, essentially, it uses several tables to store dynamic attributes of objects. Great parts about this solution is that it:</p> <ul> <li>uses several pure and simple Django models to represent dynamic fields, which makes it simple to understand and database-agnostic; </li> <li><p>allows you to effectively attach/detach dynamic attribute storage to Django model with simple commands like:</p> <pre><code>eav.unregister(Encounter) eav.register(Patient) </code></pre></li> <li><p><strong><a href="https://github.com/mvpdev/django-eav/blob/master/eav/admin.py" rel="noreferrer">Nicely integrates with Django admin</a></strong>;</p></li> <li><p>At the same time being really powerful.</p></li> </ul> <p>Downsides:</p> <ul> <li>Not very efficient. This is more of a criticism of the EAV pattern itself, which requires manually merging the data from a column format to a set of key-value pairs in the model.</li> <li>Harder to maintain. Maintaining data integrity requires a multi-column unique key constraint, which may be inefficient on some databases.</li> <li>You will need to select <a href="https://github.com/mvpdev/django-eav/network" rel="noreferrer">one of the forks</a>, since the official package is no longer maintained and there is no clear leader.</li> </ul> <p>The usage is pretty straightforward:</p> <pre><code>import eav from app.models import Patient, Encounter eav.register(Encounter) eav.register(Patient) Attribute.objects.create(name='age', datatype=Attribute.TYPE_INT) Attribute.objects.create(name='height', datatype=Attribute.TYPE_FLOAT) Attribute.objects.create(name='weight', datatype=Attribute.TYPE_FLOAT) Attribute.objects.create(name='city', datatype=Attribute.TYPE_TEXT) Attribute.objects.create(name='country', datatype=Attribute.TYPE_TEXT) self.yes = EnumValue.objects.create(value='yes') self.no = EnumValue.objects.create(value='no') self.unkown = EnumValue.objects.create(value='unkown') ynu = EnumGroup.objects.create(name='Yes / No / Unknown') ynu.enums.add(self.yes) ynu.enums.add(self.no) ynu.enums.add(self.unkown) Attribute.objects.create(name='fever', datatype=Attribute.TYPE_ENUM,\ enum_group=ynu) # When you register a model within EAV, # you can access all of EAV attributes: Patient.objects.create(name='Bob', eav__age=12, eav__fever=no, eav__city='New York', eav__country='USA') # You can filter queries based on their EAV fields: query1 = Patient.objects.filter(Q(eav__city__contains='Y')) query2 = Q(eav__city__contains='Y') | Q(eav__fever=no) </code></pre></li> <li><p><strong>Hstore, JSON or JSONB fields in PostgreSQL</strong></p> <p>PostgreSQL supports several more complex data types. Most are supported via third-party packages, but in recent years Django has adopted them into django.contrib.postgres.fields.</p> <p><strong>HStoreField</strong>:</p> <p><a href="https://github.com/jordanm/django-hstore" rel="noreferrer">Django-hstore</a> was originally a third-party package, but Django 1.8 added <strong><a href="https://docs.djangoproject.com/en/1.8/ref/contrib/postgres/fields/#hstorefield" rel="noreferrer">HStoreField</a></strong> as a built-in, along with several other PostgreSQL-supported field types.</p> <p>This approach is good in a sense that it lets you have the best of both worlds: dynamic fields and relational database. However, hstore is <a href="http://archives.postgresql.org/pgsql-performance/2011-05/msg00263.php" rel="noreferrer">not ideal performance-wise</a>, especially if you are going to end up storing thousands of items in one field. It also only supports strings for values.</p> <pre><code>#app/models.py from django.contrib.postgres.fields import HStoreField class Something(models.Model): name = models.CharField(max_length=32) data = models.HStoreField(db_index=True) </code></pre> <p>In Django's shell you can use it like this: </p> <pre><code>&gt;&gt;&gt; instance = Something.objects.create( name='something', data={'a': '1', 'b': '2'} ) &gt;&gt;&gt; instance.data['a'] '1' &gt;&gt;&gt; empty = Something.objects.create(name='empty') &gt;&gt;&gt; empty.data {} &gt;&gt;&gt; empty.data['a'] = '1' &gt;&gt;&gt; empty.save() &gt;&gt;&gt; Something.objects.get(name='something').data['a'] '1' </code></pre> <p>You can issue indexed queries against hstore fields:</p> <pre><code># equivalence Something.objects.filter(data={'a': '1', 'b': '2'}) # subset by key/value mapping Something.objects.filter(data__a='1') # subset by list of keys Something.objects.filter(data__has_keys=['a', 'b']) # subset by single key Something.objects.filter(data__has_key='a') </code></pre> <p><strong>JSONField</strong>:</p> <p>JSON/JSONB fields support any JSON-encodable data type, not just key/value pairs, but also tend to be faster and (for JSONB) more compact than Hstore. Several packages implement JSON/JSONB fields including <strong><a href="https://django-pgfields.readthedocs.org/en/latest/fields.html" rel="noreferrer">django-pgfields</a></strong>, but as of Django 1.9, <strong><a href="https://docs.djangoproject.com/en/1.9/ref/contrib/postgres/fields/#jsonfield" rel="noreferrer">JSONField</a></strong> is a built-in using JSONB for storage. <strong>JSONField</strong> is similar to HStoreField, and may perform better with large dictionaries. It also supports types other than strings, such as integers, booleans and nested dictionaries.</p> <pre><code>#app/models.py from django.contrib.postgres.fields import JSONField class Something(models.Model): name = models.CharField(max_length=32) data = JSONField(db_index=True) </code></pre> <p>Creating in the shell:</p> <pre><code>&gt;&gt;&gt; instance = Something.objects.create( name='something', data={'a': 1, 'b': 2, 'nested': {'c':3}} ) </code></pre> <p>Indexed queries are nearly identical to HStoreField, except nesting is possible. Complex indexes may require manually creation (or a scripted migration).</p> <pre><code>&gt;&gt;&gt; Something.objects.filter(data__a=1) &gt;&gt;&gt; Something.objects.filter(data__nested__c=3) &gt;&gt;&gt; Something.objects.filter(data__has_key='a') </code></pre></li> <li><p><strong><a href="http://django-mongodb-engine.readthedocs.org/en/latest/" rel="noreferrer">Django MongoDB</a></strong></p> <p>Or other NoSQL Django adaptations -- with them you can have fully dynamic models.</p> <p>NoSQL Django libraries are great, but keep in mind that they are not 100% the Django-compatible, for example, to migrate to <a href="http://www.allbuttonspressed.com/projects/django-nonrel" rel="noreferrer">Django-nonrel</a> from standard Django you will need to replace ManyToMany with <a href="https://stackoverflow.com/questions/3877246/django-nonrel-on-google-app-engine-implications-of-using-listfield-for-manytom">ListField</a> among other things. </p> <p>Checkout this Django MongoDB example:</p> <pre><code>from djangotoolbox.fields import DictField class Image(models.Model): exif = DictField() ... &gt;&gt;&gt; image = Image.objects.create(exif=get_exif_data(...)) &gt;&gt;&gt; image.exif {u'camera_model' : 'Spamcams 4242', 'exposure_time' : 0.3, ...} </code></pre> <p>You can even create <a href="http://django-mongodb.org/topics/embedded-models.html" rel="noreferrer">embedded lists</a> of any Django models:</p> <pre><code>class Container(models.Model): stuff = ListField(EmbeddedModelField()) class FooModel(models.Model): foo = models.IntegerField() class BarModel(models.Model): bar = models.CharField() ... &gt;&gt;&gt; Container.objects.create( stuff=[FooModel(foo=42), BarModel(bar='spam')] ) </code></pre></li> <li><p><strong><a href="https://github.com/charettes/django-mutant" rel="noreferrer">Django-mutant: Dynamic models based on syncdb and South-hooks</a></strong></p> <p><a href="https://github.com/charettes/django-mutant" rel="noreferrer">Django-mutant</a> implements fully dynamic Foreign Key and m2m fields. And is inspired by incredible but somewhat hackish solutions by <a href="http://dynamic-models.readthedocs.org/en/latest/index.html" rel="noreferrer">Will Hardy</a> and Michael Hall.</p> <p>All of these are based on Django South hooks, which, according to <a href="http://blip.tv/djangocon-europe-2011/wednesday-1415-will-hardy-5311186" rel="noreferrer">Will Hardy's talk at DjangoCon 2011</a> <strong>(watch it!)</strong> are nevertheless robust and tested in production (<a href="http://dynamic-models.readthedocs.org/en/latest/" rel="noreferrer">relevant source code</a>).</p> <p>First to <a href="https://bitbucket.org/mhall119/dynamo/overview" rel="noreferrer">implement this</a> was <a href="http://mhall119.com/2011/02/fun-with-django-meta-classes-and-dynamic-models/" rel="noreferrer">Michael Hall</a>.</p> <p>Yes, this is magic, with these approaches you can achieve <strong>fully dynamic Django apps, models and fields</strong> with any relational database backend. But at what cost? Will stability of application suffer upon heavy use? These are the questions to be considered. You need to be sure to maintain a proper <a href="https://stackoverflow.com/questions/1123200/how-to-lock-a-critical-section-in-django">lock</a> in order to allow simultaneous database altering requests.</p> <p>If you are using Michael Halls lib, your code will look like this:</p> <pre><code>from dynamo import models test_app, created = models.DynamicApp.objects.get_or_create( name='dynamo' ) test, created = models.DynamicModel.objects.get_or_create( name='Test', verbose_name='Test Model', app=test_app ) foo, created = models.DynamicModelField.objects.get_or_create( name = 'foo', verbose_name = 'Foo Field', model = test, field_type = 'dynamiccharfield', null = True, blank = True, unique = False, help_text = 'Test field for Foo', ) bar, created = models.DynamicModelField.objects.get_or_create( name = 'bar', verbose_name = 'Bar Field', model = test, field_type = 'dynamicintegerfield', null = True, blank = True, unique = False, help_text = 'Test field for Bar', ) </code></pre></li> </ol>
11,786,530
Can python threads access variables in the namespace?
<p>I have a script that creates a bunch of threads, runs a program to use the threads to run tasks from a queue, and returns something from each thread. I want to count how many of these returned successfully, so I set a variable "successful=0" and increment it every time the queue reports a task completed successfully.</p> <p>However, I'm getting "UnboundLocalError: local variable 'successful' referenced before assignment"</p> <p>What's going on?</p> <p>Here's some example code:</p> <pre><code>successful = 0 q = Queue(200) for i in range(100): t=Thread(target=foo) t.daemon=True t.start() def foo(): while True: task=q.get() #do some work print task successful+=1 # triggers an error q.task_done() for i in range(100): q.put("Foo") q.join() print successful </code></pre>
11,786,875
3
0
null
2012-08-02 22:07:00.563 UTC
13
2012-08-03 15:47:32.743 UTC
null
null
null
null
331,118
null
1
18
python|multithreading|scope|queue
27,154
<pre><code>successful+=1 </code></pre> <p>is not a thread-safe operation. With multiple threads trying to increment a shared global variable, collisions may happen and <code>successful</code> will not be incremented properly.</p> <p>To avoid this error, use a lock:</p> <pre><code>lock = threading.Lock() def foo(): global successful while True: ... with lock: successful+=1 </code></pre> <hr> <p>Here is some code to demonstrate that x += 1 is not threadsafe:</p> <pre><code>import threading lock = threading.Lock() x = 0 def foo(): global x for i in xrange(1000000): # with lock: # Uncomment this to get the right answer x += 1 threads = [threading.Thread(target=foo), threading.Thread(target=foo)] for t in threads: t.daemon = True t.start() for t in threads: t.join() print(x) </code></pre> <p>yields:</p> <pre><code>% test.py 1539065 % test.py 1436487 </code></pre> <p>These results do not agree and are less than the expected 2000000. Uncommenting the lock yields the correct result.</p>
11,980,062
In python, how do you import all classes from another module without keeping the imported module's namespace?
<p>How do you import classes and methods from another module without retaining the former module namespace? </p> <p>I am current refactoring some legacy code and am frequently doing imports similar to these. </p> <pre><code>from legacy_module import ClassA as ClassA from legacy_module import ClassB as ClassB from legacy_module import ClassC as ClassC from legacy_module import methodA as methodA from legacy_module import methodB as methodB </code></pre> <p>This is done so that the classes can be referenced as ClassA rather than legacy_module.ClassA. </p> <p>In python, how do you import all of the classes and methods above in a single statement? </p> <pre><code>from legacy_module import * as * </code></pre>
11,980,088
1
0
null
2012-08-16 02:48:55.443 UTC
null
2012-08-16 03:34:21.743 UTC
null
null
null
null
160,507
null
1
32
python
39,008
<p>Use <code>from legacy_module import *</code> as your entire import.</p>
11,489,055
SQLite ORDER BY string containing number starting with 0
<p>as the title states:</p> <p>I have a select query, which I'm trying to "order by" a field which contains numbers, the thing is this numbers are really strings starting with 0s, so the "order by" is doing this...</p> <pre><code>... 10 11 12 01 02 03 ... </code></pre> <p>Any thoughts?</p> <p>EDIT: if I do this: "...ORDER BY (field+1)" I can workaround this, because somehow the string is internally being converted to integer. Is this the a way to "officially" convert it like C's atoi? </p>
11,489,098
5
4
null
2012-07-15 03:01:51.49 UTC
12
2019-07-12 12:49:17.043 UTC
2013-09-04 03:16:52.95 UTC
null
1,447,087
null
1,447,087
null
1
39
sql|string|sqlite|sql-order-by|numeric
35,284
<p>You can use <code>CAST</code> <a href="http://www.sqlite.org/lang_expr.html#castexpr" rel="noreferrer">http://www.sqlite.org/lang_expr.html#castexpr</a> to cast the expression to an Integer.</p> <pre><code>sqlite&gt; CREATE TABLE T (value VARCHAR(2)); sqlite&gt; INSERT INTO T (value) VALUES ('10'); sqlite&gt; INSERT INTO T (value) VALUES ('11'); sqlite&gt; INSERT INTO T (value) VALUES ('12'); sqlite&gt; INSERT INTO T (value) VALUES ('01'); sqlite&gt; INSERT INTO T (value) VALUES ('02'); sqlite&gt; INSERT INTO T (value) VALUES ('03'); sqlite&gt; SELECT * FROM T ORDER BY CAST(value AS INTEGER); 01 02 03 10 11 12 sqlite&gt; </code></pre> <blockquote> <p>if I do this: &quot;...ORDER BY (field+1)&quot; I can workaround this, because somehow the string is internally being converted to integer. Is the a way to &quot;officially&quot; convert it like C's atoi?</p> </blockquote> <p>Well thats interesting, though I dont know how many <code>DBMS</code> support such an operation so I don't recommend it just in case you ever need to use a different system that doesn't support it, not to mention you are adding an extra operation, which can affect performance, though you also do this <code>ORDER BY (field + 0)</code> Im going to investigate the performance</p> <p>taken from the sqlite3 docs:</p> <blockquote> <p>A CAST expression is used to convert the value of to a different storage class in a similar way to the conversion that takes place when a <b>column affinity</b> is applied to a value. Application of a CAST expression is different to application of a column affinity, as with a CAST expression the storage class conversion is forced even if it is lossy and irrreversible.</p> <p>4.0 Operators<br/> All mathematical operators (+, -, *, /, %, &lt;&lt;, &gt;&gt;, &amp;, and |) cast both operands to the NUMERIC storage class prior to being carried out. The cast is carried through even if it is lossy and irreversible. A NULL operand on a mathematical operator yields a NULL result. An operand on a mathematical operator that does not look in any way numeric and is not NULL is converted to 0 or 0.0.</p> </blockquote> <p>I was curios so I ran some benchmarks:</p> <pre><code>&gt;&gt;&gt; setup = &quot;&quot;&quot; ... import sqlite3 ... import timeit ... ... conn = sqlite3.connect(':memory:') ... c = conn.cursor() ... c.execute('CREATE TABLE T (value int)') ... for index in range(4000000, 0, -1): ... _ = c.execute('INSERT INTO T (value) VALUES (%i)' % index) ... conn.commit() ... &quot;&quot;&quot; &gt;&gt;&gt; &gt;&gt;&gt; cast_conv = &quot;result = c.execute('SELECT * FROM T ORDER BY CAST(value AS INTEGER)')&quot; &gt;&gt;&gt; cast_affinity = &quot;result = c.execute('SELECT * FROM T ORDER BY (value + 0)')&quot; &gt;&gt;&gt; timeit.Timer(cast_conv, setup).timeit(number = 1) 18.145697116851807 &gt;&gt;&gt; timeit.Timer(cast_affinity, setup).timeit(number = 1) 18.259973049163818 &gt;&gt;&gt; </code></pre> <p>As we can see its a bit slower though not by much, interesting.</p>
11,476,371
Sort by multiple keys using different orderings
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/11206884/how-to-write-python-sort-key-functions-for-descending-values">How to write Python sort key functions for descending values</a> </p> </blockquote> <p>In Python 3, it's pretty easy to sort a list of objects lexicographically using multiple keys. For example:</p> <p><code>items.sort(key = lambda obj: obj.firstname, obj.lastname)</code></p> <p>The <code>reverse</code> argument lets you specify whether you want ascending or descending order. But what do you do in the case where you want to sort by multiple keys, but you want to sort using descending order for the first key, and ascending order for the second?</p> <p>For example, suppose we have an object with two attributes, <code>points</code> and <code>name</code>, where <code>points</code> is an <code>int</code> and <code>name</code> is a <code>str</code>. We want to sort a list of these objects by <code>points</code> in <em>descending</em> order (so that the object with the greatest number of points comes first), but for objects with an equal number of <code>points</code>, we want to sort these by <code>name</code> in alphabetical (<em>ascending</em>) order.</p> <p>How can this be achieved?</p>
11,476,588
3
1
null
2012-07-13 18:38:38.597 UTC
23
2012-07-13 19:47:20.807 UTC
2017-05-23 12:18:07.867 UTC
null
-1
null
469,408
null
1
60
python|python-3.x
35,151
<p>There is no built-in way to handle this. For the general case, you must sort twice: first by the secondary sort, then by the primary sort. As @Mark Ransom mentioned in his comment, in many cases the variables are numeric, and so you can use the negative value to flip the ordering.</p> <p>If you know the type of the variable you're trying to sort on and how to work with it, you could also write a key function that returns a decreasing value for increasing keys. See <a href="http://www.gossamer-threads.com/lists/python/python/539884" rel="noreferrer">this thread</a> for an example for strings. (Basically, you take the negative of the ASCII numerical value of the characters.)</p> <p>In Python 2, you could also use a <code>cmp</code> function instead of a key, but this will likely make the sort slower. Whether it will make it too slow depends on how big and unsorted the list is. In Python 3, the <code>cmp</code> argument is gone, but as @Mark Ransom notes you could use <code>cmp_to_key</code>.</p>
11,830,174
How to flatten tree via LINQ?
<p>So I have simple tree:</p> <pre><code>class MyNode { public MyNode Parent; public IEnumerable&lt;MyNode&gt; Elements; int group = 1; } </code></pre> <p>I have a <code>IEnumerable&lt;MyNode&gt;</code>. I want to get a list of all <code>MyNode</code> (including inner node objects (<code>Elements</code>)) as one flat list <code>Where</code> <code>group == 1</code>. How to do such thing via LINQ?</p>
11,830,287
16
4
null
2012-08-06 14:22:05.487 UTC
49
2022-08-25 11:03:58.62 UTC
null
null
null
null
1,056,328
null
1
107
c#|.net|linq|.net-4.0|tree
56,669
<p>You can flatten a tree like this:</p> <pre><code>IEnumerable&lt;MyNode&gt; Flatten(IEnumerable&lt;MyNode&gt; e) =&gt; e.SelectMany(c =&gt; Flatten(c.Elements)).Concat(new[] { e }); </code></pre> <p>You can then filter by <code>group</code> using <code>Where(...)</code>.</p> <p>To earn some "points for style", convert <code>Flatten</code> to an extension function in a static class.</p> <pre><code>public static IEnumerable&lt;MyNode&gt; Flatten(this IEnumerable&lt;MyNode&gt; e) =&gt; e.SelectMany(c =&gt; c.Elements.Flatten()).Concat(e); </code></pre> <p>To earn more points for "even better style", convert <code>Flatten</code> to a generic extension method that takes a tree and a function that produces descendants from a node:</p> <pre><code>public static IEnumerable&lt;T&gt; Flatten&lt;T&gt;( this IEnumerable&lt;T&gt; e , Func&lt;T,IEnumerable&lt;T&gt;&gt; f ) =&gt; e.SelectMany(c =&gt; f(c).Flatten(f)).Concat(e); </code></pre> <p>Call this function like this:</p> <pre><code>IEnumerable&lt;MyNode&gt; tree = .... var res = tree.Flatten(node =&gt; node.Elements); </code></pre> <p>If you would prefer flattening in pre-order rather than in post-order, switch around the sides of the <code>Concat(...)</code>.</p>
11,787,330
Is it possible in SASS to inherit from a class in another file?
<p>The question pretty much says it all.</p> <p>For instance, if I were using, say, <a href="http://twitter.github.com/bootstrap/" rel="noreferrer">Twitter Bootstrap</a>, could I define classes in my own SASS stylesheet that inherit from Bootstrap's CSS classes? Or does inheritance in SASS only work within the scope of a single file?</p>
15,272,790
4
0
null
2012-08-02 23:36:00.413 UTC
13
2020-06-25 13:06:29.667 UTC
2013-03-07 13:47:55.883 UTC
null
2,053,161
null
105,570
null
1
111
css|inheritance|stylesheet|sass
66,788
<p><strong>YES!</strong> its possible.</p> <p>If you want all <code>&lt;button&gt;</code> elements to inherit the <code>.btn</code> class from <a href="http://twitter.github.com/bootstrap/base-css.html#buttons">Twitter Bootstrap's Default buttons</a></p> <p>In your <code>styles.scss</code> file you would have to first import <code>_bootstrap.scss</code>:</p> <pre><code>@import "_bootstrap.scss"; </code></pre> <p>Then below the import:</p> <pre><code>button { @extend .btn; } </code></pre>
11,614,047
What makes a keychain item unique (in iOS)?
<p>My question concerns keychains in iOS (iPhone, iPad, ...). I think (but am not sure) that the implementation of keychains under Mac OS X raises the same question with the same answer.</p> <hr> <p>iOS provides five types (classes) of keychain items. You must chose one of those five values for the key <code>kSecClass</code> to determine the type:</p> <pre><code>kSecClassGenericPassword used to store a generic password kSecClassInternetPassword used to store an internet password kSecClassCertificate used to store a certificate kSecClassKey used to store a kryptographic key kSecClassIdentity used to store an identity (certificate + private key) </code></pre> <p>After long time of reading apples documentation, blogs and forum-entries, I found out that a keychain item of type <code>kSecClassGenericPassword</code> gets its uniqueness from the attributes <code>kSecAttrAccessGroup</code>, <code>kSecAttrAccount</code> and <code>kSecAttrService</code>.</p> <p>If those three attributes in request 1 are the same as in request 2, then you receive the same generic password keychain item, regardless of any other attributes. If one (or two or all) of this attributes changes its value, then you get different items.</p> <p>But <code>kSecAttrService</code> is only available for items of type <code>kSecClassGenericPassword</code>, so it can't be part of the "unique key" of an item of any other type, and there seems to be no documentation that points out clearly which attributes uniquely determine a keychain item.</p> <p>The sample code in the class "KeychainItemWrapper" of "GenericKeychain" uses the attribute <code>kSecAttrGeneric</code> to make an item unique, but this is a bug. The two entries in this example only are stored as two distinct entries, because their <code>kSecAttrAccessGroup</code> is different (one has the access group set, the other lets it free). If you try to add a 2nd password without an access group, using Apple's <code>KeychainItemWrapper</code>, you will fail.</p> <p><strong>So, please, answer my questions:</strong> </p> <ul> <li>Is it true, that the combination of <code>kSecAttrAccessGroup</code>, <code>kSecAttrAccount</code> and <code>kSecAttrService</code> is the "unique key" of a keychain item whose kSecClass is <code>kSecClassGenericPassword</code>? </li> <li>Which attributes makes a keychain item unique if its <code>kSecClass</code> is not <code>kSecClassGenericPassword</code>?</li> </ul>
11,672,200
4
1
null
2012-07-23 14:00:14.523 UTC
92
2020-03-18 15:33:58.38 UTC
2016-08-17 21:49:16.307 UTC
null
231,684
null
1,302,716
null
1
121
objective-c|ios|macos|keychain
25,999
<p>The primary keys are as follows (derived from open source files from Apple, see <a href="http://www.opensource.apple.com/source/libsecurity_cdsa_utilities/libsecurity_cdsa_utilities-55006/lib/Schema.m4" rel="noreferrer">Schema.m4</a>, <a href="http://www.opensource.apple.com/source/libsecurity_cdsa_utilities/libsecurity_cdsa_utilities-55006/lib/KeySchema.m4" rel="noreferrer">KeySchema.m4</a> and <a href="http://opensource.apple.com/source/libsecurity_keychain/libsecurity_keychain-55050.2/lib/SecItem.cpp" rel="noreferrer">SecItem.cpp</a>):</p> <ul> <li>For a keychain item of class <code>kSecClassGenericPassword</code>, the primary key is the combination of <code>kSecAttrAccount</code> and <code>kSecAttrService</code>.</li> <li>For a keychain item of class <code>kSecClassInternetPassword</code>, the primary key is the combination of <code>kSecAttrAccount</code>, <code>kSecAttrSecurityDomain</code>, <code>kSecAttrServer</code>, <code>kSecAttrProtocol</code>, <code>kSecAttrAuthenticationType</code>, <code>kSecAttrPort</code> and <code>kSecAttrPath</code>.</li> <li>For a keychain item of class <code>kSecClassCertificate</code>, the primary key is the combination of <code>kSecAttrCertificateType</code>, <code>kSecAttrIssuer</code> and <code>kSecAttrSerialNumber</code>.</li> <li>For a keychain item of class <code>kSecClassKey</code>, the primary key is the combination of <code>kSecAttrApplicationLabel</code>, <code>kSecAttrApplicationTag</code>, <code>kSecAttrKeyType</code>, <code>kSecAttrKeySizeInBits</code>, <code>kSecAttrEffectiveKeySize</code>, and the creator, start date and end date which are not exposed by SecItem yet.</li> <li>For a keychain item of class <code>kSecClassIdentity</code> I haven't found info on the primary key fields in the open source files, but as an identity is the combination of a private key and a certificate, I assume the primary key is the combination of the primary key fields for <code>kSecClassKey</code> and <code>kSecClassCertificate</code>.</li> </ul> <p>As each keychain item belongs to a keychain access group, it feels like the keychain access group (field <code>kSecAttrAccessGroup</code>) is an added field to all these primary keys.</p>
3,505,170
Entity Framework - what's the difference between using Include/eager loading and lazy loading?
<p>I've been trying to familiarize myself with the Entity Framework. Most of it seems straight forward, but I'm a bit confused on the difference between eager loading with the Include method and default lazy loading. Both seem like they load related entities, so on the surface it looks like they do the same thing. What am I missing?</p>
3,505,233
4
0
null
2010-08-17 17:27:55.9 UTC
12
2018-03-28 05:37:11.543 UTC
null
null
null
null
399,584
null
1
18
entity-framework|lazy-loading|eager-loading
11,800
<p>Let's say you have two entities with a one-to-many relationship: Customer and Order, where each Customer can have multiple Orders.</p> <p>When loading up a Customer entity, Entity Framework allows you to either eager load or lazy load the Customer's Orders collection. If you choose to eager load the Orders collection, when you retrieve a Customer out of the database Entity Framework will generate SQL that retrieves <em>both</em> the Customer's information and the Customer's Orders in one query. However, if you choose to lazy load the Orders collection, when you retrieve a Customer out of the database Entity Framework will generate SQL that <em>only</em> pulls the Customer's information (Entity Framework will then generate a separate SQL statement if you access the Customer's Orders collection later in your code).</p> <p>Determining when to use eager loading and when to use lazy loading all comes down to what you expect to do with the entities you retrieve. If you know you only need a Customer's information, then you should lazy-load the Orders collection (so that the SQL query can be efficient by only retrieving the Customer's information). Conversely, if you know you'll need to traverse through a Customer's Orders, then you should eager-load the Orders (so you'll save yourself an extra database hit once you access the Customer's Orders in your code).</p> <p>P.S. Be very careful when using lazy-loading as it can lead to the N+1 problem. For example, let's say you have a page that displays a list of Customers and their Orders. However, you decide to use lazy-loading when fetching the Orders. When you iterate over the Customers collection, then over each Customer's Orders, you'll perform a database hit for each Customer to lazy-load in their Orders collection. This means that for N customers, you'll have N+1 database hits (1 database hit to load up all the Customers, then N database hits to load up each of their Orders) instead of just 1 database hit had you used eager loading (which would have retrieved all Customers and their Orders in one query).</p>
3,511,057
Git receive/update hooks and new branches
<p>I have a problem with the 'update' hook. In the case of a new branch, it gets a 0000000000000000000000000000000000000000 as the 'oldrev'. And I don't know how to handle that case.</p> <p>We have the requirement, that every commit message references a valid Jira issue. So I have installed an "update" hook on our central repository. That hook gets an "oldrev" and a "newrev". I then pass those to "git rev-list" like this:</p> <p><code>git rev-list $oldrev..$newrev</code></p> <p>This gives me the list of all revs, which I can then iterate through, and do whatever I need to do.</p> <p>The problem is, when the user pushes a new branch, the hook gets 0000000000000000000000000000000000000000 as the oldrev. And "git rev-list" simply complains with:</p> <p><code>fatal: Invalid revision range 0000000000000000000000000000000000000000..21bac83b2</code></p> <p>So how do I get the list of all the revs that are on that new branch? I have searched the net for quite some time now, and found nothing. The example hooks I found either</p> <ul> <li>don't handle the problem, and fail with the above error message</li> <li>incorrectly try to fix the problem by setting the oldrev to "", which returns the wrong results from rev-list</li> <li>simply give up when they encounter that oldrev</li> </ul> <p>None of these sound particularly exciting.</p> <p>So does someone have any idea how to get the right answer in that case? I was thinking about querying git for "give me all revs that are reachable from newrev, but not from any of the other branches (=all branches except the new one)". But even that would give the wrong answer if there had been a merge from the new branch to any of the old ones.</p>
3,512,275
4
1
null
2010-08-18 10:23:24.847 UTC
5
2014-06-19 17:15:51.533 UTC
null
null
null
null
410,713
null
1
34
git|git-push|githooks
11,934
<p>The term "right answer" is a bit ambiguous in this case. I actually think that "all revs reachable from newrev but nowhere else" is completely correct. This is true even if there was a merge - in that case, you should see the commits unique to the new ref, and the merge commit, but not the commits that were merged.</p> <p>So, I would say, check if the "oldrev" is all zeroes, and if it is, act accordingly:</p> <pre class="lang-sh prettyprint-override"><code>if [ "$oldrev" -eq 0 ]; then # list everything reachable from newrev but not any heads git rev-list $(git for-each-ref --format='%(refname)' refs/heads/* | sed 's/^/\^/') "$newrev" else git rev-list "$oldrev..$newrev" fi </code></pre>
3,338,680
Is there a CSS selector by class prefix?
<p>I want to apply a CSS rule to any element whose one of the classes matches specified prefix.</p> <p>E.g. I want a rule that will apply to div that has class that starts with <code>status-</code> (A and C, but not B in following snippet):</p> <pre class="lang-html prettyprint-override"><code>&lt;div id='A' class='foo-class status-important bar-class'&gt;&lt;/div&gt; &lt;div id='B' class='foo-class bar-class'&gt;&lt;/div&gt; &lt;div id='C' class='foo-class status-low-priority bar-class'&gt;&lt;/div&gt; </code></pre> <p>Some sort of combination of:<br> <code>div[class|=status]</code> and <code>div[class~=status-]</code></p> <p>Is it doable under CSS 2.1? Is it doable under any CSS spec?</p> <p>Note: I do know I can use jQuery to emulate that.</p>
8,588,532
4
0
null
2010-07-26 20:22:08.693 UTC
56
2018-11-19 00:38:14.027 UTC
2015-06-22 01:09:21.33 UTC
null
2,756,409
null
93,422
null
1
225
css|css-selectors
150,513
<p>It's not doable with CSS2.1, but it is possible with CSS3 attribute substring-matching selectors (which <em>are</em> supported in IE7+):</p> <pre><code>div[class^="status-"], div[class*=" status-"] </code></pre> <p>Notice the space character in the second attribute selector. This picks up <code>div</code> elements whose <code>class</code> attribute meets either of these conditions:</p> <ul> <li><p><code>[class^="status-"]</code> — starts with "status-"</p></li> <li><p><code>[class*=" status-"]</code> — contains the substring "status-" occurring directly after a space character. Class names are separated by whitespace <a href="http://www.w3.org/TR/html5/dom.html#classes" rel="noreferrer">per the HTML spec</a>, hence the significant space character. This checks any other classes after the first if multiple classes are specified, <em>and</em> adds a bonus of checking the first class in case the attribute value is space-padded (which can happen with some applications that output <code>class</code> attributes dynamically).</p></li> </ul> <p>Naturally, this also works in jQuery, as demonstrated <a href="https://stackoverflow.com/questions/4524412/jquery-selector-to-target-any-class-name-of-multiple-present-starting-with-a-p/4524477#4524477">here</a>.</p> <p>The reason you need to combine two attribute selectors as described above is because an attribute selector such as <code>[class*="status-"]</code> will match the following element, which may be undesirable:</p> <pre><code>&lt;div id='D' class='foo-class foo-status-bar bar-class'&gt;&lt;/div&gt; </code></pre> <p>If you can ensure that such a scenario will <strong>never</strong> happen, then you are free to use such a selector for the sake of simplicity. However, the combination above is much more robust.</p> <p>If you have control over the HTML source or the application generating the markup, it may be simpler to just make the <code>status-</code> prefix its own <code>status</code> class instead <a href="https://stackoverflow.com/questions/3338680/is-there-a-css-selector-by-class-prefix/3338690#3338690">as Gumbo suggests</a>.</p>
3,946,709
#1222 - The used SELECT statements have a different number of columns
<p>Why am i getting a #1222 - The used SELECT statements have a different number of columns ? i am trying to load wall posts from this users friends and his self.</p> <pre><code>SELECT u.id AS pid, b2.id AS id, b2.message AS message, b2.date AS date FROM ( ( SELECT b.id AS id, b.pid AS pid, b.message AS message, b.date AS date FROM wall_posts AS b JOIN Friends AS f ON f.id = b.pid WHERE f.buddy_id = '1' AND f.status = 'b' ORDER BY date DESC LIMIT 0, 10 ) UNION ( SELECT * FROM wall_posts WHERE pid = '1' ORDER BY date DESC LIMIT 0, 10 ) ORDER BY date DESC LIMIT 0, 10 ) AS b2 JOIN Users AS u ON b2.pid = u.id WHERE u.banned='0' AND u.email_activated='1' ORDER BY date DESC LIMIT 0, 10 </code></pre> <p>The wall_posts table structure looks like <code>id</code> <code>date</code> <code>privacy</code> <code>pid</code> <code>uid</code> <code>message</code></p> <p>The Friends table structure looks like <code>Fid</code> <code>id</code> <code>buddy_id</code> <code>invite_up_date</code> <code>status</code></p> <p>pid stands for profile id. I am not really sure whats going on.</p>
3,946,730
5
0
null
2010-10-15 22:50:23.323 UTC
3
2020-09-23 09:04:23.313 UTC
2010-10-15 22:53:45.187 UTC
null
135,152
null
458,642
null
1
12
sql|mysql|mysql-error-1222
55,954
<p>The first statement in the UNION returns four columns:</p> <pre><code>SELECT b.id AS id, b.pid AS pid, b.message AS message, b.date AS date FROM wall_posts AS b </code></pre> <p>The second one returns <strong><em>six</em></strong>, because the * expands to include all the columns from <code>WALL_POSTS</code>:</p> <pre><code>SELECT b.id, b.date, b.privacy, b.pid. b.uid message FROM wall_posts AS b </code></pre> <p>The <code>UNION</code> and <code>UNION ALL</code> operators require that:</p> <ol> <li>The same number of columns exist in all the statements that make up the UNION'd query</li> <li>The data types have to match at each position/column</li> </ol> <p>Use:</p> <pre><code>FROM ((SELECT b.id AS id, b.pid AS pid, b.message AS message, b.date AS date FROM wall_posts AS b JOIN Friends AS f ON f.id = b.pid WHERE f.buddy_id = '1' AND f.status = 'b' ORDER BY date DESC LIMIT 0, 10) UNION (SELECT id, pid, message, date FROM wall_posts WHERE pid = '1' ORDER BY date DESC LIMIT 0, 10)) </code></pre>
3,822,609
Documentation and API Samples for drawing on Windows Aero Glass (DWM, GDI, GDI+) for all Win32 programmers
<p>I am looking for good resources for learning to use the Win32/GDI APIs or whatever supercedes it to draw and paint directly using the Win32 API to a glass form.</p> <p>While I am using Delphi, I tagged this as Delphi or Visual C++. Any code samples and articles that you can find would be appreciated. MSDN articles do not seem to be written about this.</p> <p>As a goal, let's imagine you want to either: (a) Reproduce what Google Chrome does (tabs as part of the glass frame) (b) Reproduce what MS Office 2010 does (save button on the glass frame, referred to in MFC for VS 2010, as "Quick Access Toolbar" (see picture below).</p> <p>I am not using MFC, but if examining the MFC sources would be a good source of information, I am curious to know where in the MFC sources or BCG original sources (I have both) are implemented the Quick Access Toolbar rendering/painting code.</p> <p><img src="https://i.stack.imgur.com/FsMaR.png" alt="alt text"></p> <p>Update: A related neato link from one of the answers below shows the NC (nonclient) Paint message, and how to handle it when painting on a glass frame, and an MSDN article about it <a href="http://msdn.microsoft.com/en-us/library/bb688195(VS.85).aspx" rel="noreferrer">here</a>.</p>
3,826,784
5
0
null
2010-09-29 14:31:08.64 UTC
17
2013-12-03 23:38:13.147 UTC
2013-12-03 23:38:13.147 UTC
null
464,709
null
84,704
null
1
18
windows|delphi|visual-c++|windows-7|aero-glass
6,666
<p>This is a subset of my "Glass" bookmarks folder, the result of a <em>lot</em> of research / searching on this topic. I've found all of these useful for learning about glass and solving various problems drawing on it. Most of these include Delphi code, but I've noted where it's for another language.</p> <h2>Plain Glass links</h2> <ul> <li><a href="http://blog.delphi-jedi.net/2008/05/01/translucent-windows-with-aero/" rel="noreferrer">Using translucent windows with Delphi</a>: good introduction (from the very basics) for using Glass in Delphi forms</li> <li><a href="http://delphihaven.wordpress.com/2010/08/19/custom-drawing-on-glass-1/" rel="noreferrer">Custom drawing on glass</a>: covers how to draw a bitmap or other image on a glass area of the window. Covers alpha channels etc too, good overview</li> <li><a href="http://www.codeproject.com/KB/vista/VGGlassIntro.aspx" rel="noreferrer">Using glass in a VC++ project</a>: covers turning glass on, drawing text, handling notifications etc - a good general introduction to how it works. A lot of the underlying details are handled by the VCL (eg the <a href="http://docwiki.embarcadero.com/VCL/en/Forms.TForm.GlassFrame" rel="noreferrer">GlassFrame property</a> and TForm internals look after a lot of this) but it's very useful to understand the basics of how it's implemented at an API level anyway</li> <li><a href="http://www.codeproject.com/KB/dialog/AeroNonClientAreaButtons.aspx" rel="noreferrer">How to draw on the non-client area</a>: this shows how to draw something like Office's toolbar in the title bar. .Net code, but translatable</li> <li><a href="http://delphihaven.wordpress.com/2010/04/19/setting-up-a-custom-titlebar/" rel="noreferrer">Setting up a custom title bar</a>: very detailed article about non-client-area drawing (in Delphi, so Delphi code). Followed up by <a href="http://delphihaven.wordpress.com/2010/04/22/setting-up-a-custom-title-bar-reprise/" rel="noreferrer">part 2</a>, which demonstrates completely taking over the entire window and mimicking the standard title bar yourself. <strong>These two articles will let you mimic Office and Chrome</strong> as you requested in the question</li> <li><a href="http://delphihaven.wordpress.com/2010/07/29/controls-and-glass/" rel="noreferrer">How to set up various VCL controls to work best on a glass area</a>: the VCL does not support glass very well. You'll often get artifacts, or controls simply not drawing properly at all, no matter what you do to try and solve it. This article lists the basic VCL visual components (labels, buttons, progress bars, etc) and what to set up for each so they draw perfectly, or at least 'as well as possible' when they're placed on a glass area</li> </ul> <h2>Advanced, or tangentially related:</h2> <ul> <li><a href="http://blogs.msdn.com/b/greg_schechter/archive/2006/05/02/588934.aspx" rel="noreferrer">How desktop composition works, with GDI and DirectX surfaces</a></li> <li><a href="http://blogs.msdn.com/b/greg_schechter/archive/2006/09/14/753605.aspx" rel="noreferrer">List of desktop manager APIs</a> (only some of which are Aero-related)</li> </ul>
3,287,966
Reasons for and against moving from SQL server to MongoDB
<p>I know this is a big question and it's not a yes or no answer but we develop web apps and are looking into using MongoDB for our persistence solution. Combining MongoDB with NoRM for object storage.</p> <p>What I want to ask is what pitfalls have you experienced with switching from SQL to mongo? When is mongo simply not the right solution and is mongodb's advantages enough to move development from SQL?</p>
3,288,325
6
0
null
2010-07-20 07:52:10.463 UTC
16
2018-07-25 16:59:53.557 UTC
2017-11-26 10:21:28.897 UTC
null
3,885,376
null
43,337
null
1
47
c#|sql|mongodb|nosql
17,276
<p>In my opinion the format of your data should be the primary concern when choosing a storage backend. Do you have data that is relational in nature? If so, can it and is it a good idea to model the data in documents? Data modeling is as important in a document database as in an relational database, it just done differently. How many types of objects do you have and how are they related? Can DBrefs in Mongodb do the trick or will you miss foreign keys so much it will be painful? What are your access patterns for the data? Are you just fetching data of one type filtered by a field value, or do you have intricate fetching modes? </p> <p>Do you need ACID transactional integrity? Does the domain enforce a lot of constraints on the data? Do you need the scalability factor of a document database or is that just a "cool" thing to have?</p> <p>What are your consistency and data integrity requirements? Some NoSQL solutions and MongoDB in particular are quite loose on the write consistency in order to get performance. NoSQL is no uniform landscape and other products, e.g. CouchDB has other characteristics in this department. Some are tunable too.</p> <p>These are all questions that should go into the choice of storage. </p> <p><strong>Some Experiences</strong> </p> <ul> <li>Doing extensive reporting on the stored data can be harder when using MongoDB or any document database and some use cases have been combining RDBMS and document-db for that purpose.</li> <li>(Very) Different query model. MongoDB differs from other document-dbs too.</li> <li>Flexible to change data format/schema during development</li> <li>Unknown territory</li> <li>varying degree of maturity in drivers and frameworks</li> <li>Fast</li> <li>Simpler (in many ways) product and management tools (compared to many RDBMS products)</li> <li>No more impedance mismatch. The storage fits the data, not the other way around. </li> <li>Less friction and more direct access to data. </li> <li>Domain more tied to persistence (depending on the ORM "level" of NoRM, on how much it abstract away the backend. I haven't used NoRM so I can't answer that.)</li> </ul>
3,728,617
Adding model-wide help text to a django model's admin form
<p>In my django app, I would like to be able to add customized help text to the admin change form for some of my models. Note I'm not talking about the field specific <code>help_text</code> attribute that I can set on individual fields. For example, at the top of the change form for <code>My_Model</code> in <code>My_App</code> I'd like to be able to add some HTML that says "For additional information about My Model, see <a href="http://example.com" rel="noreferrer">http://example.com</a>" in order to provide a link to an internal documentation wiki.</p> <p>Is there any simple way of accomplishing this, or do I need to create a custom admin form for the model? If so, can you give me an example of how I would do that?</p>
3,729,995
6
0
null
2010-09-16 16:20:20.717 UTC
23
2021-08-19 18:26:22.88 UTC
null
null
null
null
58,001
null
1
54
python|django|django-models|django-admin
24,594
<p>There is a fairly simple, yet underdocumented way of accomplishing this. </p> <h2>Define render_change_form in the Admin class</h2> <p>First, you need to pass extra context to your admin. To do this, you can define a render_change_form function within your admin Class, e.g.:</p> <pre><code># admin.py class CustomAdmin(admin.ModelAdmin): def render_change_form(self, request, context, *args, **kwargs): # here we define a custom template self.change_form_template = 'admin/myapp/change_form_help_text.html' extra = { 'help_text': "This is a help message. Good luck filling out the form." } context.update(extra) return super(CustomAdmin, self).render_change_form(request, context, *args, **kwargs) </code></pre> <h2>Creating a custom template</h2> <p>Next, you need to create that custom template (change_form_help_text.html) and extend the default 'admin/change_form.html'.</p> <pre><code># change_form_help_text.html {% extends 'admin/change_form.html' %} {% block form_top %} {% if help_text %}&lt;p&gt;{{ help_text }}&lt;/p&gt;{% endif %} {% endblock %} </code></pre> <p>I've chosen to place this template inside templates/admin/myapp/, but this is also flexible.</p> <hr> <p>More info available at:</p> <p><a href="http://davidmburke.com/2010/05/24/django-hack-adding-extra-data-to-admin-interface/" rel="noreferrer">http://davidmburke.com/2010/05/24/django-hack-adding-extra-data-to-admin-interface/</a></p> <p><a href="http://code.djangoproject.com/wiki/NewformsHOWTO#Q:HowcanIpassextracontextvariablesintomyaddandchangeviews" rel="noreferrer">http://code.djangoproject.com/wiki/NewformsHOWTO#Q:HowcanIpassextracontextvariablesintomyaddandchangeviews</a></p>
3,335,162
Creating stored procedure and SQLite?
<p>Is it somehow possible to create a stored procedure, when using SQLite?</p>
3,335,202
6
0
null
2010-07-26 13:23:53.893 UTC
29
2022-09-16 00:42:28.87 UTC
2012-10-23 19:53:41.92 UTC
null
41,071
null
304,357
null
1
223
sqlite|stored-procedures
203,847
<blockquote> <p>SQLite has had to sacrifice other characteristics that some people find useful, such as high concurrency, fine-grained access control, a rich set of built-in functions, <strong><em>stored procedures</em></strong>, esoteric SQL language features, XML and/or Java extensions, tera- or peta-byte scalability, and so forth</p> </blockquote> <p>Source : <a href="http://www.sqlite.org/whentouse.html" rel="noreferrer">Appropriate Uses For SQLite</a></p>
3,464,061
Cast base class to derived class python (or more pythonic way of extending classes)
<p>I need to extend the Networkx python package and add a few methods to the <code>Graph</code> class for my particular need</p> <p>The way I thought about doing this is simplying deriving a new class say <code>NewGraph</code>, and adding the required methods.</p> <p>However there are several other functions in networkx which create and return <code>Graph</code> objects (e.g. generate a random graph). I now need to turn these <code>Graph</code> objects into <code>NewGraph</code> objects so that I can use my new methods.</p> <p>What is the best way of doing this? Or should I be tackling the problem in a completely different manner?</p>
3,464,154
9
0
null
2010-08-12 01:20:12.843 UTC
23
2021-05-24 11:11:47.653 UTC
null
null
null
null
93,580
null
1
58
python|inheritance|derived-class|base-class
53,323
<p>If you are just adding behavior, and not depending on additional instance values, you can assign to the object's <code>__class__</code>:</p> <pre><code>from math import pi class Circle(object): def __init__(self, radius): self.radius = radius def area(self): return pi * self.radius**2 class CirclePlus(Circle): def diameter(self): return self.radius*2 def circumference(self): return self.radius*2*pi c = Circle(10) print c.radius print c.area() print repr(c) c.__class__ = CirclePlus print c.diameter() print c.circumference() print repr(c) </code></pre> <p>Prints:</p> <pre><code>10 314.159265359 &lt;__main__.Circle object at 0x00A0E270&gt; 20 62.8318530718 &lt;__main__.CirclePlus object at 0x00A0E270&gt; </code></pre> <p>This is as close to a "cast" as you can get in Python, and like casting in C, it is not to be done without giving the matter some thought. I've posted a fairly limited example, but if you can stay within the constraints (just add behavior, no new instance vars), then this might help address your problem.</p>
3,861,634
How to reduce compiled file size?
<p>Lets compare c and go: Hello_world.c :</p> <pre><code>#include&lt;stdio.h&gt; int main(){ printf("Hello world!"); } </code></pre> <p>Hello_world.go:</p> <pre><code>package main import "fmt" func main(){ fmt.Printf("Hello world!") } </code></pre> <p>Compile both:</p> <pre><code>$gcc Hello_world.c -o Hello_c $8g Hello_world.go -o Hello_go.8 $8l Hello_go.8 -o Hello_go </code></pre> <p>and ... what is it?</p> <pre><code>$ls -ls ... 5,4K 2010-10-05 11:09 Hello_c ... 991K 2010-10-05 11:17 Hello_go </code></pre> <p>About 1Mb Hello world. Are you kidding me? What I do wrong?</p> <p>(strip Hello_go -> 893K only)</p>
3,861,677
11
6
null
2010-10-05 07:29:48.647 UTC
32
2021-11-22 09:37:14.983 UTC
null
null
null
null
461,133
null
1
100
go
60,007
<h2>Note: This answer is outdated</h2> <p>Please note that this answer is outdated. Please refer to the other higher-voted answers. I would like to delete this post, accepted answers can't be deleted though.</p> <hr /> <p>Is it a problem that the file is larger? I don't know Go but I would assume that it statically links some runtime lib which is not the case for the C program. But probably that is nothing to worry about as soon as your program gets larger.</p> <p>As described <a href="http://golang.org/doc/gccgo_install.html" rel="nofollow noreferrer">here</a>, statically linking the Go runtime is the default. That page also tells you how to set up for dynamic linking.</p>
3,687,315
How to delete shared preferences data from App in Android
<p>How do I delete SharedPreferences data for my application?</p> <p>I'm creating an application that uses a lot of web services to sync data. For testing purposes, I need to wipe out some SharedPreferences values when I restart the app.</p>
3,687,333
29
0
null
2010-09-10 18:34:52.493 UTC
103
2022-07-26 11:10:42.233 UTC
2019-11-14 07:13:37.843 UTC
null
6,717,610
null
406,790
null
1
570
android|sharedpreferences
473,660
<p>To remove specific values: <a href="https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#remove(java.lang.String)" rel="noreferrer">SharedPreferences.Editor.remove()</a> followed by a <code>commit()</code></p> <p>To remove them all <code>SharedPreferences.Editor.clear()</code> followed by a <code>commit()</code></p> <p>If you don't care about the return value and you're using this from your application's main thread, consider using <code>apply()</code> instead.</p>
7,983,655
Why should someone use the .NET Framework 4 Client Profile?
<p>Are there any good reasons to use .NET Framework 4 <a href="https://en.wikipedia.org/wiki/.NET_Framework_version_history#.NET_Framework_3.5_SP1_Client_Profile" rel="noreferrer">Client Profile</a> instead of the <em>full version</em>?</p> <p>I mean, real-life reasons. I am creating a .NET application, and since it's quite easy to create an installer that will install the .NET framework on a client machine, why bother using the Client Profile?</p>
7,983,733
4
1
null
2011-11-02 16:15:46.633 UTC
3
2014-04-25 21:07:13.837 UTC
2013-05-22 13:46:13.59 UTC
null
63,550
user1026028
null
null
1
29
.net
37,313
<p>The <a href="http://msdn.microsoft.com/en-us/library/cc656912.aspx">documentation</a> answers this:</p> <blockquote> <p>The .NET Framework 4 Client Profile is a subset of the .NET Framework 4 that is optimized for client applications. It provides functionality for most client applications, including Windows Presentation Foundation (WPF), Windows Forms, Windows Communication Foundation (WCF), and ClickOnce features. This enables faster deployment and a smaller install package for applications that target the .NET Framework 4 Client Profile.</p> </blockquote> <p>A smaller install package could be a bonus, especially if you're targeting non-traditional devices like tablets with less storage space. It's also a shorter download time if the Framework needs to be installed.</p>
8,293,426
error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
<p>Wrong form: </p> <pre><code>int &amp;z = 12; </code></pre> <p>Correct form:</p> <pre><code>int y; int &amp;r = y; </code></pre> <p><em><strong>Question</em></strong>:<br> Why is the first code wrong? What is the "<strong>meaning</strong>" of the error in the title?</p>
8,294,009
5
4
null
2011-11-28 08:51:09.847 UTC
43
2017-02-09 14:22:44.573 UTC
null
null
null
null
462,608
null
1
95
c++|pointers|reference
195,394
<p>C++03 3.10/1 says: "Every expression is either an lvalue or an rvalue." It's important to remember that lvalueness versus rvalueness is a property of expressions, not of objects.</p> <p>Lvalues name objects that persist beyond a single expression. For example, <code>obj</code> , <code>*ptr</code> , <code>ptr[index]</code> , and <code>++x</code> are all lvalues.</p> <p>Rvalues are temporaries that evaporate at the end of the full-expression in which they live ("at the semicolon"). For example, <code>1729</code> , <code>x + y</code> , <code>std::string("meow")</code> , and <code>x++</code> are all rvalues.</p> <p>The address-of operator requires that its "operand shall be an lvalue". if we could take the address of one expression, the expression is an lvalue, otherwise it's an rvalue. </p> <pre><code> &amp;obj; // valid &amp;12; //invalid </code></pre>
7,764,812
How to write C# Scheduler
<p>How do I write a Alert which will run at 00:00, 00:15, 00:30, and so on every day?</p> <p>Can you give me an example code?</p> <p>Thank you.</p>
7,764,862
6
3
null
2011-10-14 08:11:43.38 UTC
5
2013-12-13 09:12:42.733 UTC
2011-10-17 10:09:57.137 UTC
null
149,578
null
149,578
null
1
10
c#
44,289
<p>You can use a timer that runs every minute that checks the current time. The check can look like:</p> <pre><code>private void OnTimerTick() { if(DateTime.Now.Minutes%15==0) { //Do something } } </code></pre> <p>But if you are looking for a program or service that has to be run every 15 minutes you can just write your application and have it started using a windows planned task.</p>
8,070,805
Difference between UIImage and UIImageView
<p>What is the difference between <code>UIImage</code> and <code>UIImageView</code>? Can someone explain it with an example?</p>
8,070,847
8
0
null
2011-11-09 19:57:43.483 UTC
10
2020-08-20 11:29:50.92 UTC
2011-11-09 21:11:11.937 UTC
null
603,977
null
605,395
null
1
36
objective-c|ios|cocoa-touch|uiimageview|uiimage
26,783
<p>Example:</p> <pre><code>UIImage *bgImage = [UIImage imageNamed:@"[email protected]"]; UIImageView *backgroundImageView = [[UIImageView alloc] initWithImage:bgImage]; backgroundImageView.frame = [[UIScreen mainScreen] bounds]; </code></pre> <p><a href="http://developer.apple.com/library/ios/#documentation/uikit/reference/UIImage_Class/Reference/Reference.html"><code>UIImage</code> Overview</a>:</p> <blockquote> <p>A <code>UIImage</code> object is a high-level way to display image data. You can create images from files, from Quartz image objects, or from raw image data you receive. The UIImage class also offers several options for drawing images to the current graphics context using different blend modes and opacity values.</p> <p>Image objects are immutable, so you cannot change their properties after creation. This means that you generally specify an image’s properties at initialization time or rely on the image’s metadata to provide the property value. In some cases, however, the UIImage class provides convenience methods for obtaining a copy of the image that uses custom values for a property.</p> <p>Because image objects are immutable, they also do not provide direct access to their underlying image data. However, you can get an NSData object containing either a PNG or JPEG representation of the image data using the <code>UIImagePNGRepresentation</code> and <code>UIImageJPEGRepresentation</code> functions.</p> <p>The system uses image objects to represent still pictures taken with the camera on supported devices. To take a picture, use the UIImagePickerController class. To save a picture to the Saved Photos album, use the <code>UIImageWriteToSavedPhotosAlbum</code> function.</p> </blockquote> <p><a href="http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UIImageView_Class/Reference/Reference.html"><code>UIImageView</code> Overview</a>:</p> <blockquote> <p>An <code>UIImageView</code> provides a view-based container for displaying either a single image or for animating a series of images. For animating the images, the <code>UIImageView</code> class provides controls to set the duration and frequency of the animation. You can also start and stop the animation freely.</p> <p>New image view objects are configured to disregard user events by default. If you want to handle events in a custom subclass of <code>UIImageView</code>, you must explicitly change the value of the <code>userInteractionEnabled</code> property to <code>YES</code> after initializing the object.</p> <p>When a <code>UIImageView</code> object displays one of its images, the actual behavior is based on the properties of the image and the view. If either of the image’s <code>leftCapWidth</code> or <code>topCapHeight</code> properties are non-zero, then the image is stretched according to the values in those properties. Otherwise, the image is scaled, sized to fit, or positioned in the image view according to the contentMode property of the view. It is recommended (but not required) that you use images that are all the same size. If the images are different sizes, each will be adjusted to fit separately based on that mode.</p> <p>All images associated with a <code>UIImageView</code> object should use the same scale. If your application uses images with different scales, they may render incorrectly.</p> </blockquote>
8,302,928
AngularJS with Django - Conflicting template tags
<p>I want to use AngularJS with Django however they both use <code>{{ }}</code> as their template tags. Is there an easy way to change one of the two to use some other custom templating tag?</p>
11,108,407
12
3
null
2011-11-28 21:55:48.517 UTC
117
2017-09-16 22:39:14.273 UTC
2012-03-06 09:53:24.417 UTC
null
71,343
null
432,193
null
1
306
javascript|django|django-templates|angularjs
75,378
<p>For Angular 1.0 you should use the $interpolateProvider apis to configure the interpolation symbols: <a href="http://docs.angularjs.org/api/ng.%24interpolateProvider">http://docs.angularjs.org/api/ng.$interpolateProvider</a>.</p> <p>Something like this should do the trick:</p> <pre><code>myModule.config(function($interpolateProvider) { $interpolateProvider.startSymbol('{[{'); $interpolateProvider.endSymbol('}]}'); }); </code></pre> <p>Keep in mind two things:</p> <ul> <li>mixing server-side and client-side templates is rarely a good idea and should be used with caution. The main issues are: maintainability (hard to read) and security (double interpolation could expose a new security vector - e.g. while escaping of serverside and clientside templating by themselves might be secure, their combination might not be).</li> <li>if you start using third-party directives (components) that use <code>{{ }}</code> in their templates then your configuration will break them. (<a href="https://github.com/angular/angular.js/pull/1256">fix pending</a>)</li> </ul> <p>While there is nothing we can do about the first issue, except for warning people, we do need to address the second issue.</p>
4,480,278
List of Python format characters
<p>I've been looking for the list Python format characters for a good 30 minutes. I can't find any.</p> <p>Examples are</p> <blockquote> <p>%d, %r</p> </blockquote> <p>etc but I need a list with them along with a description if possible please.</p>
4,480,309
3
2
null
2010-12-18 21:33:10.81 UTC
11
2016-06-14 04:49:30.5 UTC
null
null
null
null
540,909
null
1
23
python|format|character
166,889
<p>Here you go, Python documentation on <a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow noreferrer">old string formatting</a>. tutorial -> 7.1.1. Old String Formatting -> "More information can be found in the [link] section".</p> <p>Note that you should start using the <a href="http://docs.python.org/tutorial/inputoutput.html#fancier-output-formatting" rel="nofollow noreferrer">new string formatting</a> when possible.</p>
4,762,594
jQuery: keyup for TAB-key?
<p>So, i'm having some trouble getting my script to run IF the Tab key is pressed. After some quick googling, the charcode for Tab is 9. Also, while we're talking, is there any better ways of checking if a key is pressed without using charcodes? I'm asking because i keep getting the following Warning by firebug when using charcode:</p> <blockquote> <p>The 'charCode' property of a keyup event should not be used. The value is meaningless.</p> </blockquote> <p>Anyway, it still works, so that's not the problem. This is the code i use:</p> <pre><code>$('/* my inputs */').keyup(function(e) { console.log('keyup called'); var code = e.keyCode || e.which; if (code == '9') { console.log('Tab pressed'); } }); </code></pre> <p>Using the above code the console is left blank, nothing is added (using Firebug). Of course i've tried actually doing stuff instead of logging text, but nothing executes. So can anyone see why this isn't working? Is there a better way of checking if a key is pressed?</p> <p>Thanks in advance.</p>
4,762,812
3
0
null
2011-01-21 18:48:54.447 UTC
6
2011-01-21 19:47:03.91 UTC
2011-01-21 18:51:14.65 UTC
null
220,819
null
584,899
null
1
43
jquery|tabs
76,112
<p>My hunch is that when you press the tab key, your form's input loses focus, before the keyup happens. Try changing the binding to the body, like this:</p> <pre><code> $('body').keyup(function(e) { console.log('keyup called'); var code = e.keyCode || e.which; if (code == '9') { alert('Tab pressed'); } }); </code></pre> <p>Then, if that works (it does for me) try changing the binding to keyDown, instead, and return false. That way you can implement your own custom behavior.</p> <pre><code>$('.yourSelector').keydown(function(e) { console.log('keyup called'); var code = e.keyCode || e.which; if (code == '9') { alert('Tab pressed'); return false; } }); </code></pre> <p>One of these two should work... if it's body, you could attach a keydown handler on body, then if it's tab, find the field with focus (I think there's function .hasFocus()?), and if it's the one you want, proceed and return false. Otherwise, let the browser do its thing.</p> <p>If you wanted to update the field WITH a tab character, try this in your callback:</p> <pre><code>var theVal = $(this).val(); theVal = theVal + ' '; $(this).val(theVal); </code></pre> <p>Haven't tested it, but it should work. You could also append 3 or 4 spaces instead of the tab character, if it's giving you trouble.</p>
4,498,998
How to initialize members in Go struct
<p>I am new to Golang so allocation in it makes me insane:</p> <pre><code>import "sync" type SyncMap struct { lock *sync.RWMutex hm map[string]string } func (m *SyncMap) Put (k, v string) { m.lock.Lock() defer m.lock.Unlock() m.hm[k] = v, true } </code></pre> <p>and later, I just call:</p> <pre><code>sm := new(SyncMap) sm.Put("Test, "Test") </code></pre> <p>At this moment I get a nil pointer panic. </p> <p>I've worked around it by using another one function, and calling it right after <code>new()</code>:</p> <pre><code>func (m *SyncMap) Init() { m.hm = make(map[string]string) m.lock = new(sync.RWMutex) } </code></pre> <p>But I wonder, if it's possible to get rid of this boilerplate initializing?</p>
4,499,375
3
1
null
2010-12-21 11:58:09.343 UTC
20
2016-08-02 18:43:16.253 UTC
2016-08-02 18:43:16.253 UTC
user6169399
null
null
255,667
null
1
58
new-operator|go
63,453
<p>You just need a constructor. A common used pattern is</p> <pre><code>func NewSyncMap() *SyncMap { return &amp;SyncMap{hm: make(map[string]string)} } </code></pre> <p>In case of more fields inside your struct, starting a goroutine as backend, or registering a finalizer everything could be done in this constructor.</p> <pre><code>func NewSyncMap() *SyncMap { sm := SyncMap{ hm: make(map[string]string), foo: "Bar", } runtime.SetFinalizer(sm, (*SyncMap).stop) go sm.backend() return &amp;sm } </code></pre>
4,475,726
Devise and OmniAuth remembering OAuth
<p>So, I just got setup using Rails 3, Devise and OmniAuth via <a href="https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview" rel="noreferrer">https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview</a>.</p> <p>I'm successfully authenticating users via Facebook, but they are not "rememberable" despite being marked with:</p> <pre><code>devise [...]: rememberable, :omniauthable </code></pre> <p>I tried calling:</p> <pre><code>@the_user.remember_me! </code></pre> <p>...to no avail. No cookie is being stored/set which means the user does not persist across sessions.</p> <p>Has anybody managed to get a user sourced from FB remembered via cookies? In my mind, this should be happening automatically.</p> <p>Thanks for any ideas or feedback you guys might have.</p>
4,679,631
4
0
null
2010-12-17 23:42:15.55 UTC
12
2014-05-07 16:43:45.073 UTC
null
null
null
null
520,267
null
1
18
facebook|devise|ruby-on-rails-3|omniauth
3,948
<p>I agree that you would expect Devise to set a session before the request goes to FB. I guess this is a missing feature of Devise.</p> <p>I had the problem myself where I used token_authenticatable. An api client was calling the following url directly:</p> <pre><code>/users/auth/facebook?auth_token=TnMn7pjfADapMdsafOFIHKgJVgrBEbjKqrubwMXUca0n16m3Hzr7CnrP1s4z </code></pre> <p>Since I was using token_authenticatable i was assuming this would sign in the user. Unfortunately this doesn't work out of the box. What you have to do to get this working is making sure that the user is logged in before it gets to this path. You can do it in other ways, but the easiest way is to give a different url to the API client (in this case "users/connect/facebook". Here is my addition to the routes file that makes it work (assuming you have a user model with devise and you didn't change defaults):</p> <pre><code>authenticate :user do get 'users/connect/:network', :to =&gt; redirect("/users/auth/%{network}") end </code></pre> <p>This will make sure the session is correctly created so the user is being recognized when he/she returns from facebook.</p>
4,743,030
Passing object as parameter to constructor function and copy its properties to the new object?
<p>I have a JavaScript constructor like this:</p> <pre><code>function Box(obj) { this.obj = obj; } </code></pre> <p>which i want to pass an object as a parameter like this:</p> <pre><code>var box = new Box({prop1: "a", prop2: "b", prop3: "c"}) </code></pre> <p>and gives me something like this:</p> <pre><code>box.obj.prop1 box.obj.prop2 box.obj.prop3 </code></pre> <p>but I would like the properties to be directly on the object like this:</p> <pre><code>box.prop1 box.prop2 box.prop3 </code></pre> <p>I know I could do something like this:</p> <pre><code>function Box(obj) { this.prop1 = obj.prop1; this.prop2 = obj.prop2; this.prop3 = obj.prop3; } </code></pre> <p>But that is not good because then my constructor would have to "know" before the names of the properties of the object parameter. What I would like is to be able to pass different objects as parameters and assign their properties directly as properties of the new custom object created by the constructor so I get <code>box.propX</code> and not <code>box.obj.propX</code>. Hope I am making myself clear, maybe I am measing something very obvious but I am a newbie so please need your help!</p> <p>Thanks in advance.</p>
4,743,038
4
1
null
2011-01-20 02:56:38.987 UTC
8
2020-08-23 01:11:16.51 UTC
null
null
null
null
483,780
null
1
35
javascript|jquery|object|constructor
28,258
<p>You could do this. There is probably also a jquery way...</p> <pre><code>function Box(obj) { for (var fld in obj) { this[fld] = obj[fld]; } } </code></pre> <p>You can include a test for hasOwnProperty if you've (I think foolishly) extended object</p> <pre><code>function Box(obj) { for (var fld in obj) { if (obj.hasOwnProperty(fld)) { this[fld] = obj[fld]; } } } </code></pre> <p><strong>Edit</strong></p> <p>Ah, ha! it's <code>jQuery.extend</code></p> <p>So, the jQuery way is:</p> <pre><code>function Box(obj) { $.extend(this, obj); } </code></pre>
4,373,485
Android Swipe on List
<p>Does anyone have a simple example of a ListActivity displaying Textviews in a column and when you swipe left to right you see that row in a new view? This would be to say edit the data for that row or show more detailed info on that row. Please do not reference code shogun or other sites as I have googled and have not seen this answered.</p>
9,340,202
4
2
null
2010-12-07 04:45:06.38 UTC
65
2015-01-24 14:34:01.513 UTC
null
null
null
null
346,309
null
1
48
android|list|textview|listactivity|swipe
31,165
<p>I had the same problem and I didn't find my answer here.</p> <p>I wanted to detect a swipe action in ListView item and mark it as swiped, while continue to support OnItemClick and OnItemLongClick.</p> <p>Here is me solution:</p> <p>1st The SwipeDetector class:</p> <pre><code>import android.util.Log; import android.view.MotionEvent; import android.view.View; public class SwipeDetector implements View.OnTouchListener { public static enum Action { LR, // Left to Right RL, // Right to Left TB, // Top to bottom BT, // Bottom to Top None // when no action was detected } private static final String logTag = "SwipeDetector"; private static final int MIN_DISTANCE = 100; private float downX, downY, upX, upY; private Action mSwipeDetected = Action.None; public boolean swipeDetected() { return mSwipeDetected != Action.None; } public Action getAction() { return mSwipeDetected; } @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: downX = event.getX(); downY = event.getY(); mSwipeDetected = Action.None; return false; // allow other events like Click to be processed case MotionEvent.ACTION_UP: upX = event.getX(); upY = event.getY(); float deltaX = downX - upX; float deltaY = downY - upY; // horizontal swipe detection if (Math.abs(deltaX) &gt; MIN_DISTANCE) { // left or right if (deltaX &lt; 0) { Log.i(logTag, "Swipe Left to Right"); mSwipeDetected = Action.LR; return false; } if (deltaX &gt; 0) { Log.i(logTag, "Swipe Right to Left"); mSwipeDetected = Action.RL; return false; } } else if (Math.abs(deltaY) &gt; MIN_DISTANCE) { // vertical swipe // detection // top or down if (deltaY &lt; 0) { Log.i(logTag, "Swipe Top to Bottom"); mSwipeDetected = Action.TB; return false; } if (deltaY &gt; 0) { Log.i(logTag, "Swipe Bottom to Top"); mSwipeDetected = Action.BT; return false; } } return false; } return false; } } </code></pre> <p>2nd I use the swipe detector class in the list view:</p> <pre><code> final ListView lv = getListView(); final SwipeDetector swipeDetector = new SwipeDetector(); lv.setOnTouchListener(swipeDetector); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { if (swipeDetector.swipeDetected()){ // do the onSwipe action } else { // do the onItemClick action } } }); lv.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView&lt;?&gt; parent, View view,int position, long id) { if (swipeDetector.swipeDetected()){ // do the onSwipe action } else { // do the onItemLongClick action } } }); </code></pre> <p>This way I can support 3 actions - swipe, click, long click and I can use the ListView item info.</p> <p><strong>ADDED LATER:</strong></p> <p>Since ListView catches a scrolling action, it is sometimes hard to swipe. To fix it, I made the following change to SwipeDetector.onTouch:</p> <pre><code>public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: { downX = event.getX(); downY = event.getY(); mSwipeDetected = Action.None; return false; // allow other events like Click to be processed } case MotionEvent.ACTION_MOVE: { upX = event.getX(); upY = event.getY(); float deltaX = downX - upX; float deltaY = downY - upY; // horizontal swipe detection if (Math.abs(deltaX) &gt; HORIZONTAL_MIN_DISTANCE) { // left or right if (deltaX &lt; 0) { Log.i(logTag, "Swipe Left to Right"); mSwipeDetected = Action.LR; return true; } if (deltaX &gt; 0) { Log.i(logTag, "Swipe Right to Left"); mSwipeDetected = Action.RL; return true; } } else // vertical swipe detection if (Math.abs(deltaY) &gt; VERTICAL_MIN_DISTANCE) { // top or down if (deltaY &lt; 0) { Log.i(logTag, "Swipe Top to Bottom"); mSwipeDetected = Action.TB; return false; } if (deltaY &gt; 0) { Log.i(logTag, "Swipe Bottom to Top"); mSwipeDetected = Action.BT; return false; } } return true; } } return false; } </code></pre>
4,050,784
Defining multiple foreign keys in one table to many tables
<p>I have 3 models:</p> <p><strong>Post</strong>:</p> <ul> <li>id</li> <li>title</li> <li>body</li> </ul> <p><strong>Photo</strong>:</p> <ul> <li>id</li> <li>filepath</li> </ul> <p><strong>Comment</strong>:</p> <ul> <li>id</li> <li>post_id</li> <li>body</li> </ul> <p>and corresponding tables in DB. Now, if I want to have comments only for my posts I can simply add following foreign key: <code>ALTER TABLE comment ADD FOREIGN KEY (post_id) REFERENCES post (id)</code>. But I want to have comments for other models (photo, profile, video, etc) and keep all comments in <strong>one</strong> table. How can I define foreign keys (i definitely need FKs for ORM) in such case?</p>
4,050,811
5
0
null
2010-10-29 09:54:15.47 UTC
9
2010-11-01 05:58:40.097 UTC
null
null
null
null
450,449
null
1
14
database-design|foreign-keys
21,116
<p>You could do this:</p> <pre><code> post: * post_id (PK) * title * body photo: * photo_id (PK) * filepath comment: * comment_id (PK) * body comment_to_post * comment_id (PK) -&gt; FK to comment.comment_id * post_id (PK) -&gt; FK to post.post_id comment_to_photo * comment_id (PK) -&gt; FK to comment.comment_id * photo_id (PK) -&gt; FK to photo.photo_id </code></pre> <p>There's still the possibility of having a comment that belongs to two different items. If you think that would be an issue I can try to improve the design.</p>
4,103,809
How to create a ssh tunnel in ruby and then connect to mysql server on the remote host
<p>I would like to create a ruby script that I can run mysql commands on a remote server through a ssh tunnel. </p> <p>Right now I have a manual process to do this:</p> <ol> <li>Create a tunnel -> ssh -L 3307:127.0.0.1:3306 </li> <li>run ruby script.</li> <li>Close tunnel.</li> </ol> <p>I would love to be able to automate this so I can just run the script.</p> <p>example:</p> <pre><code>require 'rubygems' require 'net/ssh/gateway' require 'mysql' #make the ssh connection -&gt; I don't think I am doing this right. Net::SSH.start('server','user') do |session| session.forward.local(3307,'127.0.0.1', 3306)&lt;br&gt; mysql = Mysql.connect("127.0.0.1","root","","",3307) dbs = mysql.list_dbs&lt;br&gt; dbs.each do |db|&lt;br&gt; puts db &lt;br&gt; end session.loop(0){true}&lt;br&gt; end </code></pre> <p>An update - 2010-11-10:<br> I'm really close with this code:</p> <pre><code>require 'rubygems' require 'mysql' require 'net/ssh/gateway' gateway = Net::SSH::Gateway.new("host","user",{:verbose =&gt; :debug}) port = gateway.open("127.0.0.1",3306,3307) # mysql = Mysql.connect("127.0.0.1","user","password","mysql",3307) # puts "here" # mysql.close sleep(10) gateway.close(port) </code></pre> <p>When its sleeping, I am able to open a terminal window and connect to mysql on the remote host. This verifies the tunnel is created and working.</p> <p>The problem now is when I uncomment the 3 lines, it just hangs. </p>
9,912,538
5
0
null
2010-11-05 05:36:45.707 UTC
17
2014-12-04 16:55:51.307 UTC
2011-02-21 05:18:45.567 UTC
null
557,279
null
498,023
null
1
30
mysql|ruby|ssh
19,715
<p>I was able to get this to work without a fork using the mysql2 gem</p> <pre><code>require 'rubygems' require 'mysql2' require 'net/ssh/gateway' gateway = Net::SSH::Gateway.new( 'remotehost.com', 'username' ) port = gateway.open('127.0.0.1', 3306, 3307) client = Mysql2::Client.new( host: "127.0.0.1", username: 'dbuser', password: 'dbpass', database: 'dbname', port: port ) results = client.query("SELECT * FROM projects") results.each do |row| p row end client.close </code></pre>
4,196,968
ObservableCollection<> vs. List<>
<p>I have lots of entities with nested <code>List&lt;&gt;</code> in each.</p> <p>For example, I have <code>BaseEntity</code> which has <code>List&lt;ColumnEntity&gt;</code>. <code>ColumnEntity</code> class has <code>List&lt;Info&gt;</code> and so on.</p> <p>We are working with a <a href="http://en.wikipedia.org/wiki/Windows_Presentation_Foundation" rel="noreferrer">WPF</a> UI, and we need to track all changes in every List of <code>BaseEntity</code>. It is implemented by instantiating a <code>new ObservableCollection</code> based on the needed list, and with binding to that <code>ObservableCollection</code>.</p> <p>What are the pros and cons changing all these nested <code>Lists</code> to <code>ObservableCollections</code>? So we can track all changes in <code>BaseEntity</code> itself without reassigning each list of <code>BaseEntity</code> to modified bound <code>ObservableCollection</code>?</p> <p>Assuming that methods specific to <code>List</code> are never used.</p>
4,197,068
5
0
null
2010-11-16 17:19:40.38 UTC
18
2021-12-07 17:39:58.483 UTC
2016-11-27 14:04:40.603 UTC
null
63,550
null
399,250
null
1
82
c#|.net|wpf
99,592
<p>Interesting question, considering that both <code>List</code> and <code>ObservableCollection</code> implement <code>IList&lt;T&gt;</code> there isn't much of a difference there, <code>ObservableCollection</code> also implements <code>INotifyCollectionChanged</code> interface, which allows WPF to bind to it.</p> <p>One of the main differences is that <code>ObservableCollection</code> does not have <code>AddRange</code> method, which might have some implications.</p> <p>Also, I would not use <code>ObservableCollection</code> for places where I know I would not be binding to, for this reason, it is important to go over your design and make sure that you are taking the correct approach in separating layers of concern.</p> <p>As far as the differences between <code>Collection&lt;T&gt;</code> and <code>List&lt;T&gt;</code> you can have a look here <a href="https://web.archive.org/web/20160523222548/http://netundocumented.com:80/2004/08/generic_lists.html" rel="noreferrer">Generic Lists vs Collection</a></p>
4,833,635
C# properties: how to use custom set property without private field?
<p>I want to do this:</p> <pre><code>public Name { get; set { dosomething(); ??? = value } } </code></pre> <p>Is it possible to use the auto-generated private field? <br>Or is it required that I implement it this way:</p> <pre><code>private string name; public string Name { get { return name; } set { dosomething(); name = value } } </code></pre>
4,833,660
5
1
null
2011-01-28 22:23:54.047 UTC
5
2019-05-23 15:33:47.4 UTC
2011-01-28 22:29:11.49 UTC
null
23,234
null
107,029
null
1
121
c#|properties
115,514
<p>Once you want to do anything custom in either the getter or the setter you cannot use auto properties anymore.</p>
4,664,893
How to manually set an authenticated user in Spring Security / SpringMVC
<p>After a new user submits a 'New account' form, I want to manually log that user in so they don't have to login on the subsequent page.</p> <p>The normal form login page going through the spring security interceptor works just fine.</p> <p>In the new-account-form controller I am creating a UsernamePasswordAuthenticationToken and setting it in the SecurityContext manually:</p> <pre><code>SecurityContextHolder.getContext().setAuthentication(authentication); </code></pre> <p>On that same page I later check that the user is logged in with:</p> <pre><code>SecurityContextHolder.getContext().getAuthentication().getAuthorities(); </code></pre> <p>This returns the authorities I set earlier in the authentication. All is well.</p> <p>But when this same code is called on the very next page I load, the authentication token is just UserAnonymous.</p> <p>I'm not clear why it did not keep the authentication I set on the previous request. Any thoughts?</p> <ul> <li>Could it have to do with session ID's not being set up correctly?</li> <li>Is there something that is possibly overwriting my authentication somehow?</li> <li>Perhaps I just need another step to save the authentication?</li> <li>Or is there something I need to do to declare the authentication across the whole session rather than a single request somehow?</li> </ul> <p>Just looking for some thoughts that might help me see what's happening here.</p>
4,672,083
6
4
null
2011-01-12 02:44:11.57 UTC
65
2021-12-09 05:01:21.573 UTC
null
null
null
null
4,790,871
null
1
120
java|authentication|spring-mvc|spring-security
204,591
<p>I had the same problem as you a while back. I can't remember the details but the following code got things working for me. This code is used within a Spring Webflow flow, hence the RequestContext and ExternalContext classes. But the part that is most relevant to you is the doAutoLogin method. </p> <pre><code>public String registerUser(UserRegistrationFormBean userRegistrationFormBean, RequestContext requestContext, ExternalContext externalContext) { try { Locale userLocale = requestContext.getExternalContext().getLocale(); this.userService.createNewUser(userRegistrationFormBean, userLocale, Constants.SYSTEM_USER_ID); String emailAddress = userRegistrationFormBean.getChooseEmailAddressFormBean().getEmailAddress(); String password = userRegistrationFormBean.getChoosePasswordFormBean().getPassword(); doAutoLogin(emailAddress, password, (HttpServletRequest) externalContext.getNativeRequest()); return "success"; } catch (EmailAddressNotUniqueException e) { MessageResolver messageResolvable = new MessageBuilder().error() .source(UserRegistrationFormBean.PROPERTYNAME_EMAIL_ADDRESS) .code("userRegistration.emailAddress.not.unique") .build(); requestContext.getMessageContext().addMessage(messageResolvable); return "error"; } } private void doAutoLogin(String username, String password, HttpServletRequest request) { try { // Must be called from request filtered by Spring Security, otherwise SecurityContextHolder is not updated UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password); token.setDetails(new WebAuthenticationDetails(request)); Authentication authentication = this.authenticationProvider.authenticate(token); logger.debug("Logging in with [{}]", authentication.getPrincipal()); SecurityContextHolder.getContext().setAuthentication(authentication); } catch (Exception e) { SecurityContextHolder.getContext().setAuthentication(null); logger.error("Failure in autoLogin", e); } } </code></pre>
4,481,163
Most Popular/Frequently Used/Important Interfaces in C# .NET?
<p>Apart from IEnumerable, IComparable, what other "important" (or frequently used) interfaces are there for me to know in C#.NET? </p>
4,481,345
7
3
null
2010-12-19 01:26:44.29 UTC
13
2010-12-21 15:35:42.4 UTC
2010-12-19 01:35:17.79 UTC
null
257,558
null
257,558
null
1
40
c#|.net
16,211
<p><a href="https://stackoverflow.com/questions/4240438/what-are-the-most-used-interfaces-in-c/4240764#4240764">Same question</a></p> <p>Copy-Paste from there:</p> <ul> <li>IEnumerable (and IEnumerable): for use with foreach and LINQ</li> <li>IDisposable: for resources requiring cleanup, used with using</li> <li>IQueryable: lets you execute requests against queriable data sources.</li> <li>INotifyPropertyChange : For data binding to UI classes in WPF, winforms and silverlight</li> <li>IComparable and IComparer: for generalized sorting</li> <li>IEquatable and IEqualityComparer: for generalized equality</li> <li>IList and ICollection: for mutable collections</li> <li>IDictionary: for lookup collections</li> </ul>
4,387,680
Transparent background on winforms?
<p>I wanted to make my windows form transparent so removed the borders, controls and everything leaving only the forms box, then I tried to the BackColor and TransparencyKey to transparent but it didnt work out as BackColor would not accept transparent color. After searching around I found this at msdn:</p> <pre><code>SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.SupportsTransparentBackColor, true); this.BackColor = Color.Transparent; this.TransparencyKey = BackColor; </code></pre> <p>Unhappyly it did not work either. I still get the grey or any other selected color background.</p> <p>All I wanted to do is to have the windows form transparent so I could use a background image that would act as if it was my windows form.</p> <p>I searched around here and saw many topics in regards opacity which is not what I am looking for and also saw some in regards this method I was trying but have not found an answer yet.</p> <p>Hope anyone can light my path.</p> <p>UPDATE:</p> <p>image removed as problem is solved</p>
4,387,762
8
7
null
2010-12-08 12:57:40.95 UTC
12
2020-06-26 11:16:14.24 UTC
2016-07-08 18:47:15.583 UTC
null
2,827,771
null
342,740
null
1
52
c#|winforms|background|transparent
122,676
<p>The manner I have used before is to use a wild color (a color no one in their right mind would use) for the BackColor and then set the transparency key to that.</p> <pre><code>this.BackColor = Color.LimeGreen; this.TransparencyKey = Color.LimeGreen; </code></pre>
4,173,787
String exact match
<p>I have a string in which the word "LOCAL" occurs many times. I used the <code>find()</code> function to search for this word but it returns another word "Locally" as well. How can I match the word "local" exactly?</p>
4,173,810
9
0
null
2010-11-13 17:32:18.883 UTC
6
2022-08-11 12:07:51.147 UTC
2016-03-24 21:19:43.34 UTC
null
-1
null
1,648,247
null
1
24
python|string
92,978
<p>For this kind of thing, regexps are very useful :</p> <pre><code>import re print(re.findall('\\blocal\\b', "Hello, locally local test local.")) // ['local', 'local'] </code></pre> <p>\b means word boundary, basically. Can be space, punctuation, etc.</p> <p>Edit for comment :</p> <pre><code>print(re.sub('\\blocal\\b', '*****', "Hello, LOCAL locally local test local.", flags=re.IGNORECASE)) // Hello, ***** locally ***** test *****. </code></pre> <p>You can remove flags=re.IGNORECASE if you don't want to ignore the case, obviously.</p>
4,654,653
How can I use NSError in my iPhone App?
<p>I am working on catching errors in my app, and I am looking into using <code>NSError</code>. I am slightly confused about how to use it, and how to populate it.</p> <p><strong>Could someone provide an example on how I populate then use <code>NSError</code>?</strong></p>
4,654,759
9
0
null
2011-01-11 05:53:59.593 UTC
93
2020-04-02 16:10:38.99 UTC
2015-10-26 09:16:11.183 UTC
null
2,725,435
null
144,695
null
1
235
iphone|ios|objective-c|ios4|nserror
137,597
<p>Well, what I usually do is have my methods that could error-out at runtime take a reference to a <code>NSError</code> pointer. If something does indeed go wrong in that method, I can populate the <code>NSError</code> reference with error data and return nil from the method.</p> <p>Example:</p> <pre><code>- (id) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error { // begin feeding the world's children... // it's all going well until.... if (ohNoImOutOfMonies) { // sad, we can't solve world hunger, but we can let people know what went wrong! // init dictionary to be used to populate error object NSMutableDictionary* details = [NSMutableDictionary dictionary]; [details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey]; // populate the error object with the details *error = [NSError errorWithDomain:@"world" code:200 userInfo:details]; // we couldn't feed the world's children...return nil..sniffle...sniffle return nil; } // wohoo! We fed the world's children. The world is now in lots of debt. But who cares? return YES; } </code></pre> <p>We can then use the method like this. Don't even bother to inspect the error object unless the method returns nil:</p> <pre><code>// initialize NSError object NSError* error = nil; // try to feed the world id yayOrNay = [self endWorldHunger:smallAmountsOfMonies error:&amp;error]; if (!yayOrNay) { // inspect error NSLog(@"%@", [error localizedDescription]); } // otherwise the world has been fed. Wow, your code must rock. </code></pre> <p>We were able to access the error's <code>localizedDescription</code> because we set a value for <code>NSLocalizedDescriptionKey</code>. </p> <p>The best place for more information is <a href="https://developer.apple.com/documentation/foundation/nserror" rel="noreferrer">Apple's documentation</a>. It really is good.</p> <p>There is also a nice, simple tutorial on <a href="http://www.cimgf.com/2008/04/04/cocoa-tutorial-using-nserror-to-great-effect/" rel="noreferrer">Cocoa Is My Girlfriend</a>. </p>
2,631,305
Visual Studio: What happened to the "Break when an exception is unhandled" option?
<p>As far as I remember, Visual Studio (both 2008 and 2010) used to have an option to break either on thrown exceptions or on unhandled exceptions. Now when I bring up the Exceptions dialog (Ctr+Alt+E), it just offers to break when an exception is thrown:</p> <p><img src="https://i.stack.imgur.com/1Mdm4.png" alt="enter image description here"></p> <p>I've tried resizing to the columns in that dialog, but that did not help. Is this a bug, or am I missing something?</p>
2,631,353
2
0
null
2010-04-13 16:29:50.377 UTC
5
2014-08-08 15:16:37.54 UTC
2014-08-08 15:16:37.54 UTC
null
394,157
null
59,301
null
1
30
visual-studio|visual-studio-2008|debugging|exception|visual-studio-2010
3,050
<p><a href="http://vaultofthoughts.net/UserUnhandledCheckboxMissingFromExceptionsWindow.aspx" rel="noreferrer">This</a> seems to indicate it can occur if you don't have "Enable Just My Code (Managed Only)" enabled.</p> <p>Edit: just tried it here (VS 2008) and I can verify that disabling that option will cause the User-Unhandled column to disappear. You can find the option here: Tools -> Options -> Debugging -> General</p>
2,921,945
Useful example of a shutdown hook in Java?
<p>I'm trying to make sure my Java application takes reasonable steps to be robust, and part of that involves shutting down gracefully. I am reading about <a href="http://www.ibm.com/developerworks/ibm/library/i-signalhandling/?open&amp;l=409,t=grj,p=jsh#9" rel="noreferrer">shutdown hooks</a> and I don't actually get how to make use of them in practice.</p> <p>Is there a practical example out there?</p> <p>Let's say I had a really simple application like this one below, which writes numbers to a file, 10 to a line, in batches of 100, and I want to make sure a given batch finishes if the program is interrupted. I get how to register a shutdown hook but I have no idea how to integrate that into my application. Any suggestions?</p> <pre><code>package com.example.test.concurrency; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; public class GracefulShutdownTest1 { final private int N; final private File f; public GracefulShutdownTest1(File f, int N) { this.f=f; this.N = N; } public void run() { PrintWriter pw = null; try { FileOutputStream fos = new FileOutputStream(this.f); pw = new PrintWriter(fos); for (int i = 0; i &lt; N; ++i) writeBatch(pw, i); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { pw.close(); } } private void writeBatch(PrintWriter pw, int i) { for (int j = 0; j &lt; 100; ++j) { int k = i*100+j; pw.write(Integer.toString(k)); if ((j+1)%10 == 0) pw.write('\n'); else pw.write(' '); } } static public void main(String[] args) { if (args.length &lt; 2) { System.out.println("args = [file] [N] " +"where file = output filename, N=batch count"); } else { new GracefulShutdownTest1( new File(args[0]), Integer.parseInt(args[1]) ).run(); } } } </code></pre>
2,922,031
2
1
null
2010-05-27 14:20:58.127 UTC
59
2015-08-30 09:42:40.297 UTC
2011-08-16 15:32:32.183 UTC
null
276,052
null
44,330
null
1
130
java|shutdown-hook
146,504
<p>You could do the following:</p> <ul> <li>Let the shutdown hook set some AtomicBoolean (or volatile boolean) "keepRunning" to false</li> <li>(Optionally, <code>.interrupt</code> the working threads if they wait for data in some blocking call)</li> <li>Wait for the working threads (executing <code>writeBatch</code> in your case) to finish, by calling the <code>Thread.join()</code> method on the working threads.</li> <li>Terminate the program</li> </ul> <p>Some sketchy code:</p> <ul> <li>Add a <code>static volatile boolean keepRunning = true;</code></li> <li><p>In <em>run()</em> you change to</p> <pre><code>for (int i = 0; i &lt; N &amp;&amp; keepRunning; ++i) writeBatch(pw, i); </code></pre></li> <li><p>In <em>main()</em> you add:</p> <pre><code>final Thread mainThread = Thread.currentThread(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { keepRunning = false; mainThread.join(); } }); </code></pre></li> </ul> <p>That's roughly how I do a graceful "reject all clients upon hitting Control-C" in terminal.</p> <hr> <p>From <a href="http://download.oracle.com/javase/7/docs/api/java/lang/Runtime.html#addShutdownHook%28java.lang.Thread%29" rel="noreferrer">the docs</a>:</p> <blockquote> <p>When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently. <strong>When all the hooks have finished it will then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual machine will halt.</strong></p> </blockquote> <p>That is, a shutdown hook keeps the JVM running until the hook has terminated (returned from the <em>run()</em>-method.</p>
26,446,338
How to multiply all integers inside list
<p>Hello so I want to multiply the integers inside a list.</p> <p>For example;</p> <pre><code>l = [1, 2, 3] l = [1*2, 2*2, 3*2] </code></pre> <p>output:</p> <pre><code>l = [2, 4, 6] </code></pre> <p>So I was searching online and most of the answers were regarding multiply all the integers with each other such as:</p> <p>[1*2*3]</p>
26,446,349
6
0
null
2014-10-19 01:29:28.9 UTC
9
2020-04-27 05:31:38.51 UTC
2016-06-17 18:46:41.18 UTC
null
906,693
null
3,973,873
null
1
63
python|list|multiplication|scalar|elementwise-operations
226,643
<p>Try a <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="noreferrer">list comprehension</a>:</p> <pre><code>l = [x * 2 for x in l] </code></pre> <p>This goes through <code>l</code>, multiplying each element by two.</p> <p>Of course, there's more than one way to do it. If you're into <a href="http://www.secnetix.de/olli/Python/lambda_functions.hawk" rel="noreferrer">lambda functions</a> and <a href="https://docs.python.org/2/library/functions.html#map" rel="noreferrer"><code>map</code></a>, you can even do</p> <pre><code>l = map(lambda x: x * 2, l) </code></pre> <p>to apply the function <code>lambda x: x * 2</code> to each element in <code>l</code>. This is equivalent to:</p> <pre><code>def timesTwo(x): return x * 2 l = map(timesTwo, l) </code></pre> <p>Note that <code>map()</code> returns a map object, not a list, so if you really need a list afterwards you can use the <code>list()</code> function afterwards, for instance:</p> <pre><code>l = list(map(timesTwo, l)) </code></pre> <p>Thanks to <a href="https://stackoverflow.com/questions/26446338/how-to-multiply-all-integers-inside-list/26446349#comment106637455_26446349">Minyc510 in the comments</a> for this clarification.</p>
38,703,876
Log warning: Thread starvation or clock leap detected (housekeeper delta=springHikariConnectionPool)
<p>I'm using HikariCP 2.4.6 and at Tomcat 8 startup, I get a warning message:</p> <pre><code>01-Aug-2016 11:18:01.599 INFO [RMI TCP Connection(4)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring FrameworkServlet 'Spring MVC Dispatcher Servlet' [2016-08-01 11:18:01,654] Artifact blueberry:war exploded: Artifact is deployed successfully [2016-08-01 11:18:01,655] Artifact blueberry:war exploded: Deploy took 33,985 milliseconds Aug 01 2016 11:26:52.802 AM [DEV] (HikariPool.java:614) WARN : com.zaxxer.hikari.pool.HikariPool - 9m13s102ms - Thread starvation or clock leap detected (housekeeper delta=springHikariConnectionPool). </code></pre> <p>I don't see any other errors or issues reading/writing from the DB. Is this something to be concerned about? I tried searching around, but no luck. </p> <p>We're also using Hibernate 4.3.8.Final over MySQL 5 and the MySQL 5.1.39 connector with Spring 4.1.0.RELEASE. We're working to upgrade to Hibernate 5 and will see whether this goes away, but don't know whether that will matter.</p>
38,703,956
7
0
null
2016-08-01 16:35:59.443 UTC
20
2021-10-09 14:15:44.2 UTC
2016-10-05 18:56:16.373 UTC
null
192,465
null
192,465
null
1
87
hikaricp
127,263
<p>There's a good <a href="https://groups.google.com/forum/#!topic/hikari-cp/inAL5wyUIxk" rel="noreferrer">rundown</a> of why clock leap detections might legitimately occur. To quote the external link by Brett Woolridge:</p> <blockquote> <p>This runs on the housekeeper thread, which executes every 30 seconds. If you are on Mac OS X, the clockSource is System.currentTimeMillis(), any other platform the clockSource is System.nanoTime(). Both in theory are monotonically increasing, but various things can affect that such as NTP servers. Most OSes are designed to handle backward NTP time adjustments to preserve the illusion of the forward flow of time.</p> <p>This code is saying, if time moves backwards (now &lt; previous), or if time has "jumped forward" more than two housekeeping periods (more than 60 seconds), then something strange is likely going on.</p> <p>A couple of things might be going on:</p> <ol> <li><p>You could be running in a virtual container (VMWare, AWS, etc.) that for some reason is doing a particularly poor job of maintaining the illusion of the forward flow of time.</p></li> <li><p>Because other things occur in the housekeeper thread -- specifically, closing idle connections -- it is possible that for some reason closing connections is blocking the housekeeper thread for more than two housekeeping periods (60 seconds).</p></li> <li><p>The server is so busy, with all CPUs pegged, that thread starvation is occurring, which is preventing the housekeeper thread from running for more than two housekeeping periods.</p></li> </ol> <p>Considering these, maybe you can provide additional context.</p> <p>EDIT: Note that this is based on HikariCP 2.4.1 code. Make sure you are running the most up-to-date version available.</p> </blockquote> <p>(It also looks like the parameters were updated on the warning statement in the latest code.)</p>
40,704,760
InvalidOperationException: Could not find 'UserSecretsIdAttribute' on assembly
<p>After deploying ASP.NET Core app to azure and opening the site, I get the following error:</p> <blockquote> <p>InvalidOperationException: Could not find 'UserSecretsIdAttribute' on assembly '******, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.</p> </blockquote> <p>The exception details also include that the error happens at Startup.cs on this line of code:</p> <blockquote> <p>builder.AddUserSecrets();</p> </blockquote> <p>Thank you</p>
40,704,864
3
0
null
2016-11-20 13:47:40.02 UTC
1
2021-07-14 14:20:52.517 UTC
2016-11-20 13:53:10.743 UTC
null
3,453,517
null
3,453,517
null
1
31
asp.net|azure|asp.net-core
14,700
<p>There was an update to the user secrets module just recently. Version 1.0.1 and up now requires you specify an assembly-level attribute for the id of the user secrets, or as a fallback, the way it was previously in project.json.</p> <p>Here is the announcement on GitHub: <a href="https://github.com/aspnet/Announcements/issues/209" rel="noreferrer">https://github.com/aspnet/Announcements/issues/209</a></p> <p>You can define the secrets id in the .csproj like this:</p> <pre><code>&lt;PropertyGroup&gt; &lt;UserSecretsId&gt;aspnet-TestApp-ce345b64-19cf-4972-b34f-d16f2e7976ed&lt;/UserSecretsId&gt; &lt;/PropertyGroup&gt; </code></pre> <p>This generates the following assembly-level attribute. Alternatively, instead of adding it in the .csproj file, you can of course add it yourself e.g. to Startup.cs:</p> <pre><code>[assembly: UserSecretsId("aspnet-TestApp-ce345b64-19cf-4972-b34f-d16f2e7976ed")] </code></pre> <p>Also, you should use:</p> <pre><code>builder.AddUserSecrets&lt;Startup&gt;(); </code></pre> <p>It will search for that attribute in the assembly of the given type, in this case I used the Startup class.</p> <p><strong>Note: this will be deprecated in 2.0: (1.0.2 and 1.1.1 have marked it obsolete)</strong></p> <pre><code>builder.AddUserSecrets(); </code></pre> <p>I checked the <a href="https://github.com/aspnet/Configuration/blob/rel/1.1.0/src/Microsoft.Extensions.Configuration.UserSecrets/ConfigurationExtensions.cs" rel="noreferrer">source code</a> for the user secrets configuration, and calling <code>AddUserSecrets()</code> without the type does this:</p> <pre><code>var attribute = entryAssembly.GetCustomAttribute&lt;UserSecretsIdAttribute&gt;(); if (attribute != null) { return AddUserSecrets(configuration, attribute.UserSecretsId); } // try fallback to project.json for legacy support try { var fileProvider = configuration.GetFileProvider(); return AddSecretsFile(configuration, PathHelper.GetSecretsPath(fileProvider)); } catch { } // Show the error about missing UserSecretIdAttribute instead an error about missing // project.json as PJ is going away. throw MissingAttributeException(entryAssembly); </code></pre> <p>It's trying to find the <code>UserSecretsId</code> attribute on your assembly, and failing that, checking if it could find it in project.json. Then (as commented) returns an error about the missing attribute as they wouldn't want to complain about project.json anymore as it is being deprecated.</p>
48,714,689
Javascript re-assign let variable with destructuring
<p>In my React app I am using airbnb's eslint style guide which will throw an error if I do not use destructuing.</p> <p>In the situation below, I first use <code>let</code> to assign the two variables <code>latitude</code> and <code>longitude</code> to the coordinates of the first item in an array of location objects. Then I try to use destructuring to re-assign their values if the user has given me access to their location.</p> <pre><code>let latitude = locations[0].coordinates[1]; let longitude = locations[0].coordinates[0]; if (props.userLocation.coords) { // doesn't work - unexpected token { latitude, longitude } = props.userLocation.coords; // causes linting errors // latitude = props.userLocation.coords.latitude; // longitude = props.userLocation.coords.longitude; } </code></pre> <p>Destructuring inside the <code>if</code> statement causes an <code>unexpected token</code> error.</p> <p>Re-assigning the variables the old fashioned way causes an <code>ESlint: Use object destructuring</code> error.</p>
48,714,713
1
0
null
2018-02-09 21:57:12.683 UTC
14
2018-02-09 21:59:03.02 UTC
null
null
null
null
3,833,246
null
1
125
javascript|ecmascript-6|eslint
21,877
<pre><code> ({ latitude, longitude } = props.userLocation.coords); </code></pre> <p>Destructuring needs to be either after a <code>let</code>, <code>const</code> or <code>var</code> declaration or it needs to be in an expression context to distinguish it from a block statement.</p>
33,701,160
python, heapq: difference between heappushpop() and heapreplace()
<p>I couldn't figure out the difference (other than ordinality of push/pop actions) between functions heapq.heappushpop() and heapq.heapreplace() when i tested out the following code.</p> <pre><code>&gt;&gt;&gt; from heapq import * &gt;&gt;&gt; a=[2,7,4,0,8,12,14,13,10,3,4] &gt;&gt;&gt; heapify(a) &gt;&gt;&gt; heappush(a,9) &gt;&gt;&gt; a [0, 2, 4, 7, 3, 9, 14, 13, 10, 8, 4, 12] &gt;&gt;&gt; heappop(a) 0 &gt;&gt;&gt; b=a.copy() &gt;&gt;&gt; heappushpop(a,6) 2 &gt;&gt;&gt; heapreplace(b,6) 2 &gt;&gt;&gt; a [3, 4, 4, 7, 6, 9, 14, 13, 10, 8, 12] &gt;&gt;&gt; b [3, 4, 4, 7, 6, 9, 14, 13, 10, 8, 12] </code></pre>
33,701,261
4
0
null
2015-11-13 20:22:01.793 UTC
7
2021-04-03 13:28:58.06 UTC
null
null
null
null
1,682,131
null
1
31
python|heap
17,499
<p><code>heapreplace(a, x)</code> returns the smallest value originally in <code>a</code> regardless of the value of <code>x</code>, while, as the name suggests, <code>heappushpop(a, x)</code> pushes <code>x</code> onto <code>a</code> <em>before</em> popping the smallest value. Using your data, here's a sequence that shows the difference:</p> <pre><code>&gt;&gt;&gt; from heapq import * &gt;&gt;&gt; a = [2,7,4,0,8,12,14,13,10,3,4] &gt;&gt;&gt; heapify(a) &gt;&gt;&gt; b = a[:] &gt;&gt;&gt; heappushpop(a, -1) -1 &gt;&gt;&gt; heapreplace(b, -1) 0 </code></pre>
34,580,095
Using R and plot.ly - how do I script saving my output as a webpage
<p>I want to make some interactive graphs using R and <a href="https://plot.ly/" rel="noreferrer">plot.ly</a>. When I run the following code in R-Studio, it produces an interactive graph. </p> <pre><code>library(plotly) set.seed(100) d &lt;- diamonds[sample(nrow(diamonds), 1000), ] plot_ly(d, x = carat, y = price, text = paste("Clarity: ", clarity), mode = "markers", color = carat, size = carat) </code></pre> <p>After producing this graph, when I click on the "Export" button in the Plot window of R-Studio, it gives me the option to save the plot as a webpage. How can I script the process of saving produced plots as webpages? My ultimate goal is to run Rscripts iteratively from inside a bash script to produce multiple webpages. </p>
34,605,451
2
0
null
2016-01-03 18:33:34.837 UTC
12
2019-02-09 12:58:16.1 UTC
null
null
null
null
2,396,037
null
1
31
r|plotly
34,893
<p>Assign the <code>plot_ly</code> object to a variable and then use <code>htmlwidgets::saveWidget()</code> to save the actual file, like so:</p> <pre><code>library(plotly) set.seed(100) d &lt;- diamonds[sample(nrow(diamonds), 1000), ] p &lt;- plot_ly(d, x = carat, y = price, text = paste("Clarity: ", clarity), mode = "markers", color = carat, size = carat) htmlwidgets::saveWidget(as_widget(p), "index.html") </code></pre>
53,636,756
Typescript - interface extending another interface with nested properties
<p>I have an interface like:</p> <pre><code>export interface Module { name: string; data: any; structure: { icon: string; label: string; ... } } </code></pre> <p>How can I extend it, so that I add some new properties to structure, without repeating myself? Do I have to make a new interface for structure and extend that and make a new Module with the new structure interface or is there some other syntax to achieve this? </p> <p>Ideally, I would just write something like:</p> <pre><code>export interface DataModule extends Module { structure: { visible: boolean; } } export interface UrlModule extends Module { structure: { url: string; } } </code></pre> <p>Thanks!</p>
53,636,853
1
0
null
2018-12-05 16:32:46.91 UTC
10
2022-08-29 19:25:44.393 UTC
null
null
null
null
5,603,476
null
1
45
typescript|syntax
29,271
<p>Interfaces can't add to the types of members in the base interface (at least not directly). You can use an intersection type instead:</p> <pre><code>export interface Module { name: string; data: any; structure: { icon: string; label: string; } } export type DataModule = Module &amp; { structure: { visible: boolean; } } export type UrlModule = Module &amp; { structure: { url: string; } } let urlModule: UrlModule = { name: &quot;&quot;, data: {}, structure: { icon: '', label: '', url: '' } } </code></pre> <p>They should behave similarly to interfaces, they can be implemented by classes and they will get checked when you assign object literals to them.</p> <p>You can also do it with interfaces but it's a bit more verbose, and implies using a type query to get the original type of the field, and again an intersection:</p> <pre><code>export interface DataModule extends Module { structure: Module['structure'] &amp; { visible: boolean; } } export interface UrlModule extends Module { structure: Module['structure'] &amp; { url: string; } } </code></pre> <p>The really verbose option (although in some ways simpler to understand) is of course to just define a separate interface for structure:</p> <pre><code>export interface IModuleStructure { icon: string; label: string; } export interface Module { name: string; data: any; structure: IModuleStructure; } export interface IDataModuleStructure extends IModuleStructure { visible: boolean; } export interface DataModule extends Module { structure: IDataModuleStructure; } export interface IUrlModuleStructure extends IModuleStructure { url: string; } export interface UrlModule extends Module { structure: IUrlModuleStructure; } let urlModule: UrlModule = { name: &quot;&quot;, data: {}, structure: { icon: '', label: '', url: '' } } </code></pre> <p><strong>Edit</strong></p> <p>As pe @jcalz suggestion, we could also make the module interface generic, and pass in the apropriate structure interface:</p> <pre><code>export interface IModuleStructure { icon: string; label: string; } export interface Module&lt;T extends IModuleStructure = IModuleStructure&gt; { name: string; data: any; structure: T; } export interface IDataModuleStructure extends IModuleStructure { visible: boolean; } export interface DataModule extends Module&lt;IDataModuleStructure&gt; { } export interface IUrlModuleStructure extends IModuleStructure { url: string; } export interface UrlModule extends Module&lt;IUrlModuleStructure&gt; { } let urlModule: UrlModule = { // We could also just use Module&lt;IUrlModuleStructure&gt; name: &quot;&quot;, data: {}, structure: { icon: '', label: '', url: '' } } </code></pre>
29,135,885
netcdf4 extract for subset of lat lon
<p>I would like to extract a spatial subset of a rather large netcdf file. From <a href="https://stackoverflow.com/questions/18665078/loop-through-netcdf-files-and-run-calculations-python-or-r">Loop through netcdf files and run calculations - Python or R</a> </p> <pre><code>from pylab import * import netCDF4 f = netCDF4.MFDataset('/usgs/data2/rsignell/models/ncep/narr/air.2m.1989.nc') # print variables f.variables.keys() atemp = f.variables['air'] # TODO: extract spatial subset </code></pre> <p>How do I extract just the subset of netcdf file corresponding to a state (say Iowa). Iowa has following boundary lat lon:</p> <p>Longitude: 89° 5' W to 96° 31' W</p> <p>Latitude: 40° 36' N to 43° 30' N</p>
29,136,166
7
0
null
2015-03-19 01:46:42.997 UTC
10
2020-10-15 14:58:52.84 UTC
2019-05-15 09:28:08.793 UTC
null
6,068,294
null
308,827
null
1
10
python|netcdf|nco|cdo-climate
24,599
<p>Well this is pretty easy, you have to find the index for the upper and lower bound in latitude and longitude. You can do it by finding the value that is closest to the ones you're looking for.</p> <pre><code>latbounds = [ 40 , 43 ] lonbounds = [ -96 , -89 ] # degrees east ? lats = f.variables['latitude'][:] lons = f.variables['longitude'][:] # latitude lower and upper index latli = np.argmin( np.abs( lats - latbounds[0] ) ) latui = np.argmin( np.abs( lats - latbounds[1] ) ) # longitude lower and upper index lonli = np.argmin( np.abs( lons - lonbounds[0] ) ) lonui = np.argmin( np.abs( lons - lonbounds[1] ) ) </code></pre> <p>Then just subset the variable array. </p> <pre><code># Air (time, latitude, longitude) airSubset = f.variables['air'][ : , latli:latui , lonli:lonui ] </code></pre> <ul> <li>Note, i'm assuming the longitude dimension variable is in degrees east, and the air variable has time, latitude, longitude dimensions.</li> </ul>
29,162,662
postgresql insert null value on query
<p>In my php code query, i got some error when i will place a null value into the table. The column names "number1","number2", and "number3" are integers and can have a null value. </p> <p>if there is no null value, the query works</p> <p>query is like this <strong>insert into table(number1,number2,number3) values (1,2,3);</strong></p> <p>but when I leave a blank value on the input form on the PHP, </p> <p>for example I will not place value for column "number2", the query will look like this. </p> <p><strong>insert into table(number1,number2,number3) values (1,,3);</strong></p> <p>it says ERROR: syntax error at or near "," SQL state: 42601</p> <p>Does anybody have an idea how to solve this?</p> <p>this query is likely to be the solution but is there any other way? <strong>insert into table(number1,number2,number3) values (1,null,3);</strong></p> <p>because i got so many variables like that and am a bit lazy to place some conditions like when that variable returns a blank value then value="null"</p>
29,162,719
1
0
null
2015-03-20 08:53:28.3 UTC
2
2022-06-12 14:51:15.197 UTC
2015-03-20 09:10:27.51 UTC
null
4,693,222
null
4,693,222
null
1
27
php|postgresql
86,088
<p>You insert <code>NULL</code> value by typing NULL:</p> <pre><code>INSERT INTO table(number1,number2,number3) VALUES (1,NULL,3); </code></pre> <p>If you have a variable and when that variable is empty you want to insert a <code>NULL</code> value you can use <code>NULLIF</code> with the variable enclosed in single quotes to prepare for that (this is somewhat dirty solution as you have to treat the variable as an empty string and then convert it to integer):</p> <pre><code>INSERT INTO table(number1,number2,number3) VALUES (1,NULLIF('$var','')::integer,3); </code></pre>
29,463,131
Mapping multiple locations with Google Maps JavaScript API v3 and Geocoding API
<p>I'm using Google Maps JavaScript API v3 to generate a map with multiple locations/markers. I only have the address for these locations, not the coordinates, so I'm using the Geocoding API to get the coordinates.</p> <p>I finally got Google's geocoding to work, so the location markers are showing up where they are supposed to be. However, the <em>same content</em> is showing up in every InfoWindow. I seem to be unable to pass the location arrays into the geocode function. (Incidentally, I also tried creating a variable for the geocode results and moving the infoWindow function <em>outside</em> of the geocode function, but I couldn't make that work either.)</p> <p>I've tried this a hundred different ways already. I hoping someone else will see what I haven't been able to see.</p> <pre><code> var locations = [ ['Location 1 Name', 'Location 1 Address', 'Location 1 URL'], ['Location 2 Name', 'Location 2 Address', 'Location 2 URL'], ['Location 3 Name', 'Location 3 Address', 'Location 3 URL'] ]; geocoder = new google.maps.Geocoder(); for (i = 0; i &lt; locations.length; i++) { title = locations[i][0]; address = locations[i][1]; url = locations[i][2]; geocoder.geocode({ 'address' : locations[i][1] }, function(results, status) { marker = new google.maps.Marker({ icon: 'marker_blue.png', map: map, position: results[0].geometry.location, title: title, animation: google.maps.Animation.DROP, address: address, url: url }) infoWindow(marker, map, title, address, url); }) } function infoWindow(marker, map, title, address, url) { google.maps.event.addListener(marker, 'click', function() { var html = "&lt;div&gt;&lt;h3&gt;" + title + "&lt;/h3&gt;&lt;p&gt;" + address + "&lt;br&gt;&lt;/div&gt;&lt;a href='" + url + "'&gt;View location&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;"; iw = new google.maps.InfoWindow({ content : html, maxWidth : 350}); iw.open(map,marker); }); } </code></pre>
29,463,348
3
0
null
2015-04-05 22:55:17.217 UTC
8
2020-10-16 18:17:14.923 UTC
null
null
null
null
3,878,771
null
1
6
javascript|google-maps|google-maps-api-3|google-geocoder|google-geocoding-api
59,433
<p>This is a duplicate of <a href="https://stackoverflow.com/questions/13278368/google-map-info-window-multiple-addresses-via-xml">google map info window multiple addresses via xml</a>, just not an exact duplicate. The geocoder is asynchronous, so when the geocoder callback runs, the value of address is that from the end of the loop for all the calls.</p> <p>The answer is the same: The simplest solution is to use function closure to associate the call to the geocoder with the returned result:</p> <pre><code>function geocodeAddress(locations, i) { var title = locations[i][0]; var address = locations[i][1]; var url = locations[i][2]; geocoder.geocode({ 'address': locations[i][1] }, function (results, status) { if (status == google.maps.GeocoderStatus.OK) { var marker = new google.maps.Marker({ icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png', map: map, position: results[0].geometry.location, title: title, animation: google.maps.Animation.DROP, address: address, url: url }) infoWindow(marker, map, title, address, url); bounds.extend(marker.getPosition()); map.fitBounds(bounds); } else { alert("geocode of " + address + " failed:" + status); } }); } </code></pre> <p><a href="https://jsfiddle.net/geocodezip/sdhb4fcu/" rel="nofollow noreferrer">Working fiddle</a></p> <p>code snippet:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var locations = [ ['Location 1 Name', 'New York, NY', 'Location 1 URL'], ['Location 2 Name', 'Newark, NJ', 'Location 2 URL'], ['Location 3 Name', 'Philadelphia, PA', 'Location 3 URL'] ]; var geocoder; var map; var bounds = new google.maps.LatLngBounds(); function initialize() { map = new google.maps.Map( document.getElementById("map_canvas"), { center: new google.maps.LatLng(37.4419, -122.1419), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }); geocoder = new google.maps.Geocoder(); for (i = 0; i &lt; locations.length; i++) { geocodeAddress(locations, i); } } google.maps.event.addDomListener(window, "load", initialize); function geocodeAddress(locations, i) { var title = locations[i][0]; var address = locations[i][1]; var url = locations[i][2]; geocoder.geocode({ 'address': locations[i][1] }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var marker = new google.maps.Marker({ icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png', map: map, position: results[0].geometry.location, title: title, animation: google.maps.Animation.DROP, address: address, url: url }) infoWindow(marker, map, title, address, url); bounds.extend(marker.getPosition()); map.fitBounds(bounds); } else { alert("geocode of " + address + " failed:" + status); } }); } function infoWindow(marker, map, title, address, url) { google.maps.event.addListener(marker, 'click', function() { var html = "&lt;div&gt;&lt;h3&gt;" + title + "&lt;/h3&gt;&lt;p&gt;" + address + "&lt;br&gt;&lt;/div&gt;&lt;a href='" + url + "'&gt;View location&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;"; iw = new google.maps.InfoWindow({ content: html, maxWidth: 350 }); iw.open(map, marker); }); } function createMarker(results) { var marker = new google.maps.Marker({ icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png', map: map, position: results[0].geometry.location, title: title, animation: google.maps.Animation.DROP, address: address, url: url }) bounds.extend(marker.getPosition()); map.fitBounds(bounds); infoWindow(marker, map, title, address, url); return marker; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body, #map_canvas { height: 100%; width: 100%; margin: 0px; padding: 0px }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"&gt;&lt;/script&gt; &lt;div id="map_canvas" style="border: 2px solid #3872ac;"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
44,923,353
unable to select top 10 records per group in sparksql
<p>Hi I am new to spark sql. I have a data frame like this.</p> <pre><code> ---+----------+----+----+----+------------------------+ |tag id|timestamp|listner| orgid |org2id|RSSI +---+----------+----+----+----+------------------------+ | 4|1496745912| 362| 4| 3| 0.60| | 4|1496745924|1901| 4| 3| 0.60| | 4|1496746030|1901| 4| 3| 0.60| | 4|1496746110| 718| 4| 3| 0.30| | 2|1496746128| 718| 4| 3| 0.60| | 2|1496746188|1901| 4| 3| 0.10| </code></pre> <p>I want to select for each listner top 10 timestamp values in spark sql.</p> <p>I tried the following query.It throws errors.</p> <pre><code> val avg = sqlContext.sql("select top 10 * from avg_table") // throws error. val avg = sqlContext.sql("select rssi,timestamp,tagid from avg_table order by desc limit 10") // it prints only 10 records. </code></pre> <p>I want to select for each listner I need to take top 10 timestamp values. Any help will be appreciated.</p>
44,924,156
3
0
null
2017-07-05 10:16:15.403 UTC
4
2019-08-01 23:53:59.957 UTC
2019-08-01 23:53:59.957 UTC
null
6,395,770
null
8,235,369
null
1
12
sql|apache-spark-sql
49,456
<p>Doesn't this work?</p> <pre><code>select rssi, timestamp, tagid from avg_table order by timestamp desc limit 10; </code></pre> <p>EDIT:</p> <p>Oh, I get it. You want <code>row_number()</code>:</p> <pre><code>select rssi, timestamp, tagid from (select a.*, row_number() over (partition by listner order by timestamp desc) as seqnum from avg_table ) a where seqnum &lt;= 10 order by a.timestamp desc; </code></pre>
31,685,244
Updating existing Excel file in Java Apache POI
<p>I'm trying to write a Java program that will run daily (using a task scheduler) and will append a column to an Excel spreadsheet every time it runs. The problem I am having is it merely re-writes the file, not appending to it. I am using Apache POI, here is the relevant code:</p> <pre><code> public static void toExcel(List&lt;String&gt; results, List&lt;Integer&gt; notActive)throws IOException{ try { FileInputStream fIPS= new FileInputStream("test.xls"); //Read the spreadsheet that needs to be updated HSSFWorkbook wb; HSSFSheet worksheet; if(fIPS.available()&gt;=512) { wb = new HSSFWorkbook(fIPS); //If there is already data in a workbook worksheet = wb.getSheetAt(0); }else{ wb = new HSSFWorkbook(); //if the workbook was just created worksheet = wb.createSheet("Data"); } //Access the worksheet, so that we can update / modify it HSSFRow row1 = worksheet.createRow(0); //0 = row number int i=0; Cell c = row1.getCell(i); while (!(c == null || c.getCellType() == Cell.CELL_TYPE_BLANK)) { //cell is empty i++; c=row1.getCell(i); } HSSFRow rowx; int x=0; for(String s : results) { rowx = worksheet.createRow(x); HSSFCell cellx = rowx.createCell(i); //0 = column number cellx.setCellValue(s); x++; } fIPS.close(); //Close the InputStream FileOutputStream output_file =new FileOutputStream("test.xls");//Open FileOutputStream to write updates wb.write(output_file); //write changes output_file.close(); //close the stream } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } </code></pre>
31,685,290
1
0
null
2015-07-28 19:18:06.343 UTC
7
2018-11-24 12:03:55.597 UTC
2015-07-29 09:24:30.103 UTC
null
1,606,632
null
4,147,997
null
1
7
java|excel|apache-poi
46,943
<p>I think you are creating the new rows and cells again and again and causing the re-write of excel.</p> <blockquote> <p>Essentially you need to get the rows and cells instead of creating them in your program.</p> </blockquote> <pre><code>HSSFRow row1 = worksheet.createRow(0); </code></pre> <p>You may need to get the row instead of creating it.</p> <pre><code>HSSFRow row1 = worksheet.getRow(0); </code></pre> <p><a href="https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Sheet.html#getRow(int)" rel="noreferrer">https://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Sheet.html#getRow(int)</a></p> <p>This small example updates the second cell of second row:</p> <pre><code>//Read the spreadsheet that needs to be updated FileInputStream fsIP= new FileInputStream(new File("C:\\Excel.xls")); //Access the workbook HSSFWorkbook wb = new HSSFWorkbook(fsIP); //Access the worksheet, so that we can update / modify it. HSSFSheet worksheet = wb.getSheetAt(0); // declare a Cell object Cell cell = null; // Access the second cell in second row to update the value cell = worksheet.getRow(1).getCell(1); // Get current cell value value and overwrite the value cell.setCellValue("OverRide existing value"); //Close the InputStream fsIP.close(); //Open FileOutputStream to write updates FileOutputStream output_file =new FileOutputStream(new File("C:\\Excel.xls")); //write changes wb.write(output_file); //close the stream output_file.close(); </code></pre>
28,332,630
Rails: Render view from outside controller
<p>I'm trying to create an HTML string using a view. I would like to render this from a class that is not a controller. How can I use the rails rendering engine outside a controller? Similar to how ActionMailer does?</p> <p>Thanks!</p>
70,027,370
9
0
null
2015-02-04 22:20:54.783 UTC
5
2021-11-22 21:19:28.45 UTC
2015-02-04 22:42:09.403 UTC
null
1,464,892
null
1,464,892
null
1
34
ruby-on-rails|ruby|ruby-on-rails-4
21,515
<p>In Rails 5:</p> <pre><code>view = ActionView::Base.new(ActionController::Base.view_paths) view.render(file: 'template.html.erb') </code></pre> <p>In Rails 6.1:</p> <pre><code>lookup_context = ActionView::LookupContext.new(ActionController::Base.view_paths) context = ActionView::Base.with_empty_template_cache.new(lookup_context, {}, nil) renderer = ActionView::Renderer.new(lookup_context) renderer.render(context, { file: 'app/views/template.html.erb' }) </code></pre> <ul> <li><code>ActionView::Renderer.new()</code> takes a <code>lookup_context</code> arg, and <code>render()</code> method takes a <code>context</code>, so we set those up first</li> <li><code>ActionView::Base</code> <a href="https://github.com/rails/rails/blob/24c8eb5dd1038df41ce84cd9f1acb965852ea449/actionview/lib/action_view/context.rb#L7" rel="nofollow noreferrer">is the default ActiveView context</a>, and must be initialized with <code>with_empty_template_cache</code> method, else <code>render()</code> will error</li> <li>The <code>{}, nil</code> are <a href="https://github.com/rails/rails/blob/c5bf2b4736f2ddafbc477af5b9478dd7143e5466/actionview/lib/action_view/base.rb#L227" rel="nofollow noreferrer">required</a> <code>assigns</code> and <code>controller</code> args, which used to default to <code>{}, nil</code> in Rails 5</li> <li>Rails 6.1 requires a full filepath <code>file: 'app/views/template.html'</code>, whereas Rails 5 only required the filename</li> </ul>
46,218,270
Swift 4 ,must be used from main thread only warning
<p>When I using <code>Swift4</code>in <code>Xcode 9</code> gives me</p> <blockquote> <p>UIApplication.delegate must be used from main thread only</p> <p>.... must be used from main thread only</p> <p>UI API called from background thread Group</p> </blockquote> <p>Purple Warning.</p> <p>My codes;</p> <pre><code>var appDelegate = UIApplication.shared.delegate as! AppDelegate public var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let prefs:UserDefaults = UserDefaults.standard var deviceUUID = UIDevice.current.identifierForVendor!.uuidString </code></pre> <p>Warning line is;</p> <pre><code> public var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext </code></pre> <p>Another warning like this;</p> <pre><code> let parameters = [ &quot;tel&quot;: &quot;\(self.phone.text!)&quot; ] as [String : String] </code></pre> <p>Gives</p> <blockquote> <p>UITextField.text must be used from main thread only</p> </blockquote> <p>Same error again..</p> <p>How can I fix it ? Any idea ?</p>
46,218,441
1
0
null
2017-09-14 11:47:00.04 UTC
7
2018-04-18 15:55:20.21 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
5,393,528
null
1
33
appdelegate|swift4|xcode9
47,743
<p>You're making this call on a background queue. To fix, try something like… </p> <pre><code>public var context: NSManagedObjectContext DispatchQueue.main.async { var appDelegate = UIApplication.shared.delegate as! AppDelegate context = appDelegate.persistentContainer.viewContext } </code></pre> <p>Although this is a pretty bad way to do this… you're using your App Delegate as a global variable (which we all know is bad!)</p> <p>You should look at passing the managed object context from view controller to view controller…</p> <pre><code>func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: (window?.rootViewController as? MyViewController)?.moc = persistentContainer.viewContext } </code></pre> <p>and so on</p>
34,252,817
Handlebarsjs check if a string is equal to a value
<p>Is it possible in Handlebars to check if a string is equal to another value without registering a helper? I can't seem to find anything relevant to this in the Handlebars reference.</p> <p>For example:</p> <pre><code>{{#if sampleString == "This is a string"}} ...do something {{/if}} </code></pre>
34,252,942
15
0
null
2015-12-13 15:37:30.237 UTC
11
2022-05-21 22:55:55.35 UTC
2018-06-25 12:44:50.62 UTC
null
2,370,483
null
2,219,876
null
1
71
string|handlebars.js|logical-operators
144,915
<p>It seems you can't do it "directly"</p> <p>Try use helper, why not?</p> <p>Register helper in your javascript code:</p> <pre><code>Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) { return (arg1 == arg2) ? options.fn(this) : options.inverse(this); }); </code></pre> <p>Use in template:</p> <pre><code>{{#ifEquals sampleString "This is a string"}} Your HTML here {{/ifEquals}} </code></pre> <p>More details here: <a href="https://stackoverflow.com/questions/8853396/logical-operator-in-a-handlebars-js-if-conditional">Logical operator in a handlebars.js {{#if}} conditional</a></p> <p><strong>Update:</strong> Another way:</p> <p>lets assume, your data is:</p> <pre><code>var data = { sampleString: 'This is a string' }; </code></pre> <p>Then (using jQuery):</p> <pre><code>$.extend(data, {isSampleString: function() { return this.sampleString == 'This is a string';} }); </code></pre> <p>An use template:</p> <pre><code>{{#if isSampleString}} Your HTML here {{/if}} </code></pre>
50,844,781
Android MVVM ViewModel and Repositories for each entity?
<p>With the Android Architecture components and the MVVM pattern I have some question.</p> <p>Based on most examples around the web there are usually simple examples.</p> <ol> <li>Have an entity for Room</li> </ol> <pre><code> @Entity public class User{ ... } </code></pre> <ol start="2"> <li>Have a DAO</li> </ol> <pre><code> @Dao public interface UserDao{ ... } </code></pre> <ol start="3"> <li>Have a repository</li> </ol> <pre><code> public class UserRepository{ } </code></pre> <ol start="4"> <li>ViewModel</li> </ol> <pre><code> public class UsersListViewModel extends AndroidViewModel{ .... } </code></pre> <p>Now let's extend this and beside <code>user</code> have <code>user_access</code> and <code>user_actions</code> for instance, so have 3 tables.</p> <p>Questions:</p> <ol> <li><p>For each table in Room I create entities. Should I have 3 <code>Dao</code> one for each entity (userDao, userAccessDao, userActionsDao) or just a general <code>AppDao</code> class?</p> </li> <li><p>Same goes for Repository. One repository for the entire app or Repositories for each Entitiy (RepositoryUser, RepositoryUserAccess, RepositoryUserActions?</p> </li> <li><p>If my app has one main activity and multiple fragments, should I create one ViewModel for each fragment?</p> </li> </ol>
50,844,907
1
0
null
2018-06-13 19:22:47.09 UTC
13
2020-07-08 13:13:06.78 UTC
2020-07-08 13:13:06.78 UTC
null
1,466,287
null
379,865
null
1
40
android|mvvm|android-architecture-components|android-jetpack
9,733
<h1>1</h1> <p>You should have contextual DAOs, let's say an UserDao which should contains the queries related to the users, if you have posts in your app, you should have a PostDao for everything related to posts.</p> <h1>2</h1> <p>Same logic for repositories, remember the Single Responsibility Principle for classes, sticking to that principle you should have repositories for each kind of entities separated (UserRepository, PostRepository...).</p> <h1>3</h1> <p>Following all the new concepts described as Jetpack you should have one viewmodel per fragment, unless for one strange reason you have two fragments that need the exact same logic, and that is very unlikely to happen since the objective of a fragment is to be reused.</p>
31,561,090
Finding Records in a Database using a Textbox and Search Button in VB.Net
<p>I am Trying to Create a Library management system, I am a beginner at coding. The Problem I am having is I want to search my books database by title in Visual Basic, using a Textbox and Search button and wanting it to display the results in an seperate form. How would I go about a search in my database in visual basic.</p> <p>I have imported my database into visual basic. I have used the query below to make it work in Microsoft Access, but couldn't in Visual Basic. The Query I used in Microsoft access was this:</p> <pre><code>SELECT Books.[Book ID], Books.Title, Books.Author, Books.Category, Books.Location, Books.[Fiction/Non-Fiction], Books.Loaned FROM Books WHERE (((Books.Title) Like [Search Certin Title] &amp; "*")); </code></pre> <p>Please help me in this regard.</p>
31,577,240
2
1
null
2015-07-22 10:54:30.067 UTC
null
2020-01-30 20:10:55.6 UTC
2015-07-23 01:23:43.507 UTC
null
4,634,499
null
4,634,499
null
1
2
database|visual-studio|ms-access|visual-studio-2012
56,382
<p>I have found someone elses code and have modified it to work with my application <a href="http://www.sattsoft.com/sourcecodes/details/1/4/vb-net-add-edit-delete-and-search-data-from-access-database.html" rel="nofollow">http://www.sattsoft.com/sourcecodes/details/1/4/vb-net-add-edit-delete-and-search-data-from-access-database.html</a></p> <p>The Code used is as followed:</p> <pre><code> Private Sub search_btn_Click(sender As Object, e As EventArgs) Handles search_btn.Click Searched_Books_frm.Show() Search_Record() End Sub Private Sub Search_Record() 'The Code Below is not Mine, But I modified it to work with my code. This Code below belongs to Christopher Tubig, Code from: http://goo.gl/113Jd7 (Url have been shortend for convenience) User Profile: Dim conn As New OleDbConnection Dim cmd As New OleDbCommand Dim da As New OleDbDataAdapter Dim dt As New DataTable Dim sSQL As String = String.Empty Try 'get connection string declared in the Module1.vb and assing it to conn variable conn = New OleDbConnection(Get_Constring) conn.Open() cmd.Connection = conn cmd.CommandType = CommandType.Text sSQL = "SELECT Books.[Book ID], Books.Title, Books.Author, Books.Category, Books.Location, Books.[Fiction/Non-Fiction], Books.Loaned FROM Books" sSQL = sSQL &amp; " Where Books.Title like '%" &amp; Me.search_txt.Text &amp; "%'" cmd.CommandText = sSQL da.SelectCommand = cmd da.Fill(dt) Searched_Books_frm.search_datagrid.DataSource = dt If dt.Rows.Count = 0 Then MsgBox("No record found!") End If Catch ex As Exception MsgBox(ErrorToString) Finally conn.Close() End Try End Sub </code></pre> <p>This works perfectly fine for me :)</p>
6,061,869
Are block-level elements allowed inside inline-level elements in HTML5?
<p><strong>For an example</strong></p> <p>Is <code>&lt;a href="#"&gt;&lt;h1&gt;Heading&lt;/h1&gt;&lt;/a&gt;</code> valid in HTML5?</p>
6,062,035
1
0
null
2011-05-19 16:35:47.217 UTC
9
2014-09-21 15:19:03.237 UTC
2014-09-21 15:19:03.237 UTC
null
1,779,477
null
84,201
null
1
26
html|semantic-markup
9,962
<p>yes what you've written is valid in HTML5, but it's not all inline elements, I think it's just <code>&lt;a&gt;</code> 's it applies to..</p> <h3>Reference: <a href="http://html5doctor.com/block-level-links-in-html-5/" rel="noreferrer">“Block-level” links in HTML5 </a></h3> <p>Tip: if using this set the <code>&lt;a&gt;</code> to <code>display: block;</code> or there may be unintended visual styling results : <a href="http://mattwilcox.net/sandbox/html5-block-anchor/test.html" rel="noreferrer">Source: Test Case</a></p> <h3>Update:</h3> <p>It is &quot;disallowed&quot; for other &quot;block in inline&quot; combinations where &quot;default styles are likely to lead to confusion&quot; - <a href="http://dev.w3.org/html5/spec/Overview.html#restrictions-on-content-models-and-on-attribute-values" rel="noreferrer">explanation is here</a>:</p> <blockquote> <h3>Cases where the default styles are likely to lead to confusion</h3> <p>Certain elements have default styles or behaviors that make certain combinations likely to lead to confusion. Where these have equivalent alternatives without this problem, the confusing combinations are disallowed.</p> <p>For example, div elements are rendered as block boxes, and span elements as inline boxes. Putting a block box in an inline box is unnecessarily confusing; since either nesting just div elements, or nesting just span elements, or nesting span elements inside div elements all serve the same purpose as <strong>nesting a div element in a span element</strong>, but only the latter involves a block box in an inline box, <strong>the latter combination is disallowed.</strong></p> </blockquote>
6,223,864
How to install Punjabi Language font in android samsung galaxy?
<p>i have an Android Phone, Samsung Galaxy Pop and I want my phone to read the Punjabi font too. So can you tell me how to install Punjabi font in my mobile Phone. suggest me any solution for it.</p>
6,223,931
2
1
null
2011-06-03 06:44:47.45 UTC
2
2014-04-04 18:56:44.453 UTC
2013-09-26 06:26:46.56 UTC
null
243,557
null
552,027
null
1
0
android-emulator
67,499
<p>I think you should check out this app:</p> <p><a href="http://www.androidzoom.com/android_applications/productivity/gurmukhi-keyboard_rppe.html" rel="nofollow">http://www.androidzoom.com/android_applications/productivity/gurmukhi-keyboard_rppe.html</a></p> <p>The app provides an input method in Gurmukhi Locale with dictionary support. Hopefully it is what you're looking for! (btw I have the same phone, good choice)</p>
24,548,032
How do I match a Google Play Services revision with an install version?
<p>Android SDK Manager notified me this morning that there was a new Google Play Services release to download: revision 18. So how do I find the corresponding long version number to put in my build.gradle file? All my test devices are running version 5.0.84, so I tried updating</p> <pre><code>compile 'com.google.android.gms:play-services:4.4.52' </code></pre> <p>to</p> <pre><code>compile 'com.google.android.gms:play-services:5.0.84' </code></pre> <p>But that resulted in an error:</p> <blockquote> <p>Gradle 'MyApp' project refresh failed: Could not find com.google.android.gms:play-services:5.0.84. Required by: <em>{my app}</em> Gradle settings</p> </blockquote> <p>I'm running Android Studio 0.5.2 and building for API19 (I haven't upgraded to Android L/API20 yet): maybe that's the issue? But in general, <strong>how do you match a revision number shown in SDK Manager (e.g. 18) with a version code for build.gradle (e.g. 5.0.84)?</strong></p> <p>Here's my full build.gradle in case it helps:</p> <pre><code>apply plugin: 'android' android { compileSdkVersion 19 buildToolsVersion "19.1.0" defaultConfig { minSdkVersion 14 targetSdkVersion 19 versionCode 1 versionName "1.0" } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } // Avoid "Duplicate files copied in APK" errors when using Jackson packagingOptions { exclude 'META-INF/LICENSE' exclude 'META-INF/NOTICE' } } dependencies { // Was "compile 'com.android.support:support-v4:+'" but this caused build errors when L SDK released compile 'com.android.support:support-v4:19.1.0' compile fileTree(dir: 'libs', include: ['*.jar']) // Support for Google Cloud Messaging // Was "compile 'com.android.support:appcompat-v7:+'" but this caused build errors when L SDK released compile 'com.android.support:appcompat-v7:19.1.0' compile 'com.google.android.gms:play-services:5.0.84' // Jackson compile 'com.fasterxml.jackson.core:jackson-core:2.3.3' compile 'com.fasterxml.jackson.core:jackson-annotations:2.3.3' compile 'com.fasterxml.jackson.core:jackson-databind:2.3.3' } </code></pre>
24,548,522
2
0
null
2014-07-03 07:53:00.327 UTC
12
2015-03-28 09:16:59.773 UTC
2015-03-28 09:16:59.773 UTC
null
440,921
null
440,921
null
1
24
android|gradle|google-play-services|android-gradle-plugin|build.gradle
22,632
<p>OK, I haven't quite managed to find a mapping of one to the other, but I've managed the next best thing which is to see a list of Play Services long version numbers installed on my development machine.</p> <p>For Windows, it's in <code>[android-sdk]\extras\google\m2repository\com\google\android\gms\play-services</code> (where <code>[android-sdk]</code> is the path to your Android SDK folder).</p> <p>On a Mac, it's inside the Android.app package: browse to <code>sdk/extras/google/m2repository/com/google/android/gms/play-services</code></p> <p>The latest version on my machine was 5.0.77 (not 5.0.84), and putting that in my build.gradle worked fine.</p> <p>Here's the kind of thing you should see at that location:</p> <p><img src="https://i.stack.imgur.com/X2HBr.png" alt="Google Play Services versions on Windows"></p> <p><img src="https://i.stack.imgur.com/Rtpyh.png" alt="Google Play Services versions on OSX"></p>
56,608,996
SwiftUI - Search in List Header
<p>I am trying to to recreate what everyone know from UITableView with SwiftUI: A simple search field in the header of the tableview:</p> <p><a href="https://i.stack.imgur.com/KZoXE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KZoXE.png" alt="A simple search field in the header of the tableview"></a></p> <p>However, the List View in SwiftUI does not even seem to have a way to add a header or footer. You can set a header with a TextField to sections like this:</p> <pre><code>@State private var searchQuery: String = "" var body: some View { List { Section(header: Group{ TextField($searchQuery, placeholder: Text("Search")) .background(Color.white) }) { ListCell() ListCell() ListCell() } } } </code></pre> <p>However, I am not sure if this is the best way to do it because:</p> <ol> <li>The header does not hide when you scroll down as you know it from UITableView.</li> <li>The SearchField does not look like the search field we know and love.</li> </ol> <p>Has anyone found a good approach? I don't want to fall back on UITableView.</p>
56,611,503
4
0
null
2019-06-15 09:10:57.553 UTC
9
2021-06-09 19:48:10.147 UTC
null
null
null
null
345,258
null
1
16
uitableview|search|textfield|swiftui
13,872
<p><strong>Xcode 13 / SwiftUI 3</strong></p> <p>You can now use <code>.searchable</code> to make a List... searchable!</p> <pre><code>struct ContentView: View { @State private var searchQuery: String = &quot;&quot; var body: some View { NavigationView { List { ForEach(Array(1...100) .map { &quot;\($0)&quot; } .filter { searchQuery.isEmpty ? true : $0.contains(searchQuery) } ,id: \.self) { item in Text(verbatim: item) } } .navigationTitle(&quot;Fancy Numbers&quot;) .searchable(text: $searchQuery) } } } </code></pre> <p>The search bar seems to appear only if the <code>List</code> is embedded in a <code>NavigationView</code>.</p> <hr /> <p><strong>Xcode 12, SwiftUI 1/2</strong></p> <p>You can port <code>UISearchBar</code> to SwiftUI.</p> <p>(More about this can be found in the excellent WWDC 2019 talk - <a href="https://developer.apple.com/videos/play/wwdc2019/231/" rel="nofollow noreferrer">Integrating SwiftUI</a>)</p> <pre class="lang-swift prettyprint-override"><code>struct SearchBar: UIViewRepresentable { @Binding var text: String class Coordinator: NSObject, UISearchBarDelegate { @Binding var text: String init(text: Binding&lt;String&gt;) { _text = text } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { text = searchText } } func makeCoordinator() -&gt; Coordinator { return Coordinator(text: $text) } func makeUIView(context: UIViewRepresentableContext&lt;SearchBar&gt;) -&gt; UISearchBar { let searchBar = UISearchBar(frame: .zero) searchBar.delegate = context.coordinator return searchBar } func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext&lt;SearchBar&gt;) { uiView.text = text } } </code></pre> <p>And use it like this:</p> <pre class="lang-swift prettyprint-override"><code>struct ContentView: View { @State private var searchQuery: String = &quot;&quot; var body: some View { List { Section(header: SearchBar(text: self.$searchQuery)) { ForEach(Array(1...100).filter { self.searchQuery.isEmpty ? true : &quot;\($0)&quot;.contains(self.searchQuery) }, id: \.self) { item in Text(&quot;\(item)&quot;) } } } } } </code></pre> <p>It's the proper search bar, but it doesn't hide - I'm sure we'll be able to do it at some point via SwiftUI API.</p> <p><strong>Looks like this</strong>:</p> <p><a href="https://i.stack.imgur.com/hO2Vnl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hO2Vnl.png" alt="enter image description here" /></a></p>
18,620,711
PhoneGap with Django Backend
<p>I'm working on a web application that uses django. </p> <p>I would like to create a native application of the site for ios / android using phone gap. </p> <p>Is this possible? As I understand native devices cannot interpret python code. </p> <p>It is early in the project and if it proves too difficult I may go with a different framework I.e backbone.js. </p> <p>Any thoughts / experiences?</p>
18,622,571
1
0
null
2013-09-04 17:56:26.613 UTC
12
2013-09-05 20:23:46.833 UTC
null
null
null
user1725997
null
null
1
15
ios|django|cordova
11,831
<p>That's right, you cannot run python code on iOS or Android using PhoneGap, but there is no need to do that. Yes, you can build a native mobile application of your site using PhoneGap.</p> <p>I'll try to explain a bit how these technologies compare to each other:</p> <ul> <li>Django is a python web framework running on a web server</li> <li>PhoneGap is a framework for building native mobile applications using web technologies (HTML5+CSS+Javascript), the application will run on a mobile device</li> </ul> <p>One common approach is to build the mobile UI with i.e. <a href="http://jquerymobile.com" rel="nofollow noreferrer">jQuery Mobile</a> and use the Django web application to provide a <a href="http://en.wikipedia.org/wiki/Representational_state_transfer#RESTful_web_APIs" rel="nofollow noreferrer">RESTful API</a> to get data to the application.</p> <p>Take a look at <a href="https://stackoverflow.com/questions/10745177/building-a-mobile-app-with-jquery-mobile-django-and-phonegap">this another question</a> for more details.</p> <hr> <p>Edit: Answer the question in the first comment</p> <p>Yes, it's possible to build a fast and well working application with these frameworks. The performance with today's smartphones is more dependent on the quality of the implementation than i.e. jQuery mobile and Django in themselves. </p> <p>Basically with PhoneGap there are three different ways for showing the content to the user:</p> <ul> <li>server side generated pages</li> <li>pages generated on the client side with Javascript usin data from the server, transferred in a predefined format using for example <a href="http://en.wikipedia.org/wiki/JSON" rel="nofollow noreferrer">JSON</a></li> <li>a combination of the previous two</li> </ul> <p><a href="https://softwareengineering.stackexchange.com/a/171210">This answer</a> clarifies server-client communication and page rendering quite well.</p> <p>You could use PhoneGap a bit like a constrained web browser, and basically show content directly from your server as you would when the user accesses the site with a normal web browser. <strong>But I don't recommend this</strong>, though. This approach has many downsides to it (i.e. what happens when the user opens a link from your website leading to another website?)</p> <p>To be accurate, at least in my opinion, UI written with Javascript and running inside an app built with PhoneGap is not native. Comparing native applications and PhoneGap applications is another thing, here is one <a href="http://boagworld.com/mobile-web/mobile-app-vs-mobile-website-design/" rel="nofollow noreferrer">take on explaining the differences</a>.</p> <p>I don't know what kind of service you are building, but in general I'd suggest evaluating the different approaches before starting to build an application. Would a responsive mobile optimized web site do or is there real need for what an app can provide?</p> <p>If you decide to build an app with PhoneGap, I'd suggest that you do it with client side Javascript and fetch the data from the Django backend with XHR requests in JSON format. There are lots of <a href="http://coenraets.org/blog/2013/06/sample-mobile-phonegap-application-with-backbone-js-and-topcoat/" rel="nofollow noreferrer">examples</a> available in the internet.</p>
792,170
iPhone/Xcode: can different project targets have different bundle identifiers?
<p>I'm a little confused how this works - this is my understanding:</p> <ul> <li>A target's provisioning profile is linked to a specific app ID</li> <li>The bundle identifier for a target is found under <strong>Target info\Properies\Identifier</strong></li> </ul> <p>But... bundle ID is also located in Info.plist. It seems that if you change the bundle ID in <strong>Info.plist</strong>, Xcode changes it automatically in <strong>Target info\Properties\Identifier</strong>, and vice versa.</p> <p>So which is it that takes precedence? The <strong>Target info\Properties\Identifier</strong> bundle ID or the <strong>Info.plist</strong> bundle ID?</p> <p>The reason I ask is because I'd like to have two versions for my app - a free ad supported version and a paid version, and I'd like to accomplish that with two different targets. Since they will be two different apps in the App Store, my understanding is they need two different app IDs (and I don't want to go down the * route with app IDs, the description of how that works on the App Store made my brain hurt).</p> <p>Would I need two different Info.plists for each target if I did this, or can I use the same Info.plist, and just have the different targets use a different development/distribution provisioning profile?</p>
795,726
1
0
null
2009-04-27 03:30:48.89 UTC
11
2014-06-04 14:24:37.22 UTC
2009-04-27 13:12:51.737 UTC
null
18,505
null
18,505
null
1
15
iphone|xcode
14,697
<p>There isn't a precedence, the properties dialog is just serving as another way for you to see your Info.plist.</p> <p>To share the plist between the targets but have different identifiers, make sure that the "Expand Build Settings in Info.plist File" option is enabled for both targets. Then, for each target, make a new user-created variable in the target settings for your bundle ID (e.g., APPLICATION_BUNDLE_IDENTIFIER, see here: <a href="https://stackoverflow.com/a/18472235/308315">https://stackoverflow.com/a/18472235/308315</a>) and set it to the right value for that target. In your plist, put the following for bundle ID:</p> <pre><code>&lt;key&gt;CFBundleIdentifier&lt;/key&gt; &lt;string&gt;$(APPLICATION_BUNDLE_IDENTIFIER)&lt;/string&gt; </code></pre> <p>The variable will be evaluated at build time for each target, so each will get the right bundle ID.</p>
719,609
Having HierarchicalDataTemplates in a TreeView
<p><em>With regards to a question I posted earlier on (<a href="https://stackoverflow.com/questions/718858/wpf-correctly-storing-an-object-in-a-treeviewitem/718895#718895">WPF: Correctly storing an object in a TreeViewItem</a>)</em></p> <p><strong>Is it possible to have nested <code>HierarchicalDataTemplate</code>s in a TreeView?</strong></p> <hr> <p>Take the following example: </p> <p><em>Code:</em></p> <pre><code>public class Artist { private readonly ICollection&lt;Album&gt; _children = new ObservableCollection&lt;Album&gt;(); public string Name { get; set; } public ICollection&lt;Album&gt; Albums { get { return _children;} } } public class Album { private readonly ICollection&lt;Track&gt; _children = new ObservableCollection&lt;Track&gt;(); public string Name { get; set; } public ICollection&lt;Track&gt; Tracks { get { return _children;} } } </code></pre> <p><em>Xaml:</em></p> <pre><code>&lt;TreeView x:Name="_treeView"&gt; &lt;TreeView.Resources&gt; &lt;HierarchicalDataTemplate DataType="{x:Type local:Artist}" ItemsSource="{Binding Albums}"&gt; &lt;TextBlock Text="{Binding Name}"/&gt; &lt;/HierarchicalDataTemplate&gt; &lt;/TreeView.Resources&gt; &lt;/TreeView&gt; </code></pre> <p>As you see from the above, the TreeView is only binding the Artists and their albums. How can I modify it to include also the Tracks of the albums (as a sub-list of the albums ie) ?</p>
719,840
1
0
null
2009-04-05 20:19:41.063 UTC
9
2012-06-08 14:43:12.987 UTC
2017-05-23 12:01:02.72 UTC
null
-1
Dreas Grech
44,084
null
1
27
c#|.net|wpf|xaml|treeview
37,302
<p>You dont need a nested template here, since TreeView control will take care of nesting it based on the DataType it requires. So just define Two HierarchicalDataTemplates for Album and Artist Type and one ordinary DataTemplate for your Track class.</p> <pre><code> &lt;HierarchicalDataTemplate DataType="{x:Type local:Artist}" ItemsSource="{Binding Albums}" &gt; &lt;TextBlock Text="{Binding Name}"/&gt; &lt;/HierarchicalDataTemplate&gt; &lt;HierarchicalDataTemplate DataType="{x:Type local:Album}" ItemsSource="{Binding Tracks}" &gt; &lt;TextBlock Text="{Binding Name}"/&gt; &lt;/HierarchicalDataTemplate&gt; &lt;DataTemplate DataType="{x:Type local:Track}"&gt; &lt;TextBlock Text="{Binding Name}"/&gt; &lt;/DataTemplate&gt; </code></pre>
63,455,427
fatal error: opencv2/opencv_modules.hpp: No such file or directory #include "opencv2/opencv_modules.hpp"
<p>Hello all I am trying to use opencv-c++ API (version 4.4.0) which I have built from source. It is installed in /usr/local/ and I was simply trying to load and display an image using the following code -</p> <pre><code>#include &lt;iostream&gt; #include &lt;opencv4/opencv2/opencv.hpp&gt; #include &lt;opencv4/opencv2/core.hpp&gt; #include &lt;opencv4/opencv2/imgcodecs.hpp&gt; #include &lt;opencv4/opencv2/highgui.hpp&gt; #include &lt;opencv4/opencv2/core/cuda.hpp&gt; using namespace cv; int main() { std::string image_path = &quot;13.jpg&quot;; cv::Mat img = cv::imreadmulti(image_path, IMREAD_COLOR); if(img.empty()) { std::cout&lt;&lt;&quot;COULD NOT READ IMAGE&quot;&lt;&lt;std::endl; return 1; } imshow(&quot;Display Window&quot;, img); return 0; } </code></pre> <p>And when I compile it throws the following error during compilation -</p> <pre><code>In file included from /CLionProjects/opencvTest/main.cpp:2: /usr/local/include/opencv4/opencv2/opencv.hpp:48:10: fatal error: opencv2/opencv_modules.hpp: No such file or directory #include &quot;opencv2/opencv_modules.hpp&quot; </code></pre> <p>My Cmake is as follows -</p> <pre><code>cmake_minimum_required(VERSION 3.15) project(opencvTest) set(CMAKE_CXX_STANDARD 17) include_directories(&quot;/usr/local/include/opencv4/opencv2/&quot;) add_executable(opencvTest main.cpp) target_link_libraries(opencvTest PUBLIC &quot;/usr/local/lib/&quot;) </code></pre> <p>I do not know what am I doing wrong here.. This might be a noob question, But I ahev just started using opencv in C++</p>
63,456,129
2
5
null
2020-08-17 17:03:09.55 UTC
3
2022-08-26 14:01:45.927 UTC
2022-08-26 14:01:45.927 UTC
null
6,885,902
null
13,594,617
null
1
15
c++|opencv
39,861
<p>The solution is to just include_directories path till <code>/usr/local/opencv4</code> and it works perfectly.</p> <p>However, the best way I believe is to use the <code>find_package</code> function. I updated my Cmake to the following and it takes care of linking during build.</p> <pre><code>cmake_minimum_required(VERSION 3.15) project(opencvTest) set(CMAKE_CXX_STANDARD 17) find_package(OpenCV REQUIRED) include_directories(${OpenCV_INCLUDE_DIRS}) add_executable(opencvTest main.cpp) target_link_libraries(opencvTest ${OpenCV_LIBS}) </code></pre>
21,075,983
How to use particular CSS styles based on screen size / device
<p>Bootstrap 3 has nice CSS classes in responsive utilities that allow me to hide or show some blocks depending upon the screen resolution <a href="http://getbootstrap.com/css/#responsive-utilities-classes" rel="noreferrer">http://getbootstrap.com/css/#responsive-utilities-classes</a></p> <p>I have some style rules in a CSS file that I want to be applied or not based on screen resolution.</p> <p>How can I do it?</p> <p>I'm going to minimize all my CSS files into the one on production deployment, but this could be avoided if there are no other solutions than having separate CSS files for different screen resolutions.</p>
21,076,033
5
0
null
2014-01-12 14:46:18.857 UTC
14
2019-03-28 08:18:20.3 UTC
2015-11-12 20:02:19.523 UTC
null
2,756,409
null
118,657
null
1
63
css|twitter-bootstrap|twitter-bootstrap-3
155,333
<p>Use <a href="http://www.w3.org/TR/css3-mediaqueries/"><code>@media</code> queries</a>. They serve this exact purpose. Here's an example how they work:</p> <pre class="lang-css prettyprint-override"><code>@media (max-width: 800px) { /* CSS that should be displayed if width is equal to or less than 800px goes here */ } </code></pre> <p>This would work only on devices whose width is equal to or less than 800px.</p> <p>Read up more about media queries on the <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries">Mozilla Developer Network</a>.</p>
49,663,545
Is it possible to resize vuetify components?
<p>I recently use <strong>Vuetify</strong> to implement some UI designs. However, I found the default input component (such as v-text-field, v-select) are too large. I found that I can adjust the width of them, but for the height and font size, how can I change them?</p>
49,663,917
5
1
null
2018-04-05 03:11:08.68 UTC
5
2021-02-16 10:55:11.35 UTC
null
null
null
null
6,204,233
null
1
23
vue.js|vue-component|vuetify.js
47,721
<p>Although you can use <code>:style</code> bindings, to get what you want you'll have to resort to CSS.</p> <p>You can use <code>!important</code> to "force in" your styles, but there are alternatives that can make it work without it. See demo below.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>new Vue({ el: '#app' });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#styled-input { height: 40px; font-size: 20pt; } .styled-input label[for] { height: 40px; font-size: 20pt; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel='stylesheet prefetch' href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons'&gt; &lt;link rel='stylesheet prefetch' href='https://unpkg.com/[email protected]/dist/vuetify.min.css'&gt; &lt;script src='https://unpkg.com/babel-polyfill/dist/polyfill.min.js'&gt;&lt;/script&gt; &lt;script src='https://unpkg.com/vue/dist/vue.js'&gt;&lt;/script&gt; &lt;script src='https://unpkg.com/[email protected]/dist/vuetify.min.js'&gt;&lt;/script&gt; &lt;div id="app"&gt; &lt;v-app id="inspire"&gt; &lt;v-container fluid&gt; &lt;v-layout row&gt; &lt;v-flex&gt; &lt;v-text-field name="input-1" label="Regular Input"&gt;&lt;/v-text-field&gt; &lt;v-text-field name="input-1" label="Styled Input" id="styled-input" class="styled-input"&gt;&lt;/v-text-field&gt; &lt;/v-flex&gt; &lt;/v-layout&gt; &lt;/v-container&gt; &lt;/v-app&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
47,563,013
Unable to import path from django.urls
<p>Tried to run command:</p> <pre><code>from django.urls import path </code></pre> <p>Getting error:</p> <blockquote> <p>Traceback (most recent call last): File "&lt; stdin >", line 1, in ImportError: cannot import name 'path'</p> </blockquote> <p>I am using django version 1.11</p>
47,563,055
14
0
null
2017-11-29 22:37:39.533 UTC
9
2022-03-27 09:23:23.72 UTC
2018-02-18 03:31:24.717 UTC
null
3,476,943
null
3,476,943
null
1
55
python|django|python-3.x|django-views
140,456
<p>The reason you cannot import path is because it is new in Django 2.0 as is mentioned here: <a href="https://docs.djangoproject.com/en/2.0/ref/urls/#path" rel="noreferrer">https://docs.djangoproject.com/en/2.0/ref/urls/#path</a>. </p> <p>On that page in the bottom right hand corner you can change the documentation version to the version that you have installed. If you do this you will see that there is no entry for <code>path</code> on the <code>1.11</code> docs.</p>
26,090,198
Concatenate string and int in Python 3 .4
<p>I'm new to Python, so I've been running through my own set of exercises to simply start memorizing basic functions and syntax.</p> <p>I'm using the <a href="https://en.wikipedia.org/wiki/PyCharm" rel="nofollow noreferrer">PyCharm</a> IDE and Python 3.4. I've run into an issue when running through some basic string and integer concatenation exercises. Each instance below is throwing an unsupported operand type. There are several threads on Stack Overflow that clearly states proper concatenation syntax, but the above error message continues to plague me.</p> <pre><code>print (&quot;Type string: &quot;) + str(123) print (&quot;Concatenate strings and ints &quot;), 10 </code></pre>
26,090,288
6
0
null
2014-09-28 22:14:40.023 UTC
2
2022-03-04 06:34:20.2 UTC
2022-03-04 06:19:17.07 UTC
null
63,550
null
4,083,766
null
1
5
python|string
41,206
<p>Note that <a href="https://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function" rel="nofollow noreferrer"><code>print</code> is a function in Python 3</a>. In Python 2, your first line would concatenate &quot;Type string: &quot; and &quot;123&quot; and then print them. In Python 3, you are calling the <code>print</code> function with one argument, which returns <code>None</code>, <em>and then add &quot;123&quot; to it</em>. That doesn't make any sense.</p> <p>The second line doesn't generate an error in Python 2 or 3 (I've tested it with 2.7.7 and 3.2.3). In Python 2, you get</p> <blockquote> <p>Concatenate strings and ints 10</p> </blockquote> <p>while in Python 3, your script should only print</p> <blockquote> <p>Concatenate strings and ints</p> </blockquote> <p>This is because again, print is a function, and therefore you call it with the argument &quot;Concatenate strings and ints&quot;. The <code>, 10</code> makes your line a tuple of the return value of <code>print</code>, which is <code>None</code>, and <code>10</code>. Since you don't use that tuple for anything, there is no visible effect.</p>